SQLishFormatter.tsx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import * as Sentry from '@sentry/react';
  2. import {simpleMarkup} from 'sentry/views/starfish/utils/sqlish/formatters/simpleMarkup';
  3. import {string} from 'sentry/views/starfish/utils/sqlish/formatters/string';
  4. import {SQLishParser} from 'sentry/views/starfish/utils/sqlish/SQLishParser';
  5. type StringFormatterOptions = Parameters<typeof string>[1];
  6. enum Format {
  7. STRING = 'string',
  8. SIMPLE_MARKUP = 'simpleMarkup',
  9. }
  10. const FORMATTERS = {
  11. [Format.STRING]: string,
  12. [Format.SIMPLE_MARKUP]: simpleMarkup,
  13. };
  14. export class SQLishFormatter {
  15. parser: SQLishParser;
  16. constructor() {
  17. this.parser = new SQLishParser();
  18. }
  19. toString(sql: string, options?: StringFormatterOptions) {
  20. return this.toFormat(sql, Format.STRING, options);
  21. }
  22. toSimpleMarkup(sql: string) {
  23. return this.toFormat(sql, Format.SIMPLE_MARKUP);
  24. }
  25. toFormat(sql: string, format: Format.STRING, options?: StringFormatterOptions): string;
  26. toFormat(sql: string, format: Format.SIMPLE_MARKUP): React.ReactElement[];
  27. toFormat(sql: string, format: Format, options?: StringFormatterOptions) {
  28. let tokens;
  29. const sentrySpan = Sentry.startInactiveSpan({
  30. op: 'function',
  31. name: 'SQLishFormatter.toFormat',
  32. attributes: {
  33. format,
  34. },
  35. onlyIfParent: true,
  36. });
  37. try {
  38. tokens = this.parser.parse(sql);
  39. } catch (error) {
  40. Sentry.withScope(scope => {
  41. scope.setFingerprint(['sqlish-parse-error']);
  42. // Get the last 100 characters of the error message
  43. scope.setExtra('message', error.message?.slice(-100));
  44. scope.setExtra('found', error.found);
  45. Sentry.captureException(error);
  46. });
  47. // If we fail to parse the SQL, return the original string
  48. return sql;
  49. }
  50. const formattedString = FORMATTERS[format](tokens, options);
  51. sentrySpan?.end();
  52. return formattedString;
  53. }
  54. }