rawsql-ts 0.10.6-beta → 0.10.7-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 +9 -9
- package/dist/esm/index.min.js.map +3 -3
- package/dist/esm/src/transformers/SqlParamInjector.js +8 -0
- package/dist/esm/src/transformers/SqlParamInjector.js.map +1 -1
- package/dist/esm/tsconfig.browser.tsbuildinfo +1 -1
- package/dist/esm/types/src/transformers/SqlParamInjector.d.ts +11 -5
- package/dist/index.min.js +9 -9
- package/dist/index.min.js.map +3 -3
- package/dist/src/transformers/SqlParamInjector.d.ts +11 -5
- package/dist/src/transformers/SqlParamInjector.js +8 -0
- package/dist/src/transformers/SqlParamInjector.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
package/dist/esm/index.min.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var v=class{constructor(){this.comments=null}getKind(){return this.constructor.kind}accept(e){return e.visit(this)}toSqlString(e){return this.accept(e)}};var Ke=class extends v{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var Oe=class extends v{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},D=class extends v{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},x=class extends v{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof E?this.qualifiedName.name:new E(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(e,t){super();let n=typeof t=="string"?new E(t):t;this.qualifiedName=new Fe(yn(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},W=class extends v{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,i){super(),this.qualifiedName=new Fe(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||{}),vn=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(vn||{}),Ze=class extends v{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},et=class extends v{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},Qe=class extends v{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Le=class extends v{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},ne=class extends v{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new F(e),this.expression=t}},y=class extends v{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new F(t),this.right=n}},_=class extends v{static{this.kind=Symbol("LiteralExpression")}constructor(e){super(),this.value=e}},g=class extends v{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new F(e),this.value=t,this.index=null}},fe=class extends v{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},we=class extends v{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},F=class extends v{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},E=class extends v{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},z=class extends v{static{this.kind=Symbol("ParenExpression")}constructor(e){super(),this.expression=e}},le=class extends v{static{this.kind=Symbol("CastExpression")}constructor(e,t){super(),this.input=e,this.castType=t}},ae=class extends v{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},Ce=class extends v{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},ve=class extends v{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},ye=class extends v{static{this.kind=Symbol("BetweenExpression")}constructor(e,t,n,i){super(),this.expression=e,this.lower=t,this.upper=n,this.negated=i}},$e=class extends v{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new F(e),this.value=new _(t)}},be=class extends v{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new Fe(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof F?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}},Se=class extends v{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}};function yn(o){if(o==null)return null;if(typeof o=="string")return o.trim()===""?null:[new E(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 E(t))}else{let e=o.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var Fe=class extends v{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=yn(e),typeof t=="string"?this.name=new F(t):this.name=t}toString(){let e=this.name instanceof F?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(t=>t.name).join(".")+"."+e:e}};var $=class extends v{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new E(t):null}},j=class extends v{static{this.kind=Symbol("SelectClause")}constructor(e,t=null){super(),this.items=e,this.distinct=t}},tt=class extends v{static{this.kind=Symbol("Distinct")}constructor(){super()}},nt=class extends v{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},ie=class extends v{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},Be=class extends v{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},de=class extends v{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new E(e),this.expression=t}},Je=class extends v{static{this.kind=Symbol("WindowsClause")}constructor(e){super(),this.windows=e}};var ue=class extends v{static{this.kind=Symbol("OrderByClause")}constructor(e){super(),this.order=e}},xe=class extends v{static{this.kind=Symbol("OrderByItem")}constructor(e,t,n){super(),this.value=e,this.sortDirection=t===null?"asc":t,this.nullsPosition=n}},ce=class extends v{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},pe=class extends v{static{this.kind=Symbol("HavingClause")}constructor(e){super(),this.condition=e}},B=class extends v{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof E?this.qualifiedName.name:new E(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(e,t){super();let n=typeof t=="string"?new E(t):t;this.qualifiedName=new Fe(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof F?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof F?this.qualifiedName.name.value:this.qualifiedName.name.name}},We=class extends v{static{this.kind=Symbol("FunctionSource")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"name"in e){let n=e;this.qualifiedName=new Fe(n.namespaces,n.name)}else this.qualifiedName=new Fe(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},Ve=class extends v{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},J=class extends v{static{this.kind=Symbol("SubQuerySource")}constructor(e){super(),this.query=e}},A=class extends v{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 B?this.datasource.getSourceName():null}},me=class extends v{static{this.kind=Symbol("JoinOnClause")}constructor(e){super(),this.condition=e}},Ee=class extends v{static{this.kind=Symbol("JoinUsingClause")}constructor(e){super(),this.condition=e}},he=class extends v{static{this.kind=Symbol("JoinItem")}constructor(e,t,n,i){super(),this.joinType=new F(e),this.source=t,this.condition=n,this.lateral=i}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof B?this.source.table.name:null}},V=class extends v{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 B?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}},Y=class extends v{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new q(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},X=class extends v{static{this.kind=Symbol("WithClause")}constructor(e,t){super(),this.recursive=e,this.tables=t}},re=class extends v{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var Ae=class extends v{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},je=class extends v{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},He=class extends v{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var Ne=class extends v{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},q=class extends v{static{this.kind=Symbol("SourceAliasExpression")}constructor(e,t){super(),this.table=new E(e),this.columns=t!==null?t.map(n=>new E(n)):null}},St=class extends v{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new E(t):t)}},De=class extends v{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof _e?t:new _e(t.column,t.value))}},_e=class extends v{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 E(n.column):n.column;this.qualifiedName=new Fe(n.namespaces,i)}else{let n=typeof e=="string"?new E(e):e;this.qualifiedName=new Fe(null,n)}this.value=t}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof E?this.qualifiedName.name:new E(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},it=class extends v{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 B?this.source.datasource.table.name:null}},Me=class extends v{constructor(e,t){super(),this.source=e,this.columns=t.map(n=>new E(n))}};var Q=(h=>(h[h.None=0]="None",h[h.Literal=1]="Literal",h[h.Operator=2]="Operator",h[h.OpenParen=4]="OpenParen",h[h.CloseParen=8]="CloseParen",h[h.Comma=16]="Comma",h[h.Dot=32]="Dot",h[h.Identifier=64]="Identifier",h[h.Command=128]="Command",h[h.Parameter=256]="Parameter",h[h.OpenBracket=512]="OpenBracket",h[h.CloseBracket=1024]="CloseBracket",h[h.Function=2048]="Function",h[h.StringSpecifier=4096]="StringSpecifier",h[h.Type=8192]="Type",h))(Q||{});var Z=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 se=class o{static getDebugPositionInfo(e,t){let n=Math.max(0,t-5),i=Math.min(e.length,t+5),r=e.slice(n,i),s=" ".repeat(t-n)+"^";return`${r}
|
|
1
|
+
var w=class{constructor(){this.comments=null}getKind(){return this.constructor.kind}accept(e){return e.visit(this)}toSqlString(e){return this.accept(e)}};var _e=class extends w{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var Ne=class extends w{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},M=class extends w{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},S=class extends w{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof E?this.qualifiedName.name:new E(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(e,t){super();let n=typeof t=="string"?new E(t):t;this.qualifiedName=new Qe(En(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},U=class extends w{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,i){super(),this.qualifiedName=new Qe(e,t),this.argument=n,this.over=i}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},Sn=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(Sn||{}),xn=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(xn||{}),nt=class extends w{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},it=class extends w{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},Re=class extends w{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Ae=class extends w{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},re=class extends w{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new F(e),this.expression=t}},C=class extends w{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new F(t),this.right=n}},z=class extends w{static{this.kind=Symbol("LiteralExpression")}constructor(e){super(),this.value=e}},g=class extends w{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new F(e),this.value=t,this.index=null}},ve=class extends w{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},ye=class extends w{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},F=class extends w{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},E=class extends w{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},Y=class extends w{static{this.kind=Symbol("ParenExpression")}constructor(e){super(),this.expression=e}},ce=class extends w{static{this.kind=Symbol("CastExpression")}constructor(e,t){super(),this.input=e,this.castType=t}},ue=class extends w{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},Se=class extends w{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},xe=class extends w{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},Ee=class extends w{static{this.kind=Symbol("BetweenExpression")}constructor(e,t,n,i){super(),this.expression=e,this.lower=t,this.upper=n,this.negated=i}},Ue=class extends w{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new F(e),this.value=new z(t)}},Ie=class extends w{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new Qe(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof F?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}},ge=class extends w{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}};function En(o){if(o==null)return null;if(typeof o=="string")return o.trim()===""?null:[new E(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 E(t))}else{let e=o.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var Qe=class extends w{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=En(e),typeof t=="string"?this.name=new F(t):this.name=t}toString(){let e=this.name instanceof F?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(t=>t.name).join(".")+"."+e:e}};var W=class extends w{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new E(t):null}},K=class extends w{static{this.kind=Symbol("SelectClause")}constructor(e,t=null){super(),this.items=e,this.distinct=t}},rt=class extends w{static{this.kind=Symbol("Distinct")}constructor(){super()}},st=class extends w{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},se=class extends w{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},$e=class extends w{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},we=class extends w{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new E(e),this.expression=t}},qe=class extends w{static{this.kind=Symbol("WindowsClause")}constructor(e){super(),this.windows=e}};var pe=class extends w{static{this.kind=Symbol("OrderByClause")}constructor(e){super(),this.order=e}},be=class extends w{static{this.kind=Symbol("OrderByItem")}constructor(e,t,n){super(),this.value=e,this.sortDirection=t===null?"asc":t,this.nullsPosition=n}},me=class extends w{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},he=class extends w{static{this.kind=Symbol("HavingClause")}constructor(e){super(),this.condition=e}},B=class extends w{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof E?this.qualifiedName.name:new E(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(e,t){super();let n=typeof t=="string"?new E(t):t;this.qualifiedName=new Qe(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof F?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof F?this.qualifiedName.name.value:this.qualifiedName.name.name}},Ke=class extends w{static{this.kind=Symbol("FunctionSource")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"name"in e){let n=e;this.qualifiedName=new Qe(n.namespaces,n.name)}else this.qualifiedName=new Qe(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},We=class extends w{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},q=class extends w{static{this.kind=Symbol("SubQuerySource")}constructor(e){super(),this.query=e}},A=class extends w{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 B?this.datasource.getSourceName():null}},de=class extends w{static{this.kind=Symbol("JoinOnClause")}constructor(e){super(),this.condition=e}},ke=class extends w{static{this.kind=Symbol("JoinUsingClause")}constructor(e){super(),this.condition=e}},fe=class extends w{static{this.kind=Symbol("JoinItem")}constructor(e,t,n,i){super(),this.joinType=new F(e),this.source=t,this.condition=n,this.lateral=i}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof B?this.source.table.name:null}},R=class extends w{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 B?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}},Z=class extends w{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new G(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},ee=class extends w{static{this.kind=Symbol("WithClause")}constructor(e,t){super(),this.recursive=e,this.tables=t}},oe=class extends w{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var Ve=class extends w{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},De=class extends w{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},Xe=class extends w{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var Be=class extends w{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},G=class extends w{static{this.kind=Symbol("SourceAliasExpression")}constructor(e,t){super(),this.table=new E(e),this.columns=t!==null?t.map(n=>new E(n)):null}},gt=class extends w{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new E(t):t)}},Me=class extends w{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof ze?t:new ze(t.column,t.value))}},ze=class extends w{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 E(n.column):n.column;this.qualifiedName=new Qe(n.namespaces,i)}else{let n=typeof e=="string"?new E(e):e;this.qualifiedName=new Qe(null,n)}this.value=t}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof E?this.qualifiedName.name:new E(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},ot=class extends w{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 B?this.source.datasource.table.name:null}},He=class extends w{constructor(e,t){super(),this.source=e,this.columns=t.map(n=>new E(n))}};var Q=(m=>(m[m.None=0]="None",m[m.Literal=1]="Literal",m[m.Operator=2]="Operator",m[m.OpenParen=4]="OpenParen",m[m.CloseParen=8]="CloseParen",m[m.Comma=16]="Comma",m[m.Dot=32]="Dot",m[m.Identifier=64]="Identifier",m[m.Command=128]="Command",m[m.Parameter=256]="Parameter",m[m.OpenBracket=512]="OpenBracket",m[m.CloseBracket=1024]="CloseBracket",m[m.Function=2048]="Function",m[m.StringSpecifier=4096]="StringSpecifier",m[m.Type=8192]="Type",m))(Q||{});var te=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 ae=class o{static getDebugPositionInfo(e,t){let n=Math.max(0,t-5),i=Math.min(e.length,t+5),r=e.slice(n,i),s=" ".repeat(t-n)+"^";return`${r}
|
|
2
2
|
${s}`}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
3
|
`);for(let r=0;r<i.length;r++)i[r]=i[r].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 r=t;if(t=o.skipWhiteSpace(e,t),t!==r)continue;let s=e.charCodeAt(t);if(s===45){let a=o.readLineComment(e,t);if(a.newPosition!==t){t=a.newPosition,a.comment&&n.push(a.comment.trim());continue}}else if(s===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&&!
|
|
4
|
+
${o.getDebugPositionInfo(e,t)}`);return n}static tryReadRegularIdentifier(e,t){let n=t;for(;t<e.length&&!te.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 X=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 ae.getDebugPositionInfo(this.input,e)}};var bt=class extends X{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="*")return this.position++,this.createLexeme(64,t);let n=ae.readRegularIdentifier(this.input,this.position);return this.position=n.newPosition,this.createLexeme(64,n.identifier)}};var Pe=class{constructor(e){this.trie=e}isEndOfInput(e,t,n=0){return t+n>=e.length}canParse(e,t,n=0){return!this.isEndOfInput(e,t,n)}parse(e,t){if(this.isEndOfInput(e,t))return null;this.trie.reset();let n=ae.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 r=n.identifier;if(t=ae.readWhiteSpaceAndComment(e,n.newPosition).position,this.isEndOfInput(e,t))return i===2?{keyword:r,newPosition:t}:null;for(;this.canParse(e,t);){let s=i,a=ae.tryReadRegularIdentifier(e,t);if(a!==null){if(i=this.trie.pushLexeme(a.identifier.toLowerCase()),i===0){if(s===2)break;return null}if(r+=" "+a.identifier,t=ae.readWhiteSpaceAndComment(e,a.newPosition).position,i===3)break}else{if(s===2)break;return null}}return{keyword:r,newPosition:t}}};var Oe=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 Bn=[["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"]],Vn=new Oe(Bn),wn=new Pe(Vn),kt=class extends X{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)&&te.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(te.isDigit(t))return this.createLexeme(1,this.readDigit());if((t==="+"||t==="-")&&this.determineSignOrOperator(e)==="sign"){let i=t;this.position++;let r=this.position;for(;this.canRead()&&te.isWhitespace(this.input[this.position]);)this.position++;if(this.canRead()&&(te.isDigit(this.input[this.position])||this.input[this.position]==="."&&this.canRead(1)&&te.isDigit(this.input[this.position+1])))return this.createLexeme(1,i==="-"?i+this.readDigit():this.readDigit());this.position=r-1}return null}tryReadKeyword(){let e=wn.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&256||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 r=i==="x";for(;this.canRead();){let s=this.input[this.position];if(te.isDigit(s)||r&&te.isHexChar(s))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(!te.isDigit(i))break;this.position++}if(e===this.position)throw new Error(`Unexpected character. position: ${e}
|
|
5
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
|
|
7
|
-
${this.getDebugPositionInfo(t)}`);return this.position++,this.input.slice(t+1,this.position-1)}};var I=class{constructor(e){this.input=e,this.position=0,this.readerManager=new
|
|
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&&r.push(...l.lines):((r.length>0||l.lines.length>0)&&this.addCommentsToToken(a,r,l.lines),r=[]),t[n++]=a,s=a}if(r.length>0&&n>0){let a=t[n-1];a.comments===null&&(a.comments=[]),a.comments.push(...r)}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 se.readWhiteSpaceAndComment(this.input,this.position)}getDebugPositionInfo(e){return se.getDebugPositionInfo(this.input,e)}};var ge=class o{static parseFromLexeme(e,t){let{identifiers:n,newIndex:i}=o.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:r,name:s}=o.extractNamespacesAndName(n),a=0;return i>t&&(a=e[i-1].type),{namespaces:r,name:new E(s),newIndex:i,lastTokenType:a}}static parse(e){let n=new I(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 Nt=class{static parseFromLexeme(e,t){let{namespaces:n,name:i,newIndex:r}=ge.parseFromLexeme(e,t);return{value:new x(n,i),newIndex:r}}};var dt=class{static parseFromLexeme(e,t){let n=t,i=e[n].value,r,s=hn.parse(i.toLowerCase(),0);if(s){let l=new F(s.keyword);return n++,{value:l,newIndex:n}}return/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(i)?r=Number(i):i.startsWith("'")&&i.endsWith("'")?r=i.slice(1,-1):r=i,n++,{value:new _(r),newIndex:n}}};var At=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=K.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 Oe(i.value),newIndex:n}}else{let i=b.parseArgument(4,8,e,t);return n=i.newIndex,{value:new z(i.value),newIndex:n}}}};var Qt=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 x(null,"*"),newIndex:n};let r=b.parseFromLexeme(e,n);return n=r.newIndex,{value:new ne(i,r.value),newIndex:n}}throw new Error(`Invalid unary expression at index ${t}: ${e[t].value}`)}};var Bt=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 r=new g(i);return n++,{value:r,newIndex:n}}};var Vt=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 r=e[n].value;return n++,{value:new $e(i,r),newIndex:n}}};var Rt=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 r=b.parseFromLexeme(e,n);return{value:new ne(i,r.value),newIndex:r.newIndex}}throw new Error(`Invalid modifier unary expression at index ${n}, Lexeme: ${e[n].value}`)}static parseCaseExpression(e,t){let n=t,i=b.parseFromLexeme(e,n);n=i.newIndex;let r=this.parseSwitchCaseArgument(e,n,[]);return n=r.newIndex,{value:new ae(i.value,r.value),newIndex:n}}static parseCaseWhenExpression(e,t){let n=t,i=this.parseCaseConditionValuePair(e,n);n=i.newIndex;let r=[i.value],s=this.parseSwitchCaseArgument(e,n,r);return n=s.newIndex,{value:new ae(null,s.value),newIndex:n}}static parseSwitchCaseArgument(e,t,n){let i=t,r=[...n],s=null;for(;i<e.length&&this.isCommandWithValue(e[i],"when");){i++;let l=this.parseCaseConditionValuePair(e,i);i=l.newIndex,r.push(l.value)}if(i<e.length&&this.isCommandWithValue(e[i],"else")){i++;let l=b.parseFromLexeme(e,i);s=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(r.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${i})`);return{value:new fe(r,s),newIndex:i}}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,i=b.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 r=b.parseFromLexeme(e,n);return n=r.newIndex,{value:new we(i.value,r.value),newIndex:n}}};var rt=class{static parse(e){let n=new I(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=[],r=this.parseItem(e,n);for(i.push(r.value),n=r.newIndex;n<e.length&&e[n].type&16;){n++;let s=this.parseItem(e,n);i.push(s.value),n=s.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=b.parseFromLexeme(e,n),r=i.value;if(n=i.newIndex,n>=e.length)return{value:r,newIndex:n};let s=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 s===null&&a===null?{value:r,newIndex:n}:{value:new xe(r,s,a),newIndex:n}}};var $t=class{static parse(e){let n=new I(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=[],r=b.parseFromLexeme(e,n);for(i.push(r.value),n=r.newIndex;n<e.length&&e[n].type&16;){n++;let s=b.parseFromLexeme(e,n);i.push(s.value),n=s.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 D(i)),newIndex:n}}};var st=class{static parse(e){let n=new I(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,r=null,s=null;if(n<e.length&&e[n].value==="partition by"){let a=$t.parseFromLexeme(e,n);i=a.value,n=a.newIndex}if(n<e.length&&e[n].value==="order by"){let a=rt.parseFromLexeme(e,n);r=a.value,n=a.newIndex}if(n<e.length&&this.isFrameTypeKeyword(e[n].value)){let a=this.parseFrameSpec(e,n);s=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 Le(i,r,s),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,r;switch(i){case"rows":r="rows";break;case"range":r="range";break;case"groups":r="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 s=this.parseFrameBoundary(e,n),a=s.value;if(n=s.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 Qe(r,a,u),newIndex:n}}else{let s=this.parseFrameBoundary(e,n),a=s.value;return n=s.newIndex,{value:new Qe(r,a,null),newIndex:n}}}static parseFrameBoundary(e,t){let n=t;if(n<e.length&&e[n].type&128){let i=e[n].value,r;switch(i){case"current row":r="current row";break;case"unbounded preceding":r="unbounded preceding";break;case"unbounded following":r="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 Ze(r),newIndex:n+1}}else if(n<e.length&&e[n].type&1){let i=b.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length&&e[n].type&128){let r=e[n].value,s;if(r==="preceding")s=!1;else if(r==="following")s=!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 et(i.value,s),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 ft=class{static parse(e){let n=new I(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 E(i),newIndex:n}}if(e[n].type&4)return st.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 Ge=class{static parseArrayExpression(e,t){let n=t;if(n+1<e.length&&e[n+1].type&512){n++;let i=b.parseArgument(512,1024,e,n);return n=i.newIndex,{value:new Ce(i.value),newIndex:n}}else if(n+1<e.length&&e[n+1].type&4){n++,n++;let i=K.parseFromLexeme(e,n);return n=i.newIndex,n++,{value:new ve(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,r=!0){let s=t;if(s<e.length&&e[s].type&2){let a=e[s].value.toLowerCase();if(!i&&a==="and"||!r&&a==="or")return null;if(s++,a==="between")return this.parseBetweenExpression(e,s,n,!1);if(a==="not between")return this.parseBetweenExpression(e,s,n,!0);if(a==="::"){let m=this.parseTypeValue(e,s);return s=m.newIndex,{value:new le(n,m.value),newIndex:s}}let l=b.parseFromLexeme(e,s);return s=l.newIndex,{value:new y(n,a,l.value),newIndex:s}}return null}static parseBetweenExpression(e,t,n,i){let r=t,s=b.parseFromLexeme(e,r,!1);if(r=s.newIndex,r<e.length&&e[r].type&2&&e[r].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${r}`);r++;let a=this.parseBetweenUpperBound(e,r);return r=a.newIndex,{value:new ye(n,s.value,a.value,i),newIndex:r}}static parseBetweenUpperBound(e,t){return b.parseFromLexeme(e,t,!1,!1)}static parseFunctionCall(e,t){let n=t,i=ge.parseFromLexeme(e,n),r=i.namespaces,s=i.name;if(n=i.newIndex,n<e.length&&e[n].type&4){let a=b.parseArgument(4,8,e,n);if(n=a.newIndex,n<e.length&&e[n].value==="over"){let l=ft.parseFromLexeme(e,n);return n=l.newIndex,{value:new W(r,s.name,a.value,l.value),newIndex:n}}else return{value:new W(r,s.name,a.value,null),newIndex:n}}else throw new Error(`Expected opening parenthesis after function name '${s.name}' at index ${n}`)}static parseKeywordFunction(e,t,n){let i=t,r=ge.parseFromLexeme(e,i),s=r.namespaces,a=r.name;if(i=r.newIndex,i<e.length&&e[i].type&4){i++;let l=b.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:m,required:w}of n)if(i<e.length&&e[i].type&128&&e[i].value===m)if(i++,i<e.length&&e[i].type&8192){let d=this.parseTypeValue(e,i);u=new y(u,m,d.value),i=d.newIndex}else{let d=b.parseFromLexeme(e,i);u=new y(u,m,d.value),i=d.newIndex}else if(w)throw new Error(`Keyword '${m}' is required at index ${i}`);if(i<e.length&&e[i].type&8)if(i++,i<e.length&&e[i].value==="over"){i++;let m=ft.parseFromLexeme(e,i);return i=m.newIndex,{value:new W(s,a.name,u,m.value),newIndex:i}}else return{value:new W(s,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:r,newIndex:s}=ge.parseFromLexeme(e,n);if(n=s,n<e.length&&e[n].type&4){let a=b.parseArgument(4,8,e,n);return n=a.newIndex,{value:new be(i,new F(r.name),a.value),newIndex:n}}else return{value:new be(i,new F(r.name)),newIndex:n}}};var Wt=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 r=Math.max(0,n-2),s=Math.min(t.length,n+3),a=t.slice(r,s).map((u,m)=>{let w=m+r===n?">":" ",d=Q[u.type]||u.type;return`${w} ${m+r}:${u.value} [${d}]`}).join(`
|
|
6
|
+
${this.getDebugPositionInfo(t)}`);return e?this.input.slice(t,this.position):this.input.slice(t+1,this.position-1)}};var Tt=class extends X{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(te.isNamedParameterPrefix(t)){if(this.canRead(1)&&te.isOperatorSymbol(this.input[this.position+1]))return null;this.position++;let n=this.position;for(;this.canRead()&&!te.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 It=class o extends X{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 Pt=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 Rn=new Oe([["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"]]),$n=new Oe([["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"]]),Wn=new Pe(Rn),jn=new Pe($n);var Ot=class extends X{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(te.isOperatorSymbol(t)){let i=this.position;for(;this.canRead()&&te.isOperatorSymbol(this.input[this.position]);){if(this.canRead(1)){let s=this.input[this.position];if(s==="-"&&this.input[this.position+1]==="-")break;if(s==="/"&&this.input[this.position+1]==="*")break}this.position++}let r=this.input.slice(i,this.position);return this.createLexeme(2,r)}let n=jn.parse(this.input,this.position);return n!==null?(this.position=n.newPosition,this.createLexeme(8258,n.keyword)):(n=Wn.parse(this.input,this.position),n!==null?(this.position=n.newPosition,this.createLexeme(2,n.keyword)):null)}};var Un=new Oe([["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"]]),Kn=new Oe([["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"]]),Dn=new Pe(Kn),Cn=new Pe(Un),Lt=class extends X{tryRead(e){if(this.isEndOfInput())return null;let t=Cn.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(128,t.keyword);let n=Dn.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 Jn=new Set(["e'","E'","x'","X'","b'","B'"]),_n=new Set(["u&'","U&'"]),Ft=class extends X{tryRead(e){let t=this.position;return this.canRead(1)&&Jn.has(this.input.slice(t,t+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(t,this.position))):this.canRead(2)&&_n.has(this.input.slice(t,t+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(t,this.position))):null}};var Mn=new Oe([["grouping","sets"],["array"]]),qn=new Pe(Mn),Nt=class extends X{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(2048,t.keyword);let n=ae.tryReadRegularIdentifier(this.input,this.position);if(!n)return null;this.position=n.newPosition;var i=ae.readWhiteSpaceAndComment(this.input,this.position).position-this.position;return this.canRead(i)&&this.input[this.position+i]==="("?this.createLexeme(2048,n.identifier):null}};var zn=new Oe([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),Hn=new Pe(zn),At=class extends X{tryRead(e){if(this.isEndOfInput())return null;let t=Hn.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=ae.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 Qt=class extends X{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 I=class{constructor(e){this.input=e,this.position=0,this.readerManager=new Pt(e).register(new Qt(e)).register(new Tt(e)).register(new Ft(e)).register(new kt(e)).register(new It(e)).register(new Lt(e)).register(new Ot(e)).register(new At(e)).register(new Nt(e)).register(new bt(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(),r=i.lines;this.position=i.position;let s=null;for(;this.canRead()&&this.input[this.position]!==";";){let a=this.readerManager.tryRead(this.position,s);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&&r.push(...l.lines):((r.length>0||l.lines.length>0)&&this.addCommentsToToken(a,r,l.lines),r=[]),t[n++]=a,s=a}if(r.length>0&&n>0){let a=t[n-1];a.comments===null&&(a.comments=[]),a.comments.push(...r)}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 ae.readWhiteSpaceAndComment(this.input,this.position)}getDebugPositionInfo(e){return ae.getDebugPositionInfo(this.input,e)}};var Te=class o{static parseFromLexeme(e,t){let{identifiers:n,newIndex:i}=o.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:r,name:s}=o.extractNamespacesAndName(n),a=0;return i>t&&(a=e[i-1].type),{namespaces:r,name:new E(s),newIndex:i,lastTokenType:a}}static parse(e){let n=new I(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 Bt=class{static parseFromLexeme(e,t){let{namespaces:n,name:i,newIndex:r}=Te.parseFromLexeme(e,t);return{value:new S(n,i),newIndex:r}}};var Ct=class{static parseFromLexeme(e,t){let n=t,i=e[n].value,r,s=wn.parse(i.toLowerCase(),0);if(s){let l=new F(s.keyword);return n++,{value:l,newIndex:n}}return/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(i)?r=Number(i):i.startsWith("'")&&i.endsWith("'")?r=i.slice(1,-1):r=i,n++,{value:new z(r),newIndex:n}}};var Vt=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=_.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 Ne(i.value),newIndex:n}}else{let i=b.parseArgument(4,8,e,t);return n=i.newIndex,{value:new Y(i.value),newIndex:n}}}};var Rt=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 S(null,"*"),newIndex:n};let r=b.parseFromLexeme(e,n);return n=r.newIndex,{value:new re(i,r.value),newIndex:n}}throw new Error(`Invalid unary expression at index ${t}: ${e[t].value}`)}};var $t=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 r=new g(i);return n++,{value:r,newIndex:n}}};var Wt=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 r=e[n].value;return n++,{value:new Ue(i,r),newIndex:n}}};var jt=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 r=b.parseFromLexeme(e,n);return{value:new re(i,r.value),newIndex:r.newIndex}}throw new Error(`Invalid modifier unary expression at index ${n}, Lexeme: ${e[n].value}`)}static parseCaseExpression(e,t){let n=t,i=b.parseFromLexeme(e,n);n=i.newIndex;let r=this.parseSwitchCaseArgument(e,n,[]);return n=r.newIndex,{value:new ue(i.value,r.value),newIndex:n}}static parseCaseWhenExpression(e,t){let n=t,i=this.parseCaseConditionValuePair(e,n);n=i.newIndex;let r=[i.value],s=this.parseSwitchCaseArgument(e,n,r);return n=s.newIndex,{value:new ue(null,s.value),newIndex:n}}static parseSwitchCaseArgument(e,t,n){let i=t,r=[...n],s=null;for(;i<e.length&&this.isCommandWithValue(e[i],"when");){i++;let l=this.parseCaseConditionValuePair(e,i);i=l.newIndex,r.push(l.value)}if(i<e.length&&this.isCommandWithValue(e[i],"else")){i++;let l=b.parseFromLexeme(e,i);s=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(r.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${i})`);return{value:new ve(r,s),newIndex:i}}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,i=b.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 r=b.parseFromLexeme(e,n);return n=r.newIndex,{value:new ye(i.value,r.value),newIndex:n}}};var at=class{static parse(e){let n=new I(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=[],r=this.parseItem(e,n);for(i.push(r.value),n=r.newIndex;n<e.length&&e[n].type&16;){n++;let s=this.parseItem(e,n);i.push(s.value),n=s.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 pe(i),newIndex:n}}static parseItem(e,t){let n=t,i=b.parseFromLexeme(e,n),r=i.value;if(n=i.newIndex,n>=e.length)return{value:r,newIndex:n};let s=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 s===null&&a===null?{value:r,newIndex:n}:{value:new be(r,s,a),newIndex:n}}};var Ut=class{static parse(e){let n=new I(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=[],r=b.parseFromLexeme(e,n);for(i.push(r.value),n=r.newIndex;n<e.length&&e[n].type&16;){n++;let s=b.parseFromLexeme(e,n);i.push(s.value),n=s.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 $e(i[0]),newIndex:n}:{value:new $e(new M(i)),newIndex:n}}};var lt=class{static parse(e){let n=new I(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,r=null,s=null;if(n<e.length&&e[n].value==="partition by"){let a=Ut.parseFromLexeme(e,n);i=a.value,n=a.newIndex}if(n<e.length&&e[n].value==="order by"){let a=at.parseFromLexeme(e,n);r=a.value,n=a.newIndex}if(n<e.length&&this.isFrameTypeKeyword(e[n].value)){let a=this.parseFrameSpec(e,n);s=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 Ae(i,r,s),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,r;switch(i){case"rows":r="rows";break;case"range":r="range";break;case"groups":r="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 s=this.parseFrameBoundary(e,n),a=s.value;if(n=s.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 Re(r,a,u),newIndex:n}}else{let s=this.parseFrameBoundary(e,n),a=s.value;return n=s.newIndex,{value:new Re(r,a,null),newIndex:n}}}static parseFrameBoundary(e,t){let n=t;if(n<e.length&&e[n].type&128){let i=e[n].value,r;switch(i){case"current row":r="current row";break;case"unbounded preceding":r="unbounded preceding";break;case"unbounded following":r="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 nt(r),newIndex:n+1}}else if(n<e.length&&e[n].type&1){let i=b.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length&&e[n].type&128){let r=e[n].value,s;if(r==="preceding")s=!1;else if(r==="following")s=!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 it(i.value,s),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 vt=class{static parse(e){let n=new I(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 E(i),newIndex:n}}if(e[n].type&4)return lt.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 Ze=class{static parseArrayExpression(e,t){let n=t;if(n+1<e.length&&e[n+1].type&512){n++;let i=b.parseArgument(512,1024,e,n);return n=i.newIndex,{value:new Se(i.value),newIndex:n}}else if(n+1<e.length&&e[n+1].type&4){n++,n++;let i=_.parseFromLexeme(e,n);return n=i.newIndex,n++,{value:new xe(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,r=!0){let s=t;if(s<e.length&&e[s].type&2){let a=e[s].value.toLowerCase();if(!i&&a==="and"||!r&&a==="or")return null;if(s++,a==="between")return this.parseBetweenExpression(e,s,n,!1);if(a==="not between")return this.parseBetweenExpression(e,s,n,!0);if(a==="::"){let p=this.parseTypeValue(e,s);return s=p.newIndex,{value:new ce(n,p.value),newIndex:s}}let l=b.parseFromLexeme(e,s);return s=l.newIndex,{value:new C(n,a,l.value),newIndex:s}}return null}static parseBetweenExpression(e,t,n,i){let r=t,s=b.parseFromLexeme(e,r,!1);if(r=s.newIndex,r<e.length&&e[r].type&2&&e[r].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${r}`);r++;let a=this.parseBetweenUpperBound(e,r);return r=a.newIndex,{value:new Ee(n,s.value,a.value,i),newIndex:r}}static parseBetweenUpperBound(e,t){return b.parseFromLexeme(e,t,!1,!1)}static parseFunctionCall(e,t){let n=t,i=Te.parseFromLexeme(e,n),r=i.namespaces,s=i.name;if(n=i.newIndex,n<e.length&&e[n].type&4){let a=b.parseArgument(4,8,e,n);if(n=a.newIndex,n<e.length&&e[n].value==="over"){let l=vt.parseFromLexeme(e,n);return n=l.newIndex,{value:new U(r,s.name,a.value,l.value),newIndex:n}}else return{value:new U(r,s.name,a.value,null),newIndex:n}}else throw new Error(`Expected opening parenthesis after function name '${s.name}' at index ${n}`)}static parseKeywordFunction(e,t,n){let i=t,r=Te.parseFromLexeme(e,i),s=r.namespaces,a=r.name;if(i=r.newIndex,i<e.length&&e[i].type&4){i++;let l=b.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:p,required:f}of n)if(i<e.length&&e[i].type&128&&e[i].value===p)if(i++,i<e.length&&e[i].type&8192){let T=this.parseTypeValue(e,i);u=new C(u,p,T.value),i=T.newIndex}else{let T=b.parseFromLexeme(e,i);u=new C(u,p,T.value),i=T.newIndex}else if(f)throw new Error(`Keyword '${p}' is required at index ${i}`);if(i<e.length&&e[i].type&8)if(i++,i<e.length&&e[i].value==="over"){i++;let p=vt.parseFromLexeme(e,i);return i=p.newIndex,{value:new U(s,a.name,u,p.value),newIndex:i}}else return{value:new U(s,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:r,newIndex:s}=Te.parseFromLexeme(e,n);if(n=s,n<e.length&&e[n].type&4){let a=b.parseArgument(4,8,e,n);return n=a.newIndex,{value:new Ie(i,new F(r.name),a.value),newIndex:n}}else return{value:new Ie(i,new F(r.name)),newIndex:n}}};var Kt=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 r=Math.max(0,n-2),s=Math.min(t.length,n+3),a=t.slice(r,s).map((u,p)=>{let f=p+r===n?">":" ",T=Q[u.type]||u.type;return`${f} ${p+r}:${u.value} [${T}]`}).join(`
|
|
9
9
|
`),l=`${i} Unparsed lexeme remains at index ${n}: ${t[n].value}
|
|
10
10
|
Context:
|
|
11
|
-
${a}`;return new o(l,n,a)}};var wt=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 b=class{static parse(e){let n=new I(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw Wt.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,r=!0){let s=t,a=e[s].comments,l=this.parseItem(e,s);l.value.comments=a,s=l.newIndex;let u=l.value;for(;s<e.length&&e[s].type&2;){let w=e[s].value;if(!i&&w.toLowerCase()==="and"||!r&&w.toLowerCase()==="or")break;let d=wt.getPrecedence(w);if(d<n)break;if(s++,wt.isBetweenOperator(w)){let h=Ge.parseBetweenExpression(e,s,u,w.toLowerCase().includes("not"));u=h.value,s=h.newIndex;continue}if(w==="::"){let h=Ge.parseTypeValue(e,s);u=new le(u,h.value),s=h.newIndex;continue}let p=d+1,S=this.parseExpressionWithPrecedence(e,s,p,i,r);s=S.newIndex,u=new y(u,w,S.value)}return{value:u,newIndex:s}}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 r=Nt.parseFromLexeme(e,n);if(r.newIndex>=e.length)return r;if(e[r.newIndex].type&1){let a=dt.parseFromLexeme(e,r.newIndex);return{value:new ne(e[n].value,a.value),newIndex:a.newIndex}}return r}else if(i.type&64){let{namespaces:r,name:s,newIndex:a}=ge.parseFromLexeme(e,n);return e[a-1].type&10240?Ge.parseFromLexeme(e,n):{value:new x(r,s),newIndex:a}}else{if(i.type&1)return dt.parseFromLexeme(e,n);if(i.type&4)return At.parseFromLexeme(e,n);if(i.type&2048)return Ge.parseFromLexeme(e,n);if(i.type&2)return Qt.parseFromLexeme(e,n);if(i.type&256)return Bt.parseFromLexeme(e,n);if(i.type&4096)return Vt.parseFromLexeme(e,n);if(i.type&128)return Rt.parseFromLexeme(e,n);if(i.type&512){let{namespaces:r,name:s,newIndex:a}=ge.parseFromLexeme(e,n);return{value:new x(r,s),newIndex:a}}else if(i.type&8192){let{namespaces:r,name:s,newIndex:a}=ge.parseFromLexeme(e,n);return{value:new be(r,s),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 r=i,s=[];if(r<n.length&&n[r].type===e){if(r++,r<n.length&&n[r].type===t)return r++,{value:new D([]),newIndex:r};if(r<n.length&&n[r].value==="*"){let l=new x(null,"*");if(r++,r<n.length&&n[r].type===t)return r++,{value:l,newIndex:r};throw new Error(`Expected closing parenthesis at index ${r}`)}let a=this.parseFromLexeme(n,r);for(r=a.newIndex,s.push(a.value);r<n.length&&n[r].type&16;){r++;let l=this.parseFromLexeme(n,r);r=l.newIndex,s.push(l.value)}if(r<n.length&&n[r].type===t)return r++,s.length===1?{value:s[0],newIndex:r}:{value:new D(s),newIndex:r};throw new Error(`Missing closing parenthesis at index ${r}`)}throw new Error(`Expected opening parenthesis at index ${i}`)}};var ee=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(k.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(M.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(oe.kind,e=>this.visitValuesQuery(e)),this.handlers.set(X.kind,e=>this.visitWithClause(e)),this.handlers.set(Y.kind,e=>this.visitCommonTable(e)),this.handlers.set($.kind,e=>this.visitSelectItem(e)),this.handlers.set(E.kind,e=>this.visitIdentifierString(e)),this.handlers.set(F.kind,e=>this.visitRawString(e)),this.handlers.set(x.kind,e=>this.visitColumnReference(e)),this.handlers.set(g.kind,e=>this.visitParameterExpression(e)),this.handlers.set(_.kind,e=>this.visitLiteralValue(e)),this.handlers.set(A.kind,e=>this.visitSourceExpression(e)),this.handlers.set(B.kind,e=>this.visitTableSource(e)),this.handlers.set(We.kind,e=>this.visitFunctionSource(e)),this.handlers.set(Ve.kind,e=>this.visitParenSource(e)),this.handlers.set(J.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Oe.kind,e=>this.visitInlineQuery(e)),this.handlers.set(V.kind,e=>this.visitFromClause(e)),this.handlers.set(he.kind,e=>this.visitJoinClause(e)),this.handlers.set(me.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Ee.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(ie.kind,e=>this.visitWhereClause(e)),this.handlers.set(z.kind,e=>this.visitParenExpression(e)),this.handlers.set(y.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(ne.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ae.kind,e=>this.visitCaseExpression(e)),this.handlers.set(we.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(fe.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ye.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(W.kind,e=>this.visitFunctionCall(e)),this.handlers.set(Ce.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ve.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(Se.kind,e=>this.visitTupleExpression(e)),this.handlers.set(le.kind,e=>this.visitCastExpression(e)),this.handlers.set(Le.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Qe.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(be.kind,e=>this.visitTypeValue(e)),this.handlers.set(D.kind,e=>this.visitValueList(e)),this.handlers.set($e.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(j.kind,e=>this.visitSelectClause(e)),this.handlers.set(ce.kind,e=>this.visitGroupByClause(e)),this.handlers.set(pe.kind,e=>this.visitHavingClause(e)),this.handlers.set(ue.kind,e=>this.visitOrderByClause(e)),this.handlers.set(de.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(re.kind,e=>this.visitLimitClause(e)),this.handlers.set(Ne.kind,e=>this.visitForClause(e)),this.handlers.set(xe.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 ot=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(k.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(M.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(oe.kind,e=>this.visitValuesQuery(e)),this.handlers.set($.kind,e=>this.visitSelectItem(e)),this.handlers.set(E.kind,e=>this.visitIdentifierString(e)),this.handlers.set(F.kind,e=>this.visitRawString(e)),this.handlers.set(x.kind,e=>this.visitColumnReference(e)),this.handlers.set(g.kind,e=>this.visitParameterExpression(e)),this.handlers.set(_.kind,e=>this.visitLiteralValue(e)),this.handlers.set(A.kind,e=>this.visitSourceExpression(e)),this.handlers.set(B.kind,e=>this.visitTableSource(e)),this.handlers.set(Ve.kind,e=>this.visitParenSource(e)),this.handlers.set(J.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Oe.kind,e=>this.visitInlineQuery(e)),this.handlers.set(V.kind,e=>this.visitFromClause(e)),this.handlers.set(he.kind,e=>this.visitJoinClause(e)),this.handlers.set(me.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Ee.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(ie.kind,e=>this.visitWhereClause(e)),this.handlers.set(z.kind,e=>this.visitParenExpression(e)),this.handlers.set(y.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(ne.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ae.kind,e=>this.visitCaseExpression(e)),this.handlers.set(we.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(fe.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ye.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(W.kind,e=>this.visitFunctionCall(e)),this.handlers.set(Ce.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ve.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(Se.kind,e=>this.visitTupleExpression(e)),this.handlers.set(le.kind,e=>this.visitCastExpression(e)),this.handlers.set(Le.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Qe.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(be.kind,e=>this.visitTypeValue(e)),this.handlers.set(j.kind,e=>this.visitSelectClause(e)),this.handlers.set(ce.kind,e=>this.visitGroupByClause(e)),this.handlers.set(pe.kind,e=>this.visitHavingClause(e)),this.handlers.set(ue.kind,e=>this.visitOrderByClause(e)),this.handlers.set(de.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(re.kind,e=>this.visitLimitClause(e)),this.handlers.set(Ne.kind,e=>this.visitForClause(e)),this.handlers.set(xe.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 Je(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 oe(t)}visitSelectClause(e){let t=e.items.map(n=>this.visit(n));return new j(t,e.distinct)}visitFromClause(e){let t=this.visit(e.source),n=e.joins?e.joins.map(i=>this.visit(i)):null;return new V(t,n)}visitSubQuerySource(e){let t=this.visit(e.query);return new J(t)}visitInlineQuery(e){let t=this.visit(e.selectQuery);return new Oe(t)}visitJoinClause(e){let t=this.visit(e.source),n=e.condition?this.visit(e.condition):null;return new he(e.joinType.value,t,n,e.lateral)}visitJoinOnClause(e){let t=this.visit(e.condition);return new me(t)}visitJoinUsingClause(e){let t=this.visit(e.condition);return new Ee(t)}visitWhereClause(e){let t=this.visit(e.condition);return new ie(t)}visitGroupByClause(e){let t=e.grouping.map(n=>this.visit(n));return new ce(t)}visitHavingClause(e){let t=this.visit(e.condition);return new pe(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 de(e.name.name,t)}visitLimitClause(e){let t=this.visit(e.value);return new re(t)}visitForClause(e){return new Ne(e.lockMode)}visitParenExpression(e){let t=this.visit(e.expression);return new z(t)}visitBinaryExpression(e){let t=this.visit(e.left),n=this.visit(e.right);return new y(t,e.operator.value,n)}visitUnaryExpression(e){let t=this.visit(e.expression);return new ne(e.operator.value,t)}visitCaseExpression(e){let t=e.condition?this.visit(e.condition):null,n=this.visit(e.switchCase);return new ae(t,n)}visitSwitchCaseArgument(e){let t=e.cases.map(i=>this.visit(i)),n=e.elseValue?this.visit(e.elseValue):null;return new fe(t,n)}visitCaseKeyValuePair(e){let t=this.visit(e.key),n=this.visit(e.value);return new we(t,n)}visitBetweenExpression(e){let t=this.visit(e.expression),n=this.visit(e.lower),i=this.visit(e.upper);return new ye(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 W(e.namespaces,e.name,t,n)}visitArrayExpression(e){let t=this.visit(e.expression);return new Ce(t)}visitArrayQueryExpression(e){let t=this.visit(e.query);return new ve(t)}visitTupleExpression(e){let t=e.values.map(n=>this.visit(n));return new Se(t)}visitCastExpression(e){let t=this.visit(e.input),n=this.visit(e.castType);return new le(t,n)}visitTypeValue(e){let t=e.argument?this.visit(e.argument):null;return new be(e.namespaces,e.name,t)}visitSelectItem(e){let t=this.visit(e.value);return new $(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 A(t,n)}visitTableSource(e){return e}visitParenSource(e){let t=this.visit(e.source);return new Ve(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 Le(t,n,i)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new xe(t,e.sortDirection,e.nullsPosition)}};var jt=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(k.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(M.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(oe.kind,t=>this.visitValuesQuery(t)),this.handlers.set(X.kind,t=>this.visitWithClause(t)),this.handlers.set(Y.kind,t=>this.visitCommonTable(t)),this.handlers.set(V.kind,t=>this.visitFromClause(t)),this.handlers.set(he.kind,t=>this.visitJoinClause(t)),this.handlers.set(me.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(Ee.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(A.kind,t=>this.visitSourceExpression(t)),this.handlers.set(B.kind,t=>this.visitTableSource(t)),this.handlers.set(We.kind,t=>this.visitFunctionSource(t)),this.handlers.set(Ve.kind,t=>this.visitParenSource(t)),this.handlers.set(J.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(Oe.kind,t=>this.visitInlineQuery(t)),e||(this.handlers.set(ie.kind,t=>this.visitWhereClause(t)),this.handlers.set(ce.kind,t=>this.visitGroupByClause(t)),this.handlers.set(pe.kind,t=>this.visitHavingClause(t)),this.handlers.set(ue.kind,t=>this.visitOrderByClause(t)),this.handlers.set(de.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(re.kind,t=>this.visitLimitClause(t)),this.handlers.set(Ae.kind,t=>this.visitOffsetClause(t)),this.handlers.set(je.kind,t=>this.visitFetchClause(t)),this.handlers.set(Ne.kind,t=>this.visitForClause(t)),this.handlers.set(xe.kind,t=>this.visitOrderByItem(t)),this.handlers.set(j.kind,t=>this.visitSelectClause(t)),this.handlers.set($.kind,t=>this.visitSelectItem(t)),this.handlers.set(z.kind,t=>this.visitParenExpression(t)),this.handlers.set(y.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(ne.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(ae.kind,t=>this.visitCaseExpression(t)),this.handlers.set(we.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(fe.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(ye.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(W.kind,t=>this.visitFunctionCall(t)),this.handlers.set(Ce.kind,t=>this.visitArrayExpression(t)),this.handlers.set(ve.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(Se.kind,t=>this.visitTupleExpression(t)),this.handlers.set(le.kind,t=>this.visitCastExpression(t)),this.handlers.set(D.kind,t=>this.visitValueList(t)),this.handlers.set($e.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 F?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof F?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 ee;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 c=class{constructor(e,t="",n=""){this.innerTokens=[];this.type=e,this.text=t,this.containerType=n}};var at=class{static collect(e){let t=[];function n(i){if(!(!i||typeof i!="object")){i.constructor&&i.constructor.kind===g.kind&&t.push(i);for(let r of Object.keys(i)){let s=i[r];Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&s.constructor&&s.constructor.kind&&n(s)}}}return n(e),t}};var Ut=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var Kt=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 lt=class extends v{static{this.kind=Symbol("UpdateQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.updateClause=e.updateClause,this.setClause=e.setClause instanceof De?e.setClause:new De(e.setClause),this.whereClause=e.whereClause??null,this.fromClause=e.fromClause??null,this.returningClause=e.returning??null}};var Ie=class o{constructor(e=null,t=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=e??null,this.commonTableCollector=new ee,this.commonTables=[],this.initialCommonTables=t,this.handlers=new Map,this.handlers.set(k.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(j.kind,n=>this.visitSelectClause(n)),this.handlers.set(A.kind,n=>this.visitSourceExpression(n)),this.handlers.set(V.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 x&&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 x&&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 r of e.fromClause.joins){let s=r.getSourceAliasName();s&&n.includes(s)&&this.processJoinClause(r)}}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 x(e?[e]:null,a.name))})}else new o(this.tableColumnResolver,this.commonTables).collect(t).forEach(s=>{this.addSelectValueAsUnique(s.name,new x(e?[e]:null,s.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 x){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 x(t?[t]:null,n.name))});return}else if(e.datasource instanceof B){if(this.tableColumnResolver){let t=e.datasource.getSourceName();this.tableColumnResolver(t).forEach(n=>{this.addSelectValueAsUnique(n,new x([t],n))})}return}else if(e.datasource instanceof J){let t=e.getAliasName();new o(this.tableColumnResolver,this.commonTables).collect(e.datasource.query).forEach(r=>{this.addSelectValueAsUnique(r.name,new x(t?[t]:null,r.name))});return}else if(e.datasource instanceof Ve)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 ut=class extends v{static{this.kind=Symbol("CreateTableQuery")}constructor(e){super(),this.tableName=new E(e.tableName),this.isTemporary=e.isTemporary??!1,this.asSelectQuery=e.asSelectQuery}getSelectQuery(){let e;return this.asSelectQuery?e=new Ie().collect(this.asSelectQuery).map(i=>new $(i.value,i.name)):e=[new $(new F("*"))],new k({selectClause:new j(e),fromClause:new V(new A(new B(null,this.tableName.name),null),null)})}getCountQuery(){return new k({selectClause:new j([new $(new W(null,"count",new x(null,"*"),null))]),fromClause:new V(new A(new B(null,this.tableName.name),null),null)})}};var En={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"}},Dt=class o{constructor(e){this.handlers=new Map;this.index=1;e?.preset&&(e={...e.preset,...e}),this.parameterDecorator=new Kt({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 Ut({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.handlers.set(D.kind,t=>this.visitValueList(t)),this.handlers.set(x.kind,t=>this.visitColumnReference(t)),this.handlers.set(Fe.kind,t=>this.visitQualifiedName(t)),this.handlers.set(W.kind,t=>this.visitFunctionCall(t)),this.handlers.set(ne.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(y.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(_.kind,t=>this.visitLiteralValue(t)),this.handlers.set(g.kind,t=>this.visitParameterExpression(t)),this.handlers.set(fe.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(we.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(F.kind,t=>this.visitRawString(t)),this.handlers.set(E.kind,t=>this.visitIdentifierString(t)),this.handlers.set(z.kind,t=>this.visitParenExpression(t)),this.handlers.set(le.kind,t=>this.visitCastExpression(t)),this.handlers.set(ae.kind,t=>this.visitCaseExpression(t)),this.handlers.set(Ce.kind,t=>this.visitArrayExpression(t)),this.handlers.set(ve.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(ye.kind,t=>this.visitBetweenExpression(t)),this.handlers.set($e.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(be.kind,t=>this.visitTypeValue(t)),this.handlers.set(Se.kind,t=>this.visitTupleExpression(t)),this.handlers.set(Oe.kind,t=>this.visitInlineQuery(t)),this.handlers.set(Le.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(Qe.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(Ze.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(et.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(xe.kind,t=>this.visitOrderByItem(t)),this.handlers.set($.kind,t=>this.visitSelectItem(t)),this.handlers.set(j.kind,t=>this.visitSelectClause(t)),this.handlers.set(tt.kind,t=>this.visitDistinct(t)),this.handlers.set(nt.kind,t=>this.visitDistinctOn(t)),this.handlers.set(B.kind,t=>this.visitTableSource(t)),this.handlers.set(We.kind,t=>this.visitFunctionSource(t)),this.handlers.set(A.kind,t=>this.visitSourceExpression(t)),this.handlers.set(q.kind,t=>this.visitSourceAliasExpression(t)),this.handlers.set(V.kind,t=>this.visitFromClause(t)),this.handlers.set(he.kind,t=>this.visitJoinClause(t)),this.handlers.set(me.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(Ee.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(ie.kind,t=>this.visitWhereClause(t)),this.handlers.set(ce.kind,t=>this.visitGroupByClause(t)),this.handlers.set(pe.kind,t=>this.visitHavingClause(t)),this.handlers.set(Je.kind,t=>this.visitWindowClause(t)),this.handlers.set(de.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(re.kind,t=>this.visitLimitClause(t)),this.handlers.set(Ae.kind,t=>this.visitOffsetClause(t)),this.handlers.set(je.kind,t=>this.visitFetchClause(t)),this.handlers.set(He.kind,t=>this.visitFetchExpression(t)),this.handlers.set(Ne.kind,t=>this.visitForClause(t)),this.handlers.set(X.kind,t=>this.visitWithClause(t)),this.handlers.set(Y.kind,t=>this.visitCommonTable(t)),this.handlers.set(k.kind,t=>this.visitSimpleQuery(t)),this.handlers.set(J.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(M.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(oe.kind,t=>this.visitValuesQuery(t)),this.handlers.set(Se.kind,t=>this.visitTupleExpression(t)),this.handlers.set(Ke.kind,t=>this.visitInsertQuery(t)),this.handlers.set(Me.kind,t=>this.visitInsertClause(t)),this.handlers.set(lt.kind,t=>this.visitUpdateQuery(t)),this.handlers.set(it.kind,t=>this.visitUpdateClause(t)),this.handlers.set(De.kind,t=>this.visitSetClause(t)),this.handlers.set(_e.kind,t=>this.visitSetClauseItem(t)),this.handlers.set(St.kind,t=>this.visitReturningClause(t)),this.handlers.set(ut.kind,t=>this.visitCreateTableQuery(t))}static{this.SPACE_TOKEN=new c(10," ")}static{this.COMMA_TOKEN=new c(3,",")}static{this.ARGUMENT_SPLIT_COMMA_TOKEN=new c(11,",")}static{this.PAREN_OPEN_TOKEN=new c(4,"(")}static{this.PAREN_CLOSE_TOKEN=new c(4,")")}static{this.DOT_TOKEN=new c(8,".")}visitBinarySelectQuery(e){let t=new c(0,"");return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(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 c(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 c(1,"partition by","PartitionByClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOrderByClause(e){let t=new c(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 c(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 c(1,"desc"))),e.nullsPosition&&(e.nullsPosition==="first"?(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(1,"nulls first"))):e.nullsPosition==="last"&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(1,"nulls last")))),t}parse(e){this.index=1;let t=this.visit(e),n=at.collect(e).sort((r,s)=>(r.index??0)-(s.index??0)),i=this.parameterDecorator.style;if(i==="named"){let r={};for(let s of n){let a=s.name.value;if(r.hasOwnProperty(a)){if(r[a]!==s.value)throw new Error(`Duplicate parameter name '${a}' with different values detected during query composition.`);continue}r[a]=s.value}return{token:t,params:r}}else if(i==="indexed"){let r=n.map(s=>s.value);return{token:t,params:r}}else if(i==="anonymous"){let r=n.map(s=>s.value);return{token:t,params:r}}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 c(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 c(0,"","ColumnReference");return t.innerTokens.push(e.qualifiedName.accept(this)),t}visitFunctionCall(e){let t=new c(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 c(1,"over")),e.over instanceof E?(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 c(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 c(0,"","BinaryExpression");return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(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 c(2,t,"LiteralValue")}visitParameterExpression(e){e.index=this.index;let t=this.parameterDecorator.decorate(e.name.value,e.index),n=new c(7,t);return this.index++,n}visitSwitchCaseArgument(e){let t=new c(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 c(0,"","ElseClause");t.innerTokens.push(new c(1,"else")),t.innerTokens.push(o.SPACE_TOKEN);let n=new c(0,"","CaseElseValue");return n.innerTokens.push(this.visit(e)),t.innerTokens.push(n),t}visitCaseKeyValuePair(e){let t=new c(0,"","CaseKeyValuePair");t.innerTokens.push(new c(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 c(1,"then")),t.innerTokens.push(o.SPACE_TOKEN);let n=new c(0,"","CaseThenValue");return n.innerTokens.push(this.visit(e.value)),t.innerTokens.push(n),t}visitRawString(e){return new c(2,e.value,"RawString")}visitIdentifierString(e){let t=e.name==="*"?e.name:this.identifierDecorator.decorate(e.name);return new c(2,t,"IdentifierString")}visitParenExpression(e){let t=new c(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 c(0,"","CastExpression");return t.innerTokens.push(this.visit(e.input)),t.innerTokens.push(new c(5,"::")),t.innerTokens.push(this.visit(e.castType)),t}visitCaseExpression(e){let t=new c(0,"","CaseExpression");return t.innerTokens.push(new c(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 c(1,"end")),t}visitArrayExpression(e){let t=new c(0,"","ArrayExpression");return t.innerTokens.push(new c(1,"array")),t.innerTokens.push(new c(4,"[")),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(new c(4,"]")),t}visitArrayQueryExpression(e){let t=new c(0,"","ArrayExpression");return t.innerTokens.push(new c(1,"array")),t.innerTokens.push(new c(4,"(")),t.innerTokens.push(this.visit(e.query)),t.innerTokens.push(new c(4,")")),t}visitBetweenExpression(e){let t=new c(0,"","BetweenExpression");return t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(o.SPACE_TOKEN),e.negated&&(t.innerTokens.push(new c(1,"not")),t.innerTokens.push(o.SPACE_TOKEN)),t.innerTokens.push(new c(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 c(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 c(2,t+n,"StringSpecifierExpression")}visitTypeValue(e){let t=new c(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 c(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 c(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 c(0,"","WindowFrameSpec");return t.innerTokens.push(new c(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 c(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 c(1,"and")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.endBound.accept(this))),t}visitWindowFrameBoundaryValue(e){let t=new c(0,"","WindowFrameBoundaryValue");return t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(1,e.isFollowing?"following":"preceding")),t}visitWindowFrameBoundStatic(e){return new c(1,e.bound)}visitSelectItem(e){let t=new c(0,"","SelectItem");if(t.innerTokens.push(this.visit(e.value)),!e.identifier)return t;if(e.value instanceof x){let n=e.value.column.name;if(e.identifier.name===n)return t}return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.identifier)),t}visitSelectClause(e){let t=new c(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 c(1,"distinct")}visitDistinctOn(e){let t=new c(0,"","DistinctOn");return t.innerTokens.push(new c(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 c(2,t);return e.identifier&&(e.identifier.name,e.table.name),n}visitSourceExpression(e){let t=new c(0,"","SourceExpression");if(t.innerTokens.push(e.datasource.accept(this)),!e.aliasExpression)return t;if(e.datasource instanceof B){let n=e.datasource.table.name;return e.aliasExpression.table.name===n||(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(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 c(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this)),t}visitFromClause(e){let t=new c(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 c(0,"","JoinClause");return t.innerTokens.push(new c(1,e.joinType.value)),e.lateral&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(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 c(0,"","JoinOnClause");return t.innerTokens.push(new c(1,"on")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitJoinUsingClause(e){let t=new c(0,"","JoinUsingClause");return t.innerTokens.push(new c(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 c(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 c(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 c(1,"where","WhereClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitGroupByClause(e){let t=new c(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 c(1,"having","HavingClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitWindowClause(e){let t=new c(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 c(0,"","WindowFrameClause");return t.innerTokens.push(e.name.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(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 c(1,"limit","LimitClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOffsetClause(e){let t=new c(1,"offset","OffsetClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitFetchClause(e){let t=new c(1,"fetch","FetchClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.expression)),t}visitFetchExpression(e){let t=new c(0,"","FetchExpression");return t.innerTokens.push(new c(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 c(1,e.unit))),t}visitForClause(e){let t=new c(1,"for","ForClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(1,e.lockMode)),t}visitWithClause(e){let t=new c(1,"with","WithClause");t.innerTokens.push(o.SPACE_TOKEN),e.recursive&&(t.innerTokens.push(new c(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 c(0,"","CommonTable");t.innerTokens.push(e.aliasExpression.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),e.materialized!==null&&(e.materialized?t.innerTokens.push(new c(1,"materialized")):t.innerTokens.push(new c(1,"not materialized")),t.innerTokens.push(o.SPACE_TOKEN)),t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new c(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 c(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 c(0,"");t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new c(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 c(1,"values","ValuesQuery");t.innerTokens.push(o.SPACE_TOKEN);let n=new c(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 c(0,"");t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new c(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 c(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 c(0,"");if(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(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 c(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 c(1,"update","UpdateClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t}visitSetClause(e){let t=new c(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 c(0,"","SetClauseItem");return t.innerTokens.push(e.column.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(5,"=")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.value.accept(this)),t}visitReturningClause(e){let t=new c(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 c(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 c(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.asSelectQuery.accept(this))),t}};var Ct=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 fn(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.")}},fn=class{constructor(e,t){this.level=e,this.text=t}};var Jt=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 Ct(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 Ct(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 r=e.text;this.keywordCase==="upper"?r=r.toUpperCase():this.keywordCase==="lower"&&(r=r.toLowerCase()),this.linePrinter.appendText(r)}else if(e.type===3){let r=e.text;this.commaBreak==="before"?(this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)):this.commaBreak==="after"?(this.linePrinter.appendText(r),this.linePrinter.appendNewline(t)):this.linePrinter.appendText(r)}else if(e.type===5&&e.text.toLowerCase()==="and"){let r=e.text;this.keywordCase==="upper"?r=r.toUpperCase():this.keywordCase==="lower"&&(r=r.toLowerCase()),this.andBreak==="before"?(this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)):this.andBreak==="after"?(this.linePrinter.appendText(r),this.linePrinter.appendNewline(t)):this.linePrinter.appendText(r)}else if(e.containerType==="JoinClause"){let r=e.text;this.keywordCase==="upper"?r=r.toUpperCase():this.keywordCase==="lower"&&(r=r.toLowerCase()),this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)}else this.linePrinter.appendText(e.text);if(e.keywordTokens&&e.keywordTokens.length>0)for(let r=0;r<e.keywordTokens.length;r++){let s=e.keywordTokens[r];this.appendToken(s,t)}let i=t;this.newline!==" "&&n.text!==""&&this.indentIncrementContainers.has(e.containerType)&&(i++,this.linePrinter.appendNewline(i));for(let r=0;r<e.innerTokens.length;r++){let s=e.innerTokens[r];this.appendToken(s,i)}i!==t&&this.linePrinter.appendNewline(t)}};var Sl=["mysql","postgres","sqlserver","sqlite"],ct=class{constructor(e={}){let t=e.preset?En[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 Dt(n),this.printer=new Jt(e)}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var qe=class{constructor(){this.sqlFormatter=new ct({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(e,t=null){return t&&(this.sqlFormatter=new ct(t)),this.sqlFormatter.format(e).formattedSql}formatWithParameters(e,t=null){t&&(this.sqlFormatter=new ct(t));let n=this.sqlFormatter.format(e);return{sql:n.formattedSql,params:n.params}}visit(e){return this.format(e)}};var _t=class{constructor(){this.sourceCollector=new jt(!0),this.cteCollector=new ee,this.formatter=new qe}build(e){if(e.length===0)return new X(!1,e);let t=this.resolveDuplicateNames(e),{tableMap:n,recursiveCTEs:i,dependencies:r}=this.buildDependencyGraph(t),s=this.sortCommonTables(t,n,i,r);return new X(i.size>0,s)}resolveDuplicateNames(e){let t=new Map;for(let i of e){let r=i.aliasExpression.table.name;t.has(r)||t.set(r,[]),t.get(r).push(i)}let n=[];for(let[i,r]of t.entries()){if(r.length===1){n.push(r[0]);continue}let s=r.map(l=>this.formatter.format(l.query));if(new Set(s).size===1)n.push(r[0]);else throw new Error(`CTE name conflict detected: '${i}' has multiple different definitions`)}return n}buildDependencyGraph(e){let t=new Map;for(let s of e)t.set(s.aliasExpression.table.name,s);let n=new Set,i=new Map,r=new Map;for(let s of e){let a=s.aliasExpression.table.name,l=this.sourceCollector.collect(s.query);for(let m of l)if(m.table.name===a){n.add(a);break}i.has(a)||i.set(a,new Set);let u=this.cteCollector.collect(s.query);for(let m of u){let w=m.aliasExpression.table.name;t.has(w)&&(i.get(a).add(w),r.has(w)||r.set(w,new Set),r.get(w).add(a))}}return{tableMap:t,recursiveCTEs:n,dependencies:i}}sortCommonTables(e,t,n,i){let r=[],s=[],a=new Set,l=new Set,u=m=>{if(a.has(m))return;if(l.has(m))throw new Error(`Circular reference detected in CTE: ${m}`);l.add(m);let w=i.get(m)||new Set;for(let d of w)u(d);l.delete(m),a.add(m),n.has(m)?r.push(t.get(m)):s.push(t.get(m))};for(let m of e){let w=m.aliasExpression.table.name;a.has(w)||u(w)}return[...r,...s]}};var Mt=class{constructor(){this.nameConflictResolver=new _t,this.cteCollector=new ee}inject(e,t){if(t.length===0)return e;t.push(...this.cteCollector.collect(e));let n=this.nameConflictResolver.build(t);if(e instanceof k)return this.injectIntoSimpleQuery(e,n);if(e instanceof M)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 k)return this.injectIntoSimpleQuery(e.left,t),e;if(e.left instanceof M)return this.injectIntoBinaryQuery(e.left,t),e;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var Ue=class{constructor(){}static normalize(e){let n=new ee().collect(e);return n.length===0?e:(new ot().execute(e),new Mt().inject(e,n))}};var gn=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))(gn||{}),Pe=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 ee,this.commonTables=[],this.duplicateDetection=n,this.options=i||{},this.handlers=new Map,this.handlers.set(k.kind,r=>this.visitSimpleSelectQuery(r)),this.handlers.set(j.kind,r=>this.visitSelectClause(r)),this.handlers.set(V.kind,r=>this.visitFromClause(r)),this.handlers.set(ie.kind,r=>this.visitWhereClause(r)),this.handlers.set(ce.kind,r=>this.visitGroupByClause(r)),this.handlers.set(pe.kind,r=>this.visitHavingClause(r)),this.handlers.set(ue.kind,r=>this.visitOrderByClause(r)),this.handlers.set(de.kind,r=>this.visitWindowFrameClause(r)),this.handlers.set(re.kind,r=>this.visitLimitClause(r)),this.handlers.set(Ae.kind,r=>this.offsetClause(r)),this.handlers.set(je.kind,r=>this.visitFetchClause(r)),this.handlers.set(me.kind,r=>this.visitJoinOnClause(r)),this.handlers.set(Ee.kind,r=>this.visitJoinUsingClause(r)),this.handlers.set(x.kind,r=>this.visitColumnReference(r)),this.handlers.set(y.kind,r=>this.visitBinaryExpression(r)),this.handlers.set(ne.kind,r=>this.visitUnaryExpression(r)),this.handlers.set(W.kind,r=>this.visitFunctionCall(r)),this.handlers.set(z.kind,r=>this.visitParenExpression(r)),this.handlers.set(ae.kind,r=>this.visitCaseExpression(r)),this.handlers.set(le.kind,r=>this.visitCastExpression(r)),this.handlers.set(ye.kind,r=>this.visitBetweenExpression(r)),this.handlers.set(Ce.kind,r=>this.visitArrayExpression(r)),this.handlers.set(ve.kind,r=>this.visitArrayQueryExpression(r)),this.handlers.set(D.kind,r=>this.visitValueList(r)),this.handlers.set(de.kind,r=>this.visitWindowFrameClause(r)),this.handlers.set(Le.kind,r=>this.visitWindowFrameExpression(r)),this.handlers.set(Be.kind,r=>this.visitPartitionByClause(r))}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(r=>{let s="";return r.value&&typeof r.value.getNamespace=="function"&&(s=r.value.getNamespace()||""),(s?s+"."+r.name:r.name)===i})||this.selectValues.push({name:e,value:t})}}visit(e){if(!this.isRootVisit){this.visitNode(e);return}if(!(e instanceof k))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 Ie(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 Ye=class o{static parse(e){let n=new I(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=ge.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=ge.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 B(t,n.name),newIndex:i}}static parseFunctionSource(e,t){let n=t.newIndex,{namespaces:i,name:r}=t,s=b.parseArgument(4,8,e,n);n=s.newIndex;let a=r.name;return{value:new We({namespaces:i,name:a},s.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 r=this.parseSubQuerySource(e,n);if(n=r.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:r.value,newIndex:n}}else if(e[n].type==4){let r=this.parseParenSource(e,n);if(n=r.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:r.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:r}=K.parseFromLexeme(e,n);return n=r,{value:new J(i),newIndex:n}}};var pt=class{constructor(e,t){this.options=t||{},this.tableColumnResolver=e,this.columnCollector=new Pe(this.tableColumnResolver)}find(e,t){let n=typeof t=="string"?[t]:t,r=new ee().collect(e),s=new Map;for(let a of r)s.set(a.getSourceAliasName(),a);return this.findUpstream(e,n,s)}handleTableSource(e,t,n){let i=n.get(e.table.name);if(i){let r=new Map(n);r.delete(e.table.name);let s=this.findUpstream(i.query,t,r);return s.length===0?null:s}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 r=[],s=!0,a=0;for(let l of i){let u=l.datasource,m=null;if(u instanceof B)m=this.handleTableSource(u,t,n),a++;else if(u instanceof J)m=this.handleSubQuerySource(u,t,n),a++;else{if(u instanceof oe)continue;s=!1;break}if(m===null){s=!1;break}r.push(m)}return s&&r.length===a?r.flat():null}findUpstream(e,t,n){if(e instanceof k){let i=e.fromClause;if(i){let l=this.processFromClauseBranches(i,t,n);if(l)return l}let r=this.columnCollector.collect(e).map(l=>l.name),s=l=>this.options.ignoreCaseAndUnderscore?l.toLowerCase().replace(/_/g,""):l;return t.every(l=>r.some(u=>s(u)===s(l)))?[e]:[]}else if(e instanceof M){let i=this.findUpstream(e.left,t,n),r=this.findUpstream(e.right,t,n);return[...i,...r]}return[]}};var Xe=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 r=[];for(n++;n<e.length&&e[n].type&64&&(r.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(r.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 q(i,r),newIndex:n}}return{value:new q(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 Re=class{static parse(e){let n=new I(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=Ye.parseTableSourceFromLexemes(e,t);return{value:new A(n.value,null),newIndex:n.newIndex}}static parseFromLexeme(e,t){let n=t,i=Ye.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length){if(e[n].value==="as"){n++;let s=Xe.parseFromLexeme(e,n);return n=s.newIndex,{value:new A(i.value,s.value),newIndex:n}}if(n<e.length&&this.isTokenTypeAliasCandidate(e[n].type)){let s=Xe.parseFromLexeme(e,n);return n=s.newIndex,{value:new A(i.value,s.value),newIndex:n}}}return{value:new A(i.value,null),newIndex:n}}static isTokenTypeAliasCandidate(e){return(e&64)!==0||(e&2048)!==0}};var mt=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=r=>r instanceof oe?o.buildSimpleQuery(r):r,i=new M(n(e[0]),t,n(e[1]));Ue.normalize(i);for(let r=2;r<e.length;r++)i.appendSelectQuery(t,n(e[r]));return i}constructor(){}static buildSimpleQuery(e){if(e instanceof k)return e;if(e instanceof M)return o.buildSimpleBinaryQuery(e);if(e instanceof oe)return o.buildSimpleValuesQuery(e);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(e){let t=new J(e),n=new A(t,new q("bq",null)),i=new V(n,null),r=o.createSelectAllClause(),s=new k({selectClause:r,fromClause:i});return Ue.normalize(s)}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 J(e),i=new A(n,new q("vq",e.columnAliases)),r=new V(i,null),s=e.columnAliases.map(l=>new $(new x("vq",l),l)),a=new j(s,null);return new k({selectClause:a,fromClause:r})}static createSelectAllClause(){let e=new x(null,"*"),t=new $(e,"*");return new j([t],null)}static buildCreateTableQuery(e,t,n=!1){return new ut({tableName:t,isTemporary:n,asSelectQuery:e})}static buildInsertQuery(e,t){let n,i=e.selectClause.items.length;if(n=new Ie().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.
|
|
11
|
+
${a}`;return new o(l,n,a)}};var yt=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 b=class{static parse(e){let n=new I(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw Kt.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,r=!0){let s=t,a=e[s].comments,l=this.parseItem(e,s);l.value.comments=a,s=l.newIndex;let u=l.value;for(;s<e.length&&e[s].type&2;){let f=e[s].value;if(!i&&f.toLowerCase()==="and"||!r&&f.toLowerCase()==="or")break;let T=yt.getPrecedence(f);if(T<n)break;if(s++,yt.isBetweenOperator(f)){let m=Ze.parseBetweenExpression(e,s,u,f.toLowerCase().includes("not"));u=m.value,s=m.newIndex;continue}if(f==="::"){let m=Ze.parseTypeValue(e,s);u=new ce(u,m.value),s=m.newIndex;continue}let j=T+1,V=this.parseExpressionWithPrecedence(e,s,j,i,r);s=V.newIndex,u=new C(u,f,V.value)}return{value:u,newIndex:s}}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 r=Bt.parseFromLexeme(e,n);if(r.newIndex>=e.length)return r;if(e[r.newIndex].type&1){let a=Ct.parseFromLexeme(e,r.newIndex);return{value:new re(e[n].value,a.value),newIndex:a.newIndex}}return r}else if(i.type&64){let{namespaces:r,name:s,newIndex:a}=Te.parseFromLexeme(e,n);return e[a-1].type&10240?Ze.parseFromLexeme(e,n):{value:new S(r,s),newIndex:a}}else{if(i.type&1)return Ct.parseFromLexeme(e,n);if(i.type&4)return Vt.parseFromLexeme(e,n);if(i.type&2048)return Ze.parseFromLexeme(e,n);if(i.type&2)return Rt.parseFromLexeme(e,n);if(i.type&256)return $t.parseFromLexeme(e,n);if(i.type&4096)return Wt.parseFromLexeme(e,n);if(i.type&128)return jt.parseFromLexeme(e,n);if(i.type&512){let{namespaces:r,name:s,newIndex:a}=Te.parseFromLexeme(e,n);return{value:new S(r,s),newIndex:a}}else if(i.type&8192){let{namespaces:r,name:s,newIndex:a}=Te.parseFromLexeme(e,n);return{value:new Ie(r,s),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 r=i,s=[];if(r<n.length&&n[r].type===e){if(r++,r<n.length&&n[r].type===t)return r++,{value:new M([]),newIndex:r};if(r<n.length&&n[r].value==="*"){let l=new S(null,"*");if(r++,r<n.length&&n[r].type===t)return r++,{value:l,newIndex:r};throw new Error(`Expected closing parenthesis at index ${r}`)}let a=this.parseFromLexeme(n,r);for(r=a.newIndex,s.push(a.value);r<n.length&&n[r].type&16;){r++;let l=this.parseFromLexeme(n,r);r=l.newIndex,s.push(l.value)}if(r<n.length&&n[r].type===t)return r++,s.length===1?{value:s[0],newIndex:r}:{value:new M(s),newIndex:r};throw new Error(`Missing closing parenthesis at index ${r}`)}throw new Error(`Expected opening parenthesis at index ${i}`)}};var ne=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(k.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(H.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(le.kind,e=>this.visitValuesQuery(e)),this.handlers.set(ee.kind,e=>this.visitWithClause(e)),this.handlers.set(Z.kind,e=>this.visitCommonTable(e)),this.handlers.set(W.kind,e=>this.visitSelectItem(e)),this.handlers.set(E.kind,e=>this.visitIdentifierString(e)),this.handlers.set(F.kind,e=>this.visitRawString(e)),this.handlers.set(S.kind,e=>this.visitColumnReference(e)),this.handlers.set(g.kind,e=>this.visitParameterExpression(e)),this.handlers.set(z.kind,e=>this.visitLiteralValue(e)),this.handlers.set(A.kind,e=>this.visitSourceExpression(e)),this.handlers.set(B.kind,e=>this.visitTableSource(e)),this.handlers.set(Ke.kind,e=>this.visitFunctionSource(e)),this.handlers.set(We.kind,e=>this.visitParenSource(e)),this.handlers.set(q.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Ne.kind,e=>this.visitInlineQuery(e)),this.handlers.set(R.kind,e=>this.visitFromClause(e)),this.handlers.set(fe.kind,e=>this.visitJoinClause(e)),this.handlers.set(de.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(ke.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(C.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(re.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ue.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ye.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(ve.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(Ee.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(U.kind,e=>this.visitFunctionCall(e)),this.handlers.set(Se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(xe.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(ge.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ce.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ae.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Re.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Ie.kind,e=>this.visitTypeValue(e)),this.handlers.set(M.kind,e=>this.visitValueList(e)),this.handlers.set(Ue.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(K.kind,e=>this.visitSelectClause(e)),this.handlers.set(me.kind,e=>this.visitGroupByClause(e)),this.handlers.set(he.kind,e=>this.visitHavingClause(e)),this.handlers.set(pe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(we.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Be.kind,e=>this.visitForClause(e)),this.handlers.set(be.kind,e=>this.visitOrderByItem(e)),this.handlers.set($e.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 ut=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(k.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(H.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(le.kind,e=>this.visitValuesQuery(e)),this.handlers.set(W.kind,e=>this.visitSelectItem(e)),this.handlers.set(E.kind,e=>this.visitIdentifierString(e)),this.handlers.set(F.kind,e=>this.visitRawString(e)),this.handlers.set(S.kind,e=>this.visitColumnReference(e)),this.handlers.set(g.kind,e=>this.visitParameterExpression(e)),this.handlers.set(z.kind,e=>this.visitLiteralValue(e)),this.handlers.set(A.kind,e=>this.visitSourceExpression(e)),this.handlers.set(B.kind,e=>this.visitTableSource(e)),this.handlers.set(We.kind,e=>this.visitParenSource(e)),this.handlers.set(q.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Ne.kind,e=>this.visitInlineQuery(e)),this.handlers.set(R.kind,e=>this.visitFromClause(e)),this.handlers.set(fe.kind,e=>this.visitJoinClause(e)),this.handlers.set(de.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(ke.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(C.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(re.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ue.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ye.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(ve.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(Ee.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(U.kind,e=>this.visitFunctionCall(e)),this.handlers.set(Se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(xe.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(ge.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ce.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ae.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Re.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Ie.kind,e=>this.visitTypeValue(e)),this.handlers.set(K.kind,e=>this.visitSelectClause(e)),this.handlers.set(me.kind,e=>this.visitGroupByClause(e)),this.handlers.set(he.kind,e=>this.visitHavingClause(e)),this.handlers.set(pe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(we.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Be.kind,e=>this.visitForClause(e)),this.handlers.set(be.kind,e=>this.visitOrderByItem(e))}reset(){this.visitedNodes.clear()}execute(e){return this.reset(),this.visit(e)}visit(e){if(!this.isRootVisit)return this.visitNode(e);this.reset(),this.isRootVisit=!1;try{return this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return e;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t)return t(e);let n=e.getKind()?.toString()||"unknown",i=e.constructor?.name||"unknown";throw new Error(`[CTEDisabler] No handler for ${i} with kind ${n}.`)}visitSimpleSelectQuery(e){return e.withClause&&e.withClause.tables.forEach(t=>{this.visit(t.query)}),e.withClause=null,e.selectClause=this.visit(e.selectClause),e.fromClause=e.fromClause?this.visit(e.fromClause):null,e.whereClause=e.whereClause?this.visit(e.whereClause):null,e.groupByClause=e.groupByClause?this.visit(e.groupByClause):null,e.havingClause=e.havingClause?this.visit(e.havingClause):null,e.orderByClause=e.orderByClause?this.visit(e.orderByClause):null,e.windowClause&&(e.windowClause=new qe(e.windowClause.windows.map(t=>this.visit(t)))),e.limitClause=e.limitClause?this.visit(e.limitClause):null,e.forClause=e.forClause?this.visit(e.forClause):null,e}visitBinarySelectQuery(e){return e.left=this.visit(e.left),e.right=this.visit(e.right),e}visitValuesQuery(e){let t=e.tuples.map(n=>this.visit(n));return new le(t)}visitSelectClause(e){let t=e.items.map(n=>this.visit(n));return new K(t,e.distinct)}visitFromClause(e){let t=this.visit(e.source),n=e.joins?e.joins.map(i=>this.visit(i)):null;return new R(t,n)}visitSubQuerySource(e){let t=this.visit(e.query);return new q(t)}visitInlineQuery(e){let t=this.visit(e.selectQuery);return new Ne(t)}visitJoinClause(e){let t=this.visit(e.source),n=e.condition?this.visit(e.condition):null;return new fe(e.joinType.value,t,n,e.lateral)}visitJoinOnClause(e){let t=this.visit(e.condition);return new de(t)}visitJoinUsingClause(e){let t=this.visit(e.condition);return new ke(t)}visitWhereClause(e){let t=this.visit(e.condition);return new se(t)}visitGroupByClause(e){let t=e.grouping.map(n=>this.visit(n));return new me(t)}visitHavingClause(e){let t=this.visit(e.condition);return new he(t)}visitOrderByClause(e){let t=e.order.map(n=>this.visit(n));return new pe(t)}visitWindowFrameClause(e){let t=this.visit(e.expression);return new we(e.name.name,t)}visitLimitClause(e){let t=this.visit(e.value);return new oe(t)}visitForClause(e){return new Be(e.lockMode)}visitParenExpression(e){let t=this.visit(e.expression);return new Y(t)}visitBinaryExpression(e){let t=this.visit(e.left),n=this.visit(e.right);return new C(t,e.operator.value,n)}visitUnaryExpression(e){let t=this.visit(e.expression);return new re(e.operator.value,t)}visitCaseExpression(e){let t=e.condition?this.visit(e.condition):null,n=this.visit(e.switchCase);return new ue(t,n)}visitSwitchCaseArgument(e){let t=e.cases.map(i=>this.visit(i)),n=e.elseValue?this.visit(e.elseValue):null;return new ve(t,n)}visitCaseKeyValuePair(e){let t=this.visit(e.key),n=this.visit(e.value);return new ye(t,n)}visitBetweenExpression(e){let t=this.visit(e.expression),n=this.visit(e.lower),i=this.visit(e.upper);return new Ee(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 U(e.namespaces,e.name,t,n)}visitArrayExpression(e){let t=this.visit(e.expression);return new Se(t)}visitArrayQueryExpression(e){let t=this.visit(e.query);return new xe(t)}visitTupleExpression(e){let t=e.values.map(n=>this.visit(n));return new ge(t)}visitCastExpression(e){let t=this.visit(e.input),n=this.visit(e.castType);return new ce(t,n)}visitTypeValue(e){let t=e.argument?this.visit(e.argument):null;return new Ie(e.namespaces,e.name,t)}visitSelectItem(e){let t=this.visit(e.value);return new W(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 A(t,n)}visitTableSource(e){return e}visitParenSource(e){let t=this.visit(e.source);return new We(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 Ae(t,n,i)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new be(t,e.sortDirection,e.nullsPosition)}};var Dt=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(k.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(H.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(le.kind,t=>this.visitValuesQuery(t)),this.handlers.set(ee.kind,t=>this.visitWithClause(t)),this.handlers.set(Z.kind,t=>this.visitCommonTable(t)),this.handlers.set(R.kind,t=>this.visitFromClause(t)),this.handlers.set(fe.kind,t=>this.visitJoinClause(t)),this.handlers.set(de.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(ke.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(A.kind,t=>this.visitSourceExpression(t)),this.handlers.set(B.kind,t=>this.visitTableSource(t)),this.handlers.set(Ke.kind,t=>this.visitFunctionSource(t)),this.handlers.set(We.kind,t=>this.visitParenSource(t)),this.handlers.set(q.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(Ne.kind,t=>this.visitInlineQuery(t)),e||(this.handlers.set(se.kind,t=>this.visitWhereClause(t)),this.handlers.set(me.kind,t=>this.visitGroupByClause(t)),this.handlers.set(he.kind,t=>this.visitHavingClause(t)),this.handlers.set(pe.kind,t=>this.visitOrderByClause(t)),this.handlers.set(we.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(oe.kind,t=>this.visitLimitClause(t)),this.handlers.set(Ve.kind,t=>this.visitOffsetClause(t)),this.handlers.set(De.kind,t=>this.visitFetchClause(t)),this.handlers.set(Be.kind,t=>this.visitForClause(t)),this.handlers.set(be.kind,t=>this.visitOrderByItem(t)),this.handlers.set(K.kind,t=>this.visitSelectClause(t)),this.handlers.set(W.kind,t=>this.visitSelectItem(t)),this.handlers.set(Y.kind,t=>this.visitParenExpression(t)),this.handlers.set(C.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(re.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(ue.kind,t=>this.visitCaseExpression(t)),this.handlers.set(ye.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(ve.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(Ee.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(U.kind,t=>this.visitFunctionCall(t)),this.handlers.set(Se.kind,t=>this.visitArrayExpression(t)),this.handlers.set(xe.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(ge.kind,t=>this.visitTupleExpression(t)),this.handlers.set(ce.kind,t=>this.visitCastExpression(t)),this.handlers.set(M.kind,t=>this.visitValueList(t)),this.handlers.set(Ue.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 F?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof F?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 ne;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 c=class{constructor(e,t="",n=""){this.innerTokens=[];this.type=e,this.text=t,this.containerType=n}};var ct=class{static collect(e){let t=[];function n(i){if(!(!i||typeof i!="object")){i.constructor&&i.constructor.kind===g.kind&&t.push(i);for(let r of Object.keys(i)){let s=i[r];Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&s.constructor&&s.constructor.kind&&n(s)}}}return n(e),t}};var Jt=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var _t=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 pt=class extends w{static{this.kind=Symbol("UpdateQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.updateClause=e.updateClause,this.setClause=e.setClause instanceof Me?e.setClause:new Me(e.setClause),this.whereClause=e.whereClause??null,this.fromClause=e.fromClause??null,this.returningClause=e.returning??null}};var Le=class o{constructor(e=null,t=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=e??null,this.commonTableCollector=new ne,this.commonTables=[],this.initialCommonTables=t,this.handlers=new Map,this.handlers.set(k.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(K.kind,n=>this.visitSelectClause(n)),this.handlers.set(A.kind,n=>this.visitSourceExpression(n)),this.handlers.set(R.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 S&&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 S&&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 r of e.fromClause.joins){let s=r.getSourceAliasName();s&&n.includes(s)&&this.processJoinClause(r)}}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 S(e?[e]:null,a.name))})}else new o(this.tableColumnResolver,this.commonTables).collect(t).forEach(s=>{this.addSelectValueAsUnique(s.name,new S(e?[e]:null,s.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 S){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 S(t?[t]:null,n.name))});return}else if(e.datasource instanceof B){if(this.tableColumnResolver){let t=e.datasource.getSourceName();this.tableColumnResolver(t).forEach(n=>{this.addSelectValueAsUnique(n,new S([t],n))})}return}else if(e.datasource instanceof q){let t=e.getAliasName();new o(this.tableColumnResolver,this.commonTables).collect(e.datasource.query).forEach(r=>{this.addSelectValueAsUnique(r.name,new S(t?[t]:null,r.name))});return}else if(e.datasource instanceof We)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 mt=class extends w{static{this.kind=Symbol("CreateTableQuery")}constructor(e){super(),this.tableName=new E(e.tableName),this.isTemporary=e.isTemporary??!1,this.asSelectQuery=e.asSelectQuery}getSelectQuery(){let e;return this.asSelectQuery?e=new Le().collect(this.asSelectQuery).map(i=>new W(i.value,i.name)):e=[new W(new F("*"))],new k({selectClause:new K(e),fromClause:new R(new A(new B(null,this.tableName.name),null),null)})}getCountQuery(){return new k({selectClause:new K([new W(new U(null,"count",new S(null,"*"),null))]),fromClause:new R(new A(new B(null,this.tableName.name),null),null)})}};var kn={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"}},Mt=class o{constructor(e){this.handlers=new Map;this.index=1;e?.preset&&(e={...e.preset,...e}),this.parameterDecorator=new _t({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 Jt({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.handlers.set(M.kind,t=>this.visitValueList(t)),this.handlers.set(S.kind,t=>this.visitColumnReference(t)),this.handlers.set(Qe.kind,t=>this.visitQualifiedName(t)),this.handlers.set(U.kind,t=>this.visitFunctionCall(t)),this.handlers.set(re.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(C.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(z.kind,t=>this.visitLiteralValue(t)),this.handlers.set(g.kind,t=>this.visitParameterExpression(t)),this.handlers.set(ve.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(ye.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(F.kind,t=>this.visitRawString(t)),this.handlers.set(E.kind,t=>this.visitIdentifierString(t)),this.handlers.set(Y.kind,t=>this.visitParenExpression(t)),this.handlers.set(ce.kind,t=>this.visitCastExpression(t)),this.handlers.set(ue.kind,t=>this.visitCaseExpression(t)),this.handlers.set(Se.kind,t=>this.visitArrayExpression(t)),this.handlers.set(xe.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(Ee.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(Ue.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(Ie.kind,t=>this.visitTypeValue(t)),this.handlers.set(ge.kind,t=>this.visitTupleExpression(t)),this.handlers.set(Ne.kind,t=>this.visitInlineQuery(t)),this.handlers.set(Ae.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(Re.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(nt.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(it.kind,t=>this.visitWindowFrameBoundaryValue(t)),this.handlers.set($e.kind,t=>this.visitPartitionByClause(t)),this.handlers.set(pe.kind,t=>this.visitOrderByClause(t)),this.handlers.set(be.kind,t=>this.visitOrderByItem(t)),this.handlers.set(W.kind,t=>this.visitSelectItem(t)),this.handlers.set(K.kind,t=>this.visitSelectClause(t)),this.handlers.set(rt.kind,t=>this.visitDistinct(t)),this.handlers.set(st.kind,t=>this.visitDistinctOn(t)),this.handlers.set(B.kind,t=>this.visitTableSource(t)),this.handlers.set(Ke.kind,t=>this.visitFunctionSource(t)),this.handlers.set(A.kind,t=>this.visitSourceExpression(t)),this.handlers.set(G.kind,t=>this.visitSourceAliasExpression(t)),this.handlers.set(R.kind,t=>this.visitFromClause(t)),this.handlers.set(fe.kind,t=>this.visitJoinClause(t)),this.handlers.set(de.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(ke.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(se.kind,t=>this.visitWhereClause(t)),this.handlers.set(me.kind,t=>this.visitGroupByClause(t)),this.handlers.set(he.kind,t=>this.visitHavingClause(t)),this.handlers.set(qe.kind,t=>this.visitWindowClause(t)),this.handlers.set(we.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(oe.kind,t=>this.visitLimitClause(t)),this.handlers.set(Ve.kind,t=>this.visitOffsetClause(t)),this.handlers.set(De.kind,t=>this.visitFetchClause(t)),this.handlers.set(Xe.kind,t=>this.visitFetchExpression(t)),this.handlers.set(Be.kind,t=>this.visitForClause(t)),this.handlers.set(ee.kind,t=>this.visitWithClause(t)),this.handlers.set(Z.kind,t=>this.visitCommonTable(t)),this.handlers.set(k.kind,t=>this.visitSimpleQuery(t)),this.handlers.set(q.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(H.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(le.kind,t=>this.visitValuesQuery(t)),this.handlers.set(ge.kind,t=>this.visitTupleExpression(t)),this.handlers.set(_e.kind,t=>this.visitInsertQuery(t)),this.handlers.set(He.kind,t=>this.visitInsertClause(t)),this.handlers.set(pt.kind,t=>this.visitUpdateQuery(t)),this.handlers.set(ot.kind,t=>this.visitUpdateClause(t)),this.handlers.set(Me.kind,t=>this.visitSetClause(t)),this.handlers.set(ze.kind,t=>this.visitSetClauseItem(t)),this.handlers.set(gt.kind,t=>this.visitReturningClause(t)),this.handlers.set(mt.kind,t=>this.visitCreateTableQuery(t))}static{this.SPACE_TOKEN=new c(10," ")}static{this.COMMA_TOKEN=new c(3,",")}static{this.ARGUMENT_SPLIT_COMMA_TOKEN=new c(11,",")}static{this.PAREN_OPEN_TOKEN=new c(4,"(")}static{this.PAREN_CLOSE_TOKEN=new c(4,")")}static{this.DOT_TOKEN=new c(8,".")}visitBinarySelectQuery(e){let t=new c(0,"");return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(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 c(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 c(1,"partition by","PartitionByClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOrderByClause(e){let t=new c(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 c(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 c(1,"desc"))),e.nullsPosition&&(e.nullsPosition==="first"?(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(1,"nulls first"))):e.nullsPosition==="last"&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(1,"nulls last")))),t}parse(e){this.index=1;let t=this.visit(e),n=ct.collect(e).sort((r,s)=>(r.index??0)-(s.index??0)),i=this.parameterDecorator.style;if(i==="named"){let r={};for(let s of n){let a=s.name.value;if(r.hasOwnProperty(a)){if(r[a]!==s.value)throw new Error(`Duplicate parameter name '${a}' with different values detected during query composition.`);continue}r[a]=s.value}return{token:t,params:r}}else if(i==="indexed"){let r=n.map(s=>s.value);return{token:t,params:r}}else if(i==="anonymous"){let r=n.map(s=>s.value);return{token:t,params:r}}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 c(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 c(0,"","ColumnReference");return t.innerTokens.push(e.qualifiedName.accept(this)),t}visitFunctionCall(e){let t=new c(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 c(1,"over")),e.over instanceof E?(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 c(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 c(0,"","BinaryExpression");return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(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 c(2,t,"LiteralValue")}visitParameterExpression(e){e.index=this.index;let t=this.parameterDecorator.decorate(e.name.value,e.index),n=new c(7,t);return this.index++,n}visitSwitchCaseArgument(e){let t=new c(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 c(0,"","ElseClause");t.innerTokens.push(new c(1,"else")),t.innerTokens.push(o.SPACE_TOKEN);let n=new c(0,"","CaseElseValue");return n.innerTokens.push(this.visit(e)),t.innerTokens.push(n),t}visitCaseKeyValuePair(e){let t=new c(0,"","CaseKeyValuePair");t.innerTokens.push(new c(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 c(1,"then")),t.innerTokens.push(o.SPACE_TOKEN);let n=new c(0,"","CaseThenValue");return n.innerTokens.push(this.visit(e.value)),t.innerTokens.push(n),t}visitRawString(e){return new c(2,e.value,"RawString")}visitIdentifierString(e){let t=e.name==="*"?e.name:this.identifierDecorator.decorate(e.name);return new c(2,t,"IdentifierString")}visitParenExpression(e){let t=new c(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 c(0,"","CastExpression");return t.innerTokens.push(this.visit(e.input)),t.innerTokens.push(new c(5,"::")),t.innerTokens.push(this.visit(e.castType)),t}visitCaseExpression(e){let t=new c(0,"","CaseExpression");return t.innerTokens.push(new c(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 c(1,"end")),t}visitArrayExpression(e){let t=new c(0,"","ArrayExpression");return t.innerTokens.push(new c(1,"array")),t.innerTokens.push(new c(4,"[")),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(new c(4,"]")),t}visitArrayQueryExpression(e){let t=new c(0,"","ArrayExpression");return t.innerTokens.push(new c(1,"array")),t.innerTokens.push(new c(4,"(")),t.innerTokens.push(this.visit(e.query)),t.innerTokens.push(new c(4,")")),t}visitBetweenExpression(e){let t=new c(0,"","BetweenExpression");return t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(o.SPACE_TOKEN),e.negated&&(t.innerTokens.push(new c(1,"not")),t.innerTokens.push(o.SPACE_TOKEN)),t.innerTokens.push(new c(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 c(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 c(2,t+n,"StringSpecifierExpression")}visitTypeValue(e){let t=new c(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 c(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 c(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 c(0,"","WindowFrameSpec");return t.innerTokens.push(new c(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 c(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 c(1,"and")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.endBound.accept(this))),t}visitWindowFrameBoundaryValue(e){let t=new c(0,"","WindowFrameBoundaryValue");return t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(1,e.isFollowing?"following":"preceding")),t}visitWindowFrameBoundStatic(e){return new c(1,e.bound)}visitSelectItem(e){let t=new c(0,"","SelectItem");if(t.innerTokens.push(this.visit(e.value)),!e.identifier)return t;if(e.value instanceof S){let n=e.value.column.name;if(e.identifier.name===n)return t}return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.identifier)),t}visitSelectClause(e){let t=new c(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 c(1,"distinct")}visitDistinctOn(e){let t=new c(0,"","DistinctOn");return t.innerTokens.push(new c(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 c(2,t);return e.identifier&&(e.identifier.name,e.table.name),n}visitSourceExpression(e){let t=new c(0,"","SourceExpression");if(t.innerTokens.push(e.datasource.accept(this)),!e.aliasExpression)return t;if(e.datasource instanceof B){let n=e.datasource.table.name;return e.aliasExpression.table.name===n||(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(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 c(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this)),t}visitFromClause(e){let t=new c(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 c(0,"","JoinClause");return t.innerTokens.push(new c(1,e.joinType.value)),e.lateral&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(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 c(0,"","JoinOnClause");return t.innerTokens.push(new c(1,"on")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitJoinUsingClause(e){let t=new c(0,"","JoinUsingClause");return t.innerTokens.push(new c(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 c(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 c(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 c(1,"where","WhereClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitGroupByClause(e){let t=new c(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 c(1,"having","HavingClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitWindowClause(e){let t=new c(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 c(0,"","WindowFrameClause");return t.innerTokens.push(e.name.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(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 c(1,"limit","LimitClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOffsetClause(e){let t=new c(1,"offset","OffsetClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitFetchClause(e){let t=new c(1,"fetch","FetchClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.expression)),t}visitFetchExpression(e){let t=new c(0,"","FetchExpression");return t.innerTokens.push(new c(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 c(1,e.unit))),t}visitForClause(e){let t=new c(1,"for","ForClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(1,e.lockMode)),t}visitWithClause(e){let t=new c(1,"with","WithClause");t.innerTokens.push(o.SPACE_TOKEN),e.recursive&&(t.innerTokens.push(new c(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 c(0,"","CommonTable");t.innerTokens.push(e.aliasExpression.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),e.materialized!==null&&(e.materialized?t.innerTokens.push(new c(1,"materialized")):t.innerTokens.push(new c(1,"not materialized")),t.innerTokens.push(o.SPACE_TOKEN)),t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new c(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 c(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 c(0,"");t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new c(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 c(1,"values","ValuesQuery");t.innerTokens.push(o.SPACE_TOKEN);let n=new c(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 c(0,"");t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new c(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 c(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 c(0,"");if(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(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 c(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 c(1,"update","UpdateClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t}visitSetClause(e){let t=new c(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 c(0,"","SetClauseItem");return t.innerTokens.push(e.column.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new c(5,"=")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.value.accept(this)),t}visitReturningClause(e){let t=new c(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 c(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 c(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.asSelectQuery.accept(this))),t}};var St=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 vn(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.")}},vn=class{constructor(e,t){this.level=e,this.text=t}};var qt=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 St(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 St(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 r=e.text;this.keywordCase==="upper"?r=r.toUpperCase():this.keywordCase==="lower"&&(r=r.toLowerCase()),this.linePrinter.appendText(r)}else if(e.type===3){let r=e.text;this.commaBreak==="before"?(this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)):this.commaBreak==="after"?(this.linePrinter.appendText(r),this.linePrinter.appendNewline(t)):this.linePrinter.appendText(r)}else if(e.type===5&&e.text.toLowerCase()==="and"){let r=e.text;this.keywordCase==="upper"?r=r.toUpperCase():this.keywordCase==="lower"&&(r=r.toLowerCase()),this.andBreak==="before"?(this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)):this.andBreak==="after"?(this.linePrinter.appendText(r),this.linePrinter.appendNewline(t)):this.linePrinter.appendText(r)}else if(e.containerType==="JoinClause"){let r=e.text;this.keywordCase==="upper"?r=r.toUpperCase():this.keywordCase==="lower"&&(r=r.toLowerCase()),this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)}else this.linePrinter.appendText(e.text);if(e.keywordTokens&&e.keywordTokens.length>0)for(let r=0;r<e.keywordTokens.length;r++){let s=e.keywordTokens[r];this.appendToken(s,t)}let i=t;this.newline!==" "&&n.text!==""&&this.indentIncrementContainers.has(e.containerType)&&(i++,this.linePrinter.appendNewline(i));for(let r=0;r<e.innerTokens.length;r++){let s=e.innerTokens[r];this.appendToken(s,i)}i!==t&&this.linePrinter.appendNewline(t)}};var gl=["mysql","postgres","sqlserver","sqlite"],ht=class{constructor(e={}){let t=e.preset?kn[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 Mt(n),this.printer=new qt(e)}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var Ge=class{constructor(){this.sqlFormatter=new ht({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(e,t=null){return t&&(this.sqlFormatter=new ht(t)),this.sqlFormatter.format(e).formattedSql}formatWithParameters(e,t=null){t&&(this.sqlFormatter=new ht(t));let n=this.sqlFormatter.format(e);return{sql:n.formattedSql,params:n.params}}visit(e){return this.format(e)}};var zt=class{constructor(){this.sourceCollector=new Dt(!0),this.cteCollector=new ne,this.formatter=new Ge}build(e){if(e.length===0)return new ee(!1,e);let t=this.resolveDuplicateNames(e),{tableMap:n,recursiveCTEs:i,dependencies:r}=this.buildDependencyGraph(t),s=this.sortCommonTables(t,n,i,r);return new ee(i.size>0,s)}resolveDuplicateNames(e){let t=new Map;for(let i of e){let r=i.aliasExpression.table.name;t.has(r)||t.set(r,[]),t.get(r).push(i)}let n=[];for(let[i,r]of t.entries()){if(r.length===1){n.push(r[0]);continue}let s=r.map(l=>this.formatter.format(l.query));if(new Set(s).size===1)n.push(r[0]);else throw new Error(`CTE name conflict detected: '${i}' has multiple different definitions`)}return n}buildDependencyGraph(e){let t=new Map;for(let s of e)t.set(s.aliasExpression.table.name,s);let n=new Set,i=new Map,r=new Map;for(let s of e){let a=s.aliasExpression.table.name,l=this.sourceCollector.collect(s.query);for(let p of l)if(p.table.name===a){n.add(a);break}i.has(a)||i.set(a,new Set);let u=this.cteCollector.collect(s.query);for(let p of u){let f=p.aliasExpression.table.name;t.has(f)&&(i.get(a).add(f),r.has(f)||r.set(f,new Set),r.get(f).add(a))}}return{tableMap:t,recursiveCTEs:n,dependencies:i}}sortCommonTables(e,t,n,i){let r=[],s=[],a=new Set,l=new Set,u=p=>{if(a.has(p))return;if(l.has(p))throw new Error(`Circular reference detected in CTE: ${p}`);l.add(p);let f=i.get(p)||new Set;for(let T of f)u(T);l.delete(p),a.add(p),n.has(p)?r.push(t.get(p)):s.push(t.get(p))};for(let p of e){let f=p.aliasExpression.table.name;a.has(f)||u(f)}return[...r,...s]}};var Ht=class{constructor(){this.nameConflictResolver=new zt,this.cteCollector=new ne}inject(e,t){if(t.length===0)return e;t.push(...this.cteCollector.collect(e));let n=this.nameConflictResolver.build(t);if(e instanceof k)return this.injectIntoSimpleQuery(e,n);if(e instanceof H)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 k)return this.injectIntoSimpleQuery(e.left,t),e;if(e.left instanceof H)return this.injectIntoBinaryQuery(e.left,t),e;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var Je=class{constructor(){}static normalize(e){let n=new ne().collect(e);return n.length===0?e:(new ut().execute(e),new Ht().inject(e,n))}};var Tn=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))(Tn||{}),Fe=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 ne,this.commonTables=[],this.duplicateDetection=n,this.options=i||{},this.handlers=new Map,this.handlers.set(k.kind,r=>this.visitSimpleSelectQuery(r)),this.handlers.set(K.kind,r=>this.visitSelectClause(r)),this.handlers.set(R.kind,r=>this.visitFromClause(r)),this.handlers.set(se.kind,r=>this.visitWhereClause(r)),this.handlers.set(me.kind,r=>this.visitGroupByClause(r)),this.handlers.set(he.kind,r=>this.visitHavingClause(r)),this.handlers.set(pe.kind,r=>this.visitOrderByClause(r)),this.handlers.set(we.kind,r=>this.visitWindowFrameClause(r)),this.handlers.set(oe.kind,r=>this.visitLimitClause(r)),this.handlers.set(Ve.kind,r=>this.offsetClause(r)),this.handlers.set(De.kind,r=>this.visitFetchClause(r)),this.handlers.set(de.kind,r=>this.visitJoinOnClause(r)),this.handlers.set(ke.kind,r=>this.visitJoinUsingClause(r)),this.handlers.set(S.kind,r=>this.visitColumnReference(r)),this.handlers.set(C.kind,r=>this.visitBinaryExpression(r)),this.handlers.set(re.kind,r=>this.visitUnaryExpression(r)),this.handlers.set(U.kind,r=>this.visitFunctionCall(r)),this.handlers.set(Y.kind,r=>this.visitParenExpression(r)),this.handlers.set(ue.kind,r=>this.visitCaseExpression(r)),this.handlers.set(ce.kind,r=>this.visitCastExpression(r)),this.handlers.set(Ee.kind,r=>this.visitBetweenExpression(r)),this.handlers.set(Se.kind,r=>this.visitArrayExpression(r)),this.handlers.set(xe.kind,r=>this.visitArrayQueryExpression(r)),this.handlers.set(M.kind,r=>this.visitValueList(r)),this.handlers.set(we.kind,r=>this.visitWindowFrameClause(r)),this.handlers.set(Ae.kind,r=>this.visitWindowFrameExpression(r)),this.handlers.set($e.kind,r=>this.visitPartitionByClause(r))}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(r=>{let s="";return r.value&&typeof r.value.getNamespace=="function"&&(s=r.value.getNamespace()||""),(s?s+"."+r.name:r.name)===i})||this.selectValues.push({name:e,value:t})}}visit(e){if(!this.isRootVisit){this.visitNode(e);return}if(!(e instanceof k))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 Le(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 et=class o{static parse(e){let n=new I(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=Te.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=Te.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 B(t,n.name),newIndex:i}}static parseFunctionSource(e,t){let n=t.newIndex,{namespaces:i,name:r}=t,s=b.parseArgument(4,8,e,n);n=s.newIndex;let a=r.name;return{value:new Ke({namespaces:i,name:a},s.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 r=this.parseSubQuerySource(e,n);if(n=r.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:r.value,newIndex:n}}else if(e[n].type==4){let r=this.parseParenSource(e,n);if(n=r.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:r.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:r}=_.parseFromLexeme(e,n);return n=r,{value:new q(i),newIndex:n}}};var dt=class{constructor(e,t){this.options=t||{},this.tableColumnResolver=e,this.columnCollector=new Fe(this.tableColumnResolver)}find(e,t){let n=typeof t=="string"?[t]:t,r=new ne().collect(e),s=new Map;for(let a of r)s.set(a.getSourceAliasName(),a);return this.findUpstream(e,n,s)}handleTableSource(e,t,n){let i=n.get(e.table.name);if(i){let r=new Map(n);r.delete(e.table.name);let s=this.findUpstream(i.query,t,r);return s.length===0?null:s}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 r=[],s=!0,a=0;for(let l of i){let u=l.datasource,p=null;if(u instanceof B)p=this.handleTableSource(u,t,n),a++;else if(u instanceof q)p=this.handleSubQuerySource(u,t,n),a++;else{if(u instanceof le)continue;s=!1;break}if(p===null){s=!1;break}r.push(p)}return s&&r.length===a?r.flat():null}findUpstream(e,t,n){if(e instanceof k){let i=e.fromClause;if(i){let l=this.processFromClauseBranches(i,t,n);if(l)return l}let r=this.columnCollector.collect(e).map(l=>l.name),s=l=>this.options.ignoreCaseAndUnderscore?l.toLowerCase().replace(/_/g,""):l;return t.every(l=>r.some(u=>s(u)===s(l)))?[e]:[]}else if(e instanceof H){let i=this.findUpstream(e.left,t,n),r=this.findUpstream(e.right,t,n);return[...i,...r]}return[]}};var tt=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 r=[];for(n++;n<e.length&&e[n].type&64&&(r.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(r.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 G(i,r),newIndex:n}}return{value:new G(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 je=class{static parse(e){let n=new I(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=et.parseTableSourceFromLexemes(e,t);return{value:new A(n.value,null),newIndex:n.newIndex}}static parseFromLexeme(e,t){let n=t,i=et.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length){if(e[n].value==="as"){n++;let s=tt.parseFromLexeme(e,n);return n=s.newIndex,{value:new A(i.value,s.value),newIndex:n}}if(n<e.length&&this.isTokenTypeAliasCandidate(e[n].type)){let s=tt.parseFromLexeme(e,n);return n=s.newIndex,{value:new A(i.value,s.value),newIndex:n}}}return{value:new A(i.value,null),newIndex:n}}static isTokenTypeAliasCandidate(e){return(e&64)!==0||(e&2048)!==0}};var ft=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=r=>r instanceof le?o.buildSimpleQuery(r):r,i=new H(n(e[0]),t,n(e[1]));Je.normalize(i);for(let r=2;r<e.length;r++)i.appendSelectQuery(t,n(e[r]));return i}constructor(){}static buildSimpleQuery(e){if(e instanceof k)return e;if(e instanceof H)return o.buildSimpleBinaryQuery(e);if(e instanceof le)return o.buildSimpleValuesQuery(e);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(e){let t=new q(e),n=new A(t,new G("bq",null)),i=new R(n,null),r=o.createSelectAllClause(),s=new k({selectClause:r,fromClause:i});return Je.normalize(s)}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 q(e),i=new A(n,new G("vq",e.columnAliases)),r=new R(i,null),s=e.columnAliases.map(l=>new W(new S("vq",l),l)),a=new K(s,null);return new k({selectClause:a,fromClause:r})}static createSelectAllClause(){let e=new S(null,"*"),t=new W(e,"*");return new K([t],null)}static buildCreateTableQuery(e,t,n=!1){return new mt({tableName:t,isTemporary:n,asSelectQuery:e})}static buildInsertQuery(e,t){let n,i=e.selectClause.items.length;if(n=new Le().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
13
|
Select clause column count: ${i}, Columns with valid names: ${n.length}
|
|
14
|
-
Detected column names: [${n.join(", ")}]`);let a=Re.parse(t);return new Ke({insertClause:new Me(a,n),selectQuery:e})}static buildUpdateQuery(e,t,n,i){let r=new it(Re.parse(n)),s=Array.isArray(i)?i:[i],l=new Ie().collect(e),m=new ee().collect(e);new ot().execute(e);for(let C of s)if(!l.some(G=>G.name===C))throw new Error(`Primary key column '${C}' is not present in selectQuery select list.`);let d=r.getSourceAliasName();if(!d)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let S=l.filter(C=>!s.includes(C.name)).map(C=>new _e(C.name,new x(d,C.name))),h=new De(S),L=new V(e.toSource(t),null),T=null;for(let C of s){let G=new y(new x(d,C),"=",new x(t,C));T=T?new y(T,"and",G):G}let N=new ie(T);return new lt({updateClause:r,setClause:h,fromClause:L,whereClause:N,withClause:m.length>0?new X(!1,m):void 0})}};var ze=class{static set(e,t,n){let i=at.collect(e),r=!1;for(let s of i)s.name.value===t&&(s.value=n,r=!0);if(!r)throw new Error(`Parameter '${t}' not found in query.`)}};var k=class extends v{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 mt.buildBinaryQuery([this,t],e)}appendWhereRaw(e){let t=b.parse(e);this.appendWhere(t)}appendWhere(e){this.whereClause?this.whereClause.condition=new y(this.whereClause.condition,"and",e):this.whereClause=new ie(e)}appendHavingRaw(e){let t=b.parse(e);this.appendHaving(t)}appendHaving(e){this.havingClause?this.havingClause.condition=new y(this.havingClause.condition,"and",e):this.havingClause=new pe(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,r=null){let s=Ye.parse(t),a=new A(s,new q(n,null));this.joinSource(e,a,i,r)}joinSource(e,t,n,i=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let r=Array.isArray(n)?n:[n],a=new Pe(i).collect(this),l=null,u=0,m=t.getAliasName();if(!m)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let p of a)if(r.some(S=>S==p.name)){let S=new y(p.value,"=",new x([m],p.name));l?l=new y(l,"and",S):l=S,u++}if(!l||u!==r.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${r.join(", ")}`);let w=new me(l),d=new he(e,t,w,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(d):this.fromClause.joins=[d]),Ue.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 A(new J(this),new q(e,null))}appendWith(e){let t=Array.isArray(e)?e:[e];this.withClause?this.withClause.tables.push(...t):this.withClause=new X(!1,t),Ue.normalize(this)}appendWithRaw(e,t){let n=K.parse(e),i=new Y(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],s=new qe().visit(i.value),a=t(s);i.value=b.parse(a)}appendWhereExpr(e,t,n){if(n&&n.upstream){let r=new pt().find(this,[e]),s=new Pe,a=new qe;for(let l of r){let u=s.collect(l).filter(w=>w.name===e).map(w=>w.value);if(u.length!==1)throw new Error(`Expected exactly one expression for column '${e}'`);let m=a.format(u[0]);l.appendWhereRaw(t(m))}}else{let i=new Pe,r=new qe,s=i.collect(this).filter(l=>l.name===e).map(l=>l.value);if(s.length!==1)throw new Error(`Expected exactly one expression for column '${e}'`);let a=r.format(s[0]);this.appendWhereRaw(t(a))}}setParameter(e,t){return ze.set(this,e,t),this}};var M=class o extends v{static{this.kind=Symbol("BinarySelectQuery")}constructor(e,t,n){super(),this.left=e,this.operator=new F(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 F(e),this.right=t,Ue.normalize(this),this}unionRaw(e){let t=K.parse(e);return this.union(t)}unionAllRaw(e){let t=K.parse(e);return this.unionAll(t)}intersectRaw(e){let t=K.parse(e);return this.intersect(t)}intersectAllRaw(e){let t=K.parse(e);return this.intersectAll(t)}exceptRaw(e){let t=K.parse(e);return this.except(t)}exceptAllRaw(e){let t=K.parse(e);return this.exceptAll(t)}toSource(e="subq"){return new A(new J(this),new q(e,null))}setParameter(e,t){return ze.set(this,e,t),this}};var oe=class extends v{static{this.kind=Symbol("ValuesQuery")}constructor(e,t=null){super(),this.tuples=e,this.columnAliases=t}toSimpleSelectQuery(){return mt.buildSimpleQuery(this)}setParameter(e,t){return ze.set(this,e,t),this}};var qt=class{static parse(e){let n=new I(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 tt;else if(n<e.length&&e[n].value==="distinct on"){n++;let a=b.parseArgument(4,8,e,n);i=new nt(a.value),n=a.newIndex}let r=[],s=zt.parseItem(e,n);for(r.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let a=zt.parseItem(e,n);r.push(a.value),n=a.newIndex}if(r.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 j(r,i),newIndex:n}}},zt=class{static parse(e){let n=new I(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=b.parseFromLexeme(e,n),r=i.value;if(n=i.newIndex,n<e.length&&e[n].value==="as"&&n++,n<e.length&&e[n].type&64){let s=e[n].value;return n++,{value:new $(r,s),newIndex:n}}else if(r instanceof x&&r.column.name!=="*")return{value:new $(r,r.column.name),newIndex:n};return{value:new $(r),newIndex:n}}};var Ht=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="on"){n++;let i=b.parseFromLexeme(e,n);return n=i.newIndex,{value:new me(i.value),newIndex:n}}return null}};var Gt=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="using"){n++;let i=b.parseArgument(4,8,e,n),r=i.value;return n=i.newIndex,{value:new Ee(r),newIndex:n}}return null}};var Yt=class{static tryParse(e,t){let n=t,i=[];for(;this.isJoinCommand(e,n);){let r=this.parseJoinClause(e,n);i.push(r.value),n=r.newIndex}return i.length>0?{value:i,newIndex:n}:null}static isJoinKeyword(e){return!!dn.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 r=this.parseLateral(e,n),s=r.value;n=r.newIndex;let a=Re.parseFromLexeme(e,n);if(n=a.newIndex,n<e.length){let u=Ht.tryParse(e,n);if(u)return{value:new he(i,a.value,u.value,s),newIndex:u.newIndex};let m=Gt.tryParse(e,n);if(m)return{value:new he(i,a.value,m.value,s),newIndex:m.newIndex}}return{value:new he(i,a.value,null,s),newIndex:n}}};var Xt=class{static parse(e){let n=new I(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=Re.parseFromLexeme(e,n);n=i.newIndex;let r=Yt.tryParse(e,n);return n=r?.newIndex||n,r!==null?{value:new V(i.value,r.value),newIndex:n}:{value:new V(i.value,null),newIndex:n}}};var Zt=class{static parse(e){let n=new I(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=b.parseFromLexeme(e,n);return{value:new ie(i.value),newIndex:i.newIndex}}};var en=class{static parse(e){let n=new I(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=[],r=this.parseItem(e,n);for(i.push(r.value),n=r.newIndex;n<e.length&&e[n].type&16;){n++;let s=this.parseItem(e,n);i.push(s.value),n=s.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 ce(i),newIndex:n}}static parseItem(e,t){let n=t,i=b.parseFromLexeme(e,n),r=i.value;return n=i.newIndex,{value:r,newIndex:n}}};var tn=class{static parse(e){let n=new I(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=b.parseFromLexeme(e,n);return{value:new pe(i.value),newIndex:i.newIndex}}};var nn=class{static parse(e){let n=new I(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 r=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 s=st.parseFromLexeme(e,n);if(n=s.newIndex,i.push(new de(r,s.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 Je(i),newIndex:n}}};var rn=class{static parse(e){let n=new I(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=b.parseFromLexeme(e,n);return n=i.newIndex,{value:new re(i.value),newIndex:n}}};var sn=class{static parse(e){let n=new I(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,r;switch(i){case"update":r="update",n++;break;case"share":r="share",n++;break;case"key share":r="key share",n++;break;case"no key update":r="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 Ne(r),newIndex:n}}};var vt=class{static parse(e){let n=new I(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=Xe.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 r=null;if(n<e.length){let l=e[n].value;l==="materialized"?(r=!0,n++):l==="not materialized"&&(r=!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 s=K.parseFromLexeme(e,n);if(n=s.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 Y(s.value,i.value,r),newIndex:n}}};var ht=class{static parse(e){let n=new I(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 r=[],s=vt.parseFromLexeme(e,n);for(r.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let a=vt.parseFromLexeme(e,n);r.push(a.value),n=a.newIndex}return{value:new X(i,r),newIndex:n}}};var on=class{static parse(e){let n=new I(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=[],r=this.parseTuple(e,n);for(i.push(r.value),n=r.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 oe(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 Se([]),newIndex:n};let r=b.parseFromLexeme(e,n);for(i.push(r.value),n=r.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 s=b.parseFromLexeme(e,n);i.push(s.value),n=s.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 Se(i),newIndex:n}}};var an=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=wn.parseFromLexeme(e,n),r=i.value;return n=i.newIndex,{value:new je(r),newIndex:n}}},wn=class{static parseFromLexeme(e,t){let n=t,i,r=e[n].value;if(r==="first")i="first";else if(r==="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 s=null,a=null;if(e[n].value==="row only"||e[n].value==="rows only")return s=new _(1),a="rows only",n++,{value:new He(i,s,a),newIndex:n};let l=b.parseFromLexeme(e,n);if(s=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 He(i,s,a),newIndex:n}}};var ln=class{static parse(e){let n=new I(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=b.parseFromLexeme(e,n);return n=i.newIndex,n<e.length&&(e[n].value==="row"||e[n].value==="rows")&&n++,{value:new Ae(i.value),newIndex:n}}};var K=class{static parse(e){let n=new I(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 r=this.selectCommandSet.has(i)?this.parseSimpleSelectQuery(e,n):this.parseValuesQuery(e,n),s=r.value;for(n=r.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);s=new M(s,a,u.value),n=u.newIndex}else if(l==="values"){let u=this.parseValuesQuery(e,n);s=new M(s,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:s,newIndex:n}}static parseSimpleSelectQuery(e,t){let n=t,i=null;if(n<e.length&&e[n].value==="with"&&(i=ht.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 r=qt.parseFromLexeme(e,n);n=r.newIndex;let s=null;n<e.length&&e[n].value==="from"&&(s=Xt.parseFromLexeme(e,n),n=s.newIndex);let a=null;n<e.length&&e[n].value==="where"&&(a=Zt.parseFromLexeme(e,n),n=a.newIndex);let l=null;n<e.length&&e[n].value==="group by"&&(l=en.parseFromLexeme(e,n),n=l.newIndex);let u=null;n<e.length&&e[n].value==="having"&&(u=tn.parseFromLexeme(e,n),n=u.newIndex);let m=null;n<e.length&&e[n].value==="window"&&(m=nn.parseFromLexeme(e,n),n=m.newIndex);let w=null;n<e.length&&e[n].value==="order by"&&(w=rt.parseFromLexeme(e,n),n=w.newIndex);let d=null;n<e.length&&e[n].value==="limit"&&(d=rn.parseFromLexeme(e,n),n=d.newIndex);let p=null;n<e.length&&e[n].value==="offset"&&(p=ln.parseFromLexeme(e,n),n=p.newIndex);let S=null;n<e.length&&e[n].value==="fetch"&&(S=an.parseFromLexeme(e,n),n=S.newIndex);let h=null;return n<e.length&&e[n].value.toLowerCase()==="for"&&(h=sn.parseFromLexeme(e,n),n=h.newIndex),{value:new k({withClause:i?i.value:null,selectClause:r.value,fromClause:s?s.value:null,whereClause:a?a.value:null,groupByClause:l?l.value:null,havingClause:u?u.value:null,orderByClause:w?w.value:null,windowClause:m?m.value:null,limitClause:d?d.value:null,offsetClause:p?p.value:null,fetchClause:S?S.value:null,forClause:h?h.value:null}),newIndex:n}}static parseValuesQuery(e,t){let n=on.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}};var bn=class{static parse(e){let n=new I(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=ht.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 r=Re.parseTableSourceFromLexemes(e,n);n=r.newIndex;let s=[];if(e[n]?.type===4){for(n++;n<e.length&&e[n].type===64&&(s.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=K.parseFromLexeme(e,n);if(i)if(a.value instanceof k)a.value.withClause=i;else throw new Error("WITH clause is not supported in this context.");return n=a.newIndex,{value:new Ke({insertClause:new Me(r.value,s),selectQuery:a.value}),newIndex:n}}};var un=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],r=e.aliasExpression.table.name,s=this.collectAndSortObjectEntities(n,t),a=this.groupEntitiesByDepth(s),l=Array.from(a.keys()).sort((u,m)=>m-u);for(let u of l){let m=a.get(u),w=`${o.CTE_OBJECT_PREFIX}${u}`,d=this.buildDepthCte(m,r,w,n,t);i.push(d),r=w}return{ctes:i,lastCteAlias:r}}collectAndSortObjectEntities(e,t){let n=[],i=r=>{let s=t.get(r);if(!s)throw new Error(`Entity ${r} not found for depth calculation.`);if(s.isRoot)return 0;if(!s.parentId)return 1;let a=s.parentId,l=0,u=new Set;for(u.add(r);a;){if(u.has(a))throw new Error(`Circular dependency detected: ${a} already visited in path for ${r}`);u.add(a);let m=t.get(a);if(!m)throw new Error(`Parent entity ${a} not found during depth calculation for ${r}`);let w=!1;if(m.isRoot)w=!0;else{let d=e.nestedEntities.find(p=>p.id===a);if(d)d.relationshipType==="object"&&(w=!0);else throw new Error(`Parent entity ${a} (ancestor of ${r}) has no definition in mapping.nestedEntities and is not root.`)}if(w&&l++,m.isRoot)break;a=m.parentId}return l};return e.nestedEntities.forEach(r=>{if(r.relationshipType==="object"){let s=t.get(r.id);s&&!s.isRoot&&n.push({entity:s,depth:i(r.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,r){let s=[new $(new x(null,new E(o.WILDCARD_COLUMN)))];for(let{entity:l}of e){let u=this.buildEntityJsonColumn(l,i,r);s.push(u)}let a=new k({selectClause:new j(s),fromClause:new V(new A(new B(null,new E(t)),null),null)});return new Y(a,new q(n,null),null)}buildEntityJsonColumn(e,t,n){let{jsonObjectArgs:i,nullChecks:r}=this.prepareEntityColumns(e);this.addChildObjectRelationships(e,i,t,n);let s=this.createJsonObject(i,t.useJsonb),a=this.buildNullCondition(r),l=this.createCaseExpression(a,s),u=`${e.name.toLowerCase()}${o.JSON_COLUMN_SUFFIX}`;return new $(l,u)}prepareEntityColumns(e){let t=[],n=[];return Object.entries(e.columns).forEach(([i,r])=>{t.push(new _(i)),t.push(new x(null,new E(r))),n.push(new y(new x(null,new E(r)),"is",new _(null)))}),{jsonObjectArgs:t,nullChecks:n}}addChildObjectRelationships(e,t,n,i){n.nestedEntities.filter(s=>s.parentId===e.id&&s.relationshipType==="object").forEach(s=>{let a=i.get(s.id);if(a){t.push(new _(s.propertyName));let l=`${a.name.toLowerCase()}${o.JSON_COLUMN_SUFFIX}`;t.push(new x(null,new E(l)))}})}createJsonObject(e,t=!1){let n=t?"jsonb_build_object":"json_build_object";return new W(null,new F(n),new D(e),null)}buildNullCondition(e){return e.reduce((t,n)=>t?new y(t,"and",n):n)}createCaseExpression(e,t){return new ae(null,new fe([new we(e,new _(null))],t))}};var cn=class o{static{this.CTE_ARRAY_PREFIX="cte_array_depth_"}buildArrayEntityCtes(e,t,n,i){let r=[...e],s=t,a=this.collectAndSortArrayEntities(i,n);if(a.length===0)return{updatedCtes:r,lastCteAlias:s};let l=this.groupEntitiesByDepth(a),u=Array.from(l.keys()).sort((m,w)=>w-m);for(let m of u){let w=l.get(m),{cte:d,newCteAlias:p}=this.buildDepthCte(w,s,r,m,i);r.push(d),s=p}return{updatedCtes:r,lastCteAlias:s}}collectAndSortArrayEntities(e,t){let n=[],i=r=>{let s=t.get(r);return!s||s.isRoot?0:s.parentId?1+i(s.parentId):1};return e.nestedEntities.forEach(r=>{if(r.relationshipType==="array"){let s=t.get(r.id),a=t.get(r.parentId);if(!s||!a)throw new Error(`Configuration error: Array entity '${r.id}' or its parent '${r.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 '${r.name}'.`);let u=l[0];n.push({entity:s,parentEntity:a,parentIdColumnSqlName:u,depth:i(r.id)})}}),n.sort((r,s)=>s.depth-r.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,r){let s=new Set;e.forEach(S=>{Object.values(S.entity.columns).forEach(h=>s.add(h))});let a=n.find(S=>S.aliasExpression.table.name===t)?.query;if(!a)throw new Error(`CTE not found: ${t}`);let l=new Ie(null,n).collect(a),u=[],m=[];l.forEach(S=>{s.has(S.name)||(m.push(new $(new x(null,new E(S.name)),S.name)),u.push(new x(null,new E(S.name))))});for(let S of e){let h=this.buildAggregationDetailsForArrayEntity(S.entity,r.nestedEntities,new Map,r.useJsonb);m.push(new $(h.jsonAgg,S.entity.propertyName))}let w=`${o.CTE_ARRAY_PREFIX}${i}`,d=new k({selectClause:new j(m),fromClause:new V(new A(new B(null,new E(t)),null),null),groupByClause:u.length>0?new ce(u):null});return{cte:new Y(d,new q(w,null),null),newCteAlias:w}}buildAggregationDetailsForArrayEntity(e,t,n,i=!1){let r=i?"jsonb_build_object":"json_build_object",s=[];Object.entries(e.columns).forEach(([w,d])=>{s.push(new _(w)),s.push(new x(null,new E(d)))}),t.filter(w=>w.parentId===e.id).forEach(w=>{if(s.push(new _(w.propertyName)),w.relationshipType==="object"){let d=`${w.name.toLowerCase()}_json`;s.push(new x(null,new E(d)))}else w.relationshipType==="array"&&s.push(new x(null,new E(w.propertyName)))});let l=new W(null,new F(r),new D(s),null),u=i?"jsonb_agg":"json_agg";return{jsonAgg:new W(null,new F(u),new D([l]),null)}}};var kn=class{constructor(){this.selectValueCollector=new Ie(null),this.objectEntityCteBuilder=new un,this.arrayEntityCteBuilder=new cn}validateMapping(e,t){let i=new Ie().collect(e),r=new Set(i.map(u=>u.name));for(let u in t.rootEntity.columns){let m=t.rootEntity.columns[u];if(!r.has(m))throw new Error(`Validation Error: Column "${m}" for JSON key "${u}" in root entity "${t.rootEntity.name}" not found in the query's select list.`)}let s=new Set([t.rootEntity.id]),a=new Map;t.nestedEntities.forEach(u=>{s.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(!s.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 m in u.columns){let w=u.columns[m];if(!r.has(w))throw new Error(`Validation Error: Column "${w}" for JSON key "${m}" 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 m=t.nestedEntities.filter(p=>p.parentId===u);if(m.filter(p=>p.relationshipType==="array").length>1){let p=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(S=>S.id===u)?.name;throw new Error(`Validation Error: Parent entity "${p}" (ID: ${u}) has multiple direct array children. This is not supported.`)}let d=new Set;for(let p of m){if(d.has(p.propertyName)){let S=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(h=>h.id===u)?.name;throw new Error(`Validation Error: Parent entity "${S}" (ID: ${u}) has duplicate property name "${p.propertyName}" for its children.`)}d.add(p.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),r=[n],s=i,a=new Map;a.set(t.rootEntity.id,{...t.rootEntity,isRoot:!0,propertyName:t.rootName}),t.nestedEntities.forEach(m=>a.set(m.id,{...m,isRoot:!1,propertyName:m.propertyName}));let l=this.objectEntityCteBuilder.buildObjectEntityCtes(n,a,t);r=l.ctes,s=l.lastCteAlias;let u=this.arrayEntityCteBuilder.buildArrayEntityCtes(r,s,a,t);return r=u.updatedCtes,s=u.lastCteAlias,this.buildFinalSelectQuery(r,s,a,t)}createInitialCte(e){let t="origin_query";return{initialCte:new Y(e,new q(t,null),null),initialCteAlias:t}}buildFinalSelectQuery(e,t,n,i){let r=[...e],s=`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,i.rootName),m=new Y(new k({selectClause:new j([u]),fromClause:new V(new A(new B(null,new E(t)),null),null)}),new q(s,null),null);r.push(m);let w=i.useJsonb?"jsonb_agg":"json_agg",d=new W(null,new F(w),new D([new x(null,new E(i.rootName))]),null);return new k({withClause:new X(!1,r),selectClause:new j([new $(d,`${i.rootName}_array`)]),fromClause:new V(new A(new B(null,new E(s)),null),null)})}else{let l=this.buildEntityJsonObject(a,null,i.nestedEntities,n,i.useJsonb),u=new $(l,i.rootName),m=new Y(new k({selectClause:new j([u]),fromClause:new V(new A(new B(null,new E(t)),null),null)}),new q(s,null),null);return r.push(m),new k({withClause:new X(!1,r),selectClause:new j([new $(new x(null,new E(i.rootName)),i.rootName)]),fromClause:new V(new A(new B(null,new E(s)),null),null),limitClause:new re(new _(1))})}}buildEntityJsonObject(e,t,n,i,r=!1){let s=r?"jsonb_build_object":"json_build_object",a=[];return Object.entries(e.columns).forEach(([u,m])=>{a.push(new _(u)),a.push(new x(null,new E(m)))}),n.filter(u=>u.parentId===e.id).forEach(u=>{let m=i.get(u.id);if(m)if(a.push(new _(u.propertyName)),u.relationshipType==="object"){let w=`${m.name.toLowerCase()}_json`;a.push(new x(null,new E(w)))}else u.relationshipType==="array"&&a.push(new x(null,new E(u.propertyName)))}),new W(null,new F(s),new D(a),null)}};var pn=class{constructor(e,t){this.name=e,this.columns=t}},mn=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(k.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(M.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 k||e instanceof M))throw new Error(`Unsupported SQL component type for schema collection. Received: ${e.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let t=new ee;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 pn(t,Array.from(n).sort()))}handleTableSource(e,t,n){if(e.datasource instanceof B){let i=e.datasource.getSourceName(),r=this.commonTables.filter(s=>s.getSourceAliasName()===i);if(r.length>0)r[0].query.accept(this);else{let s=e.getAliasName()??i;this.processCollectTableSchema(i,s,t,n)}}else throw new Error("Datasource is not an instance of TableSource")}visitSimpleSelectQuery(e){if(e.fromClause===null)return;let i=new Pe(this.tableColumnResolver,!0,"fullName").collect(e).filter(r=>r.value instanceof x).map(r=>r.value).map(r=>({table:r.getNamespace(),column:r.column.name}));if(e.fromClause.joins!==null&&e.fromClause.joins.length>0){let r=i.filter(s=>s.table==="").map(s=>s.column);if(r.length>0)throw new Error(`Column reference(s) without table name found in query: ${r.join(", ")}`)}if(e.fromClause.source.datasource instanceof B?this.handleTableSource(e.fromClause.source,i,!0):e.fromClause.source.datasource instanceof J&&e.fromClause.source.datasource.query.accept(this),e.fromClause?.joins)for(let r of e.fromClause.joins)r.source.datasource instanceof B?this.handleTableSource(r.source,i,!1):r.source.datasource instanceof J&&r.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 r=n.filter(a=>a.column!=="*").filter(a=>a.table===t||i&&a.table==="").map(a=>a.column),s=new pn(e,r);this.tableSchemas.push(s)}};var Tn=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=K.parse(e));let n=new pt(this.tableColumnResolver,this.options),i=new Pe(this.tableColumnResolver),r=d=>this.options.ignoreCaseAndUnderscore?d.toLowerCase().replace(/_/g,""):d,s=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"];for(let[d,p]of Object.entries(t)){if(p===void 0)continue;if(p!==null&&typeof p=="object"&&!Array.isArray(p)&&"or"in p){let h=p.or;if(h&&h.length>0){let L=h.map(f=>f.column||d).filter((f,C,G)=>G.indexOf(f)===C),T=null;for(let f of L){let C=n.find(e,f);if(C.length>0){T=C[0];break}}if(!T)throw new Error(`None of the OR condition columns [${L.join(", ")}] found in query`);let N=i.collect(T);l(T,d,h,r,N,i);continue}}if(p!==null&&typeof p=="object"&&!Array.isArray(p)&&"and"in p){let h=p.and;if(h&&h.length>0){let L=h.map(f=>f.column||d).filter((f,C,G)=>G.indexOf(f)===C),T=null;for(let f of L){let C=n.find(e,f);if(C.length>0){T=C[0];break}}if(!T)throw new Error(`None of the AND condition columns [${L.join(", ")}] found in query`);let N=i.collect(T);a(T,d,h,r,N,i);continue}}if(p!==null&&typeof p=="object"&&!Array.isArray(p)&&"column"in p&&!("or"in p)){let h=p.column;if(h){let L=n.find(e,h);if(L.length===0)throw new Error(`Explicit column '${h}' not found in query`);for(let T of L){let f=i.collect(T).find(C=>r(C.name)===r(h));if(!f)throw new Error(`Explicit column '${h}' not found in query`);p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.getPrototypeOf(p)===Object.prototype&&u(p,s,d),w(T,f.value,d,p)}continue}}let S=n.find(e,d);if(S.length===0)throw new Error(`Column '${d}' not found in query`);for(let h of S){let L=i.collect(h),T=L.find(G=>r(G.name)===r(d));if(!T)throw new Error(`Column '${d}' not found in query`);let N=T.value;p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.getPrototypeOf(p)===Object.prototype&&u(p,s,d);let f=N,C=d;if(p!==null&&typeof p=="object"&&!Array.isArray(p)&&"column"in p){let G=p.column;if(G){let te=L.find(O=>r(O.name)===r(G));te&&(f=te.value,C=G)}}p===null||typeof p!="object"||Array.isArray(p)||p instanceof Date?m(h,f,C,p):w(h,f,C,p)}}function a(d,p,S,h,L,T){for(let N=0;N<S.length;N++){let f=S[N],C=f.column||p,G=L.find(O=>h(O.name)===h(C));if(!G)throw new Error(`Column '${C}' not found in query for AND condition`);let te=G.value;if("="in f&&f["="]!==void 0){let O=`${p}_and_${N}_eq`,P=new g(O,f["="]);d.appendWhere(new y(te,"=",P))}if("min"in f&&f.min!==void 0){let O=`${p}_and_${N}_min`,P=new g(O,f.min);d.appendWhere(new y(te,">=",P))}if("max"in f&&f.max!==void 0){let O=`${p}_and_${N}_max`,P=new g(O,f.max);d.appendWhere(new y(te,"<=",P))}if("like"in f&&f.like!==void 0){let O=`${p}_and_${N}_like`,P=new g(O,f.like);d.appendWhere(new y(te,"like",P))}if("ilike"in f&&f.ilike!==void 0){let O=`${p}_and_${N}_ilike`,P=new g(O,f.ilike);d.appendWhere(new y(te,"ilike",P))}if("in"in f&&f.in!==void 0){let P=f.in.map((R,U)=>new g(`${p}_and_${N}_in_${U}`,R));d.appendWhere(new y(te,"in",new z(new D(P))))}if("any"in f&&f.any!==void 0){let O=`${p}_and_${N}_any`,P=new g(O,f.any);d.appendWhere(new y(te,"=",new W(null,"any",P,null)))}if("<"in f&&f["<"]!==void 0){let O=`${p}_and_${N}_lt`,P=new g(O,f["<"]);d.appendWhere(new y(te,"<",P))}if(">"in f&&f[">"]!==void 0){let O=`${p}_and_${N}_gt`,P=new g(O,f[">"]);d.appendWhere(new y(te,">",P))}if("!="in f&&f["!="]!==void 0){let O=`${p}_and_${N}_neq`,P=new g(O,f["!="]);d.appendWhere(new y(te,"!=",P))}if("<>"in f&&f["<>"]!==void 0){let O=`${p}_and_${N}_ne`,P=new g(O,f["<>"]);d.appendWhere(new y(te,"<>",P))}if("<="in f&&f["<="]!==void 0){let O=`${p}_and_${N}_le`,P=new g(O,f["<="]);d.appendWhere(new y(te,"<=",P))}if(">="in f&&f[">="]!==void 0){let O=`${p}_and_${N}_ge`,P=new g(O,f[">="]);d.appendWhere(new y(te,">=",P))}}}function l(d,p,S,h,L,T){let N=[];for(let f=0;f<S.length;f++){let C=S[f],G=C.column||p,te=L.find(R=>h(R.name)===h(G));if(!te)throw new Error(`Column '${G}' not found in query for OR condition`);let O=te.value,P=[];if("="in C&&C["="]!==void 0){let R=`${p}_or_${f}_eq`,U=new g(R,C["="]);P.push(new y(O,"=",U))}if("min"in C&&C.min!==void 0){let R=`${p}_or_${f}_min`,U=new g(R,C.min);P.push(new y(O,">=",U))}if("max"in C&&C.max!==void 0){let R=`${p}_or_${f}_max`,U=new g(R,C.max);P.push(new y(O,"<=",U))}if("like"in C&&C.like!==void 0){let R=`${p}_or_${f}_like`,U=new g(R,C.like);P.push(new y(O,"like",U))}if("ilike"in C&&C.ilike!==void 0){let R=`${p}_or_${f}_ilike`,U=new g(R,C.ilike);P.push(new y(O,"ilike",U))}if("in"in C&&C.in!==void 0){let U=C.in.map((Ln,Fn)=>new g(`${p}_or_${f}_in_${Fn}`,Ln));P.push(new y(O,"in",new z(new D(U))))}if("any"in C&&C.any!==void 0){let R=`${p}_or_${f}_any`,U=new g(R,C.any);P.push(new y(O,"=",new W(null,"any",U,null)))}if("<"in C&&C["<"]!==void 0){let R=`${p}_or_${f}_lt`,U=new g(R,C["<"]);P.push(new y(O,"<",U))}if(">"in C&&C[">"]!==void 0){let R=`${p}_or_${f}_gt`,U=new g(R,C[">"]);P.push(new y(O,">",U))}if("!="in C&&C["!="]!==void 0){let R=`${p}_or_${f}_neq`,U=new g(R,C["!="]);P.push(new y(O,"!=",U))}if("<>"in C&&C["<>"]!==void 0){let R=`${p}_or_${f}_ne`,U=new g(R,C["<>"]);P.push(new y(O,"<>",U))}if("<="in C&&C["<="]!==void 0){let R=`${p}_or_${f}_le`,U=new g(R,C["<="]);P.push(new y(O,"<=",U))}if(">="in C&&C[">="]!==void 0){let R=`${p}_or_${f}_ge`,U=new g(R,C[">="]);P.push(new y(O,">=",U))}if(P.length>0){let R=P[0];for(let U=1;U<P.length;U++)R=new y(R,"and",P[U]);P.length>1?N.push(new z(R)):N.push(R)}}if(N.length>0){let f=N[0];for(let C=1;C<N.length;C++)f=new y(f,"or",N[C]);d.appendWhere(new z(f))}}function u(d,p,S){Object.keys(d).forEach(h=>{if(!p.includes(h))throw new Error(`Unsupported operator '${h}' for state key '${S}'`)})}function m(d,p,S,h){let L=new g(S,h);d.appendWhere(new y(p,"=",L))}function w(d,p,S,h){let L=[];if("="in h){let T=new g(S,h["="]);L.push(new y(p,"=",T))}if("min"in h){let T=new g(S+"_min",h.min);L.push(new y(p,">=",T))}if("max"in h){let T=new g(S+"_max",h.max);L.push(new y(p,"<=",T))}if("like"in h){let T=new g(S+"_like",h.like);L.push(new y(p,"like",T))}if("ilike"in h){let T=new g(S+"_ilike",h.ilike);L.push(new y(p,"ilike",T))}if("in"in h){let N=h.in.map((f,C)=>new g(`${S}_in_${C}`,f));L.push(new y(p,"in",new z(new D(N))))}if("any"in h){let T=new g(S+"_any",h.any);L.push(new y(p,"=",new W(null,"any",T,null)))}if("<"in h){let T=new g(S+"_lt",h["<"]);L.push(new y(p,"<",T))}if(">"in h){let T=new g(S+"_gt",h[">"]);L.push(new y(p,">",T))}if("!="in h){let T=new g(S+"_neq",h["!="]);L.push(new y(p,"!=",T))}if("<>"in h){let T=new g(S+"_ne",h["<>"]);L.push(new y(p,"<>",T))}if("<="in h){let T=new g(S+"_le",h["<="]);L.push(new y(p,"<=",T))}if(">="in h){let T=new g(S+"_ge",h[">="]);L.push(new y(p,">=",T))}if(L.length===1)d.appendWhere(L[0]);else if(L.length>1){let T=L[0];for(let N=1;N<L.length;N++)T=new y(T,"and",L[N]);d.appendWhere(new z(T))}}return e}};var In=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=K.parse(e)),!(e instanceof k))throw new Error("Complex queries are not supported for ORDER BY removal");return new k({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:null,windowClause:e.windowClause,limitClause:e.limitClause,offsetClause:e.offsetClause,fetchClause:e.fetchClause,forClause:e.forClause})}inject(e,t){if(typeof e=="string"&&(e=K.parse(e)),!(e instanceof k))throw new Error("Complex queries are not supported for sorting");let i=new Pe(this.tableColumnResolver).collect(e);for(let l of Object.keys(t))if(!i.find(m=>m.name===l))throw new Error(`Column or alias '${l}' not found in current query`);let r=[];for(let[l,u]of Object.entries(t)){let m=i.find(h=>h.name===l);if(!m)continue;let w=m.value;this.validateSortCondition(l,u);let d;u.desc?d="desc":d="asc";let p=null;u.nullsFirst?p="first":u.nullsLast&&(p="last");let S=new xe(w,d,p);r.push(S)}let s=[];e.orderByClause?s=[...e.orderByClause.order,...r]:s=r;let a=s.length>0?new ue(s):null;return new k({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:a,windowClause:e.windowClause,limitClause:e.limitClause,offsetClause:e.offsetClause,fetchClause:e.fetchClause,forClause:e.forClause})}validateSortCondition(e,t){if(t.asc&&t.desc)throw new Error(`Conflicting sort directions for column '${e}': both asc and desc specified`);if(t.nullsFirst&&t.nullsLast)throw new Error(`Conflicting nulls positions for column '${e}': both nullsFirst and nullsLast specified`);if(!t.asc&&!t.desc&&!t.nullsFirst&&!t.nullsLast)throw new Error(`Empty sort condition for column '${e}': at least one sort option must be specified`)}};var Pn=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=K.parse(e)),!(e instanceof k))throw new Error("Complex queries are not supported for pagination");if(e.limitClause||e.offsetClause)throw new Error("Query already contains LIMIT or OFFSET clause. Use removePagination() first if you want to override existing pagination.");let n=(t.page-1)*t.pageSize,i=new re(new g("paging_limit",t.pageSize)),r=new Ae(new g("paging_offset",n));return new k({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,windowClause:e.windowClause,limitClause:i,offsetClause:r,fetchClause:e.fetchClause,forClause:e.forClause})}static removePagination(e){if(typeof e=="string"&&(e=K.parse(e)),!(e instanceof k))throw new Error("Complex queries are not supported for pagination removal");return new k({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,windowClause:e.windowClause,limitClause:null,offsetClause:null,fetchClause:e.fetchClause,forClause:e.forClause})}validatePaginationOptions(e){if(!e)throw new Error("Pagination options are required");if(typeof e.page!="number"||e.page<1)throw new Error("Page number must be a positive integer (1 or greater)");if(typeof e.pageSize!="number"||e.pageSize<1)throw new Error("Page size must be a positive integer (1 or greater)");if(e.pageSize>1e3)throw new Error("Page size cannot exceed 1000 items")}};var On=class{static validate(e,t){let n=typeof e=="string"?K.parse(e):e,i=Array.isArray(t)?l=>{let u=t.find(m=>m.name===l);return u?u.columns:[]}:t,s=new mn(i).collect(n),a=[];for(let l of s){let u=i(l.name);if(u.length===0){a.push(`Table '${l.name}' is not defined.`);continue}let m=l.columns.filter(w=>!u.includes(w));m.length>0&&a.push(`Table '${l.name}' contains undefined columns: ${m.join(", ")}.`)}if(a.length>0)throw new Error(a.join(`
|
|
15
|
-
`))}};var
|
|
14
|
+
Detected column names: [${n.join(", ")}]`);let a=je.parse(t);return new _e({insertClause:new He(a,n),selectQuery:e})}static buildUpdateQuery(e,t,n,i){let r=new ot(je.parse(n)),s=Array.isArray(i)?i:[i],l=new Le().collect(e),p=new ne().collect(e);new ut().execute(e);for(let x of s)if(!l.some(L=>L.name===x))throw new Error(`Primary key column '${x}' is not present in selectQuery select list.`);let T=r.getSourceAliasName();if(!T)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let V=l.filter(x=>!s.includes(x.name)).map(x=>new ze(x.name,new S(T,x.name))),m=new Me(V),h=new R(e.toSource(t),null),D=null;for(let x of s){let L=new C(new S(T,x),"=",new S(t,x));D=D?new C(D,"and",L):L}let y=new se(D);return new pt({updateClause:r,setClause:m,fromClause:h,whereClause:y,withClause:p.length>0?new ee(!1,p):void 0})}};var Ye=class{static set(e,t,n){let i=ct.collect(e),r=!1;for(let s of i)s.name.value===t&&(s.value=n,r=!0);if(!r)throw new Error(`Parameter '${t}' not found in query.`)}};var k=class extends w{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 ft.buildBinaryQuery([this,t],e)}appendWhereRaw(e){let t=b.parse(e);this.appendWhere(t)}appendWhere(e){this.whereClause?this.whereClause.condition=new C(this.whereClause.condition,"and",e):this.whereClause=new se(e)}appendHavingRaw(e){let t=b.parse(e);this.appendHaving(t)}appendHaving(e){this.havingClause?this.havingClause.condition=new C(this.havingClause.condition,"and",e):this.havingClause=new he(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,r=null){let s=et.parse(t),a=new A(s,new G(n,null));this.joinSource(e,a,i,r)}joinSource(e,t,n,i=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let r=Array.isArray(n)?n:[n],a=new Fe(i).collect(this),l=null,u=0,p=t.getAliasName();if(!p)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let j of a)if(r.some(V=>V==j.name)){let V=new C(j.value,"=",new S([p],j.name));l?l=new C(l,"and",V):l=V,u++}if(!l||u!==r.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${r.join(", ")}`);let f=new de(l),T=new fe(e,t,f,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(T):this.fromClause.joins=[T]),Je.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 A(new q(this),new G(e,null))}appendWith(e){let t=Array.isArray(e)?e:[e];this.withClause?this.withClause.tables.push(...t):this.withClause=new ee(!1,t),Je.normalize(this)}appendWithRaw(e,t){let n=_.parse(e),i=new Z(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],s=new Ge().visit(i.value),a=t(s);i.value=b.parse(a)}appendWhereExpr(e,t,n){if(n&&n.upstream){let r=new dt().find(this,[e]),s=new Fe,a=new Ge;for(let l of r){let u=s.collect(l).filter(f=>f.name===e).map(f=>f.value);if(u.length!==1)throw new Error(`Expected exactly one expression for column '${e}'`);let p=a.format(u[0]);l.appendWhereRaw(t(p))}}else{let i=new Fe,r=new Ge,s=i.collect(this).filter(l=>l.name===e).map(l=>l.value);if(s.length!==1)throw new Error(`Expected exactly one expression for column '${e}'`);let a=r.format(s[0]);this.appendWhereRaw(t(a))}}setParameter(e,t){return Ye.set(this,e,t),this}};var H=class o extends w{static{this.kind=Symbol("BinarySelectQuery")}constructor(e,t,n){super(),this.left=e,this.operator=new F(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 F(e),this.right=t,Je.normalize(this),this}unionRaw(e){let t=_.parse(e);return this.union(t)}unionAllRaw(e){let t=_.parse(e);return this.unionAll(t)}intersectRaw(e){let t=_.parse(e);return this.intersect(t)}intersectAllRaw(e){let t=_.parse(e);return this.intersectAll(t)}exceptRaw(e){let t=_.parse(e);return this.except(t)}exceptAllRaw(e){let t=_.parse(e);return this.exceptAll(t)}toSource(e="subq"){return new A(new q(this),new G(e,null))}setParameter(e,t){return Ye.set(this,e,t),this}};var le=class extends w{static{this.kind=Symbol("ValuesQuery")}constructor(e,t=null){super(),this.tuples=e,this.columnAliases=t}toSimpleSelectQuery(){return ft.buildSimpleQuery(this)}setParameter(e,t){return Ye.set(this,e,t),this}};var Gt=class{static parse(e){let n=new I(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 rt;else if(n<e.length&&e[n].value==="distinct on"){n++;let a=b.parseArgument(4,8,e,n);i=new st(a.value),n=a.newIndex}let r=[],s=Yt.parseItem(e,n);for(r.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let a=Yt.parseItem(e,n);r.push(a.value),n=a.newIndex}if(r.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 K(r,i),newIndex:n}}},Yt=class{static parse(e){let n=new I(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=b.parseFromLexeme(e,n),r=i.value;if(n=i.newIndex,n<e.length&&e[n].value==="as"&&n++,n<e.length&&e[n].type&64){let s=e[n].value;return n++,{value:new W(r,s),newIndex:n}}else if(r instanceof S&&r.column.name!=="*")return{value:new W(r,r.column.name),newIndex:n};return{value:new W(r),newIndex:n}}};var Xt=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="on"){n++;let i=b.parseFromLexeme(e,n);return n=i.newIndex,{value:new de(i.value),newIndex:n}}return null}};var Zt=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="using"){n++;let i=b.parseArgument(4,8,e,n),r=i.value;return n=i.newIndex,{value:new ke(r),newIndex:n}}return null}};var en=class{static tryParse(e,t){let n=t,i=[];for(;this.isJoinCommand(e,n);){let r=this.parseJoinClause(e,n);i.push(r.value),n=r.newIndex}return i.length>0?{value:i,newIndex:n}:null}static isJoinKeyword(e){return!!Cn.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 r=this.parseLateral(e,n),s=r.value;n=r.newIndex;let a=je.parseFromLexeme(e,n);if(n=a.newIndex,n<e.length){let u=Xt.tryParse(e,n);if(u)return{value:new fe(i,a.value,u.value,s),newIndex:u.newIndex};let p=Zt.tryParse(e,n);if(p)return{value:new fe(i,a.value,p.value,s),newIndex:p.newIndex}}return{value:new fe(i,a.value,null,s),newIndex:n}}};var tn=class{static parse(e){let n=new I(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=je.parseFromLexeme(e,n);n=i.newIndex;let r=en.tryParse(e,n);return n=r?.newIndex||n,r!==null?{value:new R(i.value,r.value),newIndex:n}:{value:new R(i.value,null),newIndex:n}}};var nn=class{static parse(e){let n=new I(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=b.parseFromLexeme(e,n);return{value:new se(i.value),newIndex:i.newIndex}}};var rn=class{static parse(e){let n=new I(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=[],r=this.parseItem(e,n);for(i.push(r.value),n=r.newIndex;n<e.length&&e[n].type&16;){n++;let s=this.parseItem(e,n);i.push(s.value),n=s.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 me(i),newIndex:n}}static parseItem(e,t){let n=t,i=b.parseFromLexeme(e,n),r=i.value;return n=i.newIndex,{value:r,newIndex:n}}};var sn=class{static parse(e){let n=new I(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=b.parseFromLexeme(e,n);return{value:new he(i.value),newIndex:i.newIndex}}};var on=class{static parse(e){let n=new I(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 r=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 s=lt.parseFromLexeme(e,n);if(n=s.newIndex,i.push(new we(r,s.value)),n<e.length&&e[n].type&16)n++;else break}if(i.length===0)throw new Error("At least one WINDOW clause is required after WINDOW keyword.");return{value:new qe(i),newIndex:n}}};var an=class{static parse(e){let n=new I(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=b.parseFromLexeme(e,n);return n=i.newIndex,{value:new oe(i.value),newIndex:n}}};var ln=class{static parse(e){let n=new I(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,r;switch(i){case"update":r="update",n++;break;case"share":r="share",n++;break;case"key share":r="key share",n++;break;case"no key update":r="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 Be(r),newIndex:n}}};var xt=class{static parse(e){let n=new I(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=tt.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 r=null;if(n<e.length){let l=e[n].value;l==="materialized"?(r=!0,n++):l==="not materialized"&&(r=!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 s=_.parseFromLexeme(e,n);if(n=s.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 Z(s.value,i.value,r),newIndex:n}}};var wt=class{static parse(e){let n=new I(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 r=[],s=xt.parseFromLexeme(e,n);for(r.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let a=xt.parseFromLexeme(e,n);r.push(a.value),n=a.newIndex}return{value:new ee(i,r),newIndex:n}}};var un=class{static parse(e){let n=new I(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=[],r=this.parseTuple(e,n);for(i.push(r.value),n=r.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 le(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 ge([]),newIndex:n};let r=b.parseFromLexeme(e,n);for(i.push(r.value),n=r.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 s=b.parseFromLexeme(e,n);i.push(s.value),n=s.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 ge(i),newIndex:n}}};var cn=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=yn.parseFromLexeme(e,n),r=i.value;return n=i.newIndex,{value:new De(r),newIndex:n}}},yn=class{static parseFromLexeme(e,t){let n=t,i,r=e[n].value;if(r==="first")i="first";else if(r==="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 s=null,a=null;if(e[n].value==="row only"||e[n].value==="rows only")return s=new z(1),a="rows only",n++,{value:new Xe(i,s,a),newIndex:n};let l=b.parseFromLexeme(e,n);if(s=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 Xe(i,s,a),newIndex:n}}};var pn=class{static parse(e){let n=new I(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=b.parseFromLexeme(e,n);return n=i.newIndex,n<e.length&&(e[n].value==="row"||e[n].value==="rows")&&n++,{value:new Ve(i.value),newIndex:n}}};var _=class{static parse(e){let n=new I(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 r=this.selectCommandSet.has(i)?this.parseSimpleSelectQuery(e,n):this.parseValuesQuery(e,n),s=r.value;for(n=r.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);s=new H(s,a,u.value),n=u.newIndex}else if(l==="values"){let u=this.parseValuesQuery(e,n);s=new H(s,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:s,newIndex:n}}static parseSimpleSelectQuery(e,t){let n=t,i=null;if(n<e.length&&e[n].value==="with"&&(i=wt.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 r=Gt.parseFromLexeme(e,n);n=r.newIndex;let s=null;n<e.length&&e[n].value==="from"&&(s=tn.parseFromLexeme(e,n),n=s.newIndex);let a=null;n<e.length&&e[n].value==="where"&&(a=nn.parseFromLexeme(e,n),n=a.newIndex);let l=null;n<e.length&&e[n].value==="group by"&&(l=rn.parseFromLexeme(e,n),n=l.newIndex);let u=null;n<e.length&&e[n].value==="having"&&(u=sn.parseFromLexeme(e,n),n=u.newIndex);let p=null;n<e.length&&e[n].value==="window"&&(p=on.parseFromLexeme(e,n),n=p.newIndex);let f=null;n<e.length&&e[n].value==="order by"&&(f=at.parseFromLexeme(e,n),n=f.newIndex);let T=null;n<e.length&&e[n].value==="limit"&&(T=an.parseFromLexeme(e,n),n=T.newIndex);let j=null;n<e.length&&e[n].value==="offset"&&(j=pn.parseFromLexeme(e,n),n=j.newIndex);let V=null;n<e.length&&e[n].value==="fetch"&&(V=cn.parseFromLexeme(e,n),n=V.newIndex);let m=null;return n<e.length&&e[n].value.toLowerCase()==="for"&&(m=ln.parseFromLexeme(e,n),n=m.newIndex),{value:new k({withClause:i?i.value:null,selectClause:r.value,fromClause:s?s.value:null,whereClause:a?a.value:null,groupByClause:l?l.value:null,havingClause:u?u.value:null,orderByClause:f?f.value:null,windowClause:p?p.value:null,limitClause:T?T.value:null,offsetClause:j?j.value:null,fetchClause:V?V.value:null,forClause:m?m.value:null}),newIndex:n}}static parseValuesQuery(e,t){let n=un.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}};var In=class{static parse(e){let n=new I(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=wt.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 r=je.parseTableSourceFromLexemes(e,n);n=r.newIndex;let s=[];if(e[n]?.type===4){for(n++;n<e.length&&e[n].type===64&&(s.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=_.parseFromLexeme(e,n);if(i)if(a.value instanceof k)a.value.withClause=i;else throw new Error("WITH clause is not supported in this context.");return n=a.newIndex,{value:new _e({insertClause:new He(r.value,s),selectQuery:a.value}),newIndex:n}}};var mn=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],r=e.aliasExpression.table.name,s=this.collectAndSortObjectEntities(n,t),a=this.groupEntitiesByDepth(s),l=Array.from(a.keys()).sort((u,p)=>p-u);for(let u of l){let p=a.get(u),f=`${o.CTE_OBJECT_PREFIX}${u}`,T=this.buildDepthCte(p,r,f,n,t);i.push(T),r=f}return{ctes:i,lastCteAlias:r}}collectAndSortObjectEntities(e,t){let n=[],i=r=>{let s=t.get(r);if(!s)throw new Error(`Entity ${r} not found for depth calculation.`);if(s.isRoot)return 0;if(!s.parentId)return 1;let a=s.parentId,l=0,u=new Set;for(u.add(r);a;){if(u.has(a))throw new Error(`Circular dependency detected: ${a} already visited in path for ${r}`);u.add(a);let p=t.get(a);if(!p)throw new Error(`Parent entity ${a} not found during depth calculation for ${r}`);let f=!1;if(p.isRoot)f=!0;else{let T=e.nestedEntities.find(j=>j.id===a);if(T)T.relationshipType==="object"&&(f=!0);else throw new Error(`Parent entity ${a} (ancestor of ${r}) has no definition in mapping.nestedEntities and is not root.`)}if(f&&l++,p.isRoot)break;a=p.parentId}return l};return e.nestedEntities.forEach(r=>{if(r.relationshipType==="object"){let s=t.get(r.id);s&&!s.isRoot&&n.push({entity:s,depth:i(r.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,r){let s=[new W(new S(null,new E(o.WILDCARD_COLUMN)))];for(let{entity:l}of e){let u=this.buildEntityJsonColumn(l,i,r);s.push(u)}let a=new k({selectClause:new K(s),fromClause:new R(new A(new B(null,new E(t)),null),null)});return new Z(a,new G(n,null),null)}buildEntityJsonColumn(e,t,n){let{jsonObjectArgs:i,nullChecks:r}=this.prepareEntityColumns(e);this.addChildObjectRelationships(e,i,t,n);let s=this.createJsonObject(i,t.useJsonb),a=this.buildNullCondition(r),l=this.createCaseExpression(a,s),u=`${e.name.toLowerCase()}${o.JSON_COLUMN_SUFFIX}`;return new W(l,u)}prepareEntityColumns(e){let t=[],n=[];return Object.entries(e.columns).forEach(([i,r])=>{t.push(new z(i)),t.push(new S(null,new E(r))),n.push(new C(new S(null,new E(r)),"is",new z(null)))}),{jsonObjectArgs:t,nullChecks:n}}addChildObjectRelationships(e,t,n,i){n.nestedEntities.filter(s=>s.parentId===e.id&&s.relationshipType==="object").forEach(s=>{let a=i.get(s.id);if(a){t.push(new z(s.propertyName));let l=`${a.name.toLowerCase()}${o.JSON_COLUMN_SUFFIX}`;t.push(new S(null,new E(l)))}})}createJsonObject(e,t=!1){let n=t?"jsonb_build_object":"json_build_object";return new U(null,new F(n),new M(e),null)}buildNullCondition(e){return e.reduce((t,n)=>t?new C(t,"and",n):n)}createCaseExpression(e,t){return new ue(null,new ve([new ye(e,new z(null))],t))}};var hn=class o{static{this.CTE_ARRAY_PREFIX="cte_array_depth_"}buildArrayEntityCtes(e,t,n,i){let r=[...e],s=t,a=this.collectAndSortArrayEntities(i,n);if(a.length===0)return{updatedCtes:r,lastCteAlias:s};let l=this.groupEntitiesByDepth(a),u=Array.from(l.keys()).sort((p,f)=>f-p);for(let p of u){let f=l.get(p),{cte:T,newCteAlias:j}=this.buildDepthCte(f,s,r,p,i);r.push(T),s=j}return{updatedCtes:r,lastCteAlias:s}}collectAndSortArrayEntities(e,t){let n=[],i=r=>{let s=t.get(r);return!s||s.isRoot?0:s.parentId?1+i(s.parentId):1};return e.nestedEntities.forEach(r=>{if(r.relationshipType==="array"){let s=t.get(r.id),a=t.get(r.parentId);if(!s||!a)throw new Error(`Configuration error: Array entity '${r.id}' or its parent '${r.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 '${r.name}'.`);let u=l[0];n.push({entity:s,parentEntity:a,parentIdColumnSqlName:u,depth:i(r.id)})}}),n.sort((r,s)=>s.depth-r.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,r){let s=new Set;e.forEach(V=>{Object.values(V.entity.columns).forEach(m=>s.add(m))});let a=n.find(V=>V.aliasExpression.table.name===t)?.query;if(!a)throw new Error(`CTE not found: ${t}`);let l=new Le(null,n).collect(a),u=[],p=[];l.forEach(V=>{s.has(V.name)||(p.push(new W(new S(null,new E(V.name)),V.name)),u.push(new S(null,new E(V.name))))});for(let V of e){let m=this.buildAggregationDetailsForArrayEntity(V.entity,r.nestedEntities,new Map,r.useJsonb);p.push(new W(m.jsonAgg,V.entity.propertyName))}let f=`${o.CTE_ARRAY_PREFIX}${i}`,T=new k({selectClause:new K(p),fromClause:new R(new A(new B(null,new E(t)),null),null),groupByClause:u.length>0?new me(u):null});return{cte:new Z(T,new G(f,null),null),newCteAlias:f}}buildAggregationDetailsForArrayEntity(e,t,n,i=!1){let r=i?"jsonb_build_object":"json_build_object",s=[];Object.entries(e.columns).forEach(([f,T])=>{s.push(new z(f)),s.push(new S(null,new E(T)))}),t.filter(f=>f.parentId===e.id).forEach(f=>{if(s.push(new z(f.propertyName)),f.relationshipType==="object"){let T=`${f.name.toLowerCase()}_json`;s.push(new S(null,new E(T)))}else f.relationshipType==="array"&&s.push(new S(null,new E(f.propertyName)))});let l=new U(null,new F(r),new M(s),null),u=i?"jsonb_agg":"json_agg";return{jsonAgg:new U(null,new F(u),new M([l]),null)}}};var Pn=class{constructor(){this.selectValueCollector=new Le(null),this.objectEntityCteBuilder=new mn,this.arrayEntityCteBuilder=new hn}validateMapping(e,t){let i=new Le().collect(e),r=new Set(i.map(u=>u.name));for(let u in t.rootEntity.columns){let p=t.rootEntity.columns[u];if(!r.has(p))throw new Error(`Validation Error: Column "${p}" for JSON key "${u}" in root entity "${t.rootEntity.name}" not found in the query's select list.`)}let s=new Set([t.rootEntity.id]),a=new Map;t.nestedEntities.forEach(u=>{s.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(!s.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 p in u.columns){let f=u.columns[p];if(!r.has(f))throw new Error(`Validation Error: Column "${f}" for JSON key "${p}" 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 p=t.nestedEntities.filter(j=>j.parentId===u);if(p.filter(j=>j.relationshipType==="array").length>1){let j=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(V=>V.id===u)?.name;throw new Error(`Validation Error: Parent entity "${j}" (ID: ${u}) has multiple direct array children. This is not supported.`)}let T=new Set;for(let j of p){if(T.has(j.propertyName)){let V=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(m=>m.id===u)?.name;throw new Error(`Validation Error: Parent entity "${V}" (ID: ${u}) has duplicate property name "${j.propertyName}" for its children.`)}T.add(j.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),r=[n],s=i,a=new Map;a.set(t.rootEntity.id,{...t.rootEntity,isRoot:!0,propertyName:t.rootName}),t.nestedEntities.forEach(p=>a.set(p.id,{...p,isRoot:!1,propertyName:p.propertyName}));let l=this.objectEntityCteBuilder.buildObjectEntityCtes(n,a,t);r=l.ctes,s=l.lastCteAlias;let u=this.arrayEntityCteBuilder.buildArrayEntityCtes(r,s,a,t);return r=u.updatedCtes,s=u.lastCteAlias,this.buildFinalSelectQuery(r,s,a,t)}createInitialCte(e){let t="origin_query";return{initialCte:new Z(e,new G(t,null),null),initialCteAlias:t}}buildFinalSelectQuery(e,t,n,i){let r=[...e],s=`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 W(l,i.rootName),p=new Z(new k({selectClause:new K([u]),fromClause:new R(new A(new B(null,new E(t)),null),null)}),new G(s,null),null);r.push(p);let f=i.useJsonb?"jsonb_agg":"json_agg",T=new U(null,new F(f),new M([new S(null,new E(i.rootName))]),null);return new k({withClause:new ee(!1,r),selectClause:new K([new W(T,`${i.rootName}_array`)]),fromClause:new R(new A(new B(null,new E(s)),null),null)})}else{let l=this.buildEntityJsonObject(a,null,i.nestedEntities,n,i.useJsonb),u=new W(l,i.rootName),p=new Z(new k({selectClause:new K([u]),fromClause:new R(new A(new B(null,new E(t)),null),null)}),new G(s,null),null);return r.push(p),new k({withClause:new ee(!1,r),selectClause:new K([new W(new S(null,new E(i.rootName)),i.rootName)]),fromClause:new R(new A(new B(null,new E(s)),null),null),limitClause:new oe(new z(1))})}}buildEntityJsonObject(e,t,n,i,r=!1){let s=r?"jsonb_build_object":"json_build_object",a=[];return Object.entries(e.columns).forEach(([u,p])=>{a.push(new z(u)),a.push(new S(null,new E(p)))}),n.filter(u=>u.parentId===e.id).forEach(u=>{let p=i.get(u.id);if(p)if(a.push(new z(u.propertyName)),u.relationshipType==="object"){let f=`${p.name.toLowerCase()}_json`;a.push(new S(null,new E(f)))}else u.relationshipType==="array"&&a.push(new S(null,new E(u.propertyName)))}),new U(null,new F(s),new M(a),null)}};var dn=class{constructor(e,t){this.name=e,this.columns=t}},fn=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(k.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(H.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 k||e instanceof H))throw new Error(`Unsupported SQL component type for schema collection. Received: ${e.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let t=new ne;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 dn(t,Array.from(n).sort()))}handleTableSource(e,t,n){if(e.datasource instanceof B){let i=e.datasource.getSourceName(),r=this.commonTables.filter(s=>s.getSourceAliasName()===i);if(r.length>0)r[0].query.accept(this);else{let s=e.getAliasName()??i;this.processCollectTableSchema(i,s,t,n)}}else throw new Error("Datasource is not an instance of TableSource")}visitSimpleSelectQuery(e){if(e.fromClause===null)return;let i=new Fe(this.tableColumnResolver,!0,"fullName").collect(e).filter(r=>r.value instanceof S).map(r=>r.value).map(r=>({table:r.getNamespace(),column:r.column.name}));if(e.fromClause.joins!==null&&e.fromClause.joins.length>0){let r=i.filter(s=>s.table==="").map(s=>s.column);if(r.length>0)throw new Error(`Column reference(s) without table name found in query: ${r.join(", ")}`)}if(e.fromClause.source.datasource instanceof B?this.handleTableSource(e.fromClause.source,i,!0):e.fromClause.source.datasource instanceof q&&e.fromClause.source.datasource.query.accept(this),e.fromClause?.joins)for(let r of e.fromClause.joins)r.source.datasource instanceof B?this.handleTableSource(r.source,i,!1):r.source.datasource instanceof q&&r.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 r=n.filter(a=>a.column!=="*").filter(a=>a.table===t||i&&a.table==="").map(a=>a.column),s=new dn(e,r);this.tableSchemas.push(s)}};var On=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=_.parse(e));let n=new dt(this.tableColumnResolver,this.options),i=new Fe(this.tableColumnResolver),r=m=>this.options.ignoreCaseAndUnderscore?m.toLowerCase().replace(/_/g,""):m,s=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"],a=Object.values(t);if(a.length>0&&a.every(m=>m===void 0)&&!this.options.allowAllUndefined)throw new Error("All parameters are undefined. This would result in fetching all records. Use allowAllUndefined: true option to explicitly allow this behavior.");for(let[m,h]of Object.entries(t)){if(h===void 0)continue;if(h!==null&&typeof h=="object"&&!Array.isArray(h)&&"or"in h){let y=h.or;if(y&&y.length>0){let N=y.map(d=>d.column||m).filter((d,v,Ce)=>Ce.indexOf(d)===v),x=null;for(let d of N){let v=n.find(e,d);if(v.length>0){x=v[0];break}}if(!x)throw new Error(`None of the OR condition columns [${N.join(", ")}] found in query`);let L=i.collect(x);f(x,m,y,r,L,i);continue}}if(h!==null&&typeof h=="object"&&!Array.isArray(h)&&"and"in h){let y=h.and;if(y&&y.length>0){let N=y.map(d=>d.column||m).filter((d,v,Ce)=>Ce.indexOf(d)===v),x=null;for(let d of N){let v=n.find(e,d);if(v.length>0){x=v[0];break}}if(!x)throw new Error(`None of the AND condition columns [${N.join(", ")}] found in query`);let L=i.collect(x);p(x,m,y,r,L,i);continue}}if(h!==null&&typeof h=="object"&&!Array.isArray(h)&&"column"in h&&!("or"in h)){let y=h.column;if(y){let N=n.find(e,y);if(N.length===0)throw new Error(`Explicit column '${y}' not found in query`);for(let x of N){let d=i.collect(x).find(v=>r(v.name)===r(y));if(!d)throw new Error(`Explicit column '${y}' not found in query`);h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.getPrototypeOf(h)===Object.prototype&&T(h,s,m),V(x,d.value,m,h)}continue}}let D=n.find(e,m);if(D.length===0)throw new Error(`Column '${m}' not found in query`);for(let y of D){let N=i.collect(y),x=N.find(Ce=>r(Ce.name)===r(m));if(!x)throw new Error(`Column '${m}' not found in query`);let L=x.value;h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.getPrototypeOf(h)===Object.prototype&&T(h,s,m);let d=L,v=m;if(h!==null&&typeof h=="object"&&!Array.isArray(h)&&"column"in h){let Ce=h.column;if(Ce){let ie=N.find(O=>r(O.name)===r(Ce));ie&&(d=ie.value,v=Ce)}}h===null||typeof h!="object"||Array.isArray(h)||h instanceof Date?j(y,d,v,h):V(y,d,v,h)}}function p(m,h,D,y,N,x){for(let L=0;L<D.length;L++){let d=D[L],v=d.column||h,Ce=N.find(O=>y(O.name)===y(v));if(!Ce)throw new Error(`Column '${v}' not found in query for AND condition`);let ie=Ce.value;if("="in d&&d["="]!==void 0){let O=`${h}_and_${L}_eq`,P=new g(O,d["="]);m.appendWhere(new C(ie,"=",P))}if("min"in d&&d.min!==void 0){let O=`${h}_and_${L}_min`,P=new g(O,d.min);m.appendWhere(new C(ie,">=",P))}if("max"in d&&d.max!==void 0){let O=`${h}_and_${L}_max`,P=new g(O,d.max);m.appendWhere(new C(ie,"<=",P))}if("like"in d&&d.like!==void 0){let O=`${h}_and_${L}_like`,P=new g(O,d.like);m.appendWhere(new C(ie,"like",P))}if("ilike"in d&&d.ilike!==void 0){let O=`${h}_and_${L}_ilike`,P=new g(O,d.ilike);m.appendWhere(new C(ie,"ilike",P))}if("in"in d&&d.in!==void 0){let P=d.in.map(($,J)=>new g(`${h}_and_${L}_in_${J}`,$));m.appendWhere(new C(ie,"in",new Y(new M(P))))}if("any"in d&&d.any!==void 0){let O=`${h}_and_${L}_any`,P=new g(O,d.any);m.appendWhere(new C(ie,"=",new U(null,"any",P,null)))}if("<"in d&&d["<"]!==void 0){let O=`${h}_and_${L}_lt`,P=new g(O,d["<"]);m.appendWhere(new C(ie,"<",P))}if(">"in d&&d[">"]!==void 0){let O=`${h}_and_${L}_gt`,P=new g(O,d[">"]);m.appendWhere(new C(ie,">",P))}if("!="in d&&d["!="]!==void 0){let O=`${h}_and_${L}_neq`,P=new g(O,d["!="]);m.appendWhere(new C(ie,"!=",P))}if("<>"in d&&d["<>"]!==void 0){let O=`${h}_and_${L}_ne`,P=new g(O,d["<>"]);m.appendWhere(new C(ie,"<>",P))}if("<="in d&&d["<="]!==void 0){let O=`${h}_and_${L}_le`,P=new g(O,d["<="]);m.appendWhere(new C(ie,"<=",P))}if(">="in d&&d[">="]!==void 0){let O=`${h}_and_${L}_ge`,P=new g(O,d[">="]);m.appendWhere(new C(ie,">=",P))}}}function f(m,h,D,y,N,x){let L=[];for(let d=0;d<D.length;d++){let v=D[d],Ce=v.column||h,ie=N.find($=>y($.name)===y(Ce));if(!ie)throw new Error(`Column '${Ce}' not found in query for OR condition`);let O=ie.value,P=[];if("="in v&&v["="]!==void 0){let $=`${h}_or_${d}_eq`,J=new g($,v["="]);P.push(new C(O,"=",J))}if("min"in v&&v.min!==void 0){let $=`${h}_or_${d}_min`,J=new g($,v.min);P.push(new C(O,">=",J))}if("max"in v&&v.max!==void 0){let $=`${h}_or_${d}_max`,J=new g($,v.max);P.push(new C(O,"<=",J))}if("like"in v&&v.like!==void 0){let $=`${h}_or_${d}_like`,J=new g($,v.like);P.push(new C(O,"like",J))}if("ilike"in v&&v.ilike!==void 0){let $=`${h}_or_${d}_ilike`,J=new g($,v.ilike);P.push(new C(O,"ilike",J))}if("in"in v&&v.in!==void 0){let J=v.in.map((An,Qn)=>new g(`${h}_or_${d}_in_${Qn}`,An));P.push(new C(O,"in",new Y(new M(J))))}if("any"in v&&v.any!==void 0){let $=`${h}_or_${d}_any`,J=new g($,v.any);P.push(new C(O,"=",new U(null,"any",J,null)))}if("<"in v&&v["<"]!==void 0){let $=`${h}_or_${d}_lt`,J=new g($,v["<"]);P.push(new C(O,"<",J))}if(">"in v&&v[">"]!==void 0){let $=`${h}_or_${d}_gt`,J=new g($,v[">"]);P.push(new C(O,">",J))}if("!="in v&&v["!="]!==void 0){let $=`${h}_or_${d}_neq`,J=new g($,v["!="]);P.push(new C(O,"!=",J))}if("<>"in v&&v["<>"]!==void 0){let $=`${h}_or_${d}_ne`,J=new g($,v["<>"]);P.push(new C(O,"<>",J))}if("<="in v&&v["<="]!==void 0){let $=`${h}_or_${d}_le`,J=new g($,v["<="]);P.push(new C(O,"<=",J))}if(">="in v&&v[">="]!==void 0){let $=`${h}_or_${d}_ge`,J=new g($,v[">="]);P.push(new C(O,">=",J))}if(P.length>0){let $=P[0];for(let J=1;J<P.length;J++)$=new C($,"and",P[J]);P.length>1?L.push(new Y($)):L.push($)}}if(L.length>0){let d=L[0];for(let v=1;v<L.length;v++)d=new C(d,"or",L[v]);m.appendWhere(new Y(d))}}function T(m,h,D){Object.keys(m).forEach(y=>{if(!h.includes(y))throw new Error(`Unsupported operator '${y}' for state key '${D}'`)})}function j(m,h,D,y){let N=new g(D,y);m.appendWhere(new C(h,"=",N))}function V(m,h,D,y){let N=[];if("="in y){let x=new g(D,y["="]);N.push(new C(h,"=",x))}if("min"in y){let x=new g(D+"_min",y.min);N.push(new C(h,">=",x))}if("max"in y){let x=new g(D+"_max",y.max);N.push(new C(h,"<=",x))}if("like"in y){let x=new g(D+"_like",y.like);N.push(new C(h,"like",x))}if("ilike"in y){let x=new g(D+"_ilike",y.ilike);N.push(new C(h,"ilike",x))}if("in"in y){let L=y.in.map((d,v)=>new g(`${D}_in_${v}`,d));N.push(new C(h,"in",new Y(new M(L))))}if("any"in y){let x=new g(D+"_any",y.any);N.push(new C(h,"=",new U(null,"any",x,null)))}if("<"in y){let x=new g(D+"_lt",y["<"]);N.push(new C(h,"<",x))}if(">"in y){let x=new g(D+"_gt",y[">"]);N.push(new C(h,">",x))}if("!="in y){let x=new g(D+"_neq",y["!="]);N.push(new C(h,"!=",x))}if("<>"in y){let x=new g(D+"_ne",y["<>"]);N.push(new C(h,"<>",x))}if("<="in y){let x=new g(D+"_le",y["<="]);N.push(new C(h,"<=",x))}if(">="in y){let x=new g(D+"_ge",y[">="]);N.push(new C(h,">=",x))}if(N.length===1)m.appendWhere(N[0]);else if(N.length>1){let x=N[0];for(let L=1;L<N.length;L++)x=new C(x,"and",N[L]);m.appendWhere(new Y(x))}}return e}};var Ln=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=_.parse(e)),!(e instanceof k))throw new Error("Complex queries are not supported for ORDER BY removal");return new k({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:null,windowClause:e.windowClause,limitClause:e.limitClause,offsetClause:e.offsetClause,fetchClause:e.fetchClause,forClause:e.forClause})}inject(e,t){if(typeof e=="string"&&(e=_.parse(e)),!(e instanceof k))throw new Error("Complex queries are not supported for sorting");let i=new Fe(this.tableColumnResolver).collect(e);for(let l of Object.keys(t))if(!i.find(p=>p.name===l))throw new Error(`Column or alias '${l}' not found in current query`);let r=[];for(let[l,u]of Object.entries(t)){let p=i.find(m=>m.name===l);if(!p)continue;let f=p.value;this.validateSortCondition(l,u);let T;u.desc?T="desc":T="asc";let j=null;u.nullsFirst?j="first":u.nullsLast&&(j="last");let V=new be(f,T,j);r.push(V)}let s=[];e.orderByClause?s=[...e.orderByClause.order,...r]:s=r;let a=s.length>0?new pe(s):null;return new k({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:a,windowClause:e.windowClause,limitClause:e.limitClause,offsetClause:e.offsetClause,fetchClause:e.fetchClause,forClause:e.forClause})}validateSortCondition(e,t){if(t.asc&&t.desc)throw new Error(`Conflicting sort directions for column '${e}': both asc and desc specified`);if(t.nullsFirst&&t.nullsLast)throw new Error(`Conflicting nulls positions for column '${e}': both nullsFirst and nullsLast specified`);if(!t.asc&&!t.desc&&!t.nullsFirst&&!t.nullsLast)throw new Error(`Empty sort condition for column '${e}': at least one sort option must be specified`)}};var Fn=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=_.parse(e)),!(e instanceof k))throw new Error("Complex queries are not supported for pagination");if(e.limitClause||e.offsetClause)throw new Error("Query already contains LIMIT or OFFSET clause. Use removePagination() first if you want to override existing pagination.");let n=(t.page-1)*t.pageSize,i=new oe(new g("paging_limit",t.pageSize)),r=new Ve(new g("paging_offset",n));return new k({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,windowClause:e.windowClause,limitClause:i,offsetClause:r,fetchClause:e.fetchClause,forClause:e.forClause})}static removePagination(e){if(typeof e=="string"&&(e=_.parse(e)),!(e instanceof k))throw new Error("Complex queries are not supported for pagination removal");return new k({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,windowClause:e.windowClause,limitClause:null,offsetClause:null,fetchClause:e.fetchClause,forClause:e.forClause})}validatePaginationOptions(e){if(!e)throw new Error("Pagination options are required");if(typeof e.page!="number"||e.page<1)throw new Error("Page number must be a positive integer (1 or greater)");if(typeof e.pageSize!="number"||e.pageSize<1)throw new Error("Page size must be a positive integer (1 or greater)");if(e.pageSize>1e3)throw new Error("Page size cannot exceed 1000 items")}};var Nn=class{static validate(e,t){let n=typeof e=="string"?_.parse(e):e,i=Array.isArray(t)?l=>{let u=t.find(p=>p.name===l);return u?u.columns:[]}:t,s=new fn(i).collect(n),a=[];for(let l of s){let u=i(l.name);if(u.length===0){a.push(`Table '${l.name}' is not defined.`);continue}let p=l.columns.filter(f=>!u.includes(f));p.length>0&&a.push(`Table '${l.name}' contains undefined columns: ${p.join(", ")}.`)}if(a.length>0)throw new Error(a.join(`
|
|
15
|
+
`))}};var Et=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(([s,a])=>a.isPrimaryKey).map(([s,a])=>s).length===0&&t.push(`Table '${n}' has no primary key defined`),i.relationships?.forEach(s=>{e.includes(s.table)||t.push(`Table '${n}' references unknown table '${s.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(([r,s])=>{n[r]=s.jsonAlias||s.name});let i=[];return t.relationships?.forEach(r=>{let s=this.schemas[r.table];if(!s)throw new Error(`Related table '${r.table}' not found in schema registry`);let a={};Object.entries(s.columns).forEach(([u,p])=>{a[u]=p.jsonAlias||p.name});let l=r.type;i.push({id:r.propertyName,name:s.displayName||r.table,parentId:e,propertyName:r.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,r])=>r.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,r])=>{r.foreignKey&&n.push({column:i,referencedTable:r.foreignKey.table,referencedColumn:r.foreignKey.column})}),n}};function Yh(o){return new Et(o)}function Xh(o){return new Et(o).createTableColumnResolver()}function Zh(o,e){return new Et(o).createJsonMapping(e)}export{Se as ArrayExpression,xe as ArrayQueryExpression,Ee as BetweenExpression,C as BinaryExpression,H as BinarySelectQuery,ne as CTECollector,Je as CTENormalizer,ue as CaseExpression,ye as CaseKeyValuePair,ce as CastExpression,S as ColumnReference,Tn as DuplicateDetectionMode,Ge as Formatter,U as FunctionCall,E as IdentifierString,Ne as InlineQuery,_e as InsertQuery,In as InsertQueryParser,z as LiteralValue,g as ParameterExpression,Y as ParenExpression,Pn as PostgresJsonQueryBuilder,Qe as QualifiedName,ft as QueryBuilder,F as RawString,fn as SchemaCollector,Et as SchemaManager,_ as SelectQueryParser,Le as SelectValueCollector,Fe as SelectableColumnCollector,k as SimpleSelectQuery,ht as SqlFormatter,Fn as SqlPaginationInjector,On as SqlParamInjector,Nn as SqlSchemaValidator,Ln as SqlSortInjector,Ue as StringSpecifierExpression,ve as SwitchCaseArgument,dn as TableSchema,Dt as TableSourceCollector,ge as TupleExpression,Ie as TypeValue,re as UnaryExpression,dt as UpstreamSelectQueryFinder,gl as VALID_PRESETS,M as ValueList,le as ValuesQuery,xn as WindowFrameBound,nt as WindowFrameBoundStatic,it as WindowFrameBoundaryValue,Ae as WindowFrameExpression,Re as WindowFrameSpec,Sn as WindowFrameType,Zh as createJsonMappingFromSchema,Yh as createSchemaManager,Xh as createTableColumnResolver};
|
|
16
16
|
//# sourceMappingURL=index.min.js.map
|