rawsql-ts 0.10.1-beta → 0.10.3-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.
- package/dist/esm/index.min.js +16 -0
- package/dist/esm/index.min.js.map +7 -0
- package/dist/esm/models/ValueComponent.js +7 -0
- package/dist/esm/models/ValueComponent.js.map +1 -1
- package/dist/esm/parsers/CommandExpressionParser.js +1 -16
- package/dist/esm/parsers/CommandExpressionParser.js.map +1 -1
- package/dist/esm/parsers/FunctionExpressionParser.js +51 -6
- package/dist/esm/parsers/FunctionExpressionParser.js.map +1 -1
- package/dist/esm/parsers/SqlPrintTokenParser.js +11 -1
- package/dist/esm/parsers/SqlPrintTokenParser.js.map +1 -1
- package/dist/esm/parsers/ValueParser.js +56 -11
- package/dist/esm/parsers/ValueParser.js.map +1 -1
- package/dist/esm/tokenReaders/CommandTokenReader.js +0 -1
- package/dist/esm/tokenReaders/CommandTokenReader.js.map +1 -1
- package/dist/esm/tokenReaders/FunctionTokenReader.js +2 -0
- package/dist/esm/tokenReaders/FunctionTokenReader.js.map +1 -1
- package/dist/esm/transformers/CTECollector.js +18 -2
- package/dist/esm/transformers/CTECollector.js.map +1 -1
- package/dist/esm/transformers/CTEDisabler.js +6 -1
- package/dist/esm/transformers/CTEDisabler.js.map +1 -1
- package/dist/esm/transformers/SelectableColumnCollector.js +5 -1
- package/dist/esm/transformers/SelectableColumnCollector.js.map +1 -1
- package/dist/esm/transformers/TableSourceCollector.js +37 -2
- package/dist/esm/transformers/TableSourceCollector.js.map +1 -1
- package/dist/esm/types/models/ValueComponent.d.ts +6 -1
- package/dist/esm/types/parsers/CommandExpressionParser.d.ts +0 -1
- package/dist/esm/types/parsers/FunctionExpressionParser.d.ts +13 -1
- package/dist/esm/types/parsers/SqlPrintTokenParser.d.ts +1 -0
- package/dist/esm/types/parsers/ValueParser.d.ts +9 -1
- package/dist/esm/types/transformers/CTECollector.d.ts +3 -0
- package/dist/esm/types/transformers/CTEDisabler.d.ts +2 -1
- package/dist/esm/types/transformers/SelectableColumnCollector.d.ts +1 -0
- package/dist/esm/types/transformers/TableSourceCollector.d.ts +9 -0
- package/dist/esm/types/utils/OperatorPrecedence.d.ts +29 -0
- package/dist/esm/types/utils/ParameterRemover.d.ts +225 -0
- package/dist/esm/utils/OperatorPrecedence.js +79 -0
- package/dist/esm/utils/OperatorPrecedence.js.map +1 -0
- package/dist/esm/utils/ParameterRemover.js +777 -0
- package/dist/esm/utils/ParameterRemover.js.map +1 -0
- package/dist/index.min.js +16 -0
- package/dist/index.min.js.map +7 -0
- package/dist/models/ValueComponent.d.ts +6 -1
- package/dist/models/ValueComponent.js +9 -1
- package/dist/models/ValueComponent.js.map +1 -1
- package/dist/parsers/CommandExpressionParser.d.ts +0 -1
- package/dist/parsers/CommandExpressionParser.js +0 -15
- package/dist/parsers/CommandExpressionParser.js.map +1 -1
- package/dist/parsers/FunctionExpressionParser.d.ts +13 -1
- package/dist/parsers/FunctionExpressionParser.js +50 -5
- package/dist/parsers/FunctionExpressionParser.js.map +1 -1
- package/dist/parsers/SqlPrintTokenParser.d.ts +1 -0
- package/dist/parsers/SqlPrintTokenParser.js +10 -0
- package/dist/parsers/SqlPrintTokenParser.js.map +1 -1
- package/dist/parsers/ValueParser.d.ts +9 -1
- package/dist/parsers/ValueParser.js +55 -10
- package/dist/parsers/ValueParser.js.map +1 -1
- package/dist/tokenReaders/CommandTokenReader.js +0 -1
- package/dist/tokenReaders/CommandTokenReader.js.map +1 -1
- package/dist/tokenReaders/FunctionTokenReader.js +2 -0
- package/dist/tokenReaders/FunctionTokenReader.js.map +1 -1
- package/dist/transformers/CTECollector.d.ts +3 -0
- package/dist/transformers/CTECollector.js +16 -0
- package/dist/transformers/CTECollector.js.map +1 -1
- package/dist/transformers/CTEDisabler.d.ts +2 -1
- package/dist/transformers/CTEDisabler.js +5 -0
- package/dist/transformers/CTEDisabler.js.map +1 -1
- package/dist/transformers/SelectableColumnCollector.d.ts +1 -0
- package/dist/transformers/SelectableColumnCollector.js +4 -0
- package/dist/transformers/SelectableColumnCollector.js.map +1 -1
- package/dist/transformers/TableSourceCollector.d.ts +9 -0
- package/dist/transformers/TableSourceCollector.js +35 -0
- package/dist/transformers/TableSourceCollector.js.map +1 -1
- package/dist/utils/OperatorPrecedence.d.ts +29 -0
- package/dist/utils/OperatorPrecedence.js +83 -0
- package/dist/utils/OperatorPrecedence.js.map +1 -0
- package/dist/utils/ParameterRemover.d.ts +225 -0
- package/dist/utils/ParameterRemover.js +781 -0
- package/dist/utils/ParameterRemover.js.map +1 -0
- package/package.json +4 -2
@@ -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 Ne=class extends h{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var we=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}},w=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 ve(mn(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},O=class extends h{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,i){super(),this.qualifiedName=new ve(e,t),this.argument=n,this.over=i}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},cn=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(cn||{}),pn=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(pn||{}),Je=class extends h{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},Me=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}},Ce=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}},E=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}},ie=class extends h{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},se=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}},G=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}},Ie=class extends h{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new g(e),this.value=new V(t)}},me=class extends h{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new ve(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 mn(o){if(o==null)return null;if(typeof o=="string")return o.trim()===""?null:[new C(o)];if(Array.isArray(o)){if(o.length===0)return null;if(typeof o[0]=="string"){let e=o.filter(t=>t.trim()!=="");return e.length===0?null:e.map(t=>new C(t))}else{let e=o.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var ve=class extends h{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=mn(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 L=class extends h{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new C(t):null}},F=class extends h{static{this.kind=Symbol("SelectClause")}constructor(e,t=null){super(),this.items=e,this.distinct=t}},ze=class extends h{static{this.kind=Symbol("Distinct")}constructor(){super()}},_e=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}},ne=class extends h{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new C(e),this.expression=t}},Ve=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}},ye=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}},Y=class extends h{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},X=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 ve(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}},Pe=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 ve(n.namespaces,n.name)}else this.qualifiedName=new ve(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}},Z=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}},ee=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}},U=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}},K=class extends h{static{this.kind=Symbol("WithClause")}constructor(e,t){super(),this.recursive=e,this.tables=t}},te=class extends h{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var Le=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 Se=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}},ht=class extends h{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new C(t):t)}},Ae=class extends h{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof Be?t:new Be(t.column,t.value))}},Be=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 ve(n.namespaces,i)}else{let n=typeof e=="string"?new C(e):e;this.qualifiedName=new ve(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()}},He=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}},Re=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 o{static getDebugPositionInfo(e,t){let n=Math.max(0,t-5),i=Math.min(e.length,t+5),s=e.slice(n,i),r=" ".repeat(t-n)+"^";return`${s}
|
2
|
+
${r}`}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=o.skipWhiteSpace(e,t),t!==s)continue;let r=e.charCodeAt(t);if(r===45){let a=o.readLineComment(e,t);if(a.newPosition!==t){t=a.newPosition,a.comment&&n.push(a.comment.trim());continue}}else if(r===47){let a=o.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
|
+
${o.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 dt=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 he=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 r=i,a=M.tryReadRegularIdentifier(e,t);if(a!==null){if(i=this.trie.pushLexeme(a.identifier.toLowerCase()),i===0){if(r===2)break;return null}if(s+=" "+a.identifier,t=M.readWhiteSpaceAndComment(e,a.newPosition).position,i===3)break}else{if(r===2)break;return null}}return{keyword:s,newPosition:t}}};var de=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 Sn=[["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"]],xn=new de(Sn),on=new he(xn),ft=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=on.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 r=this.input[this.position];if(j.isDigit(r)||s&&j.isHexChar(r))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 wt=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 Ct=class o 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 o.SPECIAL_SYMBOL_TOKENS?(this.position++,this.createLexeme(o.SPECIAL_SYMBOL_TOKENS[t],t)):null}};var vt=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 En=new de([["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"]]),bn=new de([["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"]]),gn=new he(En),kn=new he(bn);var yt=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 r=this.input[this.position];if(r==="-"&&this.input[this.position+1]==="-")break;if(r==="/"&&this.input[this.position+1]==="*")break}this.position++}let s=this.input.slice(i,this.position);return this.createLexeme(2,s)}let n=kn.parse(this.input,this.position);return n!==null?(this.position=n.newPosition,this.createLexeme(8258,n.keyword)):(n=gn.parse(this.input,this.position),n!==null?(this.position=n.newPosition,this.createLexeme(2,n.keyword)):null)}};var Tn=new de([["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"]]),In=new de([["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"]]),Pn=new he(In),an=new he(Tn),St=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(128,t.keyword);let n=Pn.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 Ln=new Set(["e'","E'","x'","X'","b'","B'"]),Fn=new Set(["u&'","U&'"]),xt=class extends ${tryRead(e){let t=this.position;return this.canRead(1)&&Ln.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 de([["grouping","sets"],["array"]]),Nn=new he(On),Et=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=Nn.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 An=new de([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),Qn=new he(An),bt=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=Qn.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 gt=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 vt(e).register(new gt(e)).register(new wt(e)).register(new xt(e)).register(new ft(e)).register(new Ct(e)).register(new St(e)).register(new yt(e)).register(new bt(e)).register(new Et(e)).register(new dt(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 r=null;for(;this.canRead()&&this.input[this.position]!==";";){let a=this.readerManager.tryRead(this.position,r);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,r=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 pe=class o{static parseFromLexeme(e,t){let{identifiers:n,newIndex:i}=o.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:s,name:r}=o.extractNamespacesAndName(n),a=0;return i>t&&(a=e[i-1].type),{namespaces:s,name:new C(r),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 kt=class{static parseFromLexeme(e,t){let{namespaces:n,name:i,newIndex:s}=pe.parseFromLexeme(e,t);return{value:new w(n,i),newIndex:s}}};var ot=class{static parseFromLexeme(e,t){let n=t,i=e[n].value,s,r=on.parse(i.toLowerCase(),0);if(r){let l=new g(r.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 Tt=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 we(i.value),newIndex:n}}else{let i=y.parseArgument(4,8,e,t);return n=i.newIndex,{value:new H(i.value),newIndex:n}}}};var It=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 w(null,"*"),newIndex:n};let s=y.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 Pt=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 Lt=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 Ie(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=y.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=y.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],r=this.parseSwitchCaseArgument(e,n,s);return n=r.newIndex,{value:new _(null,r.value),newIndex:n}}static parseSwitchCaseArgument(e,t,n){let i=t,s=[...n],r=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=y.parseFromLexeme(e,i);r=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 ie(s,r),newIndex:i}}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,i=y.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=y.parseFromLexeme(e,n);return n=s.newIndex,{value:new se(i.value,s.value),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 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 r=this.parseItem(e,n);i.push(r.value),n=r.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=y.parseFromLexeme(e,n),s=i.value;if(n=i.newIndex,n>=e.length)return{value:s,newIndex:n};let r=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 r===null&&a===null?{value:s,newIndex:n}:{value:new ye(s,r,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=y.parseFromLexeme(e,n);for(i.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let r=y.parseFromLexeme(e,n);i.push(r.value),n=r.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 Ye=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,r=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=Ge.parseFromLexeme(e,n);s=a.value,n=a.newIndex}if(n<e.length&&this.isFrameTypeKeyword(e[n].value)){let a=this.parseFrameSpec(e,n);r=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 Ce(i,s,r),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 r=this.parseFrameBoundary(e,n),a=r.value;if(n=r.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 r=this.parseFrameBoundary(e,n),a=r.value;return n=r.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 Je(s),newIndex:n+1}}else if(n<e.length&&e[n].type&1){let i=y.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length&&e[n].type&128){let s=e[n].value,r;if(s==="preceding")r=!1;else if(s==="following")r=!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 Me(i.value,r),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 Ye.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 je=class{static parseArrayExpression(e,t){let n=t;if(n+1<e.length&&e[n+1].type&512){n++;let i=y.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,s=!0){let r=t;if(r<e.length&&e[r].type&2){let a=e[r].value.toLowerCase();if(!i&&a==="and"||!s&&a==="or")return null;if(r++,a==="between")return this.parseBetweenExpression(e,r,n,!1);if(a==="not between")return this.parseBetweenExpression(e,r,n,!0);if(a==="::"){let c=this.parseTypeValue(e,r);return r=c.newIndex,{value:new G(n,c.value),newIndex:r}}let l=y.parseFromLexeme(e,r);return r=l.newIndex,{value:new E(n,a,l.value),newIndex:r}}return null}static parseBetweenExpression(e,t,n,i){let s=t,r=y.parseFromLexeme(e,s,!1);if(s=r.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=this.parseBetweenUpperBound(e,s);return s=a.newIndex,{value:new ae(n,r.value,a.value,i),newIndex:s}}static parseBetweenUpperBound(e,t){return y.parseFromLexeme(e,t,!1,!1)}static parseFunctionCall(e,t){let n=t,i=pe.parseFromLexeme(e,n),s=i.namespaces,r=i.name;if(n=i.newIndex,n<e.length&&e[n].type&4){let a=y.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 O(s,r.name,a.value,l.value),newIndex:n}}else return{value:new O(s,r.name,a.value,null),newIndex:n}}else throw new Error(`Expected opening parenthesis after function name '${r.name}' at index ${n}`)}static parseKeywordFunction(e,t,n){let i=t,s=pe.parseFromLexeme(e,i),r=s.namespaces,a=s.name;if(i=s.newIndex,i<e.length&&e[i].type&4){i++;let l=y.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 E(u,c,d.value),i=d.newIndex}else{let d=y.parseFromLexeme(e,i);u=new E(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 O(r,a.name,u,c.value),newIndex:i}}else return{value:new O(r,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:r}=pe.parseFromLexeme(e,n);if(n=r,n<e.length&&e[n].type&4){let a=y.parseArgument(4,8,e,n);return n=a.newIndex,{value:new me(i,new g(s.name),a.value),newIndex:n}}else return{value:new me(i,new g(s.name)),newIndex:n}}};var Nt=class o 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),r=Math.min(t.length,n+3),a=t.slice(s,r).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 o(l,n,a)}};var lt=class{static{this.precedenceMap={or:1,and:2,"=":10,"!=":10,"<>":10,"<":10,"<=":10,">":10,">=":10,like:10,ilike:10,"not like":10,"not ilike":10,in:10,"not in":10,is:10,"is not":10,between:15,"not between":15,"+":20,"-":20,"*":30,"/":30,"%":30,"^":40,"::":50,"unary+":100,"unary-":100,not:100}}static getPrecedence(e){let t=this.precedenceMap[e.toLowerCase()];return t!==void 0?t:0}static hasHigherOrEqualPrecedence(e,t){return this.getPrecedence(e)>=this.getPrecedence(t)}static isLogicalOperator(e){let t=e.toLowerCase();return t==="and"||t==="or"}static isBetweenOperator(e){let t=e.toLowerCase();return t==="between"||t==="not between"}static isComparisonOperator(e){let t=e.toLowerCase();return["=","!=","<>","<",">","<=",">=","like","ilike","in","not in"].includes(t)}};var y=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw Nt.fromUnparsedLexemes(n,i.newIndex,"[ValueParser]");return i.value}static parseFromLexeme(e,t,n=!0,i=!0){return this.parseExpressionWithPrecedence(e,t,0,n,i)}static parseExpressionWithPrecedence(e,t,n,i=!0,s=!0){let r=t,a=e[r].comments,l=this.parseItem(e,r);l.value.comments=a,r=l.newIndex;let u=l.value;for(;r<e.length&&e[r].type&2;){let m=e[r].value;if(!i&&m.toLowerCase()==="and"||!s&&m.toLowerCase()==="or")break;let d=lt.getPrecedence(m);if(d<n)break;if(r++,lt.isBetweenOperator(m)){let S=je.parseBetweenExpression(e,r,u,m.toLowerCase().includes("not"));u=S.value,r=S.newIndex;continue}if(m==="::"){let S=je.parseTypeValue(e,r);u=new G(u,S.value),r=S.newIndex;continue}let f=d+1,v=this.parseExpressionWithPrecedence(e,r,f,i,s);r=v.newIndex,u=new E(u,m,v.value)}return{value:u,newIndex:r}}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=kt.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:r,newIndex:a}=pe.parseFromLexeme(e,n);return e[a-1].type&10240?je.parseFromLexeme(e,n):{value:new w(s,r),newIndex:a}}else{if(i.type&1)return ot.parseFromLexeme(e,n);if(i.type&4)return Tt.parseFromLexeme(e,n);if(i.type&2048)return je.parseFromLexeme(e,n);if(i.type&2)return It.parseFromLexeme(e,n);if(i.type&256)return Pt.parseFromLexeme(e,n);if(i.type&4096)return Lt.parseFromLexeme(e,n);if(i.type&128)return Ft.parseFromLexeme(e,n);if(i.type&512){let{namespaces:s,name:r,newIndex:a}=pe.parseFromLexeme(e,n);return{value:new w(s,r),newIndex:a}}else if(i.type&8192){let{namespaces:s,name:r,newIndex:a}=pe.parseFromLexeme(e,n);return{value:new me(s,r),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,r=[];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 w(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,r.push(a.value);s<n.length&&n[s].type&16;){s++;let l=this.parseFromLexeme(n,s);s=l.newIndex,r.push(l.value)}if(s<n.length&&n[s].type===t)return s++,r.length===1?{value:r[0],newIndex:s}:{value:new Q(r),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(b.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(K.kind,e=>this.visitWithClause(e)),this.handlers.set(U.kind,e=>this.visitCommonTable(e)),this.handlers.set(L.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(w.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(Pe.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(we.kind,e=>this.visitInlineQuery(e)),this.handlers.set(P.kind,e=>this.visitFromClause(e)),this.handlers.set(ee.kind,e=>this.visitJoinClause(e)),this.handlers.set(Z.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(E.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(se.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(ie.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ae.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(O.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(G.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ce.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Ee.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(me.kind,e=>this.visitTypeValue(e)),this.handlers.set(Q.kind,e=>this.visitValueList(e)),this.handlers.set(Ie.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(F.kind,e=>this.visitSelectClause(e)),this.handlers.set(Y.kind,e=>this.visitGroupByClause(e)),this.handlers.set(X.kind,e=>this.visitHavingClause(e)),this.handlers.set(ue.kind,e=>this.visitOrderByClause(e)),this.handlers.set(ne.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(te.kind,e=>this.visitLimitClause(e)),this.handlers.set(Se.kind,e=>this.visitForClause(e)),this.handlers.set(ye.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)}visitStringSpecifierExpression(e){}};var Xe=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(b.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(L.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(w.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(we.kind,e=>this.visitInlineQuery(e)),this.handlers.set(P.kind,e=>this.visitFromClause(e)),this.handlers.set(ee.kind,e=>this.visitJoinClause(e)),this.handlers.set(Z.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(E.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(se.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(ie.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ae.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(O.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(G.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ce.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Ee.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(me.kind,e=>this.visitTypeValue(e)),this.handlers.set(F.kind,e=>this.visitSelectClause(e)),this.handlers.set(Y.kind,e=>this.visitGroupByClause(e)),this.handlers.set(X.kind,e=>this.visitHavingClause(e)),this.handlers.set(ue.kind,e=>this.visitOrderByClause(e)),this.handlers.set(ne.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(te.kind,e=>this.visitLimitClause(e)),this.handlers.set(Se.kind,e=>this.visitForClause(e)),this.handlers.set(ye.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 Ve(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 F(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 we(t)}visitJoinClause(e){let t=this.visit(e.source),n=e.condition?this.visit(e.condition):null;return new ee(e.joinType.value,t,n,e.lateral)}visitJoinOnClause(e){let t=this.visit(e.condition);return new Z(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 Y(t)}visitHavingClause(e){let t=this.visit(e.condition);return new X(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 ne(e.name.name,t)}visitLimitClause(e){let t=this.visit(e.value);return new te(t)}visitForClause(e){return new Se(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 E(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 ie(t,n)}visitCaseKeyValuePair(e){let t=this.visit(e.key),n=this.visit(e.value);return new se(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 O(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 G(t,n)}visitTypeValue(e){let t=e.argument?this.visit(e.argument):null;return new me(e.namespaces,e.name,t)}visitSelectItem(e){let t=this.visit(e.value);return new L(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 Ce(t,n,i)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new ye(t,e.sortDirection,e.nullsPosition)}};var At=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(b.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(K.kind,t=>this.visitWithClause(t)),this.handlers.set(U.kind,t=>this.visitCommonTable(t)),this.handlers.set(P.kind,t=>this.visitFromClause(t)),this.handlers.set(ee.kind,t=>this.visitJoinClause(t)),this.handlers.set(Z.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(Pe.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(we.kind,t=>this.visitInlineQuery(t)),e||(this.handlers.set(J.kind,t=>this.visitWhereClause(t)),this.handlers.set(Y.kind,t=>this.visitGroupByClause(t)),this.handlers.set(X.kind,t=>this.visitHavingClause(t)),this.handlers.set(ue.kind,t=>this.visitOrderByClause(t)),this.handlers.set(ne.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(te.kind,t=>this.visitLimitClause(t)),this.handlers.set(Le.kind,t=>this.visitOffsetClause(t)),this.handlers.set(Fe.kind,t=>this.visitFetchClause(t)),this.handlers.set(Se.kind,t=>this.visitForClause(t)),this.handlers.set(ye.kind,t=>this.visitOrderByItem(t)),this.handlers.set(F.kind,t=>this.visitSelectClause(t)),this.handlers.set(L.kind,t=>this.visitSelectItem(t)),this.handlers.set(H.kind,t=>this.visitParenExpression(t)),this.handlers.set(E.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(se.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(ie.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(ae.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(O.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(G.kind,t=>this.visitCastExpression(t)),this.handlers.set(Q.kind,t=>this.visitValueList(t)),this.handlers.set(Ie.kind,t=>this.visitStringSpecifierExpression(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)}visitStringSpecifierExpression(e){}};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 r=i[s];Array.isArray(r)?r.forEach(n):r&&typeof r=="object"&&r.constructor&&r.constructor.kind&&n(r)}}}return n(e),t}};var Qt=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var Vt=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 Ae?e.setClause:new Ae(e.setClause),this.whereClause=e.whereClause??null,this.fromClause=e.fromClause??null,this.returningClause=e.returning??null}};var fe=class o{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(b.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(F.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 w&&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 w&&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 r=s.getSourceAliasName();r&&n.includes(r)&&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 o(this.tableColumnResolver,i).collect(n.query).forEach(a=>{this.addSelectValueAsUnique(a.name,new w(e?[e]:null,a.name))})}else new o(this.tableColumnResolver,this.commonTables).collect(t).forEach(r=>{this.addSelectValueAsUnique(r.name,new w(e?[e]:null,r.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 w){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 w(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 w([t],n))})}return}else if(e.datasource instanceof N){let t=e.getAliasName();new o(this.tableColumnResolver,this.commonTables).collect(e.datasource.query).forEach(s=>{this.addSelectValueAsUnique(s.name,new w(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 fe().collect(this.asSelectQuery).map(i=>new L(i.value,i.name)):e=[new L(new g("*"))],new b({selectClause:new F(e),fromClause:new P(new k(new I(null,this.tableName.name),null),null)})}getCountQuery(){return new b({selectClause:new F([new L(new O(null,"count",new w(null,"*"),null))]),fromClause:new P(new k(new I(null,this.tableName.name),null),null)})}};var hn={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"}},Bt=class o{constructor(e){this.handlers=new Map;this.index=1;e?.preset&&(e={...e.preset,...e}),this.parameterDecorator=new Vt({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 Qt({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.handlers.set(Q.kind,t=>this.visitValueList(t)),this.handlers.set(w.kind,t=>this.visitColumnReference(t)),this.handlers.set(ve.kind,t=>this.visitQualifiedName(t)),this.handlers.set(O.kind,t=>this.visitFunctionCall(t)),this.handlers.set(D.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(E.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(ie.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(se.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(G.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(Ie.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(me.kind,t=>this.visitTypeValue(t)),this.handlers.set(le.kind,t=>this.visitTupleExpression(t)),this.handlers.set(we.kind,t=>this.visitInlineQuery(t)),this.handlers.set(Ce.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(Ee.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(Je.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(Me.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(ye.kind,t=>this.visitOrderByItem(t)),this.handlers.set(L.kind,t=>this.visitSelectItem(t)),this.handlers.set(F.kind,t=>this.visitSelectClause(t)),this.handlers.set(ze.kind,t=>this.visitDistinct(t)),this.handlers.set(_e.kind,t=>this.visitDistinctOn(t)),this.handlers.set(I.kind,t=>this.visitTableSource(t)),this.handlers.set(Pe.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(ee.kind,t=>this.visitJoinClause(t)),this.handlers.set(Z.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(Y.kind,t=>this.visitGroupByClause(t)),this.handlers.set(X.kind,t=>this.visitHavingClause(t)),this.handlers.set(Ve.kind,t=>this.visitWindowClause(t)),this.handlers.set(ne.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(te.kind,t=>this.visitLimitClause(t)),this.handlers.set(Le.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(Se.kind,t=>this.visitForClause(t)),this.handlers.set(K.kind,t=>this.visitWithClause(t)),this.handlers.set(U.kind,t=>this.visitCommonTable(t)),this.handlers.set(b.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(Ne.kind,t=>this.visitInsertQuery(t)),this.handlers.set(Re.kind,t=>this.visitInsertClause(t)),this.handlers.set(et.kind,t=>this.visitUpdateQuery(t)),this.handlers.set(He.kind,t=>this.visitUpdateClause(t)),this.handlers.set(Ae.kind,t=>this.visitSetClause(t)),this.handlers.set(Be.kind,t=>this.visitSetClauseItem(t)),this.handlers.set(ht.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(o.SPACE_TOKEN),t.innerTokens.push(new p(1,e.operator.value,"BinarySelectQueryOperator")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}static commaSpaceTokens(){return[o.COMMA_TOKEN,o.SPACE_TOKEN]}static argumentCommaSpaceTokens(){return[o.ARGUMENT_SPLIT_COMMA_TOKEN,o.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(o.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(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOrderByClause(e){let t=new p(1,"order by","OrderByClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.order.length;n++)n>0&&t.innerTokens.push(...o.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(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"desc"))),e.nullsPosition&&(e.nullsPosition==="first"?(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"nulls first"))):e.nullsPosition==="last"&&(t.innerTokens.push(o.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,r)=>(s.index??0)-(r.index??0)),i=this.parameterDecorator.style;if(i==="named"){let s={};for(let r of n){let a=r.name.value;if(s.hasOwnProperty(a)){if(s[a]!==r.value)throw new Error(`Duplicate parameter name '${a}' with different values detected during query composition.`);continue}s[a]=r.value}return{token:t,params:s}}else if(i==="indexed"){let s=n.map(r=>r.value);return{token:t,params:s}}else if(i==="anonymous"){let s=n.map(r=>r.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(...o.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(o.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),e.over&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"over")),e.over instanceof C?(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.over.accept(this))):(t.innerTokens.push(o.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.over)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN))),t}visitUnaryExpression(e){let t=new p(0,"","UnaryExpression");return t.innerTokens.push(this.visit(e.operator)),t.innerTokens.push(o.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(o.SPACE_TOKEN),t.innerTokens.push(new p(5,e.operator.value)),t.innerTokens.push(o.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(o.SPACE_TOKEN),t.innerTokens.push(n.accept(this));return e.elseValue&&(t.innerTokens.push(o.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(o.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(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.key)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"then")),t.innerTokens.push(o.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(o.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(o.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(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition))),t.innerTokens.push(this.visit(e.switchCase)),t.innerTokens.push(o.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(o.SPACE_TOKEN),e.negated&&(t.innerTokens.push(new p(1,"not")),t.innerTokens.push(o.SPACE_TOKEN)),t.innerTokens.push(new p(1,"between")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.lower)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"and")),t.innerTokens.push(o.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(o.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN)),t}visitTupleExpression(e){let t=new p(0,"","TupleExpression");t.innerTokens.push(o.PAREN_OPEN_TOKEN);for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...o.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t.innerTokens.push(o.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(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.order))),e.frameSpec&&(n?n=!1:t.innerTokens.push(o.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(o.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this))):(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"between")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"and")),t.innerTokens.push(o.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(o.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 w){let n=e.value.column.name;if(e.identifier.name===n)return t}return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.identifier)),t}visitSelectClause(e){let t=new p(1,"select","SelectClause");t.innerTokens.push(o.SPACE_TOKEN),e.distinct&&(t.keywordTokens=[],t.keywordTokens.push(o.SPACE_TOKEN),t.keywordTokens.push(e.distinct.accept(this)));for(let n=0;n<e.items.length;n++)n>0&&t.innerTokens.push(...o.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(o.PAREN_OPEN_TOKEN),t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(o.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(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this))),t}else return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this)),t}visitFromClause(e){let t=new p(1,"from","FromClause");if(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.joins)for(let n=0;n<e.joins.length;n++)t.innerTokens.push(o.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(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"lateral"))),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.condition&&(t.innerTokens.push(o.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(o.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(o.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.condition)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitFunctionSource(e){let t=new p(0,"","FunctionSource");return t.innerTokens.push(e.qualifiedName.accept(this)),t.innerTokens.push(o.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(o.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(o.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...o.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));t.innerTokens.push(o.PAREN_CLOSE_TOKEN)}return t}visitWhereClause(e){let t=new p(1,"where","WhereClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitGroupByClause(e){let t=new p(1,"group by","GroupByClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.grouping.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(this.visit(e.grouping[n]));return t}visitHavingClause(e){let t=new p(1,"having","HavingClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitWindowClause(e){let t=new p(1,"window","WindowClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.windows.length;n++)n>0&&t.innerTokens.push(...o.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(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(o.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitLimitClause(e){let t=new p(1,"limit","LimitClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOffsetClause(e){let t=new p(1,"offset","OffsetClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitFetchClause(e){let t=new p(1,"fetch","FetchClause");return t.innerTokens.push(o.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(o.SPACE_TOKEN),t.innerTokens.push(e.count.accept(this)),e.unit&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,e.unit))),t}visitForClause(e){let t=new p(1,"for","ForClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,e.lockMode)),t}visitWithClause(e){let t=new p(1,"with","WithClause");t.innerTokens.push(o.SPACE_TOKEN),e.recursive&&(t.innerTokens.push(new p(1,"recursive")),t.innerTokens.push(o.SPACE_TOKEN));for(let n=0;n<e.tables.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(e.tables[n].accept(this));return t.innerTokens.push(o.SPACE_TOKEN),t}visitCommonTable(e){let t=new p(0,"","CommonTable");t.innerTokens.push(e.aliasExpression.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.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(o.SPACE_TOKEN)),t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new p(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(o.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(o.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this)),e.whereClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.groupByClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.groupByClause.accept(this))),e.havingClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.havingClause.accept(this))),e.orderByClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.orderByClause.accept(this))),e.windowClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.windowClause.accept(this))),e.limitClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.limitClause.accept(this))),e.offsetClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.offsetClause.accept(this))),e.fetchClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.fetchClause.accept(this))),e.forClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.forClause.accept(this)))),t}visitSubQuerySource(e){let t=new p(0,"");t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new p(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitValuesQuery(e){let t=new p(1,"values","ValuesQuery");t.innerTokens.push(o.SPACE_TOKEN);let n=new p(0,"","Values");for(let i=0;i<e.tuples.length;i++)i>0&&n.innerTokens.push(...o.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(o.PAREN_OPEN_TOKEN);let n=new p(0,"","InlineQuery");return n.innerTokens.push(e.selectQuery.accept(this)),t.innerTokens.push(n),t.innerTokens.push(o.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(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.selectQuery))),t}visitInsertClause(e){let t=new p(0,"");if(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"insert into")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),e.columns.length>0){t.innerTokens.push(o.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(e.columns[n].accept(this));t.innerTokens.push(o.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(o.SPACE_TOKEN),t.innerTokens.push(e.setClause.accept(this)),e.fromClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this))),e.whereClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.returningClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.returningClause.accept(this))),t}visitUpdateClause(e){let t=new p(1,"update","UpdateClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t}visitSetClause(e){let t=new p(1,"set","SelectClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.items.length;n++)n>0&&t.innerTokens.push(...o.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(o.SPACE_TOKEN),t.innerTokens.push(new p(5,"=")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.value.accept(this)),t}visitReturningClause(e){let t=new p(1,"returning","ReturningClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...o.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(o.SPACE_TOKEN),t.innerTokens.push(e.tableName.accept(this)),e.asSelectQuery&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.asSelectQuery.accept(this))),t}};var ut=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 ln(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.")}},ln=class{constructor(e,t){this.level=e,this.text=t}};var Rt=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 ut(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 ut(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 r=e.keywordTokens[s];this.appendToken(r,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 r=e.innerTokens[s];this.appendToken(r,i)}i!==t&&this.linePrinter.appendNewline(t)}};var pl=["mysql","postgres","sqlserver","sqlite"],nt=class{constructor(e={}){let t=e.preset?hn[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 Bt(n),this.printer=new Rt(e)}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var We=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 Wt=class{constructor(){this.sourceCollector=new At(!0),this.cteCollector=new q,this.formatter=new We}build(e){if(e.length===0)return new K(!1,e);let t=this.resolveDuplicateNames(e),{tableMap:n,recursiveCTEs:i,dependencies:s}=this.buildDependencyGraph(t),r=this.sortCommonTables(t,n,i,s);return new K(i.size>0,r)}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 r=s.map(l=>this.formatter.format(l.query));if(new Set(r).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 r of e)t.set(r.aliasExpression.table.name,r);let n=new Set,i=new Map,s=new Map;for(let r of e){let a=r.aliasExpression.table.name,l=this.sourceCollector.collect(r.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(r.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=[],r=[],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)):r.push(t.get(c))};for(let c of e){let m=c.aliasExpression.table.name;a.has(m)||u(m)}return[...s,...r]}};var $t=class{constructor(){this.nameConflictResolver=new Wt,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 b)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 b)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 $t().inject(e,n))}};var dn=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))(dn||{}),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(b.kind,s=>this.visitSimpleSelectQuery(s)),this.handlers.set(F.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(Y.kind,s=>this.visitGroupByClause(s)),this.handlers.set(X.kind,s=>this.visitHavingClause(s)),this.handlers.set(ue.kind,s=>this.visitOrderByClause(s)),this.handlers.set(ne.kind,s=>this.visitWindowFrameClause(s)),this.handlers.set(te.kind,s=>this.visitLimitClause(s)),this.handlers.set(Le.kind,s=>this.offsetClause(s)),this.handlers.set(Fe.kind,s=>this.visitFetchClause(s)),this.handlers.set(Z.kind,s=>this.visitJoinOnClause(s)),this.handlers.set(ce.kind,s=>this.visitJoinUsingClause(s)),this.handlers.set(w.kind,s=>this.visitColumnReference(s)),this.handlers.set(E.kind,s=>this.visitBinaryExpression(s)),this.handlers.set(D.kind,s=>this.visitUnaryExpression(s)),this.handlers.set(O.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(G.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(ne.kind,s=>this.visitWindowFrameClause(s)),this.handlers.set(Ce.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 r="";return s.value&&typeof s.value.getNamespace=="function"&&(r=s.value.getNamespace()||""),(r?r+"."+s.name:s.name)===i})||this.selectValues.push({name:e,value:t})}}visit(e){if(!this.isRootVisit){this.visitNode(e);return}if(!(e instanceof b))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 fe(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 qe=class o{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=pe.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=pe.parseFromLexeme(e,n);return i.lastTokenType&2048?o.parseFunctionSource(e,i):o.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,r=y.parseArgument(4,8,e,n);n=r.newIndex;let a=s.name;return{value:new Pe({namespaces:i,name:a},r.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),r=new Map;for(let a of s)r.set(a.getSourceAliasName(),a);return this.findUpstream(e,n,r)}handleTableSource(e,t,n){let i=n.get(e.table.name);if(i){let s=new Map(n);s.delete(e.table.name);let r=this.findUpstream(i.query,t,s);return r.length===0?null:r}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=[],r=!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;r=!1;break}if(c===null){r=!1;break}s.push(c)}return r&&s.length===a?s.flat():null}findUpstream(e,t,n){if(e instanceof b){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),r=l=>this.options.ignoreCaseAndUnderscore?l.toLowerCase().replace(/_/g,""):l;return t.every(l=>s.some(u=>r(u)===r(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 De=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=qe.parseTableSourceFromLexemes(e,t);return{value:new k(n.value,null),newIndex:n.newIndex}}static parseFromLexeme(e,t){let n=t,i=qe.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length){if(e[n].value==="as"){n++;let r=De.parseFromLexeme(e,n);return n=r.newIndex,{value:new k(i.value,r.value),newIndex:n}}if(n<e.length&&this.isTokenTypeAliasCandidate(e[n].type)){let r=De.parseFromLexeme(e,n);return n=r.newIndex,{value:new k(i.value,r.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 o{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?o.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 b)return e;if(e instanceof R)return o.buildSimpleBinaryQuery(e);if(e instanceof z)return o.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=o.createSelectAllClause(),r=new b({selectClause:s,fromClause:i});return Oe.normalize(r)}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),r=e.columnAliases.map(l=>new L(new w("vq",l),l)),a=new F(r,null);return new b({selectClause:a,fromClause:s})}static createSelectAllClause(){let e=new w(null,"*"),t=new L(e,"*");return new F([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 fe().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 Ne({insertClause:new Re(a,n),selectQuery:e})}static buildUpdateQuery(e,t,n,i){let s=new He(ke.parse(n)),r=Array.isArray(i)?i:[i],l=new fe().collect(e),c=new q().collect(e);new Xe().execute(e);for(let Te of r)if(!l.some(mt=>mt.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 v=l.filter(Te=>!r.includes(Te.name)).map(Te=>new Be(Te.name,new w(d,Te.name))),S=new Ae(v),Ue=new P(e.toSource(t),null),Qe=null;for(let Te of r){let mt=new E(new w(d,Te),"=",new w(t,Te));Qe=Qe?new E(Qe,"and",mt):mt}let yn=new J(Qe);return new et({updateClause:s,setClause:S,fromClause:Ue,whereClause:yn,withClause:c.length>0?new K(!1,c):void 0})}};var $e=class{static set(e,t,n){let i=Ze.collect(e),s=!1;for(let r of i)r.name.value===t&&(r.value=n,s=!0);if(!s)throw new Error(`Parameter '${t}' not found in query.`)}};var b=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=y.parse(e);this.appendWhere(t)}appendWhere(e){this.whereClause?this.whereClause.condition=new E(this.whereClause.condition,"and",e):this.whereClause=new J(e)}appendHavingRaw(e){let t=y.parse(e);this.appendHaving(t)}appendHaving(e){this.havingClause?this.havingClause.condition=new E(this.havingClause.condition,"and",e):this.havingClause=new X(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 r=qe.parse(t),a=new k(r,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 f of a)if(s.some(v=>v==f.name)){let v=new E(f.value,"=",new w([c],f.name));l?l=new E(l,"and",v):l=v,u++}if(!l||u!==s.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${s.join(", ")}`);let m=new Z(l),d=new ee(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 K(!1,t),Oe.normalize(this)}appendWithRaw(e,t){let n=B.parse(e),i=new U(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],r=new We().visit(i.value),a=t(r);i.value=y.parse(a)}appendWhereExpr(e,t,n){if(n&&n.upstream){let s=new it().find(this,[e]),r=new xe,a=new We;for(let l of s){let u=r.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 We,r=i.collect(this).filter(l=>l.name===e).map(l=>l.value);if(r.length!==1)throw new Error(`Expected exactly one expression for column '${e}'`);let a=s.format(r[0]);this.appendWhereRaw(t(a))}}setParameter(e,t){return $e.set(this,e,t),this}};var R=class o 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 o(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 $e.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 $e.set(this,e,t),this}};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 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 ze;else if(n<e.length&&e[n].value==="distinct on"){n++;let a=y.parseArgument(4,8,e,n);i=new _e(a.value),n=a.newIndex}let s=[],r=Kt.parseItem(e,n);for(s.push(r.value),n=r.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 F(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=y.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 r=e[n].value;return n++,{value:new L(s,r),newIndex:n}}else if(s instanceof w&&s.column.name!=="*")return{value:new L(s,s.column.name),newIndex:n};return{value:new L(s),newIndex:n}}};var jt=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="on"){n++;let i=y.parseFromLexeme(e,n);return n=i.newIndex,{value:new Z(i.value),newIndex:n}}return null}};var qt=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="using"){n++;let i=y.parseArgument(4,8,e,n),s=i.value;return n=i.newIndex,{value:new ce(s),newIndex:n}}return null}};var Dt=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!!an.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),r=s.value;n=s.newIndex;let a=ke.parseFromLexeme(e,n);if(n=a.newIndex,n<e.length){let u=jt.tryParse(e,n);if(u)return{value:new ee(i,a.value,u.value,r),newIndex:u.newIndex};let c=qt.tryParse(e,n);if(c)return{value:new ee(i,a.value,c.value,r),newIndex:c.newIndex}}return{value:new ee(i,a.value,null,r),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 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=Dt.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 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 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=y.parseFromLexeme(e,n);return{value:new J(i.value),newIndex:i.newIndex}}};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 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 r=this.parseItem(e,n);i.push(r.value),n=r.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 Y(i),newIndex:n}}static parseItem(e,t){let n=t,i=y.parseFromLexeme(e,n),s=i.value;return n=i.newIndex,{value:s,newIndex:n}}};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 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=y.parseFromLexeme(e,n);return{value:new X(i.value),newIndex:i.newIndex}}};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 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 r=Ye.parseFromLexeme(e,n);if(n=r.newIndex,i.push(new ne(s,r.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 Ve(i),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 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=y.parseFromLexeme(e,n);return n=i.newIndex,{value:new te(i.value),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 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 Se(s),newIndex:n}}};var ct=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=De.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 r=B.parseFromLexeme(e,n);if(n=r.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 U(r.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=[],r=ct.parseFromLexeme(e,n);for(s.push(r.value),n=r.newIndex;n<e.length&&e[n].type&16;){n++;let a=ct.parseFromLexeme(e,n);s.push(a.value),n=a.newIndex}return{value:new K(i,s),newIndex:n}}};var Xt=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=y.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 r=y.parseFromLexeme(e,n);i.push(r.value),n=r.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 Zt=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=un.parseFromLexeme(e,n),s=i.value;return n=i.newIndex,{value:new Fe(s),newIndex:n}}},un=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 r=null,a=null;if(e[n].value==="row only"||e[n].value==="rows only")return r=new V(1),a="rows only",n++,{value:new Ke(i,r,a),newIndex:n};let l=y.parseFromLexeme(e,n);if(r=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,r,a),newIndex:n}}};var en=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=y.parseFromLexeme(e,n);return n=i.newIndex,n<e.length&&(e[n].value==="row"||e[n].value==="rows")&&n++,{value:new Le(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),r=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);r=new R(r,a,u.value),n=u.newIndex}else if(l==="values"){let u=this.parseValuesQuery(e,n);r=new R(r,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:r,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=Ut.parseFromLexeme(e,n);n=s.newIndex;let r=null;n<e.length&&e[n].value==="from"&&(r=Jt.parseFromLexeme(e,n),n=r.newIndex);let a=null;n<e.length&&e[n].value==="where"&&(a=Mt.parseFromLexeme(e,n),n=a.newIndex);let l=null;n<e.length&&e[n].value==="group by"&&(l=zt.parseFromLexeme(e,n),n=l.newIndex);let u=null;n<e.length&&e[n].value==="having"&&(u=_t.parseFromLexeme(e,n),n=u.newIndex);let c=null;n<e.length&&e[n].value==="window"&&(c=Ht.parseFromLexeme(e,n),n=c.newIndex);let m=null;n<e.length&&e[n].value==="order by"&&(m=Ge.parseFromLexeme(e,n),n=m.newIndex);let d=null;n<e.length&&e[n].value==="limit"&&(d=Gt.parseFromLexeme(e,n),n=d.newIndex);let f=null;n<e.length&&e[n].value==="offset"&&(f=en.parseFromLexeme(e,n),n=f.newIndex);let v=null;n<e.length&&e[n].value==="fetch"&&(v=Zt.parseFromLexeme(e,n),n=v.newIndex);let S=null;return n<e.length&&e[n].value.toLowerCase()==="for"&&(S=Yt.parseFromLexeme(e,n),n=S.newIndex),{value:new b({withClause:i?i.value:null,selectClause:s.value,fromClause:r?r.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:f?f.value:null,fetchClause:v?v.value:null,forClause:S?S.value:null}),newIndex:n}}static parseValuesQuery(e,t){let n=Xt.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}};var fn=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 r=[];if(e[n]?.type===4){for(n++;n<e.length&&e[n].type===64&&(r.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 b)a.value.withClause=i;else throw new Error("WITH clause is not supported in this context.");return n=a.newIndex,{value:new Ne({insertClause:new Re(s.value,r),selectQuery:a.value}),newIndex:n}}};var tn=class o{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,r=this.collectAndSortObjectEntities(n,t),a=this.groupEntitiesByDepth(r),l=Array.from(a.keys()).sort((u,c)=>c-u);for(let u of l){let c=a.get(u),m=`${o.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 r=t.get(s);if(!r)throw new Error(`Entity ${s} not found for depth calculation.`);if(r.isRoot)return 0;if(!r.parentId)return 1;let a=r.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(f=>f.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 r=t.get(s.id);r&&!r.isRoot&&n.push({entity:r,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 r=[new L(new w(null,new C(o.WILDCARD_COLUMN)))];for(let{entity:l}of e){let u=this.buildEntityJsonColumn(l,i,s);r.push(u)}let a=new b({selectClause:new F(r),fromClause:new P(new k(new I(null,new C(t)),null),null)});return new U(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 r=this.createJsonObject(i,t.useJsonb),a=this.buildNullCondition(s),l=this.createCaseExpression(a,r),u=`${e.name.toLowerCase()}${o.JSON_COLUMN_SUFFIX}`;return new L(l,u)}prepareEntityColumns(e){let t=[],n=[];return Object.entries(e.columns).forEach(([i,s])=>{t.push(new V(i)),t.push(new w(null,new C(s))),n.push(new E(new w(null,new C(s)),"is",new V(null)))}),{jsonObjectArgs:t,nullChecks:n}}addChildObjectRelationships(e,t,n,i){n.nestedEntities.filter(r=>r.parentId===e.id&&r.relationshipType==="object").forEach(r=>{let a=i.get(r.id);if(a){t.push(new V(r.propertyName));let l=`${a.name.toLowerCase()}${o.JSON_COLUMN_SUFFIX}`;t.push(new w(null,new C(l)))}})}createJsonObject(e,t=!1){let n=t?"jsonb_build_object":"json_build_object";return new O(null,new g(n),new Q(e),null)}buildNullCondition(e){return e.reduce((t,n)=>t?new E(t,"and",n):n)}createCaseExpression(e,t){return new _(null,new ie([new se(e,new V(null))],t))}};var nn=class o{static{this.CTE_ARRAY_PREFIX="cte_array_depth_"}buildArrayEntityCtes(e,t,n,i){let s=[...e],r=t,a=this.collectAndSortArrayEntities(i,n);if(a.length===0)return{updatedCtes:s,lastCteAlias:r};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:f}=this.buildDepthCte(m,r,s,c,i);s.push(d),r=f}return{updatedCtes:s,lastCteAlias:r}}collectAndSortArrayEntities(e,t){let n=[],i=s=>{let r=t.get(s);return!r||r.isRoot?0:r.parentId?1+i(r.parentId):1};return e.nestedEntities.forEach(s=>{if(s.relationshipType==="array"){let r=t.get(s.id),a=t.get(s.parentId);if(!r||!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:r,parentEntity:a,parentIdColumnSqlName:u,depth:i(s.id)})}}),n.sort((s,r)=>r.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 r=new Set;e.forEach(v=>{Object.values(v.entity.columns).forEach(S=>r.add(S))});let a=n.find(v=>v.aliasExpression.table.name===t)?.query;if(!a)throw new Error(`CTE not found: ${t}`);let l=new fe(null,n).collect(a),u=[],c=[];l.forEach(v=>{r.has(v.name)||(c.push(new L(new w(null,new C(v.name)),v.name)),u.push(new w(null,new C(v.name))))});for(let v of e){let S=this.buildAggregationDetailsForArrayEntity(v.entity,s.nestedEntities,new Map,s.useJsonb);c.push(new L(S.jsonAgg,v.entity.propertyName))}let m=`${o.CTE_ARRAY_PREFIX}${i}`,d=new b({selectClause:new F(c),fromClause:new P(new k(new I(null,new C(t)),null),null),groupByClause:u.length>0?new Y(u):null});return{cte:new U(d,new W(m,null),null),newCteAlias:m}}buildAggregationDetailsForArrayEntity(e,t,n,i=!1){let s=i?"jsonb_build_object":"json_build_object",r=[];Object.entries(e.columns).forEach(([m,d])=>{r.push(new V(m)),r.push(new w(null,new C(d)))}),t.filter(m=>m.parentId===e.id).forEach(m=>{if(r.push(new V(m.propertyName)),m.relationshipType==="object"){let d=`${m.name.toLowerCase()}_json`;r.push(new w(null,new C(d)))}else m.relationshipType==="array"&&r.push(new w(null,new C(m.propertyName)))});let l=new O(null,new g(s),new Q(r),null),u=i?"jsonb_agg":"json_agg";return{jsonAgg:new O(null,new g(u),new Q([l]),null)}}};var wn=class{constructor(){this.selectValueCollector=new fe(null),this.objectEntityCteBuilder=new tn,this.arrayEntityCteBuilder=new nn}validateMapping(e,t){let i=new fe().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 r=new Set([t.rootEntity.id]),a=new Map;t.nestedEntities.forEach(u=>{r.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(!r.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(f=>f.parentId===u);if(c.filter(f=>f.relationshipType==="array").length>1){let f=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(v=>v.id===u)?.name;throw new Error(`Validation Error: Parent entity "${f}" (ID: ${u}) has multiple direct array children. This is not supported.`)}let d=new Set;for(let f of c){if(d.has(f.propertyName)){let v=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(S=>S.id===u)?.name;throw new Error(`Validation Error: Parent entity "${v}" (ID: ${u}) has duplicate property name "${f.propertyName}" for its children.`)}d.add(f.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],r=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,r=l.lastCteAlias;let u=this.arrayEntityCteBuilder.buildArrayEntityCtes(s,r,a,t);return s=u.updatedCtes,r=u.lastCteAlias,this.buildFinalSelectQuery(s,r,a,t)}createInitialCte(e){let t="origin_query";return{initialCte:new U(e,new W(t,null),null),initialCteAlias:t}}buildFinalSelectQuery(e,t,n,i){let s=[...e],r=`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 L(l,i.rootName),c=new U(new b({selectClause:new F([u]),fromClause:new P(new k(new I(null,new C(t)),null),null)}),new W(r,null),null);s.push(c);let m=i.useJsonb?"jsonb_agg":"json_agg",d=new O(null,new g(m),new Q([new w(null,new C(i.rootName))]),null);return new b({withClause:new K(!1,s),selectClause:new F([new L(d,`${i.rootName}_array`)]),fromClause:new P(new k(new I(null,new C(r)),null),null)})}else{let l=this.buildEntityJsonObject(a,null,i.nestedEntities,n,i.useJsonb),u=new L(l,i.rootName),c=new U(new b({selectClause:new F([u]),fromClause:new P(new k(new I(null,new C(t)),null),null)}),new W(r,null),null);return s.push(c),new b({withClause:new K(!1,s),selectClause:new F([new L(new w(null,new C(i.rootName)),i.rootName)]),fromClause:new P(new k(new I(null,new C(r)),null),null),limitClause:new te(new V(1))})}}buildEntityJsonObject(e,t,n,i,s=!1){let r=s?"jsonb_build_object":"json_build_object",a=[];return Object.entries(e.columns).forEach(([u,c])=>{a.push(new V(u)),a.push(new w(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 w(null,new C(m)))}else u.relationshipType==="array"&&a.push(new w(null,new C(u.propertyName)))}),new O(null,new g(r),new Q(a),null)}};var sn=class{constructor(e,t){this.name=e,this.columns=t}},rn=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(b.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 b||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 sn(t,Array.from(n).sort()))}handleTableSource(e,t,n){if(e.datasource instanceof I){let i=e.datasource.getSourceName(),s=this.commonTables.filter(r=>r.getSourceAliasName()===i);if(s.length>0)s[0].query.accept(this);else{let r=e.getAliasName()??i;this.processCollectTableSchema(i,r,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 w).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(r=>r.table==="").map(r=>r.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),r=new sn(e,s);this.tableSchemas.push(r)}};var Cn=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,r=["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 f of d){let S=i.collect(f).find(Qe=>s(Qe.name)===s(c));if(!S)throw new Error(`Column '${c}' not found in query`);let Ue=S.value;m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.getPrototypeOf(m)===Object.prototype&&a(m,r,c),m===null||typeof m!="object"||Array.isArray(m)||m instanceof Date?l(f,Ue,c,m):u(f,Ue,c,m)}}function a(c,m,d){Object.keys(c).forEach(f=>{if(!m.includes(f))throw new Error(`Unsupported operator '${f}' for state key '${d}'`)})}function l(c,m,d,f){let v=new A(d,f);c.appendWhere(new E(m,"=",v))}function u(c,m,d,f){if("="in f){let v=new A(d,f["="]);c.appendWhere(new E(m,"=",v))}if("min"in f){let v=new A(d+"_min",f.min);c.appendWhere(new E(m,">=",v))}if("max"in f){let v=new A(d+"_max",f.max);c.appendWhere(new E(m,"<=",v))}if("like"in f){let v=new A(d+"_like",f.like);c.appendWhere(new E(m,"like",v))}if("in"in f){let S=f.in.map((Ue,Qe)=>new A(`${d}_in_${Qe}`,Ue));c.appendWhere(new E(m,"in",new H(new Q(S))))}if("any"in f){let v=new A(d+"_any",f.any);c.appendWhere(new E(m,"=",new O(null,"any",v,null)))}if("<"in f){let v=new A(d+"_lt",f["<"]);c.appendWhere(new E(m,"<",v))}if(">"in f){let v=new A(d+"_gt",f[">"]);c.appendWhere(new E(m,">",v))}if("!="in f){let v=new A(d+"_neq",f["!="]);c.appendWhere(new E(m,"!=",v))}if("<>"in f){let v=new A(d+"_ne",f["<>"]);c.appendWhere(new E(m,"<>",v))}if("<="in f){let v=new A(d+"_le",f["<="]);c.appendWhere(new E(m,"<=",v))}if(">="in f){let v=new A(d+"_ge",f[">="]);c.appendWhere(new E(m,">=",v))}}return e}};var vn=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,r=new rn(i).collect(n),a=[];for(let l of r){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 pt=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(([r,a])=>a.isPrimaryKey).map(([r,a])=>r).length===0&&t.push(`Table '${n}' has no primary key defined`),i.relationships?.forEach(r=>{e.includes(r.table)||t.push(`Table '${n}' references unknown table '${r.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,r])=>{n[s]=r.jsonAlias||r.name});let i=[];return t.relationships?.forEach(s=>{let r=this.schemas[s.table];if(!r)throw new Error(`Related table '${s.table}' not found in schema registry`);let a={};Object.entries(r.columns).forEach(([u,c])=>{a[u]=c.jsonAlias||c.name});let l=s.type;i.push({id:s.propertyName,name:r.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 Th(o){return new pt(o)}function Ih(o){return new pt(o).createTableColumnResolver()}function Ph(o,e){return new pt(o).createJsonMapping(e)}export{re as ArrayExpression,oe as ArrayQueryExpression,ae as BetweenExpression,E as BinaryExpression,R as BinarySelectQuery,q as CTECollector,Oe as CTENormalizer,_ as CaseExpression,se as CaseKeyValuePair,G as CastExpression,w as ColumnReference,dn as DuplicateDetectionMode,We as Formatter,O as FunctionCall,C as IdentifierString,we as InlineQuery,Ne as InsertQuery,fn as InsertQueryParser,V as LiteralValue,A as ParameterExpression,H as ParenExpression,wn as PostgresJsonQueryBuilder,ve as QualifiedName,st as QueryBuilder,g as RawString,rn as SchemaCollector,pt as SchemaManager,B as SelectQueryParser,fe as SelectValueCollector,xe as SelectableColumnCollector,b as SimpleSelectQuery,nt as SqlFormatter,Cn as SqlParamInjector,vn as SqlSchemaValidator,Ie as StringSpecifierExpression,ie as SwitchCaseArgument,sn as TableSchema,At as TableSourceCollector,le as TupleExpression,me as TypeValue,D as UnaryExpression,it as UpstreamSelectQueryFinder,pl as VALID_PRESETS,Q as ValueList,z as ValuesQuery,pn as WindowFrameBound,Je as WindowFrameBoundStatic,Me as WindowFrameBoundaryValue,Ce as WindowFrameExpression,Ee as WindowFrameSpec,cn as WindowFrameType,Ph as createJsonMappingFromSchema,Th as createSchemaManager,Ih as createTableColumnResolver};
|
16
|
+
//# sourceMappingURL=index.min.js.map
|