KustoQueryField.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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?: boolean) => {
  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') && !force) {
  129. // Use only last typed word as a prefix for searching
  130. if (modelPrefix.match(/\s$/i)) {
  131. prefix = '';
  132. return;
  133. }
  134. prefix = getLastWord(prefix);
  135. typeaheadContext = 'context-builtin';
  136. suggestionGroups = this.getKeywordSuggestions();
  137. } else if (force === true) {
  138. typeaheadContext = 'context-builtin-forced';
  139. if (modelPrefix.match(/\s$/i)) {
  140. prefix = '';
  141. }
  142. suggestionGroups = this.getKeywordSuggestions();
  143. }
  144. let results = 0;
  145. prefix = prefix.toLowerCase();
  146. const filteredSuggestions = suggestionGroups.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, suggestion) {
  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 = 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) => { s.type = 'function'; return s; })
  274. },
  275. {
  276. prefixMatch: true,
  277. label: 'Macros',
  278. items: grafanaMacros.map((s: any) => { s.type = 'function'; return s; })
  279. },
  280. {
  281. prefixMatch: true,
  282. label: 'Tables',
  283. items: _.map(this.schema.Databases.Default.Tables, (t: any) => ({ text: t.Name }))
  284. }
  285. ];
  286. }
  287. private getFunctionSuggestions(): SuggestionGroup[] {
  288. return [
  289. {
  290. prefixMatch: true,
  291. label: 'Functions',
  292. items: functionTokens.map((s: any) => { s.type = 'function'; return s; })
  293. },
  294. {
  295. prefixMatch: true,
  296. label: 'Macros',
  297. items: grafanaMacros.map((s: any) => { s.type = 'function'; return s; })
  298. }
  299. ];
  300. }
  301. getTableSuggestions(db = 'Default'): SuggestionGroup[] {
  302. if (this.schema.Databases[db]) {
  303. return [
  304. {
  305. prefixMatch: true,
  306. label: 'Tables',
  307. items: _.map(this.schema.Databases[db].Tables, (t: any) => ({ text: t.Name }))
  308. }
  309. ];
  310. } else {
  311. return [];
  312. }
  313. }
  314. private getColumnSuggestions(): SuggestionGroup[] {
  315. const table = this.getTableFromContext();
  316. if (table) {
  317. const tableSchema = this.schema.Databases.Default.Tables[table];
  318. if (tableSchema) {
  319. return [
  320. {
  321. prefixMatch: true,
  322. label: 'Fields',
  323. items: _.map(tableSchema.OrderedColumns, (f: any) => ({
  324. text: f.Name,
  325. hint: f.Type
  326. }))
  327. }
  328. ];
  329. }
  330. }
  331. return [];
  332. }
  333. private getTableFromContext() {
  334. const query = Plain.serialize(this.state.value);
  335. const tablePattern = /^\s*(\w+)\s*|/g;
  336. const normalizedQuery = normalizeQuery(query);
  337. const match = tablePattern.exec(normalizedQuery);
  338. if (match && match.length > 1 && match[0] && match[1]) {
  339. return match[1];
  340. } else {
  341. return null;
  342. }
  343. }
  344. private getDBFromDatabaseFunction(prefix: string) {
  345. const databasePattern = /database\(\"(\w+)\"\)/gi;
  346. const match = databasePattern.exec(prefix);
  347. if (match && match.length > 1 && match[0] && match[1]) {
  348. return match[1];
  349. } else {
  350. return null;
  351. }
  352. }
  353. private async fetchSchema() {
  354. let schema = await this.props.getSchema();
  355. if (schema) {
  356. if (schema.Type === 'AppInsights') {
  357. schema = castSchema(schema);
  358. }
  359. this.schema = schema;
  360. } else {
  361. this.schema = defaultSchema();
  362. }
  363. }
  364. }
  365. /**
  366. * Cast schema from App Insights to default Kusto schema
  367. */
  368. function castSchema(schema) {
  369. const defaultSchemaTemplate = defaultSchema();
  370. defaultSchemaTemplate.Databases.Default = schema;
  371. return defaultSchemaTemplate;
  372. }
  373. function normalizeQuery(query: string): string {
  374. const commentPattern = /\/\/.*$/gm;
  375. let normalizedQuery = query.replace(commentPattern, '');
  376. normalizedQuery = normalizedQuery.replace('\n', ' ');
  377. return normalizedQuery;
  378. }
  379. function getLastWord(str: string): string {
  380. const lastWordPattern = /(?:.*\s)?([^\s]+\s*)$/gi;
  381. const match = lastWordPattern.exec(str);
  382. if (match && match.length > 1) {
  383. return match[1];
  384. }
  385. return '';
  386. }