KustoQueryField.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import _ from 'lodash';
  2. import Plain from 'slate-plain-serializer';
  3. import QueryField from './query_field';
  4. // import debounce from './utils/debounce';
  5. // import {getNextCharacter} from './utils/dom';
  6. import debounce from 'app/features/explore/utils/debounce';
  7. import { getNextCharacter } from 'app/features/explore/utils/dom';
  8. import { KEYWORDS, functionTokens, operatorTokens, grafanaMacros } from './kusto/kusto';
  9. // import '../sass/editor.base.scss';
  10. const TYPEAHEAD_DELAY = 100;
  11. interface Suggestion {
  12. text: string;
  13. deleteBackwards?: number;
  14. type?: string;
  15. }
  16. interface SuggestionGroup {
  17. label: string;
  18. items: Suggestion[];
  19. prefixMatch?: boolean;
  20. skipFilter?: boolean;
  21. }
  22. interface KustoSchema {
  23. Databases: {
  24. Default?: KustoDBSchema;
  25. };
  26. Plugins?: any[];
  27. }
  28. interface KustoDBSchema {
  29. Name?: string;
  30. Functions?: any;
  31. Tables?: any;
  32. }
  33. const defaultSchema = () => ({
  34. Databases: {
  35. Default: {}
  36. }
  37. });
  38. const cleanText = s => s.replace(/[{}[\]="(),!~+\-*/^%]/g, '').trim();
  39. const wrapText = text => ({ text });
  40. export default class KustoQueryField extends QueryField {
  41. fields: any;
  42. events: any;
  43. schema: KustoSchema;
  44. constructor(props, context) {
  45. super(props, context);
  46. this.schema = defaultSchema();
  47. this.onTypeahead = debounce(this.onTypeahead, TYPEAHEAD_DELAY);
  48. }
  49. componentDidMount() {
  50. super.componentDidMount();
  51. this.fetchSchema();
  52. }
  53. onTypeahead = (force = false) => {
  54. const selection = window.getSelection();
  55. if (selection.anchorNode) {
  56. const wrapperNode = selection.anchorNode.parentElement;
  57. if (wrapperNode === null) {
  58. return;
  59. }
  60. const editorNode = wrapperNode.closest('.slate-query-field');
  61. if (!editorNode || this.state.value.isBlurred) {
  62. // Not inside this editor
  63. return;
  64. }
  65. // DOM ranges
  66. const range = selection.getRangeAt(0);
  67. const text = selection.anchorNode.textContent;
  68. if (text === null) {
  69. return;
  70. }
  71. const offset = range.startOffset;
  72. let prefix = cleanText(text.substr(0, offset));
  73. // Model ranges
  74. const modelOffset = this.state.value.anchorOffset;
  75. const modelPrefix = this.state.value.anchorText.text.slice(0, modelOffset);
  76. // Determine candidates by context
  77. let suggestionGroups: SuggestionGroup[] = [];
  78. const wrapperClasses = wrapperNode.classList;
  79. let typeaheadContext: string | null = null;
  80. // Built-in functions
  81. if (wrapperClasses.contains('function-context')) {
  82. typeaheadContext = 'context-function';
  83. suggestionGroups = this.getColumnSuggestions();
  84. // where
  85. } else if (modelPrefix.match(/(where\s(\w+\b)?$)/i)) {
  86. typeaheadContext = 'context-where';
  87. suggestionGroups = this.getColumnSuggestions();
  88. // summarize by
  89. } else if (modelPrefix.match(/(summarize\s(\w+\b)?$)/i)) {
  90. typeaheadContext = 'context-summarize';
  91. suggestionGroups = this.getFunctionSuggestions();
  92. } else if (modelPrefix.match(/(summarize\s(.+\s)?by\s+([^,\s]+,\s*)*([^,\s]+\b)?$)/i)) {
  93. typeaheadContext = 'context-summarize-by';
  94. suggestionGroups = this.getColumnSuggestions();
  95. // order by, top X by, ... by ...
  96. } else if (modelPrefix.match(/(by\s+([^,\s]+,\s*)*([^,\s]+\b)?$)/i)) {
  97. typeaheadContext = 'context-by';
  98. suggestionGroups = this.getColumnSuggestions();
  99. // join
  100. } else if (modelPrefix.match(/(on\s(.+\b)?$)/i)) {
  101. typeaheadContext = 'context-join-on';
  102. suggestionGroups = this.getColumnSuggestions();
  103. } else if (modelPrefix.match(/(join\s+(\(\s+)?(\w+\b)?$)/i)) {
  104. typeaheadContext = 'context-join';
  105. suggestionGroups = this.getTableSuggestions();
  106. // distinct
  107. } else if (modelPrefix.match(/(distinct\s(.+\b)?$)/i)) {
  108. typeaheadContext = 'context-distinct';
  109. suggestionGroups = this.getColumnSuggestions();
  110. // database()
  111. } else if (modelPrefix.match(/(database\(\"(\w+)\"\)\.(.+\b)?$)/i)) {
  112. typeaheadContext = 'context-database-table';
  113. const db = this.getDBFromDatabaseFunction(modelPrefix);
  114. console.log(db);
  115. suggestionGroups = this.getTableSuggestions(db);
  116. prefix = prefix.replace('.', '');
  117. // new
  118. } else if (normalizeQuery(Plain.serialize(this.state.value)).match(/^\s*\w*$/i)) {
  119. typeaheadContext = 'context-new';
  120. if (this.schema) {
  121. suggestionGroups = this.getInitialSuggestions();
  122. } else {
  123. this.fetchSchema();
  124. setTimeout(this.onTypeahead, 0);
  125. return;
  126. }
  127. // built-in
  128. } else if (prefix && !wrapperClasses.contains('argument')) {
  129. if (modelPrefix.match(/\s$/i)) {
  130. prefix = '';
  131. }
  132. typeaheadContext = 'context-builtin';
  133. suggestionGroups = this.getKeywordSuggestions();
  134. } else if (force === true) {
  135. typeaheadContext = 'context-builtin';
  136. if (modelPrefix.match(/\s$/i)) {
  137. prefix = '';
  138. }
  139. suggestionGroups = this.getKeywordSuggestions();
  140. }
  141. let results = 0;
  142. prefix = prefix.toLowerCase();
  143. const filteredSuggestions = suggestionGroups.map(group => {
  144. if (group.items && prefix && !group.skipFilter) {
  145. group.items = group.items.filter(c => c.text.length >= prefix.length);
  146. if (group.prefixMatch) {
  147. group.items = group.items.filter(c => c.text.toLowerCase().indexOf(prefix) === 0);
  148. } else {
  149. group.items = group.items.filter(c => c.text.toLowerCase().indexOf(prefix) > -1);
  150. }
  151. }
  152. results += group.items.length;
  153. return group;
  154. })
  155. .filter(group => group.items.length > 0);
  156. // console.log('onTypeahead', selection.anchorNode, wrapperClasses, text, offset, prefix, typeaheadContext);
  157. // console.log('onTypeahead', prefix, typeaheadContext);
  158. this.setState({
  159. typeaheadPrefix: prefix,
  160. typeaheadContext,
  161. typeaheadText: text,
  162. suggestions: results > 0 ? filteredSuggestions : [],
  163. });
  164. }
  165. }
  166. applyTypeahead(change, suggestion) {
  167. const { typeaheadPrefix, typeaheadContext, typeaheadText } = this.state;
  168. let suggestionText = suggestion.text || suggestion;
  169. const move = 0;
  170. // Modify suggestion based on context
  171. const nextChar = getNextCharacter();
  172. if (suggestion.type === 'function') {
  173. if (!nextChar || nextChar !== '(') {
  174. suggestionText += '(';
  175. }
  176. } else if (typeaheadContext === 'context-function') {
  177. if (!nextChar || nextChar !== ')') {
  178. suggestionText += ')';
  179. }
  180. } else {
  181. if (!nextChar || nextChar !== ' ') {
  182. suggestionText += ' ';
  183. }
  184. }
  185. this.resetTypeahead();
  186. // Remove the current, incomplete text and replace it with the selected suggestion
  187. const backward = suggestion.deleteBackwards || typeaheadPrefix.length;
  188. const text = cleanText(typeaheadText);
  189. const suffixLength = text.length - typeaheadPrefix.length;
  190. const offset = typeaheadText.indexOf(typeaheadPrefix);
  191. const midWord = typeaheadPrefix && ((suffixLength > 0 && offset > -1) || suggestionText === typeaheadText);
  192. const forward = midWord ? suffixLength + offset : 0;
  193. return change
  194. .deleteBackward(backward)
  195. .deleteForward(forward)
  196. .insertText(suggestionText)
  197. .move(move)
  198. .focus();
  199. }
  200. // private _getFieldsSuggestions(): SuggestionGroup[] {
  201. // return [
  202. // {
  203. // prefixMatch: true,
  204. // label: 'Fields',
  205. // items: this.fields.map(wrapText)
  206. // },
  207. // {
  208. // prefixMatch: true,
  209. // label: 'Variables',
  210. // items: this.props.templateVariables.map(wrapText)
  211. // }
  212. // ];
  213. // }
  214. // private _getAfterFromSuggestions(): SuggestionGroup[] {
  215. // return [
  216. // {
  217. // skipFilter: true,
  218. // label: 'Events',
  219. // items: this.events.map(wrapText)
  220. // },
  221. // {
  222. // prefixMatch: true,
  223. // label: 'Variables',
  224. // items: this.props.templateVariables
  225. // .map(wrapText)
  226. // .map(suggestion => {
  227. // suggestion.deleteBackwards = 0;
  228. // return suggestion;
  229. // })
  230. // }
  231. // ];
  232. // }
  233. // private _getAfterSelectSuggestions(): SuggestionGroup[] {
  234. // return [
  235. // {
  236. // prefixMatch: true,
  237. // label: 'Fields',
  238. // items: this.fields.map(wrapText)
  239. // },
  240. // {
  241. // prefixMatch: true,
  242. // label: 'Functions',
  243. // items: FUNCTIONS.map((s: any) => { s.type = 'function'; return s; })
  244. // },
  245. // {
  246. // prefixMatch: true,
  247. // label: 'Variables',
  248. // items: this.props.templateVariables.map(wrapText)
  249. // }
  250. // ];
  251. // }
  252. private getInitialSuggestions(): SuggestionGroup[] {
  253. return this.getTableSuggestions();
  254. }
  255. private getKeywordSuggestions(): SuggestionGroup[] {
  256. return [
  257. {
  258. prefixMatch: true,
  259. label: 'Keywords',
  260. items: KEYWORDS.map(wrapText)
  261. },
  262. {
  263. prefixMatch: true,
  264. label: 'Operators',
  265. items: operatorTokens
  266. },
  267. {
  268. prefixMatch: true,
  269. label: 'Functions',
  270. items: functionTokens.map((s: any) => { s.type = 'function'; return s; })
  271. },
  272. {
  273. prefixMatch: true,
  274. label: 'Macros',
  275. items: grafanaMacros.map((s: any) => { s.type = 'function'; return s; })
  276. },
  277. {
  278. prefixMatch: true,
  279. label: 'Tables',
  280. items: _.map(this.schema.Databases.Default.Tables, (t: any) => ({ text: t.Name }))
  281. }
  282. ];
  283. }
  284. private getFunctionSuggestions(): SuggestionGroup[] {
  285. return [
  286. {
  287. prefixMatch: true,
  288. label: 'Functions',
  289. items: functionTokens.map((s: any) => { s.type = 'function'; return s; })
  290. },
  291. {
  292. prefixMatch: true,
  293. label: 'Macros',
  294. items: grafanaMacros.map((s: any) => { s.type = 'function'; return s; })
  295. }
  296. ];
  297. }
  298. getTableSuggestions(db = 'Default'): SuggestionGroup[] {
  299. if (this.schema.Databases[db]) {
  300. return [
  301. {
  302. prefixMatch: true,
  303. label: 'Tables',
  304. items: _.map(this.schema.Databases[db].Tables, (t: any) => ({ text: t.Name }))
  305. }
  306. ];
  307. } else {
  308. return [];
  309. }
  310. }
  311. private getColumnSuggestions(): SuggestionGroup[] {
  312. const table = this.getTableFromContext();
  313. if (table) {
  314. const tableSchema = this.schema.Databases.Default.Tables[table];
  315. if (tableSchema) {
  316. return [
  317. {
  318. prefixMatch: true,
  319. label: 'Fields',
  320. items: _.map(tableSchema.OrderedColumns, (f: any) => ({
  321. text: f.Name,
  322. hint: f.Type
  323. }))
  324. }
  325. ];
  326. }
  327. }
  328. return [];
  329. }
  330. private getTableFromContext() {
  331. const query = Plain.serialize(this.state.value);
  332. const tablePattern = /^\s*(\w+)\s*|/g;
  333. const normalizedQuery = normalizeQuery(query);
  334. const match = tablePattern.exec(normalizedQuery);
  335. if (match && match.length > 1 && match[0] && match[1]) {
  336. return match[1];
  337. } else {
  338. return null;
  339. }
  340. }
  341. private getDBFromDatabaseFunction(prefix: string) {
  342. const databasePattern = /database\(\"(\w+)\"\)/gi;
  343. const match = databasePattern.exec(prefix);
  344. if (match && match.length > 1 && match[0] && match[1]) {
  345. return match[1];
  346. } else {
  347. return null;
  348. }
  349. }
  350. private async fetchSchema() {
  351. let schema = await this.props.getSchema();
  352. if (schema) {
  353. if (schema.Type === 'AppInsights') {
  354. schema = castSchema(schema);
  355. }
  356. this.schema = schema;
  357. } else {
  358. this.schema = defaultSchema();
  359. }
  360. }
  361. }
  362. /**
  363. * Cast schema from App Insights to default Kusto schema
  364. */
  365. function castSchema(schema) {
  366. const defaultSchemaTemplate = defaultSchema();
  367. defaultSchemaTemplate.Databases.Default = schema;
  368. return defaultSchemaTemplate;
  369. }
  370. function normalizeQuery(query: string): string {
  371. const commentPattern = /\/\/.*$/gm;
  372. let normalizedQuery = query.replace(commentPattern, '');
  373. normalizedQuery = normalizedQuery.replace('\n', ' ');
  374. return normalizedQuery;
  375. }