SQLishFormatter.tsx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. Sentry.captureException(error);
  44. });
  45. // If we fail to parse the SQL, return the original string
  46. return sql;
  47. }
  48. const formattedString = FORMATTERS[format](tokens);
  49. sentrySpan?.finish();
  50. return formattedString;
  51. }
  52. }