KustoQueryField.tsx 13 KB

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