import { B as tags, I as syntaxTree, O as indentNodeProp, h as continuedIndent, n as ExternalTokenizer, r as LRParser, s as LRLanguage, u as LanguageSupport, w as foldNodeProp, z as styleTags } from "./dist-CCADb07R.js";
import { l as ifNotIn, s as completeFromList } from "./dist-JEhxD_cn.js";
var whitespace = 36, LineComment = 1, BlockComment = 2, String$1 = 3, Number = 4, Bool = 5, Null = 6, ParenL = 7, ParenR = 8, BraceL = 9, BraceR = 10, BracketL = 11, BracketR = 12, Semi = 13, Dot = 14, Operator = 15, Punctuation = 16, SpecialVar = 17, Identifier = 18, QuotedIdentifier = 19, Keyword = 20, Type = 21, Bits = 22, Bytes = 23, Builtin = 24;
function isAlpha(h3) {
  return h3 >= 65 && h3 <= 90 || h3 >= 97 && h3 <= 122 || h3 >= 48 && h3 <= 57;
}
function isHexDigit(h3) {
  return h3 >= 48 && h3 <= 57 || h3 >= 97 && h3 <= 102 || h3 >= 65 && h3 <= 70;
}
function readLiteral(h3, W, G) {
  for (let K = false; ; ) {
    if (h3.next < 0) return;
    if (h3.next == W && !K) {
      h3.advance();
      return;
    }
    K = G && !K && h3.next == 92, h3.advance();
  }
}
function readDoubleDollarLiteral(h3, W) {
  scan: for (; ; ) {
    if (h3.next < 0) return;
    if (h3.next == 36) {
      h3.advance();
      for (let G = 0; G < W.length; G++) {
        if (h3.next != W.charCodeAt(G)) continue scan;
        h3.advance();
      }
      if (h3.next == 36) {
        h3.advance();
        return;
      }
    } else h3.advance();
  }
}
function readPLSQLQuotedLiteral(h3, W) {
  let G = "[{<(".indexOf(String.fromCharCode(W)), K = G < 0 ? W : "]}>)".charCodeAt(G);
  for (; ; ) {
    if (h3.next < 0) return;
    if (h3.next == K && h3.peek(1) == 39) {
      h3.advance(2);
      return;
    }
    h3.advance();
  }
}
function readWord(h3, W) {
  for (; !(h3.next != 95 && !isAlpha(h3.next)); ) W != null && (W += String.fromCharCode(h3.next)), h3.advance();
  return W;
}
function readWordOrQuoted(h3) {
  if (h3.next == 39 || h3.next == 34 || h3.next == 96) {
    let W = h3.next;
    h3.advance(), readLiteral(h3, W, false);
  } else readWord(h3);
}
function readBits(h3, W) {
  for (; h3.next == 48 || h3.next == 49; ) h3.advance();
  W && h3.next == W && h3.advance();
}
function readNumber(h3, W) {
  for (; ; ) {
    if (h3.next == 46) {
      if (W) break;
      W = true;
    } else if (h3.next < 48 || h3.next > 57) break;
    h3.advance();
  }
  if (h3.next == 69 || h3.next == 101) for (h3.advance(), (h3.next == 43 || h3.next == 45) && h3.advance(); h3.next >= 48 && h3.next <= 57; ) h3.advance();
}
function eol(h3) {
  for (; !(h3.next < 0 || h3.next == 10); ) h3.advance();
}
function inString(h3, W) {
  for (let G = 0; G < W.length; G++) if (W.charCodeAt(G) == h3) return true;
  return false;
}
var Space = " 	\r\n";
function keywords(h3, W, G) {
  let K = /* @__PURE__ */ Object.create(null);
  K.true = K.false = Bool, K.null = K.unknown = Null;
  for (let W2 of h3.split(" ")) W2 && (K[W2] = Keyword);
  for (let h4 of W.split(" ")) h4 && (K[h4] = Type);
  for (let h4 of (G || "").split(" ")) h4 && (K[h4] = Builtin);
  return K;
}
var SQLTypes = "array binary bit boolean char character clob date decimal double float int integer interval large national nchar nclob numeric object precision real smallint time timestamp varchar varying ", SQLKeywords = "absolute action add after all allocate alter and any are as asc assertion at authorization before begin between both breadth by call cascade cascaded case cast catalog check close collate collation column commit condition connect connection constraint constraints constructor continue corresponding count create cross cube current current_date current_default_transform_group current_transform_group_for_type current_path current_role current_time current_timestamp current_user cursor cycle data day deallocate declare default deferrable deferred delete depth deref desc describe descriptor deterministic diagnostics disconnect distinct do domain drop dynamic each else elseif end end-exec equals escape except exception exec execute exists exit external fetch first for foreign found from free full function general get global go goto grant group grouping handle having hold hour identity if immediate in indicator initially inner inout input insert intersect into is isolation join key language last lateral leading leave left level like limit local localtime localtimestamp locator loop map match method minute modifies module month names natural nesting new next no none not of old on only open option or order ordinality out outer output overlaps pad parameter partial path prepare preserve primary prior privileges procedure public read reads recursive redo ref references referencing relative release repeat resignal restrict result return returns revoke right role rollback rollup routine row rows savepoint schema scroll search second section select session session_user set sets signal similar size some space specific specifictype sql sqlexception sqlstate sqlwarning start state static system_user table temporary then timezone_hour timezone_minute to trailing transaction translation treat trigger under undo union unique unnest until update usage user using value values view when whenever where while with without work write year zone ", defaults = {
  backslashEscapes: false,
  hashComments: false,
  spaceAfterDashes: false,
  slashComments: false,
  doubleQuotedStrings: false,
  doubleDollarQuotedStrings: false,
  unquotedBitLiterals: false,
  treatBitsAsBytes: false,
  charSetCasts: false,
  plsqlQuotingMechanism: false,
  operatorChars: "*+-%<>!=&|~^/",
  specialVar: "?",
  identifierQuotes: '"',
  caseInsensitiveIdentifiers: false,
  words: /* @__PURE__ */ keywords(SQLKeywords, SQLTypes)
};
function dialect(h3, W, G, K) {
  let q = {};
  for (let W2 in defaults) q[W2] = (h3.hasOwnProperty(W2) ? h3 : defaults)[W2];
  return W && (q.words = keywords(W, G || "", K)), q;
}
function tokensFor(h3) {
  return new ExternalTokenizer((W) => {
    let { next: G } = W;
    if (W.advance(), inString(G, Space)) {
      for (; inString(W.next, Space); ) W.advance();
      W.acceptToken(whitespace);
    } else if (G == 36 && h3.doubleDollarQuotedStrings) {
      let h4 = readWord(W, "");
      W.next == 36 && (W.advance(), readDoubleDollarLiteral(W, h4), W.acceptToken(String$1));
    } else if (G == 39 || G == 34 && h3.doubleQuotedStrings) readLiteral(W, G, h3.backslashEscapes), W.acceptToken(String$1);
    else if (G == 35 && h3.hashComments || G == 47 && W.next == 47 && h3.slashComments) eol(W), W.acceptToken(LineComment);
    else if (G == 45 && W.next == 45 && (!h3.spaceAfterDashes || W.peek(1) == 32)) eol(W), W.acceptToken(LineComment);
    else if (G == 47 && W.next == 42) {
      W.advance();
      for (let h4 = 1; ; ) {
        let G2 = W.next;
        if (W.next < 0) break;
        if (W.advance(), G2 == 42 && W.next == 47) {
          if (h4--, W.advance(), !h4) break;
        } else G2 == 47 && W.next == 42 && (h4++, W.advance());
      }
      W.acceptToken(BlockComment);
    } else if ((G == 101 || G == 69) && W.next == 39) W.advance(), readLiteral(W, 39, true), W.acceptToken(String$1);
    else if ((G == 110 || G == 78) && W.next == 39 && h3.charSetCasts) W.advance(), readLiteral(W, 39, h3.backslashEscapes), W.acceptToken(String$1);
    else if (G == 95 && h3.charSetCasts) for (let G2 = 0; ; G2++) {
      if (W.next == 39 && G2 > 1) {
        W.advance(), readLiteral(W, 39, h3.backslashEscapes), W.acceptToken(String$1);
        break;
      }
      if (!isAlpha(W.next)) break;
      W.advance();
    }
    else if (h3.plsqlQuotingMechanism && (G == 113 || G == 81) && W.next == 39 && W.peek(1) > 0 && !inString(W.peek(1), Space)) {
      let h4 = W.peek(1);
      W.advance(2), readPLSQLQuotedLiteral(W, h4), W.acceptToken(String$1);
    } else if (inString(G, h3.identifierQuotes)) readLiteral(W, G == 91 ? 93 : G, false), W.acceptToken(QuotedIdentifier);
    else if (G == 40) W.acceptToken(ParenL);
    else if (G == 41) W.acceptToken(ParenR);
    else if (G == 123) W.acceptToken(BraceL);
    else if (G == 125) W.acceptToken(BraceR);
    else if (G == 91) W.acceptToken(BracketL);
    else if (G == 93) W.acceptToken(BracketR);
    else if (G == 59) W.acceptToken(Semi);
    else if (h3.unquotedBitLiterals && G == 48 && W.next == 98) W.advance(), readBits(W), W.acceptToken(Bits);
    else if ((G == 98 || G == 66) && (W.next == 39 || W.next == 34)) {
      let G2 = W.next;
      W.advance(), h3.treatBitsAsBytes ? (readLiteral(W, G2, h3.backslashEscapes), W.acceptToken(Bytes)) : (readBits(W, G2), W.acceptToken(Bits));
    } else if (G == 48 && (W.next == 120 || W.next == 88) || (G == 120 || G == 88) && W.next == 39) {
      let h4 = W.next == 39;
      for (W.advance(); isHexDigit(W.next); ) W.advance();
      h4 && W.next == 39 && W.advance(), W.acceptToken(Number);
    } else if (G == 46 && W.next >= 48 && W.next <= 57) readNumber(W, true), W.acceptToken(Number);
    else if (G == 46) W.acceptToken(Dot);
    else if (G >= 48 && G <= 57) readNumber(W, false), W.acceptToken(Number);
    else if (inString(G, h3.operatorChars)) {
      for (; inString(W.next, h3.operatorChars); ) W.advance();
      W.acceptToken(Operator);
    } else if (inString(G, h3.specialVar)) W.next == G && W.advance(), readWordOrQuoted(W), W.acceptToken(SpecialVar);
    else if (G == 58 || G == 44) W.acceptToken(Punctuation);
    else if (isAlpha(G)) {
      let K = readWord(W, String.fromCharCode(G));
      W.acceptToken(W.next == 46 || W.peek(-K.length - 1) == 46 ? Identifier : h3.words[K.toLowerCase()] ?? Identifier);
    }
  });
}
var tokens = /* @__PURE__ */ tokensFor(defaults), parser$1 = /* @__PURE__ */ LRParser.deserialize({
  version: 14,
  states: "%vQ]QQOOO#wQRO'#DSO$OQQO'#CwO%eQQO'#CxO%lQQO'#CyO%sQQO'#CzOOQQ'#DS'#DSOOQQ'#C}'#C}O'UQRO'#C{OOQQ'#Cv'#CvOOQQ'#C|'#C|Q]QQOOQOQQOOO'`QQO'#DOO(xQRO,59cO)PQQO,59cO)UQQO'#DSOOQQ,59d,59dO)cQQO,59dOOQQ,59e,59eO)jQQO,59eOOQQ,59f,59fO)qQQO,59fOOQQ-E6{-E6{OOQQ,59b,59bOOQQ-E6z-E6zOOQQ,59j,59jOOQQ-E6|-E6|O+VQRO1G.}O+^QQO,59cOOQQ1G/O1G/OOOQQ1G/P1G/POOQQ1G/Q1G/QP+kQQO'#C}O+rQQO1G.}O)PQQO,59cO,PQQO'#Cw",
  stateData: ",[~OtOSPOSQOS~ORUOSUOTUOUUOVROXSOZTO]XO^QO_UO`UOaPObPOcPOdUOeUOfUOgUOhUO~O^]ORvXSvXTvXUvXVvXXvXZvX]vX_vX`vXavXbvXcvXdvXevXfvXgvXhvX~OsvX~P!jOa_Ob_Oc_O~ORUOSUOTUOUUOVROXSOZTO^tO_UO`UOa`Ob`Oc`OdUOeUOfUOgUOhUO~OWaO~P$ZOYcO~P$ZO[eO~P$ZORUOSUOTUOUUOVROXSOZTO^QO_UO`UOaPObPOcPOdUOeUOfUOgUOhUO~O]hOsoX~P%zOajObjOcjO~O^]ORkaSkaTkaUkaVkaXkaZka]ka_ka`kaakabkackadkaekafkagkahka~Oska~P'kO^]O~OWvXYvX[vX~P!jOWnO~P$ZOYoO~P$ZO[pO~P$ZO^]ORkiSkiTkiUkiVkiXkiZki]ki_ki`kiakibkickidkiekifkigkihki~Oski~P)xOWkaYka[ka~P'kO]hO~P$ZOWkiYki[ki~P)xOasObsOcsO~O",
  goto: "#hwPPPPPPPPPPPPPPPPPPPPPPPPPPx||||!Y!^!d!xPPP#[TYOZeUORSTWZbdfqT[OZQZORiZSWOZQbRQdSQfTZgWbdfqQ^PWk^lmrQl_Qm`RrseVORSTWZbdfq",
  nodeNames: "\u26A0 LineComment BlockComment String Number Bool Null ( ) { } [ ] ; . Operator Punctuation SpecialVar Identifier QuotedIdentifier Keyword Type Bits Bytes Builtin Script Statement CompositeIdentifier Parens Braces Brackets Statement",
  maxTerm: 38,
  nodeProps: [[
    "isolate",
    -4,
    1,
    2,
    3,
    19,
    ""
  ]],
  skippedNodes: [
    0,
    1,
    2
  ],
  repeatNodeCount: 3,
  tokenData: "RORO",
  tokenizers: [0, tokens],
  topRules: { Script: [0, 25] },
  tokenPrec: 0
});
function tokenBefore(h3) {
  let W = h3.cursor().moveTo(h3.from, -1);
  for (; /Comment/.test(W.name); ) W.moveTo(W.from, -1);
  return W.node;
}
function idName(h3, W) {
  let G = h3.sliceString(W.from, W.to), K = /^([`'"\[])(.*)([`'"\]])$/.exec(G);
  return K ? K[2] : G;
}
function plainID(h3) {
  return h3 && (h3.name == "Identifier" || h3.name == "QuotedIdentifier");
}
function pathFor(h3, W) {
  if (W.name == "CompositeIdentifier") {
    let G = [];
    for (let K = W.firstChild; K; K = K.nextSibling) plainID(K) && G.push(idName(h3, K));
    return G;
  }
  return [idName(h3, W)];
}
function parentsFor(h3, W) {
  for (let G = []; ; ) {
    if (!W || W.name != ".") return G;
    let K = tokenBefore(W);
    if (!plainID(K)) return G;
    G.unshift(idName(h3, K)), W = tokenBefore(K);
  }
}
function sourceContext(h3, G) {
  let K = syntaxTree(h3).resolveInner(G, -1), q = getAliases(h3.doc, K);
  return K.name == "Identifier" || K.name == "QuotedIdentifier" || K.name == "Keyword" ? {
    from: K.from,
    quoted: K.name == "QuotedIdentifier" ? h3.doc.sliceString(K.from, K.from + 1) : null,
    parents: parentsFor(h3.doc, tokenBefore(K)),
    aliases: q
  } : K.name == "." ? {
    from: G,
    quoted: null,
    parents: parentsFor(h3.doc, K),
    aliases: q
  } : {
    from: G,
    quoted: null,
    parents: [],
    empty: true,
    aliases: q
  };
}
var EndFrom = /* @__PURE__ */ new Set(/* @__PURE__ */ "where group having order union intersect except all distinct limit offset fetch for".split(" "));
function getAliases(h3, W) {
  let G;
  for (let h4 = W; !G; h4 = h4.parent) {
    if (!h4) return null;
    h4.name == "Statement" && (G = h4);
  }
  let K = null;
  for (let W2 = G.firstChild, q = false, J = null; W2; W2 = W2.nextSibling) {
    let G2 = W2.name == "Keyword" ? h3.sliceString(W2.from, W2.to).toLowerCase() : null, Y = null;
    if (!q) q = G2 == "from";
    else if (G2 == "as" && J && plainID(W2.nextSibling)) Y = idName(h3, W2.nextSibling);
    else if (G2 && EndFrom.has(G2)) break;
    else J && plainID(W2) && (Y = idName(h3, W2));
    Y && (K || (K = /* @__PURE__ */ Object.create(null)), K[Y] = pathFor(h3, J)), J = /Identifier$/.test(W2.name) ? W2 : null;
  }
  return K;
}
function maybeQuoteCompletions(h3, W, G) {
  return G.map((G2) => ({
    ...G2,
    label: G2.label[0] == h3 ? G2.label : h3 + G2.label + W,
    apply: void 0
  }));
}
var Span = /^\w*$/, QuotedSpan = /^[`'"\[]?\w*[`'"\]]?$/;
function isSelfTag(h3) {
  return h3.self && typeof h3.self.label == "string";
}
var CompletionLevel = class h {
  constructor(h3, W) {
    this.idQuote = h3, this.idCaseInsensitive = W, this.list = [], this.children = void 0;
  }
  child(W) {
    let G = this.children || (this.children = /* @__PURE__ */ Object.create(null));
    return G[W] || (W && !this.list.some((h3) => h3.label == W) && this.list.push(nameCompletion(W, "type", this.idQuote, this.idCaseInsensitive)), G[W] = new h(this.idQuote, this.idCaseInsensitive));
  }
  maybeChild(h3) {
    return this.children ? this.children[h3] : null;
  }
  addCompletion(h3) {
    let W = this.list.findIndex((W2) => W2.label == h3.label);
    W > -1 ? this.list[W] = h3 : this.list.push(h3);
  }
  addCompletions(h3) {
    for (let W of h3) this.addCompletion(typeof W == "string" ? nameCompletion(W, "property", this.idQuote, this.idCaseInsensitive) : W);
  }
  addNamespace(h3) {
    Array.isArray(h3) ? this.addCompletions(h3) : isSelfTag(h3) ? this.addNamespace(h3.children) : this.addNamespaceObject(h3);
  }
  addNamespaceObject(h3) {
    for (let W of Object.keys(h3)) {
      let G = h3[W], K = null, q = W.replace(/\\?\./g, (h4) => h4 == "." ? "\0" : h4).split("\0"), J = this;
      isSelfTag(G) && (K = G.self, G = G.children);
      for (let h4 = 0; h4 < q.length; h4++) K && h4 == q.length - 1 && J.addCompletion(K), J = J.child(q[h4].replace(/\\\./g, "."));
      J.addNamespace(G);
    }
  }
};
function nameCompletion(h3, W, G, K) {
  return RegExp("^[a-z_][a-z_\\d]*$", K ? "i" : "").test(h3) ? {
    label: h3,
    type: W
  } : {
    label: h3,
    type: W,
    apply: G + h3 + getClosingQuote(G)
  };
}
function getClosingQuote(h3) {
  return h3 === "[" ? "]" : h3;
}
function completeFromSchema(h3, W, G, K, q, J) {
  var _a;
  let Y = new CompletionLevel(((_a = J == null ? void 0 : J.spec.identifierQuotes) == null ? void 0 : _a[0]) || '"', !!(J == null ? void 0 : J.spec.caseInsensitiveIdentifiers)), X = q ? Y.child(q) : null;
  return Y.addNamespace(h3), W && (X || Y).addCompletions(W), G && Y.addCompletions(G), X && Y.addCompletions(X.list), K && Y.addCompletions((X || Y).child(K).list), (h4) => {
    let { parents: W2, from: G2, quoted: q2, empty: J2, aliases: Z } = sourceContext(h4.state, h4.pos);
    if (J2 && !h4.explicit) return null;
    Z && W2.length == 1 && (W2 = Z[W2[0]] || W2);
    let Q = Y;
    for (let h5 of W2) {
      for (; !Q.children || !Q.children[h5]; ) if (Q == Y && X) Q = X;
      else if (Q == X && K) Q = Q.child(K);
      else return null;
      let W3 = Q.maybeChild(h5);
      if (!W3) return null;
      Q = W3;
    }
    let $ = Q.list;
    if (Q == Y && Z && ($ = $.concat(Object.keys(Z).map((h5) => ({
      label: h5,
      type: "constant"
    })))), q2) {
      let W3 = q2[0], K2 = getClosingQuote(W3);
      return {
        from: G2,
        to: h4.state.sliceDoc(h4.pos, h4.pos + 1) == K2 ? h4.pos + 1 : void 0,
        options: maybeQuoteCompletions(W3, K2, $),
        validFor: QuotedSpan
      };
    } else return {
      from: G2,
      options: $,
      validFor: Span
    };
  };
}
function completionType(h3) {
  return h3 == Type ? "type" : h3 == Keyword ? "keyword" : "variable";
}
function completeKeywords(h3, W, G) {
  return ifNotIn([
    "QuotedIdentifier",
    "String",
    "LineComment",
    "BlockComment",
    "."
  ], completeFromList(Object.keys(h3).map((K) => G(W ? K.toUpperCase() : K, completionType(h3[K])))));
}
var parser = /* @__PURE__ */ parser$1.configure({ props: [
  /* @__PURE__ */ indentNodeProp.add({ Statement: /* @__PURE__ */ continuedIndent() }),
  /* @__PURE__ */ foldNodeProp.add({
    Statement(h3, W) {
      return {
        from: Math.min(h3.from + 100, W.doc.lineAt(h3.from).to),
        to: h3.to
      };
    },
    BlockComment(h3) {
      return {
        from: h3.from + 2,
        to: h3.to - 2
      };
    }
  }),
  /* @__PURE__ */ styleTags({
    Keyword: tags.keyword,
    Type: tags.typeName,
    Builtin: /* @__PURE__ */ tags.standard(tags.name),
    Bits: tags.number,
    Bytes: tags.string,
    Bool: tags.bool,
    Null: tags.null,
    Number: tags.number,
    String: tags.string,
    Identifier: tags.name,
    QuotedIdentifier: /* @__PURE__ */ tags.special(tags.string),
    SpecialVar: /* @__PURE__ */ tags.special(tags.name),
    LineComment: tags.lineComment,
    BlockComment: tags.blockComment,
    Operator: tags.operator,
    "Semi Punctuation": tags.punctuation,
    "( )": tags.paren,
    "{ }": tags.brace,
    "[ ]": tags.squareBracket
  })
] }), SQLDialect = class h2 {
  constructor(h3, W, G) {
    this.dialect = h3, this.language = W, this.spec = G;
  }
  get extension() {
    return this.language.extension;
  }
  configureLanguage(W, G) {
    return new h2(this.dialect, this.language.configure(W, G), this.spec);
  }
  static define(W) {
    let G = dialect(W, W.keywords, W.types, W.builtin);
    return new h2(G, LRLanguage.define({
      name: "sql",
      parser: parser.configure({ tokenizers: [{
        from: tokens,
        to: tokensFor(G)
      }] }),
      languageData: {
        commentTokens: {
          line: "--",
          block: {
            open: "/*",
            close: "*/"
          }
        },
        closeBrackets: { brackets: [
          "(",
          "[",
          "{",
          "'",
          '"',
          "`"
        ] }
      }
    }), W);
  }
};
function defaultKeyword(h3, W) {
  return {
    label: h3,
    type: W,
    boost: -1
  };
}
function keywordCompletionSource(h3, W = false, G) {
  return completeKeywords(h3.dialect.words, W, G || defaultKeyword);
}
function schemaCompletionSource(h3) {
  return h3.schema ? completeFromSchema(h3.schema, h3.tables, h3.schemas, h3.defaultTable, h3.defaultSchema, h3.dialect || StandardSQL) : () => null;
}
function schemaCompletion(h3) {
  return h3.schema ? (h3.dialect || StandardSQL).language.data.of({ autocomplete: schemaCompletionSource(h3) }) : [];
}
function sql(h3 = {}) {
  let W = h3.dialect || StandardSQL;
  return new LanguageSupport(W.language, [schemaCompletion(h3), W.language.data.of({ autocomplete: keywordCompletionSource(W, h3.upperCaseKeywords, h3.keywordCompletion) })]);
}
var StandardSQL = /* @__PURE__ */ SQLDialect.define({}), PostgreSQL = /* @__PURE__ */ SQLDialect.define({
  charSetCasts: true,
  doubleDollarQuotedStrings: true,
  operatorChars: "+-*/<>=~!@#%^&|`?",
  specialVar: "",
  keywords: SQLKeywords + "abort abs absent access according ada admin aggregate alias also always analyse analyze array_agg array_max_cardinality asensitive assert assignment asymmetric atomic attach attribute attributes avg backward base64 begin_frame begin_partition bernoulli bit_length blocked bom cache called cardinality catalog_name ceil ceiling chain char_length character_length character_set_catalog character_set_name character_set_schema characteristics characters checkpoint class class_origin cluster coalesce cobol collation_catalog collation_name collation_schema collect column_name columns command_function command_function_code comment comments committed concurrently condition_number configuration conflict connection_name constant constraint_catalog constraint_name constraint_schema contains content control conversion convert copy corr cost covar_pop covar_samp csv cume_dist current_catalog current_row current_schema cursor_name database datalink datatype datetime_interval_code datetime_interval_precision db debug defaults defined definer degree delimiter delimiters dense_rank depends derived detach detail dictionary disable discard dispatch dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue document dump dynamic_function dynamic_function_code element elsif empty enable encoding encrypted end_frame end_partition endexec enforced enum errcode error event every exclude excluding exclusive exp explain expression extension extract family file filter final first_value flag floor following force foreach fortran forward frame_row freeze fs functions fusion generated granted greatest groups handler header hex hierarchy hint id ignore ilike immediately immutable implementation implicit import include including increment indent index indexes info inherit inherits inline insensitive instance instantiable instead integrity intersection invoker isnull key_member key_type label lag last_value lead leakproof least length library like_regex link listen ln load location lock locked log logged lower mapping matched materialized max max_cardinality maxvalue member merge message message_length message_octet_length message_text min minvalue mod mode more move multiset mumps name namespace nfc nfd nfkc nfkd nil normalize normalized nothing notice notify notnull nowait nth_value ntile nullable nullif nulls number occurrences_regex octet_length octets off offset oids operator options ordering others over overlay overriding owned owner parallel parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partition pascal passing passthrough password percent percent_rank percentile_cont percentile_disc perform period permission pg_context pg_datatype_name pg_exception_context pg_exception_detail pg_exception_hint placing plans pli policy portion position position_regex power precedes preceding prepared print_strict_params procedural procedures program publication query quote raise range rank reassign recheck recovery refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex rename repeatable replace replica requiring reset respect restart restore result_oid returned_cardinality returned_length returned_octet_length returned_sqlstate returning reverse routine_catalog routine_name routine_schema routines row_count row_number rowtype rule scale schema_name schemas scope scope_catalog scope_name scope_schema security selective self sensitive sequence sequences serializable server server_name setof share show simple skip slice snapshot source specific_name sqlcode sqlerror sqrt stable stacked standalone statement statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset subscription substring substring_regex succeeds sum symmetric sysid system system_time table_name tables tablesample tablespace temp template ties token top_level_count transaction_active transactions_committed transactions_rolled_back transform transforms translate translate_regex trigger_catalog trigger_name trigger_schema trim trim_array truncate trusted type types uescape unbounded uncommitted unencrypted unlink unlisten unlogged unnamed untyped upper uri use_column use_variable user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema vacuum valid validate validator value_of var_pop var_samp varbinary variable_conflict variadic verbose version versioning views volatile warning whitespace width_bucket window within wrapper xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate yes",
  types: SQLTypes + "bigint int8 bigserial serial8 varbit bool box bytea cidr circle precision float8 inet int4 json jsonb line lseg macaddr macaddr8 money numeric pg_lsn point polygon float4 int2 smallserial serial2 serial serial4 text timetz timestamptz tsquery tsvector txid_snapshot uuid xml"
}), MySQLTypes = SQLTypes + "bool blob long longblob longtext medium mediumblob mediumint mediumtext tinyblob tinyint tinytext text bigint int1 int2 int3 int4 int8 float4 float8 varbinary varcharacter precision datetime unsigned signed", MySQLBuiltin = "charset clear edit ego help nopager notee nowarning pager print prompt quit rehash source status system tee", MySQL = /* @__PURE__ */ SQLDialect.define({
  operatorChars: "*+-%<>!=&|^",
  charSetCasts: true,
  doubleQuotedStrings: true,
  unquotedBitLiterals: true,
  hashComments: true,
  spaceAfterDashes: true,
  specialVar: "@?",
  identifierQuotes: "`",
  keywords: SQLKeywords + "group_concat accessible algorithm analyze asensitive authors auto_increment autocommit avg avg_row_length binlog btree cache catalog_name chain change changed checkpoint checksum class_origin client_statistics coalesce code collations columns comment committed completion concurrent consistent contains contributors convert database databases day_hour day_microsecond day_minute day_second delay_key_write delayed delimiter des_key_file dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile enable enclosed ends engine engines enum errors escaped even event events every explain extended fast field fields flush force found_rows fulltext grants handler hash high_priority hosts hour_microsecond hour_minute hour_second ignore ignore_server_ids import index index_statistics infile innodb insensitive insert_method install invoker iterate keys kill linear lines list load lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modify mutex mysql_errno no_write_to_binlog offline offset one online optimize optionally outfile pack_keys parser partition partitions password phase plugin plugins prev processlist profile profiles purge query quick range read_write rebuild recover regexp relaylog remove rename reorganize repair repeatable replace require resume rlike row_format rtree schedule schema_name schemas second_microsecond security sensitive separator serializable server share show slave slow snapshot soname spatial sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result ssl starting starts std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace terminated triggers truncate uncommitted uninstall unlock upgrade use use_frm user_resources user_statistics utc_date utc_time utc_timestamp variables views warnings xa xor year_month zerofill",
  types: MySQLTypes,
  builtin: MySQLBuiltin
}), MariaSQL = /* @__PURE__ */ SQLDialect.define({
  operatorChars: "*+-%<>!=&|^",
  charSetCasts: true,
  doubleQuotedStrings: true,
  unquotedBitLiterals: true,
  hashComments: true,
  spaceAfterDashes: true,
  specialVar: "@?",
  identifierQuotes: "`",
  keywords: SQLKeywords + "always generated groupby_concat hard persistent shutdown soft virtual accessible algorithm analyze asensitive authors auto_increment autocommit avg avg_row_length binlog btree cache catalog_name chain change changed checkpoint checksum class_origin client_statistics coalesce code collations columns comment committed completion concurrent consistent contains contributors convert database databases day_hour day_microsecond day_minute day_second delay_key_write delayed delimiter des_key_file dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile enable enclosed ends engine engines enum errors escaped even event events every explain extended fast field fields flush force found_rows fulltext grants handler hash high_priority hosts hour_microsecond hour_minute hour_second ignore ignore_server_ids import index index_statistics infile innodb insensitive insert_method install invoker iterate keys kill linear lines list load lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modify mutex mysql_errno no_write_to_binlog offline offset one online optimize optionally outfile pack_keys parser partition partitions password phase plugin plugins prev processlist profile profiles purge query quick range read_write rebuild recover regexp relaylog remove rename reorganize repair repeatable replace require resume rlike row_format rtree schedule schema_name schemas second_microsecond security sensitive separator serializable server share show slave slow snapshot soname spatial sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result ssl starting starts std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace terminated triggers truncate uncommitted uninstall unlock upgrade use use_frm user_resources user_statistics utc_date utc_time utc_timestamp variables views warnings xa xor year_month zerofill",
  types: MySQLTypes,
  builtin: MySQLBuiltin
}), MSSQL = /* @__PURE__ */ SQLDialect.define({
  keywords: SQLKeywords + "add external procedure all fetch public alter file raiserror and fillfactor read any for readtext as foreign reconfigure asc freetext references authorization freetexttable replication backup from restore begin full restrict between function return break goto revert browse grant revoke bulk group right by having rollback cascade holdlock rowcount case identity rowguidcol check identity_insert rule checkpoint identitycol save close if schema clustered in securityaudit coalesce index select collate inner semantickeyphrasetable column insert semanticsimilaritydetailstable commit intersect semanticsimilaritytable compute into session_user constraint is set contains join setuser containstable key shutdown continue kill some convert left statistics create like system_user cross lineno table current load tablesample current_date merge textsize current_time national then current_timestamp nocheck to current_user nonclustered top cursor not tran database null transaction dbcc nullif trigger deallocate of truncate declare off try_convert default offsets tsequal delete on union deny open unique desc opendatasource unpivot disk openquery update distinct openrowset updatetext distributed openxml use double option user drop or values dump order varying else outer view end over waitfor errlvl percent when escape pivot where except plan while exec precision with execute primary within group exists print writetext exit proc noexpand index forceseek forcescan holdlock nolock nowait paglock readcommitted readcommittedlock readpast readuncommitted repeatableread rowlock serializable snapshot spatial_window_max_cells tablock tablockx updlock xlock keepidentity keepdefaults ignore_constraints ignore_triggers",
  types: SQLTypes + "smalldatetime datetimeoffset datetime2 datetime bigint smallint smallmoney tinyint money real text nvarchar ntext varbinary image hierarchyid uniqueidentifier sql_variant xml",
  builtin: "approx_count_distinct approx_percentile_cont approx_percentile_disc avg checksum_agg count count_big grouping grouping_id max min product stdev stdevp sum var varp ai_generate_embeddings ai_generate_chunks cume_dist first_value lag last_value lead percentile_cont percentile_disc percent_rank left_shift right_shift bit_count get_bit set_bit collationproperty tertiary_weights @@datefirst @@dbts @@langid @@language @@lock_timeout @@max_connections @@max_precision @@nestlevel @@options @@remserver @@servername @@servicename @@spid @@textsize @@version cast convert parse try_cast try_convert try_parse asymkey_id asymkeyproperty certproperty cert_id crypt_gen_random decryptbyasymkey decryptbycert decryptbykey decryptbykeyautoasymkey decryptbykeyautocert decryptbypassphrase encryptbyasymkey encryptbycert encryptbykey encryptbypassphrase hashbytes is_objectsigned key_guid key_id key_name signbyasymkey signbycert symkeyproperty verifysignedbycert verifysignedbyasymkey @@cursor_rows @@fetch_status cursor_status datalength ident_current ident_incr ident_seed identity sql_variant_property @@datefirst current_timestamp current_timezone current_timezone_id date_bucket dateadd datediff datediff_big datefromparts datename datepart datetime2fromparts datetimefromparts datetimeoffsetfromparts datetrunc day eomonth getdate getutcdate isdate month smalldatetimefromparts switchoffset sysdatetime sysdatetimeoffset sysutcdatetime timefromparts todatetimeoffset year edit_distance edit_distance_similarity jaro_winkler_distance jaro_winkler_similarity edge_id_from_parts graph_id_from_edge_id graph_id_from_node_id node_id_from_parts object_id_from_edge_id object_id_from_node_id json isjson json_array json_contains json_modify json_object json_path_exists json_query json_value regexp_like regexp_replace regexp_substr regexp_instr regexp_count regexp_matches regexp_split_to_table abs acos asin atan atn2 ceiling cos cot degrees exp floor log log10 pi power radians rand round sign sin sqrt square tan choose greatest iif least @@procid app_name applock_mode applock_test assemblyproperty col_length col_name columnproperty databasepropertyex db_id db_name file_id file_idex file_name filegroup_id filegroup_name filegroupproperty fileproperty filepropertyex fulltextcatalogproperty fulltextserviceproperty index_col indexkey_property indexproperty next value for object_definition object_id object_name object_schema_name objectproperty objectpropertyex original_db_name parsename schema_id schema_name scope_identity serverproperty stats_date type_id type_name typeproperty dense_rank ntile rank row_number publishingservername certenclosed certprivatekey current_user database_principal_id has_dbaccess has_perms_by_name is_member is_rolemember is_srvrolemember loginproperty original_login permissions pwdencrypt pwdcompare session_user sessionproperty suser_id suser_name suser_sid suser_sname system_user user user_id user_name ascii char charindex concat concat_ws difference format left len lower ltrim nchar patindex quotename replace replicate reverse right rtrim soundex space str string_agg string_escape stuff substring translate trim unicode upper $partition @@error @@identity @@pack_received @@rowcount @@trancount binary_checksum checksum compress connectionproperty context_info current_request_id current_transaction_id decompress error_line error_message error_number error_procedure error_severity error_state formatmessage get_filestream_transaction_context getansinull host_id host_name isnull isnumeric min_active_rowversion newid newsequentialid rowcount_big session_context xact_state @@connections @@cpu_busy @@idle @@io_busy @@pack_sent @@packet_errors @@timeticks @@total_errors @@total_read @@total_write textptr textvalid columns_updated eventdata trigger_nestlevel vector_distance vectorproperty vector_search generate_series opendatasource openjson openquery openrowset openxml predict string_split coalesce nullif apply catch filter force include keep keepfixed modify optimize parameterization parameters partition recompile sequence set",
  operatorChars: "*+-%<>!=^&|/",
  specialVar: "@",
  identifierQuotes: '"['
}), SQLite = /* @__PURE__ */ SQLDialect.define({
  keywords: SQLKeywords + "abort analyze attach autoincrement conflict database detach exclusive fail glob ignore index indexed instead isnull notnull offset plan pragma query raise regexp reindex rename replace temp vacuum virtual",
  types: SQLTypes + "bool blob long longblob longtext medium mediumblob mediumint mediumtext tinyblob tinyint tinytext text bigint int2 int8 unsigned signed real",
  builtin: "auth backup bail changes clone databases dbinfo dump echo eqp explain fullschema headers help import imposter indexes iotrace lint load log mode nullvalue once print prompt quit restore save scanstats separator shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width",
  operatorChars: "*+-%<>!=&|/~",
  identifierQuotes: '`"',
  specialVar: "@:?$"
}), Cassandra = /* @__PURE__ */ SQLDialect.define({
  keywords: "add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime infinity NaN",
  types: SQLTypes + "ascii bigint blob counter frozen inet list map static text timeuuid tuple uuid varint",
  slashComments: true
}), PLSQL = /* @__PURE__ */ SQLDialect.define({
  keywords: SQLKeywords + "abort accept access add all alter and any arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body by case cast char_base check close cluster clusters colauth column comment commit compress connected constant constraint crash create current currval cursor data_base database dba deallocate debugoff debugon declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry exception exception_init exchange exclusive exists external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base of off offline on online only option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw rebuild record ref references refresh rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work",
  builtin: "appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define echo editfile embedded feedback flagger flush heading headsep instance linesize lno loboffset logsource longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar repfooter repheader serveroutput shiftinout show showmode spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout timing trimout trimspool ttitle underline verify version wrap",
  types: SQLTypes + "ascii bfile bfilename bigserial bit blob dec long number nvarchar nvarchar2 serial smallint string text uid varchar2 xml",
  operatorChars: "*/+-%<>!=~",
  doubleQuotedStrings: true,
  charSetCasts: true,
  plsqlQuotingMechanism: true
});
export {
  PLSQL as a,
  SQLite as c,
  schemaCompletionSource as d,
  sql as f,
  MySQL as i,
  StandardSQL as l,
  MSSQL as n,
  PostgreSQL as o,
  MariaSQL as r,
  SQLDialect as s,
  Cassandra as t,
  keywordCompletionSource as u
};
