tokenUtils.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { LinkedToken } from '../../monarch/LinkedToken';
  2. import { FROM, SCHEMA, SELECT } from '../language';
  3. import { SQLTokenTypes } from './types';
  4. export const getSelectToken = (currentToken: LinkedToken | null) =>
  5. currentToken?.getPreviousOfType(SQLTokenTypes.Keyword, SELECT) ?? null;
  6. export const getSelectStatisticToken = (currentToken: LinkedToken | null) => {
  7. const assumedStatisticToken = getSelectToken(currentToken)?.getNextNonWhiteSpaceToken();
  8. return assumedStatisticToken?.isVariable() || assumedStatisticToken?.isFunction() ? assumedStatisticToken : null;
  9. };
  10. export const getMetricNameToken = (currentToken: LinkedToken | null) => {
  11. // statistic function is followed by `(` and then an argument
  12. const assumedMetricNameToken = getSelectStatisticToken(currentToken)?.next?.next;
  13. return assumedMetricNameToken?.isVariable() || assumedMetricNameToken?.isIdentifier() ? assumedMetricNameToken : null;
  14. };
  15. export const getFromKeywordToken = (currentToken: LinkedToken | null) => {
  16. const selectToken = getSelectToken(currentToken);
  17. return selectToken?.getNextOfType(SQLTokenTypes.Keyword, FROM);
  18. };
  19. export const getNamespaceToken = (currentToken: LinkedToken | null) => {
  20. const fromToken = getFromKeywordToken(currentToken);
  21. const nextNonWhiteSpace = fromToken?.getNextNonWhiteSpaceToken();
  22. if (
  23. nextNonWhiteSpace?.isDoubleQuotedString() ||
  24. (nextNonWhiteSpace?.isVariable() && nextNonWhiteSpace?.value.toUpperCase() !== SCHEMA)
  25. ) {
  26. // schema is not used
  27. return nextNonWhiteSpace;
  28. } else if (nextNonWhiteSpace?.isKeyword() && nextNonWhiteSpace.next?.is(SQLTokenTypes.Parenthesis, '(')) {
  29. // schema is specified
  30. const assumedNamespaceToken = nextNonWhiteSpace.next?.next;
  31. if (assumedNamespaceToken?.isDoubleQuotedString() || assumedNamespaceToken?.isVariable()) {
  32. return assumedNamespaceToken;
  33. }
  34. }
  35. return null;
  36. };