SQLishFormatter.tsx 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. enum Format {
  6. STRING = 'string',
  7. SIMPLE_MARKUP = 'simpleMarkup',
  8. }
  9. const FORMATTERS = {
  10. [Format.STRING]: string,
  11. [Format.SIMPLE_MARKUP]: simpleMarkup,
  12. };
  13. export class SQLishFormatter {
  14. parser: SQLishParser;
  15. constructor() {
  16. this.parser = new SQLishParser();
  17. }
  18. toString(sql: string) {
  19. return this.toFormat(sql, Format.STRING);
  20. }
  21. toSimpleMarkup(sql: string) {
  22. return this.toFormat(sql, Format.SIMPLE_MARKUP);
  23. }
  24. toFormat(sql: string, format: Format.STRING): string;
  25. toFormat(sql: string, format: Format.SIMPLE_MARKUP): React.ReactElement[];
  26. toFormat(sql: string, format: Format) {
  27. let tokens;
  28. const sentryTransaction = Sentry.getCurrentHub().getScope()?.getTransaction();
  29. const sentrySpan = sentryTransaction?.startChild({
  30. op: 'function',
  31. description: 'SQLishFormatter.toFormat',
  32. data: {
  33. format,
  34. },
  35. });
  36. try {
  37. tokens = this.parser.parse(sql);
  38. } catch (error) {
  39. Sentry.withScope(scope => {
  40. scope.setFingerprint(['sqlish-parse-error']);
  41. // Get the last 100 characters of the error message
  42. scope.setExtra('message', error.message?.slice(-100));
  43. scope.setExtra('found', error.found);
  44. Sentry.captureException(error);
  45. });
  46. // If we fail to parse the SQL, return the original string
  47. return sql;
  48. }
  49. const formattedString = FORMATTERS[format](tokens);
  50. sentrySpan?.finish();
  51. return formattedString;
  52. }
  53. }