SQLishFormatter.tsx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 sentryTransaction = Sentry.getActiveTransaction();
  30. const sentrySpan = sentryTransaction?.startChild({
  31. op: 'function',
  32. description: 'SQLishFormatter.toFormat',
  33. data: {
  34. format,
  35. },
  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. }