rawsql-ts 0.10.1-beta → 0.10.2-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/esm/index.min.js +16 -0
  2. package/dist/esm/index.min.js.map +7 -0
  3. package/dist/esm/models/ValueComponent.js +7 -0
  4. package/dist/esm/models/ValueComponent.js.map +1 -1
  5. package/dist/esm/parsers/CommandExpressionParser.js +1 -16
  6. package/dist/esm/parsers/CommandExpressionParser.js.map +1 -1
  7. package/dist/esm/parsers/FunctionExpressionParser.js +33 -2
  8. package/dist/esm/parsers/FunctionExpressionParser.js.map +1 -1
  9. package/dist/esm/parsers/SqlPrintTokenParser.js +11 -1
  10. package/dist/esm/parsers/SqlPrintTokenParser.js.map +1 -1
  11. package/dist/esm/tokenReaders/CommandTokenReader.js +0 -1
  12. package/dist/esm/tokenReaders/CommandTokenReader.js.map +1 -1
  13. package/dist/esm/tokenReaders/FunctionTokenReader.js +2 -0
  14. package/dist/esm/tokenReaders/FunctionTokenReader.js.map +1 -1
  15. package/dist/esm/transformers/CTECollector.js +13 -2
  16. package/dist/esm/transformers/CTECollector.js.map +1 -1
  17. package/dist/esm/transformers/CTEDisabler.js +6 -1
  18. package/dist/esm/transformers/CTEDisabler.js.map +1 -1
  19. package/dist/esm/transformers/SelectableColumnCollector.js +5 -1
  20. package/dist/esm/transformers/SelectableColumnCollector.js.map +1 -1
  21. package/dist/esm/transformers/TableSourceCollector.js +30 -2
  22. package/dist/esm/transformers/TableSourceCollector.js.map +1 -1
  23. package/dist/esm/types/models/ValueComponent.d.ts +6 -1
  24. package/dist/esm/types/parsers/CommandExpressionParser.d.ts +0 -1
  25. package/dist/esm/types/parsers/FunctionExpressionParser.d.ts +7 -0
  26. package/dist/esm/types/parsers/SqlPrintTokenParser.d.ts +1 -0
  27. package/dist/esm/types/transformers/CTECollector.d.ts +2 -0
  28. package/dist/esm/types/transformers/CTEDisabler.d.ts +2 -1
  29. package/dist/esm/types/transformers/SelectableColumnCollector.d.ts +1 -0
  30. package/dist/esm/types/transformers/TableSourceCollector.d.ts +8 -0
  31. package/dist/index.min.js +16 -0
  32. package/dist/index.min.js.map +7 -0
  33. package/dist/models/ValueComponent.d.ts +6 -1
  34. package/dist/models/ValueComponent.js +9 -1
  35. package/dist/models/ValueComponent.js.map +1 -1
  36. package/dist/parsers/CommandExpressionParser.d.ts +0 -1
  37. package/dist/parsers/CommandExpressionParser.js +0 -15
  38. package/dist/parsers/CommandExpressionParser.js.map +1 -1
  39. package/dist/parsers/FunctionExpressionParser.d.ts +7 -0
  40. package/dist/parsers/FunctionExpressionParser.js +32 -1
  41. package/dist/parsers/FunctionExpressionParser.js.map +1 -1
  42. package/dist/parsers/SqlPrintTokenParser.d.ts +1 -0
  43. package/dist/parsers/SqlPrintTokenParser.js +10 -0
  44. package/dist/parsers/SqlPrintTokenParser.js.map +1 -1
  45. package/dist/tokenReaders/CommandTokenReader.js +0 -1
  46. package/dist/tokenReaders/CommandTokenReader.js.map +1 -1
  47. package/dist/tokenReaders/FunctionTokenReader.js +2 -0
  48. package/dist/tokenReaders/FunctionTokenReader.js.map +1 -1
  49. package/dist/transformers/CTECollector.d.ts +2 -0
  50. package/dist/transformers/CTECollector.js +11 -0
  51. package/dist/transformers/CTECollector.js.map +1 -1
  52. package/dist/transformers/CTEDisabler.d.ts +2 -1
  53. package/dist/transformers/CTEDisabler.js +5 -0
  54. package/dist/transformers/CTEDisabler.js.map +1 -1
  55. package/dist/transformers/SelectableColumnCollector.d.ts +1 -0
  56. package/dist/transformers/SelectableColumnCollector.js +4 -0
  57. package/dist/transformers/SelectableColumnCollector.js.map +1 -1
  58. package/dist/transformers/TableSourceCollector.d.ts +8 -0
  59. package/dist/transformers/TableSourceCollector.js +28 -0
  60. package/dist/transformers/TableSourceCollector.js.map +1 -1
  61. package/package.json +3 -1
@@ -0,0 +1,16 @@
1
+ var h=class{constructor(){this.comments=null}getKind(){return this.constructor.kind}accept(e){return e.visit(this)}toSqlString(e){return this.accept(e)}};var Le=class extends h{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var fe=class extends h{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},Q=class extends h{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},f=class extends h{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof C?this.qualifiedName.name:new C(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(e,t){super();let n=typeof t=="string"?new C(t):t;this.qualifiedName=new Ce(pn(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},L=class extends h{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,i){super(),this.qualifiedName=new Ce(e,t),this.argument=n,this.over=i}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},un=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(un||{}),cn=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(cn||{}),qe=class extends h{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},De=class extends h{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},Ee=class extends h{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},we=class extends h{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},D=class extends h{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new g(e),this.expression=t}},b=class extends h{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new g(t),this.right=n}},V=class extends h{static{this.kind=Symbol("LiteralExpression")}constructor(e){super(),this.value=e}},A=class extends h{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new g(e),this.value=t,this.index=null}},ne=class extends h{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},ie=class extends h{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},g=class extends h{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},C=class extends h{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},H=class extends h{static{this.kind=Symbol("ParenExpression")}constructor(e){super(),this.expression=e}},se=class extends h{static{this.kind=Symbol("CastExpression")}constructor(e,t){super(),this.input=e,this.castType=t}},_=class extends h{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},re=class extends h{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},oe=class extends h{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},ae=class extends h{static{this.kind=Symbol("BetweenExpression")}constructor(e,t,n,i){super(),this.expression=e,this.lower=t,this.upper=n,this.negated=i}},Je=class extends h{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new g(e),this.value=new V(t)}},Se=class extends h{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new Ce(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof g?this.qualifiedName.name.value:this.qualifiedName.name.name;return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(t=>t.name).join(".")+"."+e:e}},le=class extends h{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}};function pn(r){if(r==null)return null;if(typeof r=="string")return r.trim()===""?null:[new C(r)];if(Array.isArray(r)){if(r.length===0)return null;if(typeof r[0]=="string"){let e=r.filter(t=>t.trim()!=="");return e.length===0?null:e.map(t=>new C(t))}else{let e=r.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var Ce=class extends h{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=pn(e),typeof t=="string"?this.name=new g(t):this.name=t}toString(){let e=this.name instanceof g?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(t=>t.name).join(".")+"."+e:e}};var F=class extends h{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new C(t):null}},O=class extends h{static{this.kind=Symbol("SelectClause")}constructor(e,t=null){super(),this.items=e,this.distinct=t}},Me=class extends h{static{this.kind=Symbol("Distinct")}constructor(){super()}},ze=class extends h{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},J=class extends h{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},be=class extends h{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},te=class extends h{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new C(e),this.expression=t}},Qe=class extends h{static{this.kind=Symbol("WindowsClause")}constructor(e){super(),this.windows=e}};var ue=class extends h{static{this.kind=Symbol("OrderByClause")}constructor(e){super(),this.order=e}},ve=class extends h{static{this.kind=Symbol("OrderByItem")}constructor(e,t,n){super(),this.value=e,this.sortDirection=t===null?"asc":t,this.nullsPosition=n}},G=class extends h{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},Y=class extends h{static{this.kind=Symbol("HavingClause")}constructor(e){super(),this.condition=e}},I=class extends h{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof C?this.qualifiedName.name:new C(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(e,t){super();let n=typeof t=="string"?new C(t):t;this.qualifiedName=new Ce(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof g?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof g?this.qualifiedName.name.value:this.qualifiedName.name.name}},Ie=class extends h{static{this.kind=Symbol("FunctionSource")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"name"in e){let n=e;this.qualifiedName=new Ce(n.namespaces,n.name)}else this.qualifiedName=new Ce(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},ge=class extends h{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},N=class extends h{static{this.kind=Symbol("SubQuerySource")}constructor(e){super(),this.query=e}},k=class extends h{static{this.kind=Symbol("SourceExpression")}constructor(e,t){super(),this.datasource=e,this.aliasExpression=t}getAliasName(){return this.aliasExpression?this.aliasExpression.table.name:this.datasource instanceof I?this.datasource.getSourceName():null}},X=class extends h{static{this.kind=Symbol("JoinOnClause")}constructor(e){super(),this.condition=e}},ce=class extends h{static{this.kind=Symbol("JoinUsingClause")}constructor(e){super(),this.condition=e}},Z=class extends h{static{this.kind=Symbol("JoinItem")}constructor(e,t,n,i){super(),this.joinType=new g(e),this.source=t,this.condition=n,this.lateral=i}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof I?this.source.table.name:null}},P=class extends h{static{this.kind=Symbol("FromClause")}constructor(e,t){super(),this.source=e,this.joins=t}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof I?this.source.datasource.table.name:null}getSources(){let e=[this.source];if(this.joins)for(let t of this.joins)e.push(t.source);return e}},K=class extends h{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new W(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},U=class extends h{static{this.kind=Symbol("WithClause")}constructor(e,t){super(),this.recursive=e,this.tables=t}},ee=class extends h{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var Pe=class extends h{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},Fe=class extends h{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},Ke=class extends h{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var ye=class extends h{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},W=class extends h{static{this.kind=Symbol("SourceAliasExpression")}constructor(e,t){super(),this.table=new C(e),this.columns=t!==null?t.map(n=>new C(n)):null}},mt=class extends h{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new C(t):t)}},Ne=class extends h{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof Ve?t:new Ve(t.column,t.value))}},Ve=class extends h{static{this.kind=Symbol("SetClauseItem")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"column"in e){let n=e,i=typeof n.column=="string"?new C(n.column):n.column;this.qualifiedName=new Ce(n.namespaces,i)}else{let n=typeof e=="string"?new C(e):e;this.qualifiedName=new Ce(null,n)}this.value=t}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof C?this.qualifiedName.name:new C(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},_e=class extends h{static{this.kind=Symbol("UpdateClause")}constructor(e){super(),this.source=e}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof I?this.source.datasource.table.name:null}},Be=class extends h{constructor(e,t){super(),this.source=e,this.columns=t.map(n=>new C(n))}};var T=(S=>(S[S.None=0]="None",S[S.Literal=1]="Literal",S[S.Operator=2]="Operator",S[S.OpenParen=4]="OpenParen",S[S.CloseParen=8]="CloseParen",S[S.Comma=16]="Comma",S[S.Dot=32]="Dot",S[S.Identifier=64]="Identifier",S[S.Command=128]="Command",S[S.Parameter=256]="Parameter",S[S.OpenBracket=512]="OpenBracket",S[S.CloseBracket=1024]="CloseBracket",S[S.Function=2048]="Function",S[S.StringSpecifier=4096]="StringSpecifier",S[S.Type=8192]="Type",S))(T||{});var j=class{static isWhitespace(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===32||t===9||t===10||t===13}static isDigit(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57}static isHexChar(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=97&&t<=102||t>=65&&t<=70}static isOperatorSymbol(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===43||t===45||t===42||t===47||t===37||t===126||t===64||t===35||t===94||t===38||t===58||t===33||t===60||t===62||t===61||t===124}static isDelimiter(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===46||t===44||t===40||t===41||t===91||t===93||t===123||t===125||t===59||t===32||t===9||t===10||t===13?!0:t===43||t===45||t===42||t===47||t===37||t===126||t===64||t===35||t===94||t===38||t===58||t===33||t===60||t===62||t===61||t===124}static isNamedParameterPrefix(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===64||t===58||t===36}};var M=class r{static getDebugPositionInfo(e,t){let n=Math.max(0,t-5),i=Math.min(e.length,t+5),s=e.slice(n,i),o=" ".repeat(t-n)+"^";return`${s}
2
+ ${o}`}static skipWhiteSpace(e,t){let n=e.length;for(;t+4<=n&&e.slice(t,t+4)===" ";)t+=4;for(;t<n;){let i=e.charCodeAt(t);if(i!==32&&i!==9&&i!==10&&i!==13)break;t++}return t}static readLineComment(e,t){if(t+1>=e.length)return{newPosition:t,comment:null};if(e.charCodeAt(t)===45&&e.charCodeAt(t+1)===45){let n=t;for(t+=2;t<e.length&&e.charCodeAt(t)!==10;)t++;let i=e.slice(n+2,t).trim();return{newPosition:t,comment:i}}return{newPosition:t,comment:null}}static readBlockComment(e,t){if(t+3>=e.length)return{newPosition:t,comments:null};if(e.charCodeAt(t)===47&&e.charCodeAt(t+1)===42&&e.charCodeAt(t+2)!==43){let n=t;for(t+=2;t+1<e.length;){if(e.charCodeAt(t)===42&&e.charCodeAt(t+1)===47){t+=2;let i=e.slice(n+2,t-2).replace(/\r/g,"").split(`
3
+ `);for(let s=0;s<i.length;s++)i[s]=i[s].trim();for(;i.length>0&&i[0]==="";)i.shift();for(;i.length>0&&i[i.length-1]==="";)i.pop();return{newPosition:t,comments:i}}t++}throw new Error(`Block comment is not closed. position: ${t}`)}return{newPosition:t,comments:null}}static readWhiteSpaceAndComment(e,t){let n=[],i=e.length;for(;t<i;){let s=t;if(t=r.skipWhiteSpace(e,t),t!==s)continue;let o=e.charCodeAt(t);if(o===45){let a=r.readLineComment(e,t);if(a.newPosition!==t){t=a.newPosition,a.comment&&n.push(a.comment.trim());continue}}else if(o===47){let a=r.readBlockComment(e,t);if(a.newPosition!==t){t=a.newPosition,a.comments&&n.push(...a.comments);continue}}break}return{position:t,lines:n}}static readRegularIdentifier(e,t){let n=this.tryReadRegularIdentifier(e,t);if(!n)throw new Error(`Unexpected character. position: ${t}
4
+ ${r.getDebugPositionInfo(e,t)}`);return n}static tryReadRegularIdentifier(e,t){let n=t;for(;t<e.length&&!j.isDelimiter(e[t]);)t++;if(n===t)return null;for(;t+1<e.length&&e[t]==="["&&e[t+1]==="]";)t+=2;return{identifier:e.slice(n,t),newPosition:t}}};var $=class{constructor(e,t=0){this.input=e,this.position=t}getPosition(){return this.position}setPosition(e){this.position=e}isEndOfInput(e=0){return this.position+e>=this.input.length}canRead(e=0){return!this.isEndOfInput(e)}read(e){if(this.isEndOfInput())throw new Error(`Unexpected character. expect: ${e}, actual: EndOfInput, position: ${this.position}`);let t=this.input[this.position];if(t!==e)throw new Error(`Unexpected character. expect: ${e}, actual: ${t}, position: ${this.position}`);return this.position++,t}createLexeme(e,t,n=null){return e===128||e===2||e===2048?{type:e,value:t.toLowerCase(),comments:n}:{type:e,value:t,comments:n}}getDebugPositionInfo(e){return M.getDebugPositionInfo(this.input,e)}};var ht=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="*")return this.position++,this.createLexeme(64,t);let n=M.readRegularIdentifier(this.input,this.position);return this.position=n.newPosition,this.createLexeme(64,n.identifier)}};var pe=class{constructor(e){this.trie=e}isEndOfInput(e,t,n=0){return t+n>=e.length}canParse(e,t,n=0){return!this.isEndOfInput(e,t,n)}parse(e,t){if(this.isEndOfInput(e,t))return null;this.trie.reset();let n=M.tryReadRegularIdentifier(e,t);if(n===null)return null;let i=this.trie.pushLexeme(n.identifier.toLowerCase());if(i===0)return null;if(i===3)return{keyword:n.identifier,newPosition:n.newPosition};let s=n.identifier;if(t=M.readWhiteSpaceAndComment(e,n.newPosition).position,this.isEndOfInput(e,t))return i===2?{keyword:s,newPosition:t}:null;for(;this.canParse(e,t);){let o=i,a=M.tryReadRegularIdentifier(e,t);if(a!==null){if(i=this.trie.pushLexeme(a.identifier.toLowerCase()),i===0){if(o===2)break;return null}if(s+=" "+a.identifier,t=M.readWhiteSpaceAndComment(e,a.newPosition).position,i===3)break}else{if(o===2)break;return null}}return{keyword:s,newPosition:t}}};var me=class{constructor(e){this.root=new Map;this.hasEndProperty=!1;this.hasMoreProperties=!1;for(let t of e)this.addKeyword(t);this.currentNode=this.root}addKeyword(e){let t=this.root;for(let n of e)t.has(n)||t.set(n,new Map),t=t.get(n);t.set("__end__",!0)}reset(){this.currentNode=this.root,this.hasEndProperty=!1,this.hasMoreProperties=!1}pushLexeme(e){return this.currentNode.has(e)?(this.currentNode=this.currentNode.get(e),this.hasEndProperty=this.currentNode.has("__end__"),this.hasMoreProperties=this.currentNode.size>(this.hasEndProperty?1:0),this.hasEndProperty&&!this.hasMoreProperties?3:this.hasEndProperty&&this.hasMoreProperties?2:1):0}};var yn=[["null"],["true"],["false"],["current_date"],["current_time"],["current_timestamp"],["localtime"],["localtimestamp"],["unbounded"],["normalized"],["nfc","normalized"],["nfd","normalized"],["nfkc","normalized"],["nfkd","normalized"],["nfc"],["nfd"],["nfkc"],["nfkd"]],Sn=new me(yn),rn=new pe(Sn),dt=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position],n=this.tryReadKeyword();if(n)return n;if(t==="."&&this.canRead(1)&&j.isDigit(this.input[this.position+1]))return this.createLexeme(1,this.readDigit());if(t==="'"){let i=this.readSingleQuotedString(!1);return this.createLexeme(1,i)}if(j.isDigit(t))return this.createLexeme(1,this.readDigit());if((t==="+"||t==="-")&&this.determineSignOrOperator(e)==="sign"){let i=t;this.position++;let s=this.position;for(;this.canRead()&&j.isWhitespace(this.input[this.position]);)this.position++;if(this.canRead()&&(j.isDigit(this.input[this.position])||this.input[this.position]==="."&&this.canRead(1)&&j.isDigit(this.input[this.position+1])))return this.createLexeme(1,i==="-"?i+this.readDigit():this.readDigit());this.position=s-1}return null}tryReadKeyword(){let e=rn.parse(this.input,this.position);return e?(this.position=e.newPosition,this.createLexeme(1,e.keyword)):null}determineSignOrOperator(e){return e===null?"sign":e.type===1||e.type===64||e.type===8?"operator":"sign"}readDigit(){let e=this.position,t=!1,n=!1;if(this.canRead(1)&&this.input[this.position]==="0"&&"xbo".includes(this.input[this.position+1].toLowerCase())){let i=this.input[this.position+1].toLowerCase();this.position+=2;let s=i==="x";for(;this.canRead();){let o=this.input[this.position];if(j.isDigit(o)||s&&j.isHexChar(o))this.position++;else break}return this.input.slice(e,this.position)}for(this.input[e]==="."&&(t=!0,this.position++);this.canRead();){let i=this.input[this.position];if(i==="."&&!t)t=!0;else if((i==="e"||i==="E")&&!n)n=!0,this.canRead(1)&&(this.input[this.position+1]==="+"||this.input[this.position+1]==="-")&&this.position++;else if(!j.isDigit(i))break;this.position++}if(e===this.position)throw new Error(`Unexpected character. position: ${e}
5
+ ${this.getDebugPositionInfo(e)}`);return this.input[e]==="."?"0"+this.input.slice(e,this.position):this.input.slice(e,this.position)}readSingleQuotedString(e){let t=this.position,n=!1;for(this.read("'");this.canRead();){let i=this.input[this.position];if(this.position++,i==="\\"&&this.canRead(1)){this.position++;continue}else if(i==="'"){n=!0;break}}if(n===!1)throw new Error(`Single quote is not closed. position: ${t}
6
+ ${this.getDebugPositionInfo(t)}`);return e?this.input.slice(t,this.position):this.input.slice(t+1,this.position-1)}};var ft=class extends ${constructor(e){super(e)}tryRead(e){if(this.isEndOfInput())return null;if(this.canRead(1)&&this.input[this.position]==="$"&&this.input[this.position+1]==="{"){this.position+=2;let n=this.position;for(;this.canRead()&&this.input[this.position]!=="}";)this.position++;if(this.isEndOfInput())throw new Error(`Unexpected end of input. Expected closing '}' for parameter at position ${n}`);let i=this.input.slice(n,this.position);if(i.length===0)throw new Error("Empty parameter name is not allowed: found ${} at position "+(n-2));return this.position++,this.createLexeme(256,"${"+i+"}")}let t=this.input[this.position];if(j.isNamedParameterPrefix(t)){if(this.canRead(1)&&j.isOperatorSymbol(this.input[this.position+1]))return null;this.position++;let n=this.position;for(;this.canRead()&&!j.isDelimiter(this.input[this.position]);)this.position++;let i=this.input.slice(n,this.position);return this.createLexeme(256,t+i)}return t==="?"?(this.position++,this.createLexeme(256,t)):null}};var wt=class r extends ${static{this.SPECIAL_SYMBOL_TOKENS={".":32,",":16,"(":4,")":8,"[":512,"]":1024}}tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];return t in r.SPECIAL_SYMBOL_TOKENS?(this.position++,this.createLexeme(r.SPECIAL_SYMBOL_TOKENS[t],t)):null}};var Ct=class{constructor(e,t=0){this.cacheHits=0;this.cacheMisses=0;this.input=e,this.position=t,this.readers=[],this.tokenCache=new Map}register(e){return this.readers.push(e),this}registerAll(e){return e.forEach(t=>this.register(t)),this}setPosition(e){this.position=e;for(let t of this.readers)t.setPosition(e)}tryRead(e,t){if(this.tokenCache.has(e))return this.cacheHits++,this.tokenCache.get(e)||null;this.cacheMisses++,this.setPosition(e);let n=null;for(let i of this.readers)if(n=i.tryRead(t),n){this.position=i.getPosition();break}for(let i of this.readers)i.setPosition(this.position);return this.tokenCache.set(e,n),n}getMaxPosition(){let e=this.position;for(let t of this.readers){let n=t.getPosition();n>e&&(e=n)}return e}getInput(){return this.input}getCacheStats(){let e=this.cacheHits+this.cacheMisses,t=e>0?this.cacheHits/e:0;return{hits:this.cacheHits,misses:this.cacheMisses,ratio:t}}};var xn=new me([["and"],["or"],["is"],["is","not"],["is","distinct","from"],["is","not","distinct","from"],["like"],["in"],["exists"],["between"],["not","like"],["not","in"],["not","exists"],["not","between"],["escape"],["uescape"],["similar"],["placing"],["not"],["both"],["leading"],["trailing"],["both","from"],["leading","from"],["trailing","from"],["year","from"],["month","from"],["day","from"],["hour","from"],["minute","from"],["second","from"],["dow","from"],["doy","from"],["isodow","from"],["quarter","from"],["week","from"],["epoch","from"],["at","time","zone"]]),En=new me([["date"],["time"],["timestamp"],["timestamptz"],["timetz"],["interval"],["boolean"],["integer"],["bigint"],["smallint"],["numeric"],["decimal"],["real"],["double","precision"],["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),bn=new pe(xn),gn=new pe(En);var vt=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(j.isOperatorSymbol(t)){let i=this.position;for(;this.canRead()&&j.isOperatorSymbol(this.input[this.position]);){if(this.canRead(1)){let o=this.input[this.position];if(o==="-"&&this.input[this.position+1]==="-")break;if(o==="/"&&this.input[this.position+1]==="*")break}this.position++}let s=this.input.slice(i,this.position);return this.createLexeme(2,s)}let n=gn.parse(this.input,this.position);return n!==null?(this.position=n.newPosition,this.createLexeme(8258,n.keyword)):(n=bn.parse(this.input,this.position),n!==null?(this.position=n.newPosition,this.createLexeme(2,n.keyword)):null)}};var kn=new me([["join"],["inner","join"],["cross","join"],["left","join"],["left","outer","join"],["right","join"],["right","outer","join"],["full","join"],["full","outer","join"],["natural","join"],["natural","inner","join"],["natural","left","join"],["natural","left","outer","join"],["natural","right","join"],["natural","right","outer","join"],["natural","full","join"],["natural","full","outer","join"]]),Tn=new me([["with"],["recursive"],["materialized"],["not","materialized"],["select"],["from"],["distinct"],["distinct","on"],["where"],["group","by"],["having"],["order","by"],["limit"],["offset"],["fetch"],["first"],["next"],["row"],["row","only"],["rows","only"],["percent"],["percent","with","ties"],["for"],["update"],["share"],["key","share"],["no","key","update"],["union"],["union","all"],["intersect"],["intersect","all"],["except"],["except","all"],["beteen"],["window"],["over"],["partition","by"],["range"],["rows"],["groups"],["current","row"],["unbounded","preceding"],["unbounded","following"],["preceding"],["following"],["on"],["using"],["lateral"],["case"],["case","when"],["when"],["then"],["else"],["end"],["insert","into"],["update"],["delete","from"],["merge","into"],["matched"],["not","matched"],["update","set"],["do","nothing"],["values"],["set"],["returning"],["create","table"],["create","temporary","table"],["tablesample"],["as"],["asc"],["desc"],["nulls","first"],["nulls","last"]]),In=new pe(Tn),on=new pe(kn),yt=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=on.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(128,t.keyword);let n=In.parse(this.input,this.position);if(n!==null)return this.position=n.newPosition,this.createLexeme(128,n.keyword);if(this.canRead(2)&&this.input[this.position]==="/"&&this.input[this.position+1]==="*"&&this.input[this.position+2]==="+"){this.position+=3;let i=this.position;for(;this.position+1<this.input.length;){if(this.input[this.position]==="*"&&this.input[this.position+1]==="/")return this.position+=2,this.createLexeme(128,"/*+ "+this.input.slice(i,this.position-2).trim()+" */");this.position++}throw new Error(`Block comment is not closed. position: ${this.position}`)}return null}};var Pn=new Set(["e'","E'","x'","X'","b'","B'"]),Fn=new Set(["u&'","U&'"]),St=class extends ${tryRead(e){let t=this.position;return this.canRead(1)&&Pn.has(this.input.slice(t,t+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(t,this.position))):this.canRead(2)&&Fn.has(this.input.slice(t,t+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(t,this.position))):null}};var On=new me([["grouping","sets"],["array"]]),Ln=new pe(On),xt=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=Ln.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(2048,t.keyword);let n=M.tryReadRegularIdentifier(this.input,this.position);if(!n)return null;this.position=n.newPosition;var i=M.readWhiteSpaceAndComment(this.input,this.position).position-this.position;return this.canRead(i)&&this.input[this.position+i]==="("?this.createLexeme(2048,n.identifier):null}};var Nn=new me([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),An=new pe(Nn),Et=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=An.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(8192,t.keyword);if(e===null)return null;let n=M.tryReadRegularIdentifier(this.input,this.position);return n?(this.position=n.newPosition,e.type&128&&e.value==="as"?this.createLexeme(8256,n.identifier):e.type&2&&e.value==="::"?this.createLexeme(8192,n.identifier):null):null}};var bt=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="`"){let n=this.readEscapedIdentifier("`");return this.createLexeme(64,n)}if(t==='"'){let n=this.readEscapedIdentifier('"');return this.createLexeme(64,n)}if(t==="["&&(e===null||e.value!=="array")){let n=this.readEscapedIdentifier("]");return this.createLexeme(64,n)}return null}readEscapedIdentifier(e){let t=this.position;for(this.position++;this.canRead()&&this.input[this.position]!==e;)this.position++;if(t===this.position)throw new Error(`Closing delimiter is not found. position: ${t}, delimiter: ${e}
7
+ ${this.getDebugPositionInfo(t)}`);return this.position++,this.input.slice(t+1,this.position-1)}};var x=class{constructor(e){this.input=e,this.position=0,this.readerManager=new Ct(e).register(new bt(e)).register(new ft(e)).register(new St(e)).register(new dt(e)).register(new wt(e)).register(new yt(e)).register(new vt(e)).register(new Et(e)).register(new xt(e)).register(new ht(e))}isEndOfInput(e=0){return this.position+e>=this.input.length}canRead(e=0){return!this.isEndOfInput(e)}readLexmes(){let e=Math.ceil(this.input.length/8),t=new Array(e),n=0,i=this.readComment(),s=i.lines;this.position=i.position;let o=null;for(;this.canRead()&&this.input[this.position]!==";";){let a=this.readerManager.tryRead(this.position,o);if(a===null)throw new Error(`Unexpected character. actual: ${this.input[this.position]}, position: ${this.position}
8
+ ${this.getDebugPositionInfo(this.position)}`);this.position=this.readerManager.getMaxPosition();let l=this.readComment();this.position=l.position,a.type&16||a.type&2?l.lines.length>0&&s.push(...l.lines):((s.length>0||l.lines.length>0)&&this.addCommentsToToken(a,s,l.lines),s=[]),t[n++]=a,o=a}if(s.length>0&&n>0){let a=t[n-1];a.comments===null&&(a.comments=[]),a.comments.push(...s)}return n===e?t:t.slice(0,n)}addPendingCommentsToLastToken(e,t){if(t.length>0&&e.length>0){let n=e[e.length-1];n.comments===null&&(n.comments=[]),n.comments.push(...t)}}addCommentsToToken(e,t,n){(t.length>0||n.length>0)&&(e.comments===null&&(e.comments=[]),t.length>0&&e.comments.unshift(...t),n.length>0&&e.comments.push(...n))}readComment(){return M.readWhiteSpaceAndComment(this.input,this.position)}getDebugPositionInfo(e){return M.getDebugPositionInfo(this.input,e)}};var he=class r{static parseFromLexeme(e,t){let{identifiers:n,newIndex:i}=r.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:s,name:o}=r.extractNamespacesAndName(n),a=0;return i>t&&(a=e[i-1].type),{namespaces:s,name:new C(o),newIndex:i,lastTokenType:a}}static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The name is complete but additional tokens were found.`);return{namespaces:i.namespaces,name:i.name}}static parseEscapedOrDotSeparatedIdentifiers(e,t){let n=t,i=[];for(;n<e.length;){if(e[n].type&512){if(n++,n>=e.length||!(e[n].type&64||e[n].type&128))throw new Error(`Expected identifier after '[' at position ${n}`);if(i.push(e[n].value),n++,n>=e.length||e[n].value!=="]")throw new Error(`Expected closing ']' after identifier at position ${n}`);n++}else if(e[n].type&64)i.push(e[n].value),n++;else if(e[n].type&2048)i.push(e[n].value),n++;else if(e[n].type&8192)i.push(e[n].value),n++;else if(e[n].value==="*"){i.push(e[n].value),n++;break}if(n<e.length&&e[n].type&32)n++;else break}return{identifiers:i,newIndex:n}}static extractNamespacesAndName(e){if(!e||e.length===0)throw new Error("Identifier list is empty");return e.length===1?{namespaces:null,name:e[0]}:{namespaces:e.slice(0,-1),name:e[e.length-1]}}};var gt=class{static parseFromLexeme(e,t){let{namespaces:n,name:i,newIndex:s}=he.parseFromLexeme(e,t);return{value:new f(n,i),newIndex:s}}};var ot=class{static parseFromLexeme(e,t){let n=t,i=e[n].value,s,o=rn.parse(i.toLowerCase(),0);if(o){let l=new g(o.keyword);return n++,{value:l,newIndex:n}}return/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(i)?s=Number(i):i.startsWith("'")&&i.endsWith("'")?s=i.slice(1,-1):s=i,n++,{value:new V(s),newIndex:n}}};var kt=class{static parseFromLexeme(e,t){let n=t;if(n+1<e.length&&e[n].type&4&&(e[n+1].value==="select"||e[n+1].value==="values"||e[n+1].value==="with")){n+=1;let i=B.parseFromLexeme(e,n);if(n=i.newIndex,n>=e.length||e[n].type!==8)throw new Error(`Expected ')' at index ${n}, but found ${e[n].value}`);return n++,{value:new fe(i.value),newIndex:n}}else{let i=v.parseArgument(4,8,e,t);return n=i.newIndex,{value:new H(i.value),newIndex:n}}}};var Tt=class{static parseFromLexeme(e,t){let n=t;if(n<e.length&&e[n].type&2){let i=e[n].value;if(n++,i==="*")return{value:new f(null,"*"),newIndex:n};let s=v.parseFromLexeme(e,n);return n=s.newIndex,{value:new D(i,s.value),newIndex:n}}throw new Error(`Invalid unary expression at index ${t}: ${e[t].value}`)}};var It=class{static parseFromLexeme(e,t){let n=t,i=e[n].value;i.startsWith("${")&&i.endsWith("}")?i=i.slice(2,-1):i=i.slice(1);let s=new A(i);return n++,{value:s,newIndex:n}}};var Pt=class{static parseFromLexeme(e,t){let n=t,i=e[n].value;if(n++,n>=e.length||e[n].type!==1)throw new Error(`Expected string literal after string specifier at index ${n}`);let s=e[n].value;return n++,{value:new Je(i,s),newIndex:n}}};var Ft=class{static parseFromLexeme(e,t){let n=t,i=e[n];return i.value==="case"?(n++,this.parseCaseExpression(e,n)):i.value==="case when"?(n++,this.parseCaseWhenExpression(e,n)):this.parseModifierUnaryExpression(e,n)}static parseModifierUnaryExpression(e,t){let n=t;if(n<e.length&&e[n].type&128){let i=e[n].value;n++;let s=v.parseFromLexeme(e,n);return{value:new D(i,s.value),newIndex:s.newIndex}}throw new Error(`Invalid modifier unary expression at index ${n}, Lexeme: ${e[n].value}`)}static parseCaseExpression(e,t){let n=t,i=v.parseFromLexeme(e,n);n=i.newIndex;let s=this.parseSwitchCaseArgument(e,n,[]);return n=s.newIndex,{value:new _(i.value,s.value),newIndex:n}}static parseCaseWhenExpression(e,t){let n=t,i=this.parseCaseConditionValuePair(e,n);n=i.newIndex;let s=[i.value],o=this.parseSwitchCaseArgument(e,n,s);return n=o.newIndex,{value:new _(null,o.value),newIndex:n}}static parseSwitchCaseArgument(e,t,n){let i=t,s=[...n],o=null;for(;i<e.length&&this.isCommandWithValue(e[i],"when");){i++;let l=this.parseCaseConditionValuePair(e,i);i=l.newIndex,s.push(l.value)}if(i<e.length&&this.isCommandWithValue(e[i],"else")){i++;let l=v.parseFromLexeme(e,i);o=l.value,i=l.newIndex}if(i<e.length&&this.isCommandWithValue(e[i],"end"))i++;else throw new Error(`The CASE expression requires 'end' keyword at the end (index ${i})`);if(s.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${i})`);return{value:new ne(s,o),newIndex:i}}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,i=v.parseFromLexeme(e,n);if(n=i.newIndex,n>=e.length||!(e[n].type&128)||e[n].value!=="then")throw new Error(`Expected 'then' after WHEN condition at index ${n}`);n++;let s=v.parseFromLexeme(e,n);return n=s.newIndex,{value:new ie(i.value,s.value),newIndex:n}}};var He=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The ORDER BY clause is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="order by")throw new Error(`Syntax error at position ${n}: Expected 'ORDER BY' keyword but found "${e[n].value}". ORDER BY clauses must start with the ORDER BY keywords.`);n++;let i=[],s=this.parseItem(e,n);for(i.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let o=this.parseItem(e,n);i.push(o.value),n=o.newIndex}if(i.length===0)throw new Error(`Syntax error at position ${t}: No ordering expressions found. The ORDER BY clause requires at least one expression to order by.`);return{value:new ue(i),newIndex:n}}static parseItem(e,t){let n=t,i=v.parseFromLexeme(e,n),s=i.value;if(n=i.newIndex,n>=e.length)return{value:s,newIndex:n};let o=n>=e.length?null:e[n].value==="asc"?(n++,"asc"):e[n].value==="desc"?(n++,"desc"):null,a=n>=e.length?null:e[n].value==="nulls first"?(n++,"first"):e[n].value==="nulls last"?(n++,"last"):null;return o===null&&a===null?{value:s,newIndex:n}:{value:new ve(s,o,a),newIndex:n}}};var Ot=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The PARTITION BY clause is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="partition by")throw new Error(`Syntax error at position ${n}: Expected 'PARTITION BY' keyword but found "${e[n].value}". PARTITION BY clauses must start with the PARTITION BY keywords.`);n++;let i=[],s=v.parseFromLexeme(e,n);for(i.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let o=v.parseFromLexeme(e,n);i.push(o.value),n=o.newIndex}if(i.length===0)throw new Error(`Syntax error at position ${t}: No partition expressions found. The PARTITION BY clause requires at least one expression to partition by.`);return i.length===1?{value:new be(i[0]),newIndex:n}:{value:new be(new Q(i)),newIndex:n}}};var Ge=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The window frame expression is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].type!==4)throw new Error(`Syntax error at position ${n}: Expected opening parenthesis '(' but found "${e[n].value}".`);n++;let i=null,s=null,o=null;if(n<e.length&&e[n].value==="partition by"){let a=Ot.parseFromLexeme(e,n);i=a.value,n=a.newIndex}if(n<e.length&&e[n].value==="order by"){let a=He.parseFromLexeme(e,n);s=a.value,n=a.newIndex}if(n<e.length&&this.isFrameTypeKeyword(e[n].value)){let a=this.parseFrameSpec(e,n);o=a.value,n=a.newIndex}if(n>=e.length||e[n].type!==8)throw new Error(`Syntax error at position ${n}: Missing closing parenthesis ')' for window frame. Each opening parenthesis must have a matching closing parenthesis.`);return n++,{value:new we(i,s,o),newIndex:n}}static isFrameTypeKeyword(e){let t=e;return t==="rows"||t==="range"||t==="groups"}static parseFrameSpec(e,t){let n=t,i=e[n].value,s;switch(i){case"rows":s="rows";break;case"range":s="range";break;case"groups":s="groups";break;default:throw new Error(`Syntax error at position ${n}: Invalid frame type "${e[n].value}". Expected one of: ROWS, RANGE, GROUPS.`)}if(n++,n<e.length&&e[n].value==="between"){n++;let o=this.parseFrameBoundary(e,n),a=o.value;if(n=o.newIndex,n>=e.length||e[n].value!=="and")throw new Error(`Syntax error at position ${n}: Expected 'AND' keyword in BETWEEN clause.`);n++;let l=this.parseFrameBoundary(e,n),u=l.value;return n=l.newIndex,{value:new Ee(s,a,u),newIndex:n}}else{let o=this.parseFrameBoundary(e,n),a=o.value;return n=o.newIndex,{value:new Ee(s,a,null),newIndex:n}}}static parseFrameBoundary(e,t){let n=t;if(n<e.length&&e[n].type&128){let i=e[n].value,s;switch(i){case"current row":s="current row";break;case"unbounded preceding":s="unbounded preceding";break;case"unbounded following":s="unbounded following";break;default:throw new Error(`Syntax error at position ${n}: Invalid frame type "${e[n].value}". Expected one of: ROWS, RANGE, GROUPS.`)}return{value:new qe(s),newIndex:n+1}}else if(n<e.length&&e[n].type&1){let i=v.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length&&e[n].type&128){let s=e[n].value,o;if(s==="preceding")o=!1;else if(s==="following")o=!0;else throw new Error(`Syntax error at position ${n}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`);return n++,{value:new De(i.value,o),newIndex:n}}else throw new Error(`Syntax error at position ${n}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`)}throw new Error(`Syntax error at position ${n}: Expected a valid frame boundary component.`)}};var at=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The OVER expression is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="over")throw new Error(`Syntax error at position ${n}: Expected 'OVER' keyword but found "${e[n].value}". OVER expressions must start with the OVER keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'OVER' keyword. Expected either a window name or an opening parenthesis '('.");if(e[n].type&64){let i=e[n].value;return n++,{value:new C(i),newIndex:n}}if(e[n].type&4)return Ge.parseFromLexeme(e,n);throw new Error(`Syntax error at position ${n}: Expected a window name or opening parenthesis '(' after OVER keyword, but found "${e[n].value}".`)}};var Ye=class{static parseArrayExpression(e,t){let n=t;if(n+1<e.length&&e[n+1].type&512){n++;let i=v.parseArgument(512,1024,e,n);return n=i.newIndex,{value:new re(i.value),newIndex:n}}else if(n+1<e.length&&e[n+1].type&4){n++,n++;let i=B.parseFromLexeme(e,n);return n=i.newIndex,n++,{value:new oe(i.value),newIndex:n}}throw new Error(`Invalid ARRAY syntax at index ${n}, expected ARRAY[... or ARRAY(...)`)}static parseFromLexeme(e,t){let n=t,i=e[n];return i.value==="array"?this.parseArrayExpression(e,n):i.value==="substring"||i.value==="overlay"?this.parseKeywordFunction(e,n,[{key:"from",required:!1},{key:"for",required:!1}]):i.value==="cast"?this.parseKeywordFunction(e,n,[{key:"as",required:!0}]):i.value==="trim"?this.parseKeywordFunction(e,n,[{key:"from",required:!1}]):this.parseFunctionCall(e,n)}static tryParseBinaryExpression(e,t,n,i=!0){let s=t;if(s<e.length&&e[s].type&2){if(!i&&e[s].value==="and")return null;let o=e[s].value;if(s++,o==="between")return this.parseBetweenExpression(e,s,n,!1);if(o==="not between")return this.parseBetweenExpression(e,s,n,!0);if(o==="::"){let u=this.parseTypeValue(e,s);return s=u.newIndex,{value:new se(n,u.value),newIndex:s}}let a=v.parseFromLexeme(e,s);return s=a.newIndex,{value:new b(n,o,a.value),newIndex:s}}return null}static parseBetweenExpression(e,t,n,i){let s=t,o=v.parseFromLexeme(e,s,!1);if(s=o.newIndex,s<e.length&&e[s].type&2&&e[s].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${s}`);s++;let a=v.parseFromLexeme(e,s);return s=a.newIndex,{value:new ae(n,o.value,a.value,i),newIndex:s}}static parseFunctionCall(e,t){let n=t,i=he.parseFromLexeme(e,n),s=i.namespaces,o=i.name;if(n=i.newIndex,n<e.length&&e[n].type&4){let a=v.parseArgument(4,8,e,n);if(n=a.newIndex,n<e.length&&e[n].value==="over"){let l=at.parseFromLexeme(e,n);return n=l.newIndex,{value:new L(s,o.name,a.value,l.value),newIndex:n}}else return{value:new L(s,o.name,a.value,null),newIndex:n}}else throw new Error(`Expected opening parenthesis after function name '${o.name}' at index ${n}`)}static parseKeywordFunction(e,t,n){let i=t,s=he.parseFromLexeme(e,i),o=s.namespaces,a=s.name;if(i=s.newIndex,i<e.length&&e[i].type&4){i++;let l=v.parseFromLexeme(e,i),u=l.value;if(i=l.newIndex,i<e.length&&e[i].type&16)return this.parseFunctionCall(e,t);for(let{key:c,required:m}of n)if(i<e.length&&e[i].type&128&&e[i].value===c)if(i++,i<e.length&&e[i].type&8192){let d=this.parseTypeValue(e,i);u=new b(u,c,d.value),i=d.newIndex}else{let d=v.parseFromLexeme(e,i);u=new b(u,c,d.value),i=d.newIndex}else if(m)throw new Error(`Keyword '${c}' is required at index ${i}`);if(i<e.length&&e[i].type&8)if(i++,i<e.length&&e[i].value==="over"){i++;let c=at.parseFromLexeme(e,i);return i=c.newIndex,{value:new L(o,a.name,u,c.value),newIndex:i}}else return{value:new L(o,a.name,u,null),newIndex:i};else throw new Error(`Missing closing parenthesis for function '${a.name}' at index ${i}`)}else throw new Error(`Missing opening parenthesis for function '${a.name}' at index ${i}`)}static parseTypeValue(e,t){let n=t,{namespaces:i,name:s,newIndex:o}=he.parseFromLexeme(e,n);if(n=o,n<e.length&&e[n].type&4){let a=v.parseArgument(4,8,e,n);return n=a.newIndex,{value:new Se(i,new g(s.name),a.value),newIndex:n}}else return{value:new Se(i,new g(s.name)),newIndex:n}}};var Lt=class r extends Error{constructor(t,n,i){super(t);this.index=n;this.context=i;this.name="ParseError"}static fromUnparsedLexemes(t,n,i){let s=Math.max(0,n-2),o=Math.min(t.length,n+3),a=t.slice(s,o).map((u,c)=>{let m=c+s===n?">":" ",d=T[u.type]||u.type;return`${m} ${c+s}:${u.value} [${d}]`}).join(`
9
+ `),l=`${i} Unparsed lexeme remains at index ${n}: ${t[n].value}
10
+ Context:
11
+ ${a}`;return new r(l,n,a)}};var v=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw Lt.fromUnparsedLexemes(n,i.newIndex,"[ValueParser]");return i.value}static parseFromLexeme(e,t,n=!0){let i=t,s=e[i].comments,o=this.parseItem(e,i);for(o.value.comments=s,i=o.newIndex;i<e.length&&e[i].type&2;){let a=Ye.tryParseBinaryExpression(e,i,o.value,n);if(a)o.value=a.value,i=a.newIndex;else break}return{value:o.value,newIndex:i}}static parseItem(e,t){let n=t;if(n>=e.length)throw new Error(`Unexpected end of lexemes at index ${t}`);let i=e[n];if(i.type&64&&i.type&2&&i.type&8192){let s=gt.parseFromLexeme(e,n);if(s.newIndex>=e.length)return s;if(e[s.newIndex].type&1){let a=ot.parseFromLexeme(e,s.newIndex);return{value:new D(e[n].value,a.value),newIndex:a.newIndex}}return s}else if(i.type&64){let{namespaces:s,name:o,newIndex:a}=he.parseFromLexeme(e,n);return e[a-1].type&10240?Ye.parseFromLexeme(e,n):{value:new f(s,o),newIndex:a}}else{if(i.type&1)return ot.parseFromLexeme(e,n);if(i.type&4)return kt.parseFromLexeme(e,n);if(i.type&2048)return Ye.parseFromLexeme(e,n);if(i.type&2)return Tt.parseFromLexeme(e,n);if(i.type&256)return It.parseFromLexeme(e,n);if(i.type&4096)return Pt.parseFromLexeme(e,n);if(i.type&128)return Ft.parseFromLexeme(e,n);if(i.type&512){let{namespaces:s,name:o,newIndex:a}=he.parseFromLexeme(e,n);return{value:new f(s,o),newIndex:a}}}throw new Error(`[ValueParser] Invalid lexeme. index: ${n}, type: ${e[n].type}, value: ${e[n].value}`)}static parseArgument(e,t,n,i){let s=i,o=[];if(s<n.length&&n[s].type===e){if(s++,s<n.length&&n[s].type===t)return s++,{value:new Q([]),newIndex:s};if(s<n.length&&n[s].value==="*"){let l=new f(null,"*");if(s++,s<n.length&&n[s].type===t)return s++,{value:l,newIndex:s};throw new Error(`Expected closing parenthesis at index ${s}`)}let a=this.parseFromLexeme(n,s);for(s=a.newIndex,o.push(a.value);s<n.length&&n[s].type&16;){s++;let l=this.parseFromLexeme(n,s);s=l.newIndex,o.push(l.value)}if(s<n.length&&n[s].type===t)return s++,o.length===1?{value:o[0],newIndex:s}:{value:new Q(o),newIndex:s};throw new Error(`Missing closing parenthesis at index ${s}`)}throw new Error(`Expected opening parenthesis at index ${i}`)}};var q=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(E.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(R.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(z.kind,e=>this.visitValuesQuery(e)),this.handlers.set(U.kind,e=>this.visitWithClause(e)),this.handlers.set(K.kind,e=>this.visitCommonTable(e)),this.handlers.set(F.kind,e=>this.visitSelectItem(e)),this.handlers.set(C.kind,e=>this.visitIdentifierString(e)),this.handlers.set(g.kind,e=>this.visitRawString(e)),this.handlers.set(f.kind,e=>this.visitColumnReference(e)),this.handlers.set(A.kind,e=>this.visitParameterExpression(e)),this.handlers.set(V.kind,e=>this.visitLiteralValue(e)),this.handlers.set(k.kind,e=>this.visitSourceExpression(e)),this.handlers.set(I.kind,e=>this.visitTableSource(e)),this.handlers.set(Ie.kind,e=>this.visitFunctionSource(e)),this.handlers.set(ge.kind,e=>this.visitParenSource(e)),this.handlers.set(N.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(fe.kind,e=>this.visitInlineQuery(e)),this.handlers.set(P.kind,e=>this.visitFromClause(e)),this.handlers.set(Z.kind,e=>this.visitJoinClause(e)),this.handlers.set(X.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(ce.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(J.kind,e=>this.visitWhereClause(e)),this.handlers.set(H.kind,e=>this.visitParenExpression(e)),this.handlers.set(b.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(D.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(_.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ie.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(ne.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ae.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(L.kind,e=>this.visitFunctionCall(e)),this.handlers.set(re.kind,e=>this.visitArrayExpression(e)),this.handlers.set(oe.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(le.kind,e=>this.visitTupleExpression(e)),this.handlers.set(se.kind,e=>this.visitCastExpression(e)),this.handlers.set(we.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Ee.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Se.kind,e=>this.visitTypeValue(e)),this.handlers.set(Q.kind,e=>this.visitValueList(e)),this.handlers.set(O.kind,e=>this.visitSelectClause(e)),this.handlers.set(G.kind,e=>this.visitGroupByClause(e)),this.handlers.set(Y.kind,e=>this.visitHavingClause(e)),this.handlers.set(ue.kind,e=>this.visitOrderByClause(e)),this.handlers.set(te.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(ee.kind,e=>this.visitLimitClause(e)),this.handlers.set(ye.kind,e=>this.visitForClause(e)),this.handlers.set(ve.kind,e=>this.visitOrderByItem(e)),this.handlers.set(be.kind,e=>this.visitPartitionByClause(e))}getCommonTables(){return this.commonTables}reset(){this.commonTables=[],this.visitedNodes.clear()}collect(e){return this.visit(e),this.getCommonTables()}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}let n=e.getKind()?.toString()||"unknown",i=e.constructor?.name||"unknown";throw new Error(`[CTECollector] No handler for ${i} with kind ${n}.`)}visitSimpleSelectQuery(e){if(e.fromClause&&e.fromClause.accept(this),e.whereClause&&e.whereClause.accept(this),e.groupByClause&&e.groupByClause.accept(this),e.havingClause&&e.havingClause.accept(this),e.orderByClause&&e.orderByClause.accept(this),e.windowClause)for(let t of e.windowClause.windows)t.accept(this);e.limitClause&&e.limitClause.accept(this),e.forClause&&e.forClause.accept(this),e.selectClause.accept(this),e.withClause&&e.withClause.accept(this)}visitBinarySelectQuery(e){e.left.accept(this),e.right.accept(this)}visitValuesQuery(e){for(let t of e.tuples)t.accept(this)}visitWithClause(e){for(let t=0;t<e.tables.length;t++)e.tables[t].accept(this)}visitCommonTable(e){e.query.accept(this),this.commonTables.push(e)}visitSelectClause(e){for(let t of e.items)t.accept(this)}visitSelectItem(e){e.value.accept(this)}visitFromClause(e){if(e.source.accept(this),e.joins)for(let t of e.joins)t.accept(this)}visitSourceExpression(e){e.datasource.accept(this)}visitTableSource(e){}visitFunctionSource(e){e.argument&&e.argument.accept(this)}visitParenSource(e){e.source.accept(this)}visitSubQuerySource(e){e.query.accept(this)}visitInlineQuery(e){e.selectQuery.accept(this)}visitJoinClause(e){e.source.accept(this),e.condition&&e.condition.accept(this)}visitJoinOnClause(e){e.condition.accept(this)}visitJoinUsingClause(e){e.condition.accept(this)}visitWhereClause(e){e.condition.accept(this)}visitGroupByClause(e){for(let t of e.grouping)t.accept(this)}visitHavingClause(e){e.condition.accept(this)}visitOrderByClause(e){for(let t of e.order)t.accept(this)}visitWindowFrameClause(e){e.expression.accept(this)}visitLimitClause(e){e.value.accept(this)}visitForClause(e){}visitOrderByItem(e){e.value.accept(this)}visitParenExpression(e){e.expression.accept(this)}visitBinaryExpression(e){e.left.accept(this),e.right.accept(this)}visitUnaryExpression(e){e.expression.accept(this)}visitCaseExpression(e){e.condition&&e.condition.accept(this),e.switchCase.accept(this)}visitSwitchCaseArgument(e){for(let t of e.cases)t.accept(this);e.elseValue&&e.elseValue.accept(this)}visitCaseKeyValuePair(e){e.key.accept(this),e.value.accept(this)}visitBetweenExpression(e){e.expression.accept(this),e.lower.accept(this),e.upper.accept(this)}visitFunctionCall(e){e.argument&&e.argument.accept(this),e.over&&e.over.accept(this)}visitArrayExpression(e){e.expression.accept(this)}visitArrayQueryExpression(e){e.query.accept(this)}visitTupleExpression(e){for(let t of e.values)t.accept(this)}visitCastExpression(e){e.input.accept(this),e.castType.accept(this)}visitTypeValue(e){e.argument&&e.argument.accept(this)}visitWindowFrameExpression(e){e.partition&&e.partition.accept(this),e.order&&e.order.accept(this),e.frameSpec&&e.frameSpec.accept(this)}visitWindowFrameSpec(e){}visitIdentifierString(e){}visitRawString(e){}visitColumnReference(e){}visitParameterExpression(e){}visitLiteralValue(e){}visitPartitionByClause(e){}visitValueList(e){for(let t of e.values)t.accept(this)}};var Xe=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(E.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(R.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(z.kind,e=>this.visitValuesQuery(e)),this.handlers.set(F.kind,e=>this.visitSelectItem(e)),this.handlers.set(C.kind,e=>this.visitIdentifierString(e)),this.handlers.set(g.kind,e=>this.visitRawString(e)),this.handlers.set(f.kind,e=>this.visitColumnReference(e)),this.handlers.set(A.kind,e=>this.visitParameterExpression(e)),this.handlers.set(V.kind,e=>this.visitLiteralValue(e)),this.handlers.set(k.kind,e=>this.visitSourceExpression(e)),this.handlers.set(I.kind,e=>this.visitTableSource(e)),this.handlers.set(ge.kind,e=>this.visitParenSource(e)),this.handlers.set(N.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(fe.kind,e=>this.visitInlineQuery(e)),this.handlers.set(P.kind,e=>this.visitFromClause(e)),this.handlers.set(Z.kind,e=>this.visitJoinClause(e)),this.handlers.set(X.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(ce.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(J.kind,e=>this.visitWhereClause(e)),this.handlers.set(H.kind,e=>this.visitParenExpression(e)),this.handlers.set(b.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(D.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(_.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ie.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(ne.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ae.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(L.kind,e=>this.visitFunctionCall(e)),this.handlers.set(re.kind,e=>this.visitArrayExpression(e)),this.handlers.set(oe.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(le.kind,e=>this.visitTupleExpression(e)),this.handlers.set(se.kind,e=>this.visitCastExpression(e)),this.handlers.set(we.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Ee.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Se.kind,e=>this.visitTypeValue(e)),this.handlers.set(O.kind,e=>this.visitSelectClause(e)),this.handlers.set(G.kind,e=>this.visitGroupByClause(e)),this.handlers.set(Y.kind,e=>this.visitHavingClause(e)),this.handlers.set(ue.kind,e=>this.visitOrderByClause(e)),this.handlers.set(te.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(ee.kind,e=>this.visitLimitClause(e)),this.handlers.set(ye.kind,e=>this.visitForClause(e)),this.handlers.set(ve.kind,e=>this.visitOrderByItem(e))}reset(){this.visitedNodes.clear()}execute(e){return this.reset(),this.visit(e)}visit(e){if(!this.isRootVisit)return this.visitNode(e);this.reset(),this.isRootVisit=!1;try{return this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return e;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t)return t(e);let n=e.getKind()?.toString()||"unknown",i=e.constructor?.name||"unknown";throw new Error(`[CTEDisabler] No handler for ${i} with kind ${n}.`)}visitSimpleSelectQuery(e){return e.withClause&&e.withClause.tables.forEach(t=>{this.visit(t.query)}),e.withClause=null,e.selectClause=this.visit(e.selectClause),e.fromClause=e.fromClause?this.visit(e.fromClause):null,e.whereClause=e.whereClause?this.visit(e.whereClause):null,e.groupByClause=e.groupByClause?this.visit(e.groupByClause):null,e.havingClause=e.havingClause?this.visit(e.havingClause):null,e.orderByClause=e.orderByClause?this.visit(e.orderByClause):null,e.windowClause&&(e.windowClause=new Qe(e.windowClause.windows.map(t=>this.visit(t)))),e.limitClause=e.limitClause?this.visit(e.limitClause):null,e.forClause=e.forClause?this.visit(e.forClause):null,e}visitBinarySelectQuery(e){return e.left=this.visit(e.left),e.right=this.visit(e.right),e}visitValuesQuery(e){let t=e.tuples.map(n=>this.visit(n));return new z(t)}visitSelectClause(e){let t=e.items.map(n=>this.visit(n));return new O(t,e.distinct)}visitFromClause(e){let t=this.visit(e.source),n=e.joins?e.joins.map(i=>this.visit(i)):null;return new P(t,n)}visitSubQuerySource(e){let t=this.visit(e.query);return new N(t)}visitInlineQuery(e){let t=this.visit(e.selectQuery);return new fe(t)}visitJoinClause(e){let t=this.visit(e.source),n=e.condition?this.visit(e.condition):null;return new Z(e.joinType.value,t,n,e.lateral)}visitJoinOnClause(e){let t=this.visit(e.condition);return new X(t)}visitJoinUsingClause(e){let t=this.visit(e.condition);return new ce(t)}visitWhereClause(e){let t=this.visit(e.condition);return new J(t)}visitGroupByClause(e){let t=e.grouping.map(n=>this.visit(n));return new G(t)}visitHavingClause(e){let t=this.visit(e.condition);return new Y(t)}visitOrderByClause(e){let t=e.order.map(n=>this.visit(n));return new ue(t)}visitWindowFrameClause(e){let t=this.visit(e.expression);return new te(e.name.name,t)}visitLimitClause(e){let t=this.visit(e.value);return new ee(t)}visitForClause(e){return new ye(e.lockMode)}visitParenExpression(e){let t=this.visit(e.expression);return new H(t)}visitBinaryExpression(e){let t=this.visit(e.left),n=this.visit(e.right);return new b(t,e.operator.value,n)}visitUnaryExpression(e){let t=this.visit(e.expression);return new D(e.operator.value,t)}visitCaseExpression(e){let t=e.condition?this.visit(e.condition):null,n=this.visit(e.switchCase);return new _(t,n)}visitSwitchCaseArgument(e){let t=e.cases.map(i=>this.visit(i)),n=e.elseValue?this.visit(e.elseValue):null;return new ne(t,n)}visitCaseKeyValuePair(e){let t=this.visit(e.key),n=this.visit(e.value);return new ie(t,n)}visitBetweenExpression(e){let t=this.visit(e.expression),n=this.visit(e.lower),i=this.visit(e.upper);return new ae(t,n,i,e.negated)}visitFunctionCall(e){let t=e.argument?this.visit(e.argument):null,n=e.over?this.visit(e.over):null;return new L(e.namespaces,e.name,t,n)}visitArrayExpression(e){let t=this.visit(e.expression);return new re(t)}visitArrayQueryExpression(e){let t=this.visit(e.query);return new oe(t)}visitTupleExpression(e){let t=e.values.map(n=>this.visit(n));return new le(t)}visitCastExpression(e){let t=this.visit(e.input),n=this.visit(e.castType);return new se(t,n)}visitTypeValue(e){let t=e.argument?this.visit(e.argument):null;return new Se(e.namespaces,e.name,t)}visitSelectItem(e){let t=this.visit(e.value);return new F(t,e.identifier?.name)}visitIdentifierString(e){return e}visitRawString(e){return e}visitColumnReference(e){return e}visitSourceExpression(e){let t=this.visit(e.datasource),n=e.aliasExpression;return new k(t,n)}visitTableSource(e){return e}visitParenSource(e){let t=this.visit(e.source);return new ge(t)}visitParameterExpression(e){return e}visitWindowFrameExpression(e){let t=e.partition?this.visit(e.partition):null,n=e.order?this.visit(e.order):null,i=e.frameSpec?this.visit(e.frameSpec):null;return new we(t,n,i)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new ve(t,e.sortDirection,e.nullsPosition)}};var Nt=class{constructor(e=!0){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.cteNames=new Set;this.isRootVisit=!0;this.selectableOnly=e,this.handlers=new Map,this.handlers.set(E.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(R.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(z.kind,t=>this.visitValuesQuery(t)),this.handlers.set(U.kind,t=>this.visitWithClause(t)),this.handlers.set(K.kind,t=>this.visitCommonTable(t)),this.handlers.set(P.kind,t=>this.visitFromClause(t)),this.handlers.set(Z.kind,t=>this.visitJoinClause(t)),this.handlers.set(X.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(ce.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(k.kind,t=>this.visitSourceExpression(t)),this.handlers.set(I.kind,t=>this.visitTableSource(t)),this.handlers.set(Ie.kind,t=>this.visitFunctionSource(t)),this.handlers.set(ge.kind,t=>this.visitParenSource(t)),this.handlers.set(N.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(fe.kind,t=>this.visitInlineQuery(t)),e||(this.handlers.set(J.kind,t=>this.visitWhereClause(t)),this.handlers.set(G.kind,t=>this.visitGroupByClause(t)),this.handlers.set(Y.kind,t=>this.visitHavingClause(t)),this.handlers.set(ue.kind,t=>this.visitOrderByClause(t)),this.handlers.set(te.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(ee.kind,t=>this.visitLimitClause(t)),this.handlers.set(Pe.kind,t=>this.visitOffsetClause(t)),this.handlers.set(Fe.kind,t=>this.visitFetchClause(t)),this.handlers.set(ye.kind,t=>this.visitForClause(t)),this.handlers.set(ve.kind,t=>this.visitOrderByItem(t)),this.handlers.set(O.kind,t=>this.visitSelectClause(t)),this.handlers.set(F.kind,t=>this.visitSelectItem(t)),this.handlers.set(H.kind,t=>this.visitParenExpression(t)),this.handlers.set(b.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(D.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(_.kind,t=>this.visitCaseExpression(t)),this.handlers.set(ie.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(ne.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(ae.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(L.kind,t=>this.visitFunctionCall(t)),this.handlers.set(re.kind,t=>this.visitArrayExpression(t)),this.handlers.set(oe.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(le.kind,t=>this.visitTupleExpression(t)),this.handlers.set(se.kind,t=>this.visitCastExpression(t)),this.handlers.set(Q.kind,t=>this.visitValueList(t)))}getTableSources(){return this.tableSources}reset(){this.tableSources=[],this.tableNameMap.clear(),this.visitedNodes.clear(),this.cteNames.clear()}getTableIdentifier(e){return e.qualifiedName.namespaces&&e.qualifiedName.namespaces.length>0?e.qualifiedName.namespaces.map(t=>t.name).join(".")+"."+(e.qualifiedName.name instanceof g?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof g?e.qualifiedName.name.value:e.qualifiedName.name.name}collect(e){return this.visit(e),this.getTableSources()}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.selectableOnly||this.collectCTEs(e),this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}collectCTEs(e){let t=new q;t.visit(e);let n=t.getCommonTables();for(let i of n)this.cteNames.add(i.aliasExpression.table.name)}visitSimpleSelectQuery(e){if(e.fromClause&&e.fromClause.accept(this),!this.selectableOnly){if(e.withClause&&e.withClause.accept(this),e.whereClause&&e.whereClause.accept(this),e.groupByClause&&e.groupByClause.accept(this),e.havingClause&&e.havingClause.accept(this),e.orderByClause&&e.orderByClause.accept(this),e.windowClause)for(let t of e.windowClause.windows)t.accept(this);e.limitClause&&e.limitClause.accept(this),e.offsetClause&&e.offsetClause.accept(this),e.fetchClause&&e.fetchClause.accept(this),e.forClause&&e.forClause.accept(this),e.selectClause.accept(this)}}visitBinarySelectQuery(e){e.left.accept(this),e.right.accept(this)}visitValuesQuery(e){if(!this.selectableOnly)for(let t of e.tuples)t.accept(this)}visitWithClause(e){if(!this.selectableOnly)for(let t of e.tables)t.accept(this)}visitCommonTable(e){this.selectableOnly||e.query.accept(this)}visitFromClause(e){if(e.source.accept(this),e.joins)for(let t of e.joins)t.accept(this)}visitSourceExpression(e){e.datasource.accept(this)}visitTableSource(e){let t=this.getTableIdentifier(e);!this.tableNameMap.has(t)&&!this.isCTETable(e.table.name)&&(this.tableNameMap.set(t,!0),this.tableSources.push(e))}visitFunctionSource(e){e.argument&&this.visitValueComponent(e.argument)}visitValueComponent(e){e.accept(this)}isCTETable(e){return this.cteNames.has(e)}visitParenSource(e){e.source.accept(this)}visitSubQuerySource(e){this.selectableOnly||e.query.accept(this)}visitInlineQuery(e){this.selectableOnly||e.selectQuery.accept(this)}visitJoinClause(e){e.source.accept(this),!this.selectableOnly&&e.condition&&e.condition.accept(this)}visitJoinOnClause(e){this.selectableOnly||e.condition.accept(this)}visitJoinUsingClause(e){this.selectableOnly||e.condition.accept(this)}visitWhereClause(e){e.condition.accept(this)}visitGroupByClause(e){for(let t of e.grouping)t.accept(this)}visitHavingClause(e){e.condition.accept(this)}visitOrderByClause(e){for(let t of e.order)t.accept(this)}visitWindowFrameClause(e){e.expression.accept(this)}visitLimitClause(e){e.value.accept(this)}visitOffsetClause(e){e.value.accept(this)}visitFetchClause(e){e.expression.accept(this)}visitForClause(e){}visitOrderByItem(e){e.value.accept(this)}visitSelectClause(e){for(let t of e.items)t.accept(this)}visitSelectItem(e){e.value.accept(this)}visitParenExpression(e){e.expression.accept(this)}visitBinaryExpression(e){e.left.accept(this),e.right.accept(this)}visitUnaryExpression(e){e.expression.accept(this)}visitCaseExpression(e){e.condition&&e.condition.accept(this),e.switchCase.accept(this)}visitSwitchCaseArgument(e){for(let t of e.cases)t.accept(this);e.elseValue&&e.elseValue.accept(this)}visitCaseKeyValuePair(e){e.key.accept(this),e.value.accept(this)}visitBetweenExpression(e){e.expression.accept(this),e.lower.accept(this),e.upper.accept(this)}visitFunctionCall(e){e.argument&&e.argument.accept(this),e.over&&e.over.accept(this)}visitArrayExpression(e){e.expression.accept(this)}visitArrayQueryExpression(e){e.query.accept(this)}visitTupleExpression(e){for(let t of e.values)t.accept(this)}visitCastExpression(e){e.input.accept(this),e.castType.accept(this)}visitValueList(e){for(let t of e.values)t.accept(this)}};var p=class{constructor(e,t="",n=""){this.innerTokens=[];this.type=e,this.text=t,this.containerType=n}};var Ze=class{static collect(e){let t=[];function n(i){if(!(!i||typeof i!="object")){i.constructor&&i.constructor.kind===A.kind&&t.push(i);for(let s of Object.keys(i)){let o=i[s];Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&o.constructor&&o.constructor.kind&&n(o)}}}return n(e),t}};var At=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var Qt=class{constructor(e){this.prefix=e?.prefix??":",this.suffix=e?.suffix??"",this.style=e?.style??"named"}decorate(e,t){let n="";return this.style==="anonymous"?n=this.prefix:this.style==="indexed"?n=this.prefix+t:this.style==="named"&&(n=this.prefix+e+this.suffix),e=n,e}};var et=class extends h{static{this.kind=Symbol("UpdateQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.updateClause=e.updateClause,this.setClause=e.setClause instanceof Ne?e.setClause:new Ne(e.setClause),this.whereClause=e.whereClause??null,this.fromClause=e.fromClause??null,this.returningClause=e.returning??null}};var de=class r{constructor(e=null,t=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=e??null,this.commonTableCollector=new q,this.commonTables=[],this.initialCommonTables=t,this.handlers=new Map,this.handlers.set(E.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(O.kind,n=>this.visitSelectClause(n)),this.handlers.set(k.kind,n=>this.visitSourceExpression(n)),this.handlers.set(P.kind,n=>this.visitFromClause(n))}getValues(){return this.selectValues}reset(){this.selectValues=[],this.visitedNodes.clear(),this.initialCommonTables?this.commonTables=this.initialCommonTables:this.commonTables=[]}collect(e){this.visit(e);let t=this.getValues();return this.reset(),t}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}visitSimpleSelectQuery(e){this.commonTables.length===0&&this.initialCommonTables===null&&(this.commonTables=this.commonTableCollector.collect(e)),e.selectClause&&e.selectClause.accept(this);let t=this.selectValues.filter(i=>i.name==="*");if(t.length===0)return;if(this.selectValues.some(i=>i.value instanceof f&&i.value.namespaces===null)){e.fromClause&&this.processFromClause(e.fromClause,!0),this.selectValues=this.selectValues.filter(i=>i.name!=="*");return}let n=t.filter(i=>i.value instanceof f&&i.value.namespaces).map(i=>i.value.getNamespace());if(e.fromClause){let i=e.fromClause.getSourceAliasName();if(i&&n.includes(i)&&this.processFromClause(e.fromClause,!1),e.fromClause.joins)for(let s of e.fromClause.joins){let o=s.getSourceAliasName();o&&n.includes(o)&&this.processJoinClause(s)}}this.selectValues=this.selectValues.filter(i=>i.name!=="*")}processFromClause(e,t){if(e){let n=e.getSourceAliasName();if(this.processSourceExpression(n,e.source),e.joins&&t)for(let i of e.joins)this.processJoinClause(i)}}processJoinClause(e){let t=e.getSourceAliasName();this.processSourceExpression(t,e.source)}processSourceExpression(e,t){let n=this.commonTables.find(i=>i.aliasExpression.table.name===e);if(n){let i=this.commonTables.filter(a=>a.aliasExpression.table.name!==e);new r(this.tableColumnResolver,i).collect(n.query).forEach(a=>{this.addSelectValueAsUnique(a.name,new f(e?[e]:null,a.name))})}else new r(this.tableColumnResolver,this.commonTables).collect(t).forEach(o=>{this.addSelectValueAsUnique(o.name,new f(e?[e]:null,o.name))})}visitSelectClause(e){for(let t of e.items)this.processSelectItem(t)}processSelectItem(e){if(e.identifier)this.addSelectValueAsUnique(e.identifier.name,e.value);else if(e.value instanceof f){let t=e.value.column.name;t==="*"?this.selectValues.push({name:t,value:e.value}):this.addSelectValueAsUnique(t,e.value)}}visitSourceExpression(e){if(e.aliasExpression&&e.aliasExpression.columns){let t=e.getAliasName();e.aliasExpression.columns.forEach(n=>{this.addSelectValueAsUnique(n.name,new f(t?[t]:null,n.name))});return}else if(e.datasource instanceof I){if(this.tableColumnResolver){let t=e.datasource.getSourceName();this.tableColumnResolver(t).forEach(n=>{this.addSelectValueAsUnique(n,new f([t],n))})}return}else if(e.datasource instanceof N){let t=e.getAliasName();new r(this.tableColumnResolver,this.commonTables).collect(e.datasource.query).forEach(s=>{this.addSelectValueAsUnique(s.name,new f(t?[t]:null,s.name))});return}else if(e.datasource instanceof ge)return this.visit(e.datasource.source)}visitFromClause(e){e&&this.processFromClause(e,!0)}addSelectValueAsUnique(e,t){this.selectValues.some(n=>n.name===e)||this.selectValues.push({name:e,value:t})}};var tt=class extends h{static{this.kind=Symbol("CreateTableQuery")}constructor(e){super(),this.tableName=new C(e.tableName),this.isTemporary=e.isTemporary??!1,this.asSelectQuery=e.asSelectQuery}getSelectQuery(){let e;return this.asSelectQuery?e=new de().collect(this.asSelectQuery).map(i=>new F(i.value,i.name)):e=[new F(new g("*"))],new E({selectClause:new O(e),fromClause:new P(new k(new I(null,this.tableName.name),null),null)})}getCountQuery(){return new E({selectClause:new O([new F(new L(null,"count",new f(null,"*"),null))]),fromClause:new P(new k(new I(null,this.tableName.name),null),null)})}};var mn={mysql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},postgres:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed"},postgresWithNamedParams:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"},sqlserver:{identifierEscape:{start:"[",end:"]"},parameterSymbol:"@",parameterStyle:"named"},sqlite:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"},oracle:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"},clickhouse:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},firebird:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},db2:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},snowflake:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},cloudspanner:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"@",parameterStyle:"named"},duckdb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},cockroachdb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed"},athena:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},bigquery:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"@",parameterStyle:"named"},hive:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},mariadb:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},redshift:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed"},flinksql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},mongodb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"}},Vt=class r{constructor(e){this.handlers=new Map;this.index=1;e?.preset&&(e={...e.preset,...e}),this.parameterDecorator=new Qt({prefix:typeof e?.parameterSymbol=="string"?e.parameterSymbol:e?.parameterSymbol?.start??":",suffix:typeof e?.parameterSymbol=="object"?e.parameterSymbol.end:"",style:e?.parameterStyle??"named"}),this.identifierDecorator=new At({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.handlers.set(Q.kind,t=>this.visitValueList(t)),this.handlers.set(f.kind,t=>this.visitColumnReference(t)),this.handlers.set(Ce.kind,t=>this.visitQualifiedName(t)),this.handlers.set(L.kind,t=>this.visitFunctionCall(t)),this.handlers.set(D.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(b.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(V.kind,t=>this.visitLiteralValue(t)),this.handlers.set(A.kind,t=>this.visitParameterExpression(t)),this.handlers.set(ne.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(ie.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(g.kind,t=>this.visitRawString(t)),this.handlers.set(C.kind,t=>this.visitIdentifierString(t)),this.handlers.set(H.kind,t=>this.visitParenExpression(t)),this.handlers.set(se.kind,t=>this.visitCastExpression(t)),this.handlers.set(_.kind,t=>this.visitCaseExpression(t)),this.handlers.set(re.kind,t=>this.visitArrayExpression(t)),this.handlers.set(oe.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(ae.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(Je.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(Se.kind,t=>this.visitTypeValue(t)),this.handlers.set(le.kind,t=>this.visitTupleExpression(t)),this.handlers.set(fe.kind,t=>this.visitInlineQuery(t)),this.handlers.set(we.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(Ee.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(qe.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(De.kind,t=>this.visitWindowFrameBoundaryValue(t)),this.handlers.set(be.kind,t=>this.visitPartitionByClause(t)),this.handlers.set(ue.kind,t=>this.visitOrderByClause(t)),this.handlers.set(ve.kind,t=>this.visitOrderByItem(t)),this.handlers.set(F.kind,t=>this.visitSelectItem(t)),this.handlers.set(O.kind,t=>this.visitSelectClause(t)),this.handlers.set(Me.kind,t=>this.visitDistinct(t)),this.handlers.set(ze.kind,t=>this.visitDistinctOn(t)),this.handlers.set(I.kind,t=>this.visitTableSource(t)),this.handlers.set(Ie.kind,t=>this.visitFunctionSource(t)),this.handlers.set(k.kind,t=>this.visitSourceExpression(t)),this.handlers.set(W.kind,t=>this.visitSourceAliasExpression(t)),this.handlers.set(P.kind,t=>this.visitFromClause(t)),this.handlers.set(Z.kind,t=>this.visitJoinClause(t)),this.handlers.set(X.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(ce.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(J.kind,t=>this.visitWhereClause(t)),this.handlers.set(G.kind,t=>this.visitGroupByClause(t)),this.handlers.set(Y.kind,t=>this.visitHavingClause(t)),this.handlers.set(Qe.kind,t=>this.visitWindowClause(t)),this.handlers.set(te.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(ee.kind,t=>this.visitLimitClause(t)),this.handlers.set(Pe.kind,t=>this.visitOffsetClause(t)),this.handlers.set(Fe.kind,t=>this.visitFetchClause(t)),this.handlers.set(Ke.kind,t=>this.visitFetchExpression(t)),this.handlers.set(ye.kind,t=>this.visitForClause(t)),this.handlers.set(U.kind,t=>this.visitWithClause(t)),this.handlers.set(K.kind,t=>this.visitCommonTable(t)),this.handlers.set(E.kind,t=>this.visitSimpleQuery(t)),this.handlers.set(N.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(R.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(z.kind,t=>this.visitValuesQuery(t)),this.handlers.set(le.kind,t=>this.visitTupleExpression(t)),this.handlers.set(Le.kind,t=>this.visitInsertQuery(t)),this.handlers.set(Be.kind,t=>this.visitInsertClause(t)),this.handlers.set(et.kind,t=>this.visitUpdateQuery(t)),this.handlers.set(_e.kind,t=>this.visitUpdateClause(t)),this.handlers.set(Ne.kind,t=>this.visitSetClause(t)),this.handlers.set(Ve.kind,t=>this.visitSetClauseItem(t)),this.handlers.set(mt.kind,t=>this.visitReturningClause(t)),this.handlers.set(tt.kind,t=>this.visitCreateTableQuery(t))}static{this.SPACE_TOKEN=new p(10," ")}static{this.COMMA_TOKEN=new p(3,",")}static{this.ARGUMENT_SPLIT_COMMA_TOKEN=new p(11,",")}static{this.PAREN_OPEN_TOKEN=new p(4,"(")}static{this.PAREN_CLOSE_TOKEN=new p(4,")")}static{this.DOT_TOKEN=new p(8,".")}visitBinarySelectQuery(e){let t=new p(0,"");return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,e.operator.value,"BinarySelectQueryOperator")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}static commaSpaceTokens(){return[r.COMMA_TOKEN,r.SPACE_TOKEN]}static argumentCommaSpaceTokens(){return[r.ARGUMENT_SPLIT_COMMA_TOKEN,r.SPACE_TOKEN]}visitQualifiedName(e){let t=new p(0,"","QualifiedName");if(e.namespaces)for(let n=0;n<e.namespaces.length;n++)t.innerTokens.push(e.namespaces[n].accept(this)),t.innerTokens.push(r.DOT_TOKEN);return t.innerTokens.push(e.name.accept(this)),t}visitPartitionByClause(e){let t=new p(1,"partition by","PartitionByClause");return t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOrderByClause(e){let t=new p(1,"order by","OrderByClause");t.innerTokens.push(r.SPACE_TOKEN);for(let n=0;n<e.order.length;n++)n>0&&t.innerTokens.push(...r.commaSpaceTokens()),t.innerTokens.push(this.visit(e.order[n]));return t}visitOrderByItem(e){let t=new p(0,"","OrderByItem");return t.innerTokens.push(this.visit(e.value)),e.sortDirection&&e.sortDirection!=="asc"&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"desc"))),e.nullsPosition&&(e.nullsPosition==="first"?(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"nulls first"))):e.nullsPosition==="last"&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"nulls last")))),t}parse(e){this.index=1;let t=this.visit(e),n=Ze.collect(e).sort((s,o)=>(s.index??0)-(o.index??0)),i=this.parameterDecorator.style;if(i==="named"){let s={};for(let o of n){let a=o.name.value;if(s.hasOwnProperty(a)){if(s[a]!==o.value)throw new Error(`Duplicate parameter name '${a}' with different values detected during query composition.`);continue}s[a]=o.value}return{token:t,params:s}}else if(i==="indexed"){let s=n.map(o=>o.value);return{token:t,params:s}}else if(i==="anonymous"){let s=n.map(o=>o.value);return{token:t,params:s}}return{token:t,params:[]}}visit(e){let t=this.handlers.get(e.getKind());if(t)return t(e);throw new Error(`[SqlPrintTokenParser] No handler for kind: ${e.getKind().toString()}`)}visitValueList(e){let t=new p(0,"","ValueList");for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...r.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t}visitColumnReference(e){let t=new p(0,"","ColumnReference");return t.innerTokens.push(e.qualifiedName.accept(this)),t}visitFunctionCall(e){let t=new p(0,"","FunctionCall");return t.innerTokens.push(e.qualifiedName.accept(this)),t.innerTokens.push(r.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(r.PAREN_CLOSE_TOKEN),e.over&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"over")),e.over instanceof C?(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.over.accept(this))):(t.innerTokens.push(r.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.over)),t.innerTokens.push(r.PAREN_CLOSE_TOKEN))),t}visitUnaryExpression(e){let t=new p(0,"","UnaryExpression");return t.innerTokens.push(this.visit(e.operator)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.expression)),t}visitBinaryExpression(e){let t=new p(0,"","BinaryExpression");return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(5,e.operator.value)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}visitLiteralValue(e){let t;return typeof e.value=="string"?t=`'${e.value.replace(/'/g,"''")}'`:e.value===null?t="null":t=e.value.toString(),new p(2,t,"LiteralValue")}visitParameterExpression(e){e.index=this.index;let t=this.parameterDecorator.decorate(e.name.value,e.index),n=new p(7,t);return this.index++,n}visitSwitchCaseArgument(e){let t=new p(0,"","SwitchCaseArgument");for(let n of e.cases)t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(n.accept(this));return e.elseValue&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.createElseToken(e.elseValue))),t}createElseToken(e){let t=new p(0,"","ElseClause");t.innerTokens.push(new p(1,"else")),t.innerTokens.push(r.SPACE_TOKEN);let n=new p(0,"","CaseElseValue");return n.innerTokens.push(this.visit(e)),t.innerTokens.push(n),t}visitCaseKeyValuePair(e){let t=new p(0,"","CaseKeyValuePair");t.innerTokens.push(new p(1,"when")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.key)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"then")),t.innerTokens.push(r.SPACE_TOKEN);let n=new p(0,"","CaseThenValue");return n.innerTokens.push(this.visit(e.value)),t.innerTokens.push(n),t}visitRawString(e){return new p(2,e.value,"RawString")}visitIdentifierString(e){let t=e.name==="*"?e.name:this.identifierDecorator.decorate(e.name);return new p(2,t,"IdentifierString")}visitParenExpression(e){let t=new p(0,"","ParenExpression");return t.innerTokens.push(r.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(r.PAREN_CLOSE_TOKEN),t}visitCastExpression(e){let t=new p(0,"","CastExpression");return t.innerTokens.push(this.visit(e.input)),t.innerTokens.push(new p(5,"::")),t.innerTokens.push(this.visit(e.castType)),t}visitCaseExpression(e){let t=new p(0,"","CaseExpression");return t.innerTokens.push(new p(1,"case")),e.condition&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition))),t.innerTokens.push(this.visit(e.switchCase)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"end")),t}visitArrayExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(new p(1,"array")),t.innerTokens.push(new p(4,"[")),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(new p(4,"]")),t}visitArrayQueryExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(new p(1,"array")),t.innerTokens.push(new p(4,"(")),t.innerTokens.push(this.visit(e.query)),t.innerTokens.push(new p(4,")")),t}visitBetweenExpression(e){let t=new p(0,"","BetweenExpression");return t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(r.SPACE_TOKEN),e.negated&&(t.innerTokens.push(new p(1,"not")),t.innerTokens.push(r.SPACE_TOKEN)),t.innerTokens.push(new p(1,"between")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.lower)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"and")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.upper)),t}visitStringSpecifierExpression(e){let t=e.specifier.accept(this).text,n=e.value.accept(this).text;return new p(2,t+n,"StringSpecifierExpression")}visitTypeValue(e){let t=new p(0,"","TypeValue");return t.innerTokens.push(e.qualifiedName.accept(this)),e.argument&&(t.innerTokens.push(r.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(r.PAREN_CLOSE_TOKEN)),t}visitTupleExpression(e){let t=new p(0,"","TupleExpression");t.innerTokens.push(r.PAREN_OPEN_TOKEN);for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...r.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t.innerTokens.push(r.PAREN_CLOSE_TOKEN),t}visitWindowFrameExpression(e){let t=new p(0,"","WindowFrameExpression"),n=!0;return e.partition&&(t.innerTokens.push(this.visit(e.partition)),n=!1),e.order&&(n?n=!1:t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.order))),e.frameSpec&&(n?n=!1:t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.frameSpec))),t}visitWindowFrameSpec(e){let t=new p(0,"","WindowFrameSpec");return t.innerTokens.push(new p(1,e.frameType)),e.endBound===null?(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this))):(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"between")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"and")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.endBound.accept(this))),t}visitWindowFrameBoundaryValue(e){let t=new p(0,"","WindowFrameBoundaryValue");return t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,e.isFollowing?"following":"preceding")),t}visitWindowFrameBoundStatic(e){return new p(1,e.bound)}visitSelectItem(e){let t=new p(0,"","SelectItem");if(t.innerTokens.push(this.visit(e.value)),!e.identifier)return t;if(e.value instanceof f){let n=e.value.column.name;if(e.identifier.name===n)return t}return t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.identifier)),t}visitSelectClause(e){let t=new p(1,"select","SelectClause");t.innerTokens.push(r.SPACE_TOKEN),e.distinct&&(t.keywordTokens=[],t.keywordTokens.push(r.SPACE_TOKEN),t.keywordTokens.push(e.distinct.accept(this)));for(let n=0;n<e.items.length;n++)n>0&&t.innerTokens.push(...r.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[n]));return t}visitDistinct(e){return new p(1,"distinct")}visitDistinctOn(e){let t=new p(0,"","DistinctOn");return t.innerTokens.push(new p(1,"distinct on")),t.innerTokens.push(r.PAREN_OPEN_TOKEN),t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(r.PAREN_CLOSE_TOKEN),t}visitTableSource(e){let t="";Array.isArray(e.namespaces)&&e.namespaces.length>0&&(t=e.namespaces.map(i=>i.accept(this).text).join(".")+"."),t+=e.table.accept(this).text;let n=new p(2,t);return e.identifier&&(e.identifier.name,e.table.name),n}visitSourceExpression(e){let t=new p(0,"","SourceExpression");if(t.innerTokens.push(e.datasource.accept(this)),!e.aliasExpression)return t;if(e.datasource instanceof I){let n=e.datasource.table.name;return e.aliasExpression.table.name===n||(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this))),t}else return t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this)),t}visitFromClause(e){let t=new p(1,"from","FromClause");if(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.joins)for(let n=0;n<e.joins.length;n++)t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.joins[n]));return t}visitJoinClause(e){let t=new p(0,"","JoinClause");return t.innerTokens.push(new p(1,e.joinType.value)),e.lateral&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"lateral"))),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.condition&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition))),t}visitJoinOnClause(e){let t=new p(0,"","JoinOnClause");return t.innerTokens.push(new p(1,"on")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitJoinUsingClause(e){let t=new p(0,"","JoinUsingClause");return t.innerTokens.push(new p(1,"using")),t.innerTokens.push(r.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.condition)),t.innerTokens.push(r.PAREN_CLOSE_TOKEN),t}visitFunctionSource(e){let t=new p(0,"","FunctionSource");return t.innerTokens.push(e.qualifiedName.accept(this)),t.innerTokens.push(r.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(r.PAREN_CLOSE_TOKEN),t}visitSourceAliasExpression(e){let t=new p(0,"","SourceAliasExpression");if(t.innerTokens.push(this.visit(e.table)),e.columns){t.innerTokens.push(r.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...r.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));t.innerTokens.push(r.PAREN_CLOSE_TOKEN)}return t}visitWhereClause(e){let t=new p(1,"where","WhereClause");return t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitGroupByClause(e){let t=new p(1,"group by","GroupByClause");t.innerTokens.push(r.SPACE_TOKEN);for(let n=0;n<e.grouping.length;n++)n>0&&t.innerTokens.push(...r.commaSpaceTokens()),t.innerTokens.push(this.visit(e.grouping[n]));return t}visitHavingClause(e){let t=new p(1,"having","HavingClause");return t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitWindowClause(e){let t=new p(1,"window","WindowClause");t.innerTokens.push(r.SPACE_TOKEN);for(let n=0;n<e.windows.length;n++)n>0&&t.innerTokens.push(...r.commaSpaceTokens()),t.innerTokens.push(this.visit(e.windows[n]));return t}visitWindowFrameClause(e){let t=new p(0,"","WindowFrameClause");return t.innerTokens.push(e.name.accept(this)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(r.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(r.PAREN_CLOSE_TOKEN),t}visitLimitClause(e){let t=new p(1,"limit","LimitClause");return t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOffsetClause(e){let t=new p(1,"offset","OffsetClause");return t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitFetchClause(e){let t=new p(1,"fetch","FetchClause");return t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.expression)),t}visitFetchExpression(e){let t=new p(0,"","FetchExpression");return t.innerTokens.push(new p(1,e.type)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.count.accept(this)),e.unit&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,e.unit))),t}visitForClause(e){let t=new p(1,"for","ForClause");return t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,e.lockMode)),t}visitWithClause(e){let t=new p(1,"with","WithClause");t.innerTokens.push(r.SPACE_TOKEN),e.recursive&&(t.innerTokens.push(new p(1,"recursive")),t.innerTokens.push(r.SPACE_TOKEN));for(let n=0;n<e.tables.length;n++)n>0&&t.innerTokens.push(...r.commaSpaceTokens()),t.innerTokens.push(e.tables[n].accept(this));return t.innerTokens.push(r.SPACE_TOKEN),t}visitCommonTable(e){let t=new p(0,"","CommonTable");t.innerTokens.push(e.aliasExpression.accept(this)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(r.SPACE_TOKEN),e.materialized!==null&&(e.materialized?t.innerTokens.push(new p(1,"materialized")):t.innerTokens.push(new p(1,"not materialized")),t.innerTokens.push(r.SPACE_TOKEN)),t.innerTokens.push(r.PAREN_OPEN_TOKEN);let n=new p(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(r.PAREN_CLOSE_TOKEN),t}visitSimpleQuery(e){let t=new p(0,"","SimpleSelectQuery");return e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(e.selectClause.accept(this)),e.fromClause&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this)),e.whereClause&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.groupByClause&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.groupByClause.accept(this))),e.havingClause&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.havingClause.accept(this))),e.orderByClause&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.orderByClause.accept(this))),e.windowClause&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.windowClause.accept(this))),e.limitClause&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.limitClause.accept(this))),e.offsetClause&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.offsetClause.accept(this))),e.fetchClause&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.fetchClause.accept(this))),e.forClause&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.forClause.accept(this)))),t}visitSubQuerySource(e){let t=new p(0,"");t.innerTokens.push(r.PAREN_OPEN_TOKEN);let n=new p(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(r.PAREN_CLOSE_TOKEN),t}visitValuesQuery(e){let t=new p(1,"values","ValuesQuery");t.innerTokens.push(r.SPACE_TOKEN);let n=new p(0,"","Values");for(let i=0;i<e.tuples.length;i++)i>0&&n.innerTokens.push(...r.commaSpaceTokens()),n.innerTokens.push(e.tuples[i].accept(this));return t.innerTokens.push(n),t}visitInlineQuery(e){let t=new p(0,"");t.innerTokens.push(r.PAREN_OPEN_TOKEN);let n=new p(0,"","InlineQuery");return n.innerTokens.push(e.selectQuery.accept(this)),t.innerTokens.push(n),t.innerTokens.push(r.PAREN_CLOSE_TOKEN),t}visitInsertQuery(e){let t=new p(0,"","InsertQuery");return t.innerTokens.push(this.visit(e.insertClause)),e.selectQuery&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(this.visit(e.selectQuery))),t}visitInsertClause(e){let t=new p(0,"");if(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"insert into")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),e.columns.length>0){t.innerTokens.push(r.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...r.commaSpaceTokens()),t.innerTokens.push(e.columns[n].accept(this));t.innerTokens.push(r.PAREN_CLOSE_TOKEN)}return t}visitUpdateQuery(e){let t=new p(0,"","UpdateQuery");return e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(e.updateClause.accept(this)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.setClause.accept(this)),e.fromClause&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this))),e.whereClause&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.returningClause&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.returningClause.accept(this))),t}visitUpdateClause(e){let t=new p(1,"update","UpdateClause");return t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t}visitSetClause(e){let t=new p(1,"set","SelectClause");t.innerTokens.push(r.SPACE_TOKEN);for(let n=0;n<e.items.length;n++)n>0&&t.innerTokens.push(...r.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[n]));return t}visitSetClauseItem(e){let t=new p(0,"","SetClauseItem");return t.innerTokens.push(e.column.accept(this)),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(5,"=")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.value.accept(this)),t}visitReturningClause(e){let t=new p(1,"returning","ReturningClause");t.innerTokens.push(r.SPACE_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...r.commaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));return t}visitCreateTableQuery(e){let t=new p(1,e.isTemporary?"create temporary table":"create table","CreateTableQuery");return t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.tableName.accept(this)),e.asSelectQuery&&(t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(r.SPACE_TOKEN),t.innerTokens.push(e.asSelectQuery.accept(this))),t}};var lt=class{constructor(e=" ",t=0,n=`\r
12
+ `){this.indentChar=e,this.indentSize=t,this.newline=n,this.lines=[],this.appendNewline(0)}print(){let e="";for(let t of this.lines)t.text!==""&&(e+=this.indent(t.level)+t.text);return e.trimEnd()}indent(e){return this.indentChar.repeat(this.indentSize*e)}appendNewline(e){if(this.lines.length>0){let t=this.lines[this.lines.length-1];t.text!==""&&(t.text=t.text.trimEnd()+this.newline)}this.lines.push(new an(e,""))}appendText(e){if(this.lines.length>0){let t=this.lines.length-1,n=this.lines[t];e===" "&&n.text===""||(n.text+=e)}else throw new Error("No tokens to append to.")}getCurrentLine(){if(this.lines.length>0)return this.lines[this.lines.length-1];throw new Error("No tokens to get current line from.")}},an=class{constructor(e,t){this.level=e,this.text=t}};var Bt=class{constructor(e){this.indentChar=e?.indentChar??"",this.indentSize=e?.indentSize??0,this.newline=e?.newline??" ",this.commaBreak=e?.commaBreak??"none",this.andBreak=e?.andBreak??"none",this.keywordCase=e?.keywordCase??"none",this.linePrinter=new lt(this.indentChar,this.indentSize,this.newline),this.indentIncrementContainers=new Set(e?.indentIncrementContainerTypes??["SelectClause","FromClause","WhereClause","GroupByClause","HavingClause","WindowFrameExpression","PartitionByClause","OrderByClause","WindowClause","LimitClause","OffsetClause","SubQuerySource","BinarySelectQueryOperator","Values","WithClause","SwitchCaseArgument","CaseKeyValuePair","CaseThenValue","ElseClause","CaseElseValue"])}print(e,t=0){return this.linePrinter=new lt(this.indentChar,this.indentSize,this.newline),this.linePrinter.lines.length>0&&t!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=t),this.appendToken(e,t),this.linePrinter.print()}appendToken(e,t){if((!e.innerTokens||e.innerTokens.length===0)&&e.text==="")return;let n=this.linePrinter.getCurrentLine();if(e.type===1){let s=e.text;this.keywordCase==="upper"?s=s.toUpperCase():this.keywordCase==="lower"&&(s=s.toLowerCase()),this.linePrinter.appendText(s)}else if(e.type===3){let s=e.text;this.commaBreak==="before"?(this.linePrinter.appendNewline(t),this.linePrinter.appendText(s)):this.commaBreak==="after"?(this.linePrinter.appendText(s),this.linePrinter.appendNewline(t)):this.linePrinter.appendText(s)}else if(e.type===5&&e.text.toLowerCase()==="and"){let s=e.text;this.keywordCase==="upper"?s=s.toUpperCase():this.keywordCase==="lower"&&(s=s.toLowerCase()),this.andBreak==="before"?(this.linePrinter.appendNewline(t),this.linePrinter.appendText(s)):this.andBreak==="after"?(this.linePrinter.appendText(s),this.linePrinter.appendNewline(t)):this.linePrinter.appendText(s)}else if(e.containerType==="JoinClause"){let s=e.text;this.keywordCase==="upper"?s=s.toUpperCase():this.keywordCase==="lower"&&(s=s.toLowerCase()),this.linePrinter.appendNewline(t),this.linePrinter.appendText(s)}else this.linePrinter.appendText(e.text);if(e.keywordTokens&&e.keywordTokens.length>0)for(let s=0;s<e.keywordTokens.length;s++){let o=e.keywordTokens[s];this.appendToken(o,t)}let i=t;this.newline!==" "&&n.text!==""&&this.indentIncrementContainers.has(e.containerType)&&(i++,this.linePrinter.appendNewline(i));for(let s=0;s<e.innerTokens.length;s++){let o=e.innerTokens[s];this.appendToken(o,i)}i!==t&&this.linePrinter.appendNewline(t)}};var ul=["mysql","postgres","sqlserver","sqlite"],nt=class{constructor(e={}){let t=e.preset?mn[e.preset]:void 0;if(e.preset&&!t)throw new Error(`Invalid preset: ${e.preset}`);let n={...t,identifierEscape:e.identifierEscape??t?.identifierEscape,parameterSymbol:e.parameterSymbol??t?.parameterSymbol,parameterStyle:e.parameterStyle??t?.parameterStyle};this.parser=new Vt(n),this.printer=new Bt(e)}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var Re=class{constructor(){this.sqlFormatter=new nt({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(e,t=null){return t&&(this.sqlFormatter=new nt(t)),this.sqlFormatter.format(e).formattedSql}formatWithParameters(e,t=null){t&&(this.sqlFormatter=new nt(t));let n=this.sqlFormatter.format(e);return{sql:n.formattedSql,params:n.params}}visit(e){return this.format(e)}};var Rt=class{constructor(){this.sourceCollector=new Nt(!0),this.cteCollector=new q,this.formatter=new Re}build(e){if(e.length===0)return new U(!1,e);let t=this.resolveDuplicateNames(e),{tableMap:n,recursiveCTEs:i,dependencies:s}=this.buildDependencyGraph(t),o=this.sortCommonTables(t,n,i,s);return new U(i.size>0,o)}resolveDuplicateNames(e){let t=new Map;for(let i of e){let s=i.aliasExpression.table.name;t.has(s)||t.set(s,[]),t.get(s).push(i)}let n=[];for(let[i,s]of t.entries()){if(s.length===1){n.push(s[0]);continue}let o=s.map(l=>this.formatter.format(l.query));if(new Set(o).size===1)n.push(s[0]);else throw new Error(`CTE name conflict detected: '${i}' has multiple different definitions`)}return n}buildDependencyGraph(e){let t=new Map;for(let o of e)t.set(o.aliasExpression.table.name,o);let n=new Set,i=new Map,s=new Map;for(let o of e){let a=o.aliasExpression.table.name,l=this.sourceCollector.collect(o.query);for(let c of l)if(c.table.name===a){n.add(a);break}i.has(a)||i.set(a,new Set);let u=this.cteCollector.collect(o.query);for(let c of u){let m=c.aliasExpression.table.name;t.has(m)&&(i.get(a).add(m),s.has(m)||s.set(m,new Set),s.get(m).add(a))}}return{tableMap:t,recursiveCTEs:n,dependencies:i}}sortCommonTables(e,t,n,i){let s=[],o=[],a=new Set,l=new Set,u=c=>{if(a.has(c))return;if(l.has(c))throw new Error(`Circular reference detected in CTE: ${c}`);l.add(c);let m=i.get(c)||new Set;for(let d of m)u(d);l.delete(c),a.add(c),n.has(c)?s.push(t.get(c)):o.push(t.get(c))};for(let c of e){let m=c.aliasExpression.table.name;a.has(m)||u(m)}return[...s,...o]}};var Wt=class{constructor(){this.nameConflictResolver=new Rt,this.cteCollector=new q}inject(e,t){if(t.length===0)return e;t.push(...this.cteCollector.collect(e));let n=this.nameConflictResolver.build(t);if(e instanceof E)return this.injectIntoSimpleQuery(e,n);if(e instanceof R)return this.injectIntoBinaryQuery(e,n);throw new Error("Unsupported query type")}injectIntoSimpleQuery(e,t){if(e.withClause)throw new Error("The query already has a WITH clause. Please remove it before injecting new CTEs.");return e.withClause=t,e}injectIntoBinaryQuery(e,t){if(e.left instanceof E)return this.injectIntoSimpleQuery(e.left,t),e;if(e.left instanceof R)return this.injectIntoBinaryQuery(e.left,t),e;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var Oe=class{constructor(){}static normalize(e){let n=new q().collect(e);return n.length===0?e:(new Xe().execute(e),new Wt().inject(e,n))}};var hn=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))(hn||{}),xe=class{constructor(e,t=!1,n="columnNameOnly",i){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=null;this.commonTables=[];this.tableColumnResolver=e??null,this.includeWildCard=t,this.commonTableCollector=new q,this.commonTables=[],this.duplicateDetection=n,this.options=i||{},this.handlers=new Map,this.handlers.set(E.kind,s=>this.visitSimpleSelectQuery(s)),this.handlers.set(O.kind,s=>this.visitSelectClause(s)),this.handlers.set(P.kind,s=>this.visitFromClause(s)),this.handlers.set(J.kind,s=>this.visitWhereClause(s)),this.handlers.set(G.kind,s=>this.visitGroupByClause(s)),this.handlers.set(Y.kind,s=>this.visitHavingClause(s)),this.handlers.set(ue.kind,s=>this.visitOrderByClause(s)),this.handlers.set(te.kind,s=>this.visitWindowFrameClause(s)),this.handlers.set(ee.kind,s=>this.visitLimitClause(s)),this.handlers.set(Pe.kind,s=>this.offsetClause(s)),this.handlers.set(Fe.kind,s=>this.visitFetchClause(s)),this.handlers.set(X.kind,s=>this.visitJoinOnClause(s)),this.handlers.set(ce.kind,s=>this.visitJoinUsingClause(s)),this.handlers.set(f.kind,s=>this.visitColumnReference(s)),this.handlers.set(b.kind,s=>this.visitBinaryExpression(s)),this.handlers.set(D.kind,s=>this.visitUnaryExpression(s)),this.handlers.set(L.kind,s=>this.visitFunctionCall(s)),this.handlers.set(H.kind,s=>this.visitParenExpression(s)),this.handlers.set(_.kind,s=>this.visitCaseExpression(s)),this.handlers.set(se.kind,s=>this.visitCastExpression(s)),this.handlers.set(ae.kind,s=>this.visitBetweenExpression(s)),this.handlers.set(re.kind,s=>this.visitArrayExpression(s)),this.handlers.set(oe.kind,s=>this.visitArrayQueryExpression(s)),this.handlers.set(Q.kind,s=>this.visitValueList(s)),this.handlers.set(te.kind,s=>this.visitWindowFrameClause(s)),this.handlers.set(we.kind,s=>this.visitWindowFrameExpression(s)),this.handlers.set(be.kind,s=>this.visitPartitionByClause(s))}getValues(){return this.selectValues}collect(e){this.visit(e);let t=this.getValues();return this.reset(),t}reset(){this.selectValues=[],this.visitedNodes.clear(),this.commonTables=[]}addSelectValueAsUnique(e,t){if(this.duplicateDetection==="columnNameOnly")this.selectValues.some(n=>n.name===e)||this.selectValues.push({name:e,value:t});else if(this.duplicateDetection==="fullName"){let n="";t&&typeof t.getNamespace=="function"&&(n=t.getNamespace()||"");let i=n?n+"."+e:e;this.selectValues.some(s=>{let o="";return s.value&&typeof s.value.getNamespace=="function"&&(o=s.value.getNamespace()||""),(o?o+"."+s.name:s.name)===i})||this.selectValues.push({name:e,value:t})}}visit(e){if(!this.isRootVisit){this.visitNode(e);return}if(!(e instanceof E))throw new Error("Root visit must be a SimpleSelectQuery");this.reset(),this.isRootVisit=!1,this.commonTables=this.commonTableCollector.collect(e);try{this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}visitSimpleSelectQuery(e){if(e.selectClause&&e.selectClause.accept(this),e.fromClause&&e.fromClause.accept(this),e.whereClause&&e.whereClause.accept(this),e.groupByClause&&e.groupByClause.accept(this),e.havingClause&&e.havingClause.accept(this),e.windowClause)for(let t of e.windowClause.windows)t.accept(this);e.orderByClause&&e.orderByClause.accept(this),e.limitClause&&e.limitClause.accept(this),e.offsetClause&&e.offsetClause.accept(this),e.fetchClause&&e.fetchClause.accept(this),e.forClause&&e.forClause.accept(this)}visitSelectClause(e){for(let t of e.items)t.identifier&&this.addSelectValueAsUnique(t.identifier.name,t.value),t.value.accept(this)}visitFromClause(e){let n=new de(this.tableColumnResolver,this.commonTables).collect(e);for(let i of n)this.addSelectValueAsUnique(i.name,i.value);if(e.joins)for(let i of e.joins)i.condition&&i.condition.accept(this)}visitWhereClause(e){e.condition&&e.condition.accept(this)}visitGroupByClause(e){if(e.grouping)for(let t of e.grouping)t.accept(this)}visitHavingClause(e){e.condition&&e.condition.accept(this)}visitOrderByClause(e){if(e.order)for(let t of e.order)t.accept(this)}visitWindowFrameClause(e){e.expression.accept(this)}visitWindowFrameExpression(e){e.partition&&e.partition.accept(this),e.order&&e.order.accept(this),e.frameSpec&&e.frameSpec.accept(this)}visitLimitClause(e){e.value&&e.value.accept(this)}offsetClause(e){e.value&&e.value.accept(this)}visitFetchClause(e){e.expression&&e.expression.accept(this)}visitJoinOnClause(e){e.condition&&e.condition.accept(this)}visitJoinUsingClause(e){e.condition&&e.condition.accept(this)}visitColumnReference(e){if(e.column.name!=="*")this.addSelectValueAsUnique(e.column.name,e);else if(this.includeWildCard)this.addSelectValueAsUnique(e.column.name,e);else return}visitBinaryExpression(e){e.left&&e.left.accept(this),e.right&&e.right.accept(this)}visitUnaryExpression(e){e.expression&&e.expression.accept(this)}visitFunctionCall(e){e.argument&&e.argument.accept(this),e.over&&e.over.accept(this)}visitParenExpression(e){e.expression&&e.expression.accept(this)}visitCaseExpression(e){e.condition&&e.condition.accept(this),e.switchCase&&e.switchCase.accept(this)}visitCastExpression(e){e.input&&e.input.accept(this)}visitBetweenExpression(e){e.expression&&e.expression.accept(this),e.lower&&e.lower.accept(this),e.upper&&e.upper.accept(this)}visitArrayExpression(e){e.expression&&e.expression.accept(this)}visitArrayQueryExpression(e){e.query.accept(this)}visitValueList(e){if(e.values)for(let t of e.values)t.accept(this)}visitPartitionByClause(e){e.value.accept(this)}};var Ue=class r{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The source component is complete but there are additional tokens.`);return i.value}static parseTableSourceFromLexemes(e,t){let n=he.parseFromLexeme(e,t);return this.parseTableSource(n)}static parseFromLexeme(e,t){let n=t;if(n<e.length&&e[n].type&4)return this.parseParenSource(e,n);let i=he.parseFromLexeme(e,n);return i.lastTokenType&2048?r.parseFunctionSource(e,i):r.parseTableSource(i)}static parseTableSource(e){let{namespaces:t,name:n,newIndex:i}=e;return{value:new I(t,n.name),newIndex:i}}static parseFunctionSource(e,t){let n=t.newIndex,{namespaces:i,name:s}=t,o=v.parseArgument(4,8,e,n);n=o.newIndex;let a=s.name;return{value:new Ie({namespaces:i,name:a},o.value),newIndex:n}}static parseParenSource(e,t){let n=t;if(n++,n>=e.length)throw new Error(`Syntax error: Unexpected end of input at position ${n}. Expected a subquery or nested expression after opening parenthesis.`);let i=e[n].value;if(i==="select"||i==="values"||i==="with"){let s=this.parseSubQuerySource(e,n);if(n=s.newIndex,n<e.length&&e[n].type==8)n++;else throw new Error(`Syntax error at position ${n}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:s.value,newIndex:n}}else if(e[n].type==4){let s=this.parseParenSource(e,n);if(n=s.newIndex,n<e.length&&e[n].type==8)n++;else throw new Error(`Syntax error at position ${n}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:s.value,newIndex:n}}throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword, 'VALUES' keyword, or opening parenthesis '(' but found "${e[n].value}".`)}static parseSubQuerySource(e,t){let n=t,{value:i,newIndex:s}=B.parseFromLexeme(e,n);return n=s,{value:new N(i),newIndex:n}}};var it=class{constructor(e,t){this.options=t||{},this.tableColumnResolver=e,this.columnCollector=new xe(this.tableColumnResolver)}find(e,t){let n=typeof t=="string"?[t]:t,s=new q().collect(e),o=new Map;for(let a of s)o.set(a.getSourceAliasName(),a);return this.findUpstream(e,n,o)}handleTableSource(e,t,n){let i=n.get(e.table.name);if(i){let s=new Map(n);s.delete(e.table.name);let o=this.findUpstream(i.query,t,s);return o.length===0?null:o}return null}handleSubQuerySource(e,t,n){let i=this.findUpstream(e.query,t,n);return i.length===0?null:i}processFromClauseBranches(e,t,n){let i=e.getSources();if(i.length===0)return null;let s=[],o=!0,a=0;for(let l of i){let u=l.datasource,c=null;if(u instanceof I)c=this.handleTableSource(u,t,n),a++;else if(u instanceof N)c=this.handleSubQuerySource(u,t,n),a++;else{if(u instanceof z)continue;o=!1;break}if(c===null){o=!1;break}s.push(c)}return o&&s.length===a?s.flat():null}findUpstream(e,t,n){if(e instanceof E){let i=e.fromClause;if(i){let l=this.processFromClauseBranches(i,t,n);if(l)return l}let s=this.columnCollector.collect(e).map(l=>l.name),o=l=>this.options.ignoreCaseAndUnderscore?l.toLowerCase().replace(/_/g,""):l;return t.every(l=>s.some(u=>o(u)===o(l)))?[e]:[]}else if(e instanceof R){let i=this.findUpstream(e.left,t,n),s=this.findUpstream(e.right,t,n);return[...i,...s]}return[]}};var je=class{static parseFromLexeme(e,t){let n=t;if(n<e.length&&(e[n].type&64||e[n].type&2048)){let i=e[n].value;if(n++,n<e.length&&e[n].type&4){let s=[];for(n++;n<e.length&&e[n].type&64&&(s.push(e[n].value),n++,n<e.length&&e[n].type&16);)n++;if(e[n].type&8)n++;else throw new Error(`Syntax error at position ${n}: Missing closing parenthesis ')' for column alias list. Each opening parenthesis must have a matching closing parenthesis.`);if(s.length===0)throw new Error(`Syntax error at position ${t}: No column aliases found. Column alias declarations must contain at least one column name.`);return{value:new W(i,s),newIndex:n}}return{value:new W(i,null),newIndex:n}}throw new Error(`Syntax error at position ${t}: Expected an identifier for table alias but found "${e[t]?.value||"end of input"}".`)}};var ke=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The source expression is complete but there are additional tokens.`);return i.value}static parseTableSourceFromLexemes(e,t){let n=Ue.parseTableSourceFromLexemes(e,t);return{value:new k(n.value,null),newIndex:n.newIndex}}static parseFromLexeme(e,t){let n=t,i=Ue.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length){if(e[n].value==="as"){n++;let o=je.parseFromLexeme(e,n);return n=o.newIndex,{value:new k(i.value,o.value),newIndex:n}}if(n<e.length&&this.isTokenTypeAliasCandidate(e[n].type)){let o=je.parseFromLexeme(e,n);return n=o.newIndex,{value:new k(i.value,o.value),newIndex:n}}}return{value:new k(i.value,null),newIndex:n}}static isTokenTypeAliasCandidate(e){return(e&64)!==0||(e&2048)!==0}};var st=class r{static buildBinaryQuery(e,t){if(!e||e.length===0)throw new Error("No queries provided to combine.");if(e.length===1)throw new Error("At least two queries are required to create a BinarySelectQuery.");let n=s=>s instanceof z?r.buildSimpleQuery(s):s,i=new R(n(e[0]),t,n(e[1]));Oe.normalize(i);for(let s=2;s<e.length;s++)i.appendSelectQuery(t,n(e[s]));return i}constructor(){}static buildSimpleQuery(e){if(e instanceof E)return e;if(e instanceof R)return r.buildSimpleBinaryQuery(e);if(e instanceof z)return r.buildSimpleValuesQuery(e);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(e){let t=new N(e),n=new k(t,new W("bq",null)),i=new P(n,null),s=r.createSelectAllClause(),o=new E({selectClause:s,fromClause:i});return Oe.normalize(o)}static buildSimpleValuesQuery(e){let t=e.tuples.length>0?e.tuples[0].values.length:0;if(e.tuples.length===0)throw new Error("Empty VALUES clause cannot be converted to a SimpleSelectQuery");if(!e.columnAliases)throw new Error("Column aliases are required to convert a VALUES clause to SimpleSelectQuery. Please specify column aliases.");if(e.columnAliases.length!==t)throw new Error(`The number of column aliases (${e.columnAliases.length}) does not match the number of columns in the first tuple (${t}).`);let n=new N(e),i=new k(n,new W("vq",e.columnAliases)),s=new P(i,null),o=e.columnAliases.map(l=>new F(new f("vq",l),l)),a=new O(o,null);return new E({selectClause:a,fromClause:s})}static createSelectAllClause(){let e=new f(null,"*"),t=new F(e,"*");return new O([t],null)}static buildCreateTableQuery(e,t,n=!1){return new tt({tableName:t,isTemporary:n,asSelectQuery:e})}static buildInsertQuery(e,t){let n,i=e.selectClause.items.length;if(n=new de().collect(e).map(l=>l.name),!n.length||i!==n.length)throw new Error(`Columns cannot be inferred from the selectQuery. Make sure you are not using wildcards or unnamed columns.
13
+ Select clause column count: ${i}, Columns with valid names: ${n.length}
14
+ Detected column names: [${n.join(", ")}]`);let a=ke.parse(t);return new Le({insertClause:new Be(a,n),selectQuery:e})}static buildUpdateQuery(e,t,n,i){let s=new _e(ke.parse(n)),o=Array.isArray(i)?i:[i],l=new de().collect(e),c=new q().collect(e);new Xe().execute(e);for(let Te of o)if(!l.some(pt=>pt.name===Te))throw new Error(`Primary key column '${Te}' is not present in selectQuery select list.`);let d=s.getSourceAliasName();if(!d)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let y=l.filter(Te=>!o.includes(Te.name)).map(Te=>new Ve(Te.name,new f(d,Te.name))),S=new Ne(y),$e=new P(e.toSource(t),null),Ae=null;for(let Te of o){let pt=new b(new f(d,Te),"=",new f(t,Te));Ae=Ae?new b(Ae,"and",pt):pt}let vn=new J(Ae);return new et({updateClause:s,setClause:S,fromClause:$e,whereClause:vn,withClause:c.length>0?new U(!1,c):void 0})}};var We=class{static set(e,t,n){let i=Ze.collect(e),s=!1;for(let o of i)o.name.value===t&&(o.value=n,s=!0);if(!s)throw new Error(`Parameter '${t}' not found in query.`)}};var E=class extends h{static{this.kind=Symbol("SelectQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.selectClause=e.selectClause,this.fromClause=e.fromClause??null,this.whereClause=e.whereClause??null,this.groupByClause=e.groupByClause??null,this.havingClause=e.havingClause??null,this.orderByClause=e.orderByClause??null,this.windowClause=e.windowClause??null,this.limitClause=e.limitClause??null,this.offsetClause=e.offsetClause??null,this.fetchClause=e.fetchClause??null,this.forClause=e.forClause??null}toUnion(e){return this.toBinaryQuery("union",e)}toUnionAll(e){return this.toBinaryQuery("union all",e)}toIntersect(e){return this.toBinaryQuery("intersect",e)}toIntersectAll(e){return this.toBinaryQuery("intersect all",e)}toExcept(e){return this.toBinaryQuery("except",e)}toExceptAll(e){return this.toBinaryQuery("except all",e)}toBinaryQuery(e,t){return st.buildBinaryQuery([this,t],e)}appendWhereRaw(e){let t=v.parse(e);this.appendWhere(t)}appendWhere(e){this.whereClause?this.whereClause.condition=new b(this.whereClause.condition,"and",e):this.whereClause=new J(e)}appendHavingRaw(e){let t=v.parse(e);this.appendHaving(t)}appendHaving(e){this.havingClause?this.havingClause.condition=new b(this.havingClause.condition,"and",e):this.havingClause=new Y(e)}innerJoinRaw(e,t,n,i=null){this.joinSourceRaw("inner join",e,t,n,i)}leftJoinRaw(e,t,n,i=null){this.joinSourceRaw("left join",e,t,n,i)}rightJoinRaw(e,t,n,i=null){this.joinSourceRaw("right join",e,t,n,i)}innerJoin(e,t,n=null){this.joinSource("inner join",e,t,n)}leftJoin(e,t,n=null){this.joinSource("left join",e,t,n)}rightJoin(e,t,n=null){this.joinSource("right join",e,t,n)}joinSourceRaw(e,t,n,i,s=null){let o=Ue.parse(t),a=new k(o,new W(n,null));this.joinSource(e,a,i,s)}joinSource(e,t,n,i=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let s=Array.isArray(n)?n:[n],a=new xe(i).collect(this),l=null,u=0,c=t.getAliasName();if(!c)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let w of a)if(s.some(y=>y==w.name)){let y=new b(w.value,"=",new f([c],w.name));l?l=new b(l,"and",y):l=y,u++}if(!l||u!==s.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${s.join(", ")}`);let m=new X(l),d=new Z(e,t,m,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(d):this.fromClause.joins=[d]),Oe.normalize(this)}toSource(e){if(!e||e.trim()==="")throw new Error("Alias is required for toSource(). Please specify a non-empty alias name.");return new k(new N(this),new W(e,null))}appendWith(e){let t=Array.isArray(e)?e:[e];this.withClause?this.withClause.tables.push(...t):this.withClause=new U(!1,t),Oe.normalize(this)}appendWithRaw(e,t){let n=B.parse(e),i=new K(n,t,null);this.appendWith(i)}overrideSelectItemExpr(e,t){let n=this.selectClause.items.filter(l=>l.identifier?.name===e);if(n.length===0)throw new Error(`Column ${e} not found in the query`);if(n.length>1)throw new Error(`Duplicate column name ${e} found in the query`);let i=n[0],o=new Re().visit(i.value),a=t(o);i.value=v.parse(a)}appendWhereExpr(e,t,n){if(n&&n.upstream){let s=new it().find(this,[e]),o=new xe,a=new Re;for(let l of s){let u=o.collect(l).filter(m=>m.name===e).map(m=>m.value);if(u.length!==1)throw new Error(`Expected exactly one expression for column '${e}'`);let c=a.format(u[0]);l.appendWhereRaw(t(c))}}else{let i=new xe,s=new Re,o=i.collect(this).filter(l=>l.name===e).map(l=>l.value);if(o.length!==1)throw new Error(`Expected exactly one expression for column '${e}'`);let a=s.format(o[0]);this.appendWhereRaw(t(a))}}setParameter(e,t){return We.set(this,e,t),this}};var R=class r extends h{static{this.kind=Symbol("BinarySelectQuery")}constructor(e,t,n){super(),this.left=e,this.operator=new g(t),this.right=n}union(e){return this.appendSelectQuery("union",e)}unionAll(e){return this.appendSelectQuery("union all",e)}intersect(e){return this.appendSelectQuery("intersect",e)}intersectAll(e){return this.appendSelectQuery("intersect all",e)}except(e){return this.appendSelectQuery("except",e)}exceptAll(e){return this.appendSelectQuery("except all",e)}appendSelectQuery(e,t){return this.left=new r(this.left,this.operator.value,this.right),this.operator=new g(e),this.right=t,Oe.normalize(this),this}unionRaw(e){let t=B.parse(e);return this.union(t)}unionAllRaw(e){let t=B.parse(e);return this.unionAll(t)}intersectRaw(e){let t=B.parse(e);return this.intersect(t)}intersectAllRaw(e){let t=B.parse(e);return this.intersectAll(t)}exceptRaw(e){let t=B.parse(e);return this.except(t)}exceptAllRaw(e){let t=B.parse(e);return this.exceptAll(t)}toSource(e="subq"){return new k(new N(this),new W(e,null))}setParameter(e,t){return We.set(this,e,t),this}};var z=class extends h{static{this.kind=Symbol("ValuesQuery")}constructor(e,t=null){super(),this.tuples=e,this.columnAliases=t}toSimpleSelectQuery(){return st.buildSimpleQuery(this)}setParameter(e,t){return We.set(this,e,t),this}};var $t=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The SELECT clause is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t,i=null;if(e[n].value!=="select")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword but found "${e[n].value}". SELECT clauses must start with the SELECT keyword.`);if(n++,n<e.length&&e[n].value==="distinct")n++,i=new Me;else if(n<e.length&&e[n].value==="distinct on"){n++;let a=v.parseArgument(4,8,e,n);i=new ze(a.value),n=a.newIndex}let s=[],o=Kt.parseItem(e,n);for(s.push(o.value),n=o.newIndex;n<e.length&&e[n].type&16;){n++;let a=Kt.parseItem(e,n);s.push(a.value),n=a.newIndex}if(s.length===0)throw new Error(`Syntax error at position ${t}: No select items found. The SELECT clause requires at least one expression to select.`);return{value:new O(s,i),newIndex:n}}},Kt=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseItem(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The select item is complete but there are additional tokens.`);return i.value}static parseItem(e,t){let n=t,i=v.parseFromLexeme(e,n),s=i.value;if(n=i.newIndex,n<e.length&&e[n].value==="as"&&n++,n<e.length&&e[n].type&64){let o=e[n].value;return n++,{value:new F(s,o),newIndex:n}}else if(s instanceof f&&s.column.name!=="*")return{value:new F(s,s.column.name),newIndex:n};return{value:new F(s),newIndex:n}}};var Ut=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="on"){n++;let i=v.parseFromLexeme(e,n);return n=i.newIndex,{value:new X(i.value),newIndex:n}}return null}};var jt=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="using"){n++;let i=v.parseArgument(4,8,e,n),s=i.value;return n=i.newIndex,{value:new ce(s),newIndex:n}}return null}};var qt=class{static tryParse(e,t){let n=t,i=[];for(;this.isJoinCommand(e,n);){let s=this.parseJoinClause(e,n);i.push(s.value),n=s.newIndex}return i.length>0?{value:i,newIndex:n}:null}static isJoinKeyword(e){return!!on.parse(e,0)}static parseLateral(e,t){let n=t;return n<e.length&&e[n].value==="lateral"?(n++,{value:!0,newIndex:n}):{value:!1,newIndex:n}}static isJoinCommand(e,t){return t>=e.length?!1:!!(e[t].type&16||this.isJoinKeyword(e[t].value)===!0)}static parseJoinClause(e,t){let n=t,i=e[n].value===","?"cross join":e[n].value;n++;let s=this.parseLateral(e,n),o=s.value;n=s.newIndex;let a=ke.parseFromLexeme(e,n);if(n=a.newIndex,n<e.length){let u=Ut.tryParse(e,n);if(u)return{value:new Z(i,a.value,u.value,o),newIndex:u.newIndex};let c=jt.tryParse(e,n);if(c)return{value:new Z(i,a.value,c.value,o),newIndex:c.newIndex}}return{value:new Z(i,a.value,null,o),newIndex:n}}};var Dt=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The FROM clause is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="from")throw new Error(`Syntax error at position ${n}: Expected 'FROM' keyword but found "${e[n].value}". FROM clauses must start with the FROM keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FROM' keyword. The FROM clause requires a table reference.");let i=ke.parseFromLexeme(e,n);n=i.newIndex;let s=qt.tryParse(e,n);return n=s?.newIndex||n,s!==null?{value:new P(i.value,s.value),newIndex:n}:{value:new P(i.value,null),newIndex:n}}};var Jt=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The WHERE clause is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="where")throw new Error(`Syntax error at position ${n}: Expected 'WHERE' keyword but found "${e[n].value}". WHERE clauses must start with the WHERE keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'WHERE' keyword. The WHERE clause requires a condition expression.");let i=v.parseFromLexeme(e,n);return{value:new J(i.value),newIndex:i.newIndex}}};var Mt=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The GROUP BY clause is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="group by")throw new Error(`Syntax error at position ${n}: Expected 'GROUP BY' keyword but found "${e[n].value}". GROUP BY clauses must start with the GROUP BY keywords.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'GROUP BY' keyword. The GROUP BY clause requires at least one expression to group by.");let i=[],s=this.parseItem(e,n);for(i.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let o=this.parseItem(e,n);i.push(o.value),n=o.newIndex}if(i.length===0)throw new Error(`Syntax error at position ${t}: No grouping expressions found. The GROUP BY clause requires at least one expression to group by.`);return{value:new G(i),newIndex:n}}static parseItem(e,t){let n=t,i=v.parseFromLexeme(e,n),s=i.value;return n=i.newIndex,{value:s,newIndex:n}}};var zt=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The HAVING clause is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="having")throw new Error(`Syntax error at position ${n}: Expected 'HAVING' keyword but found "${e[n].value}". HAVING clauses must start with the HAVING keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'HAVING' keyword. The HAVING clause requires a condition expression.");let i=v.parseFromLexeme(e,n);return{value:new Y(i.value),newIndex:i.newIndex}}};var _t=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The WINDOW clause is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="window")throw new Error(`Syntax error at position ${n}: Expected 'WINDOW' keyword but found "${e[n].value}". WINDOW clauses must start with the WINDOW keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'WINDOW' keyword. The WINDOW clause requires at least one window definition.");let i=[];for(;n<e.length;){if(n>=e.length||e[n].type!==64)throw new Error("Syntax error: Expected window name after 'WINDOW' keyword.");let s=e[n].value;if(n++,n>=e.length||e[n].value!=="as")throw new Error(`Syntax error at position ${n}: Expected 'AS' keyword after window name.`);n++;let o=Ge.parseFromLexeme(e,n);if(n=o.newIndex,i.push(new te(s,o.value)),n<e.length&&e[n].type&16)n++;else break}if(i.length===0)throw new Error("At least one WINDOW clause is required after WINDOW keyword.");return{value:new Qe(i),newIndex:n}}};var Ht=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The LIMIT clause is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="limit")throw new Error(`Syntax error at position ${n}: Expected 'LIMIT' keyword but found "${e[n].value}". LIMIT clauses must start with the LIMIT keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'LIMIT' keyword. The LIMIT clause requires a numeric expression.");let i=v.parseFromLexeme(e,n);return n=i.newIndex,{value:new ee(i.value),newIndex:n}}};var Gt=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The FOR clause is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].value.toLowerCase()!=="for")throw new Error(`Syntax error at position ${n}: Expected 'FOR' keyword but found "${e[n].value}". FOR clauses must start with the FOR keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FOR' keyword. The FOR clause requires a lock mode specification.");let i=e[n].value,s;switch(i){case"update":s="update",n++;break;case"share":s="share",n++;break;case"key share":s="key share",n++;break;case"no key update":s="no key update",n++;break;default:throw new Error(`Syntax error at position ${n}: Invalid lock mode "${i}". Valid lock modes are: UPDATE, SHARE, KEY SHARE, NO KEY UPDATE.`)}return{value:new ye(s),newIndex:n}}};var ut=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The CommonTable definition is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t,i=je.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length&&e[n].value!=="as")throw new Error(`Syntax error at position ${n}: Expected 'AS' keyword after CTE name but found "${e[n].value}".`);n++;let s=null;if(n<e.length){let l=e[n].value;l==="materialized"?(s=!0,n++):l==="not materialized"&&(s=!1,n++)}if(n<e.length&&e[n].type!==4)throw new Error(`Syntax error at position ${n}: Expected '(' after CTE name but found "${e[n].value}".`);n++;let o=B.parseFromLexeme(e,n);if(n=o.newIndex,n<e.length&&e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected ')' after CTE query but found "${e[n].value}".`);return n++,{value:new K(o.value,i.value,s),newIndex:n}}};var rt=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The WITH clause is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(n<e.length&&e[n].value.toLowerCase()==="with")n++;else throw new Error(`Syntax error at position ${n}: Expected WITH keyword.`);let i=n<e.length&&e[n].value.toLowerCase()==="recursive";i&&n++;let s=[],o=ut.parseFromLexeme(e,n);for(s.push(o.value),n=o.newIndex;n<e.length&&e[n].type&16;){n++;let a=ut.parseFromLexeme(e,n);s.push(a.value),n=a.newIndex}return{value:new U(i,s),newIndex:n}}};var Yt=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The VALUES clause is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].value.toLowerCase()!=="values")throw new Error(`Syntax error at position ${n}: Expected 'VALUES' keyword but found "${e[n].value}". VALUES clauses must start with the VALUES keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'VALUES' keyword. The VALUES clause requires at least one tuple expression.");let i=[],s=this.parseTuple(e,n);for(i.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let a=this.parseTuple(e,n);i.push(a.value),n=a.newIndex}return{value:new z(i),newIndex:n}}static parseTuple(e,t){let n=t;if(n>=e.length||e[n].type!==4)throw new Error(`Syntax error at position ${n}: Expected opening parenthesis but found "${n<e.length?e[n].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);n++;let i=[];if(n>=e.length)throw new Error("Syntax error: Unexpected end of input after opening parenthesis in tuple expression.");if(e[n].type&8)return n++,{value:new le([]),newIndex:n};let s=v.parseFromLexeme(e,n);for(i.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after comma in tuple expression.");let o=v.parseFromLexeme(e,n);i.push(o.value),n=o.newIndex}if(n>=e.length||e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected closing parenthesis but found "${n<e.length?e[n].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);return n++,{value:new le(i),newIndex:n}}};var Xt=class{static parseFromLexeme(e,t){let n=t;if(e[n].value!=="fetch")throw new Error(`Syntax error at position ${n}: Expected 'FETCH' keyword but found "${e[n].value}".`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH' keyword.");let i=ln.parseFromLexeme(e,n),s=i.value;return n=i.newIndex,{value:new Fe(s),newIndex:n}}},ln=class{static parseFromLexeme(e,t){let n=t,i,s=e[n].value;if(s==="first")i="first";else if(s==="next")i="next";else throw new Error(`Syntax error at position ${n}: Expected 'FIRST' or 'NEXT' after 'FETCH' but found "${e[n].value}".`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT'.");let o=null,a=null;if(e[n].value==="row only"||e[n].value==="rows only")return o=new V(1),a="rows only",n++,{value:new Ke(i,o,a),newIndex:n};let l=v.parseFromLexeme(e,n);if(o=l.value,n=l.newIndex,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT <count>'.");if(e[n].value==="rows only"?(a="rows only",n++):e[n].value==="percent"?(a="percent",n++):e[n].value==="percent with ties"&&(a="percent with ties",n++),!a)throw new Error("Syntax error: Expected 'ROWS ONLY', 'PERCENT', or 'PERCENT WITH TIES' after 'FETCH FIRST|NEXT <count>'.");return{value:new Ke(i,o,a),newIndex:n}}};var Zt=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The OFFSET clause is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="offset")throw new Error(`Syntax error at position ${n}: Expected 'OFFSET' keyword but found "${e[n].value}". OFFSET clauses must start with the OFFSET keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'OFFSET' keyword. The OFFSET clause requires a numeric expression.");let i=v.parseFromLexeme(e,n);return n=i.newIndex,n<e.length&&(e[n].value==="row"||e[n].value==="rows")&&n++,{value:new Pe(i.value),newIndex:n}}};var B=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`[SelectQueryParser] Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The SELECT query is complete but there are additional tokens.`);return i.value}static async parseAsync(e){return Promise.resolve(this.parse(e))}static{this.unionCommandSet=new Set(["union","union all","intersect","intersect all","except","except all"])}static{this.selectCommandSet=new Set(["with","select"])}static parseFromLexeme(e,t){let n=t;if(n>=e.length)throw new Error(`Syntax error: Unexpected end of input at position ${t}.`);let i=e[n].value;if(!this.selectCommandSet.has(i)&&i!=="values")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' or 'VALUES' keyword but found "${e[n].value}".`);let s=this.selectCommandSet.has(i)?this.parseSimpleSelectQuery(e,n):this.parseValuesQuery(e,n),o=s.value;for(n=s.newIndex;n<e.length&&this.unionCommandSet.has(e[n].value.toLowerCase());){let a=e[n].value.toLowerCase();if(n++,n>=e.length)throw new Error(`Syntax error at position ${n}: Expected a query after '${a.toUpperCase()}' but found end of input.`);let l=e[n].value.toLowerCase();if(this.selectCommandSet.has(l)){let u=this.parseSimpleSelectQuery(e,n);o=new R(o,a,u.value),n=u.newIndex}else if(l==="values"){let u=this.parseValuesQuery(e,n);o=new R(o,a,u.value),n=u.newIndex}else throw new Error(`Syntax error at position ${n}: Expected 'SELECT' or 'VALUES' after '${a.toUpperCase()}' but found "${e[n].value}".`)}return{value:o,newIndex:n}}static parseSimpleSelectQuery(e,t){let n=t,i=null;if(n<e.length&&e[n].value==="with"&&(i=rt.parseFromLexeme(e,n),n=i.newIndex),n>=e.length||e[n].value!=="select")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword but found "${n<e.length?e[n].value:"end of input"}". SELECT queries must start with the SELECT keyword.`);let s=$t.parseFromLexeme(e,n);n=s.newIndex;let o=null;n<e.length&&e[n].value==="from"&&(o=Dt.parseFromLexeme(e,n),n=o.newIndex);let a=null;n<e.length&&e[n].value==="where"&&(a=Jt.parseFromLexeme(e,n),n=a.newIndex);let l=null;n<e.length&&e[n].value==="group by"&&(l=Mt.parseFromLexeme(e,n),n=l.newIndex);let u=null;n<e.length&&e[n].value==="having"&&(u=zt.parseFromLexeme(e,n),n=u.newIndex);let c=null;n<e.length&&e[n].value==="window"&&(c=_t.parseFromLexeme(e,n),n=c.newIndex);let m=null;n<e.length&&e[n].value==="order by"&&(m=He.parseFromLexeme(e,n),n=m.newIndex);let d=null;n<e.length&&e[n].value==="limit"&&(d=Ht.parseFromLexeme(e,n),n=d.newIndex);let w=null;n<e.length&&e[n].value==="offset"&&(w=Zt.parseFromLexeme(e,n),n=w.newIndex);let y=null;n<e.length&&e[n].value==="fetch"&&(y=Xt.parseFromLexeme(e,n),n=y.newIndex);let S=null;return n<e.length&&e[n].value.toLowerCase()==="for"&&(S=Gt.parseFromLexeme(e,n),n=S.newIndex),{value:new E({withClause:i?i.value:null,selectClause:s.value,fromClause:o?o.value:null,whereClause:a?a.value:null,groupByClause:l?l.value:null,havingClause:u?u.value:null,orderByClause:m?m.value:null,windowClause:c?c.value:null,limitClause:d?d.value:null,offsetClause:w?w.value:null,fetchClause:y?y.value:null,forClause:S?S.value:null}),newIndex:n}}static parseValuesQuery(e,t){let n=Yt.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}};var dn=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The INSERT query is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t,i=null;if(e[n].value==="with"){let l=rt.parseFromLexeme(e,n);i=l.value,n=l.newIndex}if(e[n].value!=="insert into")throw new Error(`Syntax error at position ${n}: Expected 'INSERT INTO' but found '${e[n].value}'.`);n++;let s=ke.parseTableSourceFromLexemes(e,n);n=s.newIndex;let o=[];if(e[n]?.type===4){for(n++;n<e.length&&e[n].type===64&&(o.push(e[n].value),n++,e[n]?.type===16);)n++;if(e[n]?.type!==8)throw new Error(`Syntax error at position ${n}: Expected ')' after column list.`);n++}let a=B.parseFromLexeme(e,n);if(i)if(a.value instanceof E)a.value.withClause=i;else throw new Error("WITH clause is not supported in this context.");return n=a.newIndex,{value:new Le({insertClause:new Be(s.value,o),selectQuery:a.value}),newIndex:n}}};var en=class r{static{this.JSON_COLUMN_SUFFIX="_json"}static{this.CTE_OBJECT_PREFIX="cte_object_depth_"}static{this.WILDCARD_COLUMN="*"}buildObjectEntityCtes(e,t,n){let i=[e],s=e.aliasExpression.table.name,o=this.collectAndSortObjectEntities(n,t),a=this.groupEntitiesByDepth(o),l=Array.from(a.keys()).sort((u,c)=>c-u);for(let u of l){let c=a.get(u),m=`${r.CTE_OBJECT_PREFIX}${u}`,d=this.buildDepthCte(c,s,m,n,t);i.push(d),s=m}return{ctes:i,lastCteAlias:s}}collectAndSortObjectEntities(e,t){let n=[],i=s=>{let o=t.get(s);if(!o)throw new Error(`Entity ${s} not found for depth calculation.`);if(o.isRoot)return 0;if(!o.parentId)return 1;let a=o.parentId,l=0,u=new Set;for(u.add(s);a;){if(u.has(a))throw new Error(`Circular dependency detected: ${a} already visited in path for ${s}`);u.add(a);let c=t.get(a);if(!c)throw new Error(`Parent entity ${a} not found during depth calculation for ${s}`);let m=!1;if(c.isRoot)m=!0;else{let d=e.nestedEntities.find(w=>w.id===a);if(d)d.relationshipType==="object"&&(m=!0);else throw new Error(`Parent entity ${a} (ancestor of ${s}) has no definition in mapping.nestedEntities and is not root.`)}if(m&&l++,c.isRoot)break;a=c.parentId}return l};return e.nestedEntities.forEach(s=>{if(s.relationshipType==="object"){let o=t.get(s.id);o&&!o.isRoot&&n.push({entity:o,depth:i(s.id)})}}),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let i=n.depth;t.has(i)||t.set(i,[]),t.get(i).push(n)}),t}buildDepthCte(e,t,n,i,s){let o=[new F(new f(null,new C(r.WILDCARD_COLUMN)))];for(let{entity:l}of e){let u=this.buildEntityJsonColumn(l,i,s);o.push(u)}let a=new E({selectClause:new O(o),fromClause:new P(new k(new I(null,new C(t)),null),null)});return new K(a,new W(n,null),null)}buildEntityJsonColumn(e,t,n){let{jsonObjectArgs:i,nullChecks:s}=this.prepareEntityColumns(e);this.addChildObjectRelationships(e,i,t,n);let o=this.createJsonObject(i,t.useJsonb),a=this.buildNullCondition(s),l=this.createCaseExpression(a,o),u=`${e.name.toLowerCase()}${r.JSON_COLUMN_SUFFIX}`;return new F(l,u)}prepareEntityColumns(e){let t=[],n=[];return Object.entries(e.columns).forEach(([i,s])=>{t.push(new V(i)),t.push(new f(null,new C(s))),n.push(new b(new f(null,new C(s)),"is",new V(null)))}),{jsonObjectArgs:t,nullChecks:n}}addChildObjectRelationships(e,t,n,i){n.nestedEntities.filter(o=>o.parentId===e.id&&o.relationshipType==="object").forEach(o=>{let a=i.get(o.id);if(a){t.push(new V(o.propertyName));let l=`${a.name.toLowerCase()}${r.JSON_COLUMN_SUFFIX}`;t.push(new f(null,new C(l)))}})}createJsonObject(e,t=!1){let n=t?"jsonb_build_object":"json_build_object";return new L(null,new g(n),new Q(e),null)}buildNullCondition(e){return e.reduce((t,n)=>t?new b(t,"and",n):n)}createCaseExpression(e,t){return new _(null,new ne([new ie(e,new V(null))],t))}};var tn=class r{static{this.CTE_ARRAY_PREFIX="cte_array_depth_"}buildArrayEntityCtes(e,t,n,i){let s=[...e],o=t,a=this.collectAndSortArrayEntities(i,n);if(a.length===0)return{updatedCtes:s,lastCteAlias:o};let l=this.groupEntitiesByDepth(a),u=Array.from(l.keys()).sort((c,m)=>m-c);for(let c of u){let m=l.get(c),{cte:d,newCteAlias:w}=this.buildDepthCte(m,o,s,c,i);s.push(d),o=w}return{updatedCtes:s,lastCteAlias:o}}collectAndSortArrayEntities(e,t){let n=[],i=s=>{let o=t.get(s);return!o||o.isRoot?0:o.parentId?1+i(o.parentId):1};return e.nestedEntities.forEach(s=>{if(s.relationshipType==="array"){let o=t.get(s.id),a=t.get(s.parentId);if(!o||!a)throw new Error(`Configuration error: Array entity '${s.id}' or its parent '${s.parentId}' not found.`);let l=Object.values(a.columns);if(l.length===0)throw new Error(`Configuration error: Parent entity '${a.name}' (ID: ${a.id}) must have at least one column defined to serve as a linking key for child array '${s.name}'.`);let u=l[0];n.push({entity:o,parentEntity:a,parentIdColumnSqlName:u,depth:i(s.id)})}}),n.sort((s,o)=>o.depth-s.depth),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let i=n.depth;t.has(i)||t.set(i,[]),t.get(i).push(n)}),t}buildDepthCte(e,t,n,i,s){let o=new Set;e.forEach(y=>{Object.values(y.entity.columns).forEach(S=>o.add(S))});let a=n.find(y=>y.aliasExpression.table.name===t)?.query;if(!a)throw new Error(`CTE not found: ${t}`);let l=new de(null,n).collect(a),u=[],c=[];l.forEach(y=>{o.has(y.name)||(c.push(new F(new f(null,new C(y.name)),y.name)),u.push(new f(null,new C(y.name))))});for(let y of e){let S=this.buildAggregationDetailsForArrayEntity(y.entity,s.nestedEntities,new Map,s.useJsonb);c.push(new F(S.jsonAgg,y.entity.propertyName))}let m=`${r.CTE_ARRAY_PREFIX}${i}`,d=new E({selectClause:new O(c),fromClause:new P(new k(new I(null,new C(t)),null),null),groupByClause:u.length>0?new G(u):null});return{cte:new K(d,new W(m,null),null),newCteAlias:m}}buildAggregationDetailsForArrayEntity(e,t,n,i=!1){let s=i?"jsonb_build_object":"json_build_object",o=[];Object.entries(e.columns).forEach(([m,d])=>{o.push(new V(m)),o.push(new f(null,new C(d)))}),t.filter(m=>m.parentId===e.id).forEach(m=>{if(o.push(new V(m.propertyName)),m.relationshipType==="object"){let d=`${m.name.toLowerCase()}_json`;o.push(new f(null,new C(d)))}else m.relationshipType==="array"&&o.push(new f(null,new C(m.propertyName)))});let l=new L(null,new g(s),new Q(o),null),u=i?"jsonb_agg":"json_agg";return{jsonAgg:new L(null,new g(u),new Q([l]),null)}}};var fn=class{constructor(){this.selectValueCollector=new de(null),this.objectEntityCteBuilder=new en,this.arrayEntityCteBuilder=new tn}validateMapping(e,t){let i=new de().collect(e),s=new Set(i.map(u=>u.name));for(let u in t.rootEntity.columns){let c=t.rootEntity.columns[u];if(!s.has(c))throw new Error(`Validation Error: Column "${c}" for JSON key "${u}" in root entity "${t.rootEntity.name}" not found in the query's select list.`)}let o=new Set([t.rootEntity.id]),a=new Map;t.nestedEntities.forEach(u=>{o.add(u.id),a.has(u.parentId)||a.set(u.parentId,[]),a.get(u.parentId).push(u.id)});for(let u of t.nestedEntities){if(!o.has(u.parentId))throw new Error(`Validation Error: Parent entity with ID "${u.parentId}" for nested entity "${u.name}" (ID: ${u.id}) not found.`);for(let c in u.columns){let m=u.columns[c];if(!s.has(m))throw new Error(`Validation Error: Column "${m}" for JSON key "${c}" in nested entity "${u.name}" (ID: ${u.id}) not found in the query's select list.`)}}let l=new Set([t.rootEntity.id,...t.nestedEntities.map(u=>u.parentId)]);for(let u of l){let c=t.nestedEntities.filter(w=>w.parentId===u);if(c.filter(w=>w.relationshipType==="array").length>1){let w=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(y=>y.id===u)?.name;throw new Error(`Validation Error: Parent entity "${w}" (ID: ${u}) has multiple direct array children. This is not supported.`)}let d=new Set;for(let w of c){if(d.has(w.propertyName)){let y=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(S=>S.id===u)?.name;throw new Error(`Validation Error: Parent entity "${y}" (ID: ${u}) has duplicate property name "${w.propertyName}" for its children.`)}d.add(w.propertyName)}}}buildJsonQuery(e,t){return this.buildJsonWithCteStrategy(e,t)}buildJson(e,t){return console.warn("buildJson is deprecated. Use buildJsonQuery instead."),this.buildJsonQuery(e,t)}buildJsonWithCteStrategy(e,t){this.validateMapping(e,t);let{initialCte:n,initialCteAlias:i}=this.createInitialCte(e),s=[n],o=i,a=new Map;a.set(t.rootEntity.id,{...t.rootEntity,isRoot:!0,propertyName:t.rootName}),t.nestedEntities.forEach(c=>a.set(c.id,{...c,isRoot:!1,propertyName:c.propertyName}));let l=this.objectEntityCteBuilder.buildObjectEntityCtes(n,a,t);s=l.ctes,o=l.lastCteAlias;let u=this.arrayEntityCteBuilder.buildArrayEntityCtes(s,o,a,t);return s=u.updatedCtes,o=u.lastCteAlias,this.buildFinalSelectQuery(s,o,a,t)}createInitialCte(e){let t="origin_query";return{initialCte:new K(e,new W(t,null),null),initialCteAlias:t}}buildFinalSelectQuery(e,t,n,i){let s=[...e],o=`cte_root_${i.rootName.toLowerCase().replace(/[^a-z0-9_]/g,"_")}`,a=n.get(i.rootEntity.id);if(!a)throw new Error(`Root entity ${i.rootEntity.id} not found`);if(i.resultFormat==="array"||!i.resultFormat){let l=this.buildEntityJsonObject(a,null,i.nestedEntities,n,i.useJsonb),u=new F(l,i.rootName),c=new K(new E({selectClause:new O([u]),fromClause:new P(new k(new I(null,new C(t)),null),null)}),new W(o,null),null);s.push(c);let m=i.useJsonb?"jsonb_agg":"json_agg",d=new L(null,new g(m),new Q([new f(null,new C(i.rootName))]),null);return new E({withClause:new U(!1,s),selectClause:new O([new F(d,`${i.rootName}_array`)]),fromClause:new P(new k(new I(null,new C(o)),null),null)})}else{let l=this.buildEntityJsonObject(a,null,i.nestedEntities,n,i.useJsonb),u=new F(l,i.rootName),c=new K(new E({selectClause:new O([u]),fromClause:new P(new k(new I(null,new C(t)),null),null)}),new W(o,null),null);return s.push(c),new E({withClause:new U(!1,s),selectClause:new O([new F(new f(null,new C(i.rootName)),i.rootName)]),fromClause:new P(new k(new I(null,new C(o)),null),null),limitClause:new ee(new V(1))})}}buildEntityJsonObject(e,t,n,i,s=!1){let o=s?"jsonb_build_object":"json_build_object",a=[];return Object.entries(e.columns).forEach(([u,c])=>{a.push(new V(u)),a.push(new f(null,new C(c)))}),n.filter(u=>u.parentId===e.id).forEach(u=>{let c=i.get(u.id);if(c)if(a.push(new V(u.propertyName)),u.relationshipType==="object"){let m=`${c.name.toLowerCase()}_json`;a.push(new f(null,new C(m)))}else u.relationshipType==="array"&&a.push(new f(null,new C(u.propertyName)))}),new L(null,new g(o),new Q(a),null)}};var nn=class{constructor(e,t){this.name=e,this.columns=t}},sn=class{constructor(e=null){this.tableColumnResolver=e;this.tableSchemas=[];this.visitedNodes=new Set;this.commonTables=[];this.running=!1;this.handlers=new Map,this.handlers.set(E.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(R.kind,t=>this.visitBinarySelectQuery(t))}collect(e){return this.visit(e),this.tableSchemas}visit(e){if(this.running){this.visitNode(e);return}this.reset(),this.running=!0;try{if(!(e instanceof E||e instanceof R))throw new Error(`Unsupported SQL component type for schema collection. Received: ${e.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let t=new q;this.commonTables=t.collect(e),this.visitNode(e),this.consolidateTableSchemas()}finally{this.running=!1}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}reset(){this.tableSchemas=[],this.visitedNodes=new Set,this.commonTables=[]}consolidateTableSchemas(){let e=new Map;for(let t of this.tableSchemas)if(!e.has(t.name))e.set(t.name,new Set(t.columns));else{let n=e.get(t.name);t.columns.forEach(i=>n?.add(i))}this.tableSchemas=Array.from(e.entries()).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>new nn(t,Array.from(n).sort()))}handleTableSource(e,t,n){if(e.datasource instanceof I){let i=e.datasource.getSourceName(),s=this.commonTables.filter(o=>o.getSourceAliasName()===i);if(s.length>0)s[0].query.accept(this);else{let o=e.getAliasName()??i;this.processCollectTableSchema(i,o,t,n)}}else throw new Error("Datasource is not an instance of TableSource")}visitSimpleSelectQuery(e){if(e.fromClause===null)return;let i=new xe(this.tableColumnResolver,!0,"fullName").collect(e).filter(s=>s.value instanceof f).map(s=>s.value).map(s=>({table:s.getNamespace(),column:s.column.name}));if(e.fromClause.joins!==null&&e.fromClause.joins.length>0){let s=i.filter(o=>o.table==="").map(o=>o.column);if(s.length>0)throw new Error(`Column reference(s) without table name found in query: ${s.join(", ")}`)}if(e.fromClause.source.datasource instanceof I?this.handleTableSource(e.fromClause.source,i,!0):e.fromClause.source.datasource instanceof N&&e.fromClause.source.datasource.query.accept(this),e.fromClause?.joins)for(let s of e.fromClause.joins)s.source.datasource instanceof I?this.handleTableSource(s.source,i,!1):s.source.datasource instanceof N&&s.source.datasource.query.accept(this)}visitBinarySelectQuery(e){this.visitNode(e.left),this.visitNode(e.right)}processCollectTableSchema(e,t,n,i=!1){if(this.tableColumnResolver===null&&n.filter(l=>l.table===t||i&&l.table==="").filter(l=>l.column==="*").length>0){let l=e?`Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards. Target table: ${e}`:"Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards.";throw new Error(l)}let s=n.filter(a=>a.column!=="*").filter(a=>a.table===t||i&&a.table==="").map(a=>a.column),o=new nn(e,s);this.tableSchemas.push(o)}};var wn=class{constructor(e,t){typeof e=="function"?(this.tableColumnResolver=e,this.options=t||{}):(this.tableColumnResolver=void 0,this.options=e||{})}inject(e,t){typeof e=="string"&&(e=B.parse(e));let n=new it(this.tableColumnResolver,this.options),i=new xe(this.tableColumnResolver),s=c=>this.options.ignoreCaseAndUnderscore?c.toLowerCase().replace(/_/g,""):c,o=["min","max","like","in","any","=","<",">","!=","<>","<=",">="];for(let[c,m]of Object.entries(t)){if(m===void 0)continue;let d=n.find(e,c);if(d.length===0)throw new Error(`Column '${c}' not found in query`);for(let w of d){let S=i.collect(w).find(Ae=>s(Ae.name)===s(c));if(!S)throw new Error(`Column '${c}' not found in query`);let $e=S.value;m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.getPrototypeOf(m)===Object.prototype&&a(m,o,c),m===null||typeof m!="object"||Array.isArray(m)||m instanceof Date?l(w,$e,c,m):u(w,$e,c,m)}}function a(c,m,d){Object.keys(c).forEach(w=>{if(!m.includes(w))throw new Error(`Unsupported operator '${w}' for state key '${d}'`)})}function l(c,m,d,w){let y=new A(d,w);c.appendWhere(new b(m,"=",y))}function u(c,m,d,w){if("="in w){let y=new A(d,w["="]);c.appendWhere(new b(m,"=",y))}if("min"in w){let y=new A(d+"_min",w.min);c.appendWhere(new b(m,">=",y))}if("max"in w){let y=new A(d+"_max",w.max);c.appendWhere(new b(m,"<=",y))}if("like"in w){let y=new A(d+"_like",w.like);c.appendWhere(new b(m,"like",y))}if("in"in w){let S=w.in.map(($e,Ae)=>new A(`${d}_in_${Ae}`,$e));c.appendWhere(new b(m,"in",new H(new Q(S))))}if("any"in w){let y=new A(d+"_any",w.any);c.appendWhere(new b(m,"=",new L(null,"any",y,null)))}if("<"in w){let y=new A(d+"_lt",w["<"]);c.appendWhere(new b(m,"<",y))}if(">"in w){let y=new A(d+"_gt",w[">"]);c.appendWhere(new b(m,">",y))}if("!="in w){let y=new A(d+"_neq",w["!="]);c.appendWhere(new b(m,"!=",y))}if("<>"in w){let y=new A(d+"_ne",w["<>"]);c.appendWhere(new b(m,"<>",y))}if("<="in w){let y=new A(d+"_le",w["<="]);c.appendWhere(new b(m,"<=",y))}if(">="in w){let y=new A(d+"_ge",w[">="]);c.appendWhere(new b(m,">=",y))}}return e}};var Cn=class{static validate(e,t){let n=typeof e=="string"?B.parse(e):e,i=Array.isArray(t)?l=>{let u=t.find(c=>c.name===l);return u?u.columns:[]}:t,o=new sn(i).collect(n),a=[];for(let l of o){let u=i(l.name);if(u.length===0){a.push(`Table '${l.name}' is not defined.`);continue}let c=l.columns.filter(m=>!u.includes(m));c.length>0&&a.push(`Table '${l.name}' contains undefined columns: ${c.join(", ")}.`)}if(a.length>0)throw new Error(a.join(`
15
+ `))}};var ct=class{constructor(e){this.schemas=e,this.validateSchemas()}validateSchemas(){let e=Object.keys(this.schemas),t=[];if(Object.entries(this.schemas).forEach(([n,i])=>{Object.entries(i.columns).filter(([o,a])=>a.isPrimaryKey).map(([o,a])=>o).length===0&&t.push(`Table '${n}' has no primary key defined`),i.relationships?.forEach(o=>{e.includes(o.table)||t.push(`Table '${n}' references unknown table '${o.table}' in relationship`)})}),t.length>0)throw new Error(`Schema validation failed:\\n${t.join("\\n")}`)}getTableColumns(e){let t=this.schemas[e];return t?Object.keys(t.columns):[]}createTableColumnResolver(){return e=>this.getTableColumns(e)}createJsonMapping(e){let t=this.schemas[e];if(!t)throw new Error(`Table '${e}' not found in schema registry`);let n={};Object.entries(t.columns).forEach(([s,o])=>{n[s]=o.jsonAlias||o.name});let i=[];return t.relationships?.forEach(s=>{let o=this.schemas[s.table];if(!o)throw new Error(`Related table '${s.table}' not found in schema registry`);let a={};Object.entries(o.columns).forEach(([u,c])=>{a[u]=c.jsonAlias||c.name});let l=s.type;i.push({id:s.propertyName,name:o.displayName||s.table,parentId:e,propertyName:s.propertyName,relationshipType:l,columns:a})}),{rootName:e,rootEntity:{id:e,name:t.displayName||e,columns:n},nestedEntities:i,useJsonb:!0,resultFormat:"single"}}getTableNames(){return Object.keys(this.schemas)}getTable(e){return this.schemas[e]}getPrimaryKey(e){let t=this.schemas[e];if(!t)return;let n=Object.entries(t.columns).find(([i,s])=>s.isPrimaryKey);return n?n[0]:void 0}getForeignKeys(e){let t=this.schemas[e];if(!t)return[];let n=[];return Object.entries(t.columns).forEach(([i,s])=>{s.foreignKey&&n.push({column:i,referencedTable:s.foreignKey.table,referencedColumn:s.foreignKey.column})}),n}};function gh(r){return new ct(r)}function kh(r){return new ct(r).createTableColumnResolver()}function Th(r,e){return new ct(r).createJsonMapping(e)}export{re as ArrayExpression,oe as ArrayQueryExpression,ae as BetweenExpression,b as BinaryExpression,R as BinarySelectQuery,q as CTECollector,Oe as CTENormalizer,_ as CaseExpression,ie as CaseKeyValuePair,se as CastExpression,f as ColumnReference,hn as DuplicateDetectionMode,Re as Formatter,L as FunctionCall,C as IdentifierString,fe as InlineQuery,Le as InsertQuery,dn as InsertQueryParser,V as LiteralValue,A as ParameterExpression,H as ParenExpression,fn as PostgresJsonQueryBuilder,Ce as QualifiedName,st as QueryBuilder,g as RawString,sn as SchemaCollector,ct as SchemaManager,B as SelectQueryParser,de as SelectValueCollector,xe as SelectableColumnCollector,E as SimpleSelectQuery,nt as SqlFormatter,wn as SqlParamInjector,Cn as SqlSchemaValidator,Je as StringSpecifierExpression,ne as SwitchCaseArgument,nn as TableSchema,Nt as TableSourceCollector,le as TupleExpression,Se as TypeValue,D as UnaryExpression,it as UpstreamSelectQueryFinder,ul as VALID_PRESETS,Q as ValueList,z as ValuesQuery,cn as WindowFrameBound,qe as WindowFrameBoundStatic,De as WindowFrameBoundaryValue,we as WindowFrameExpression,Ee as WindowFrameSpec,un as WindowFrameType,Th as createJsonMappingFromSchema,gh as createSchemaManager,kh as createTableColumnResolver};
16
+ //# sourceMappingURL=index.min.js.map