rawsql-ts 0.10.4-beta → 0.10.5-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/README.md +105 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index.min.js +9 -9
- package/dist/esm/index.min.js.map +4 -4
- package/dist/esm/transformers/SqlPaginationInjector.js +104 -0
- package/dist/esm/transformers/SqlPaginationInjector.js.map +1 -0
- package/dist/esm/transformers/SqlSortInjector.js +146 -0
- package/dist/esm/transformers/SqlSortInjector.js.map +1 -0
- package/dist/esm/types/index.d.ts +2 -0
- package/dist/esm/types/transformers/SqlPaginationInjector.d.ts +35 -0
- package/dist/esm/types/transformers/SqlSortInjector.d.ts +36 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/index.min.js +9 -9
- package/dist/index.min.js.map +4 -4
- package/dist/transformers/SqlPaginationInjector.d.ts +35 -0
- package/dist/transformers/SqlPaginationInjector.js +108 -0
- package/dist/transformers/SqlPaginationInjector.js.map +1 -0
- package/dist/transformers/SqlSortInjector.d.ts +36 -0
- package/dist/transformers/SqlSortInjector.js +150 -0
- package/dist/transformers/SqlSortInjector.js.map +1 -0
- package/package.json +1 -1
package/dist/index.min.js
CHANGED
@@ -1,16 +1,16 @@
|
|
1
|
-
"use strict";var hn=Object.defineProperty;var On=Object.getOwnPropertyDescriptor;var Ln=Object.getOwnPropertyNames;var Fn=Object.prototype.hasOwnProperty;var Nn=(o,e)=>{for(var t in e)hn(o,t,{get:e[t],enumerable:!0})},An=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ln(e))!Fn.call(o,i)&&i!==t&&hn(o,i,{get:()=>e[i],enumerable:!(n=On(e,i))||n.enumerable});return o};var Qn=o=>An(hn({},"__esModule",{value:!0}),o);var ri={};Nn(ri,{ArrayExpression:()=>fe,ArrayQueryExpression:()=>we,BetweenExpression:()=>Ce,BinaryExpression:()=>y,BinarySelectQuery:()=>_,CTECollector:()=>G,CTENormalizer:()=>Re,CaseExpression:()=>re,CaseKeyValuePair:()=>de,CastExpression:()=>ae,ColumnReference:()=>S,DuplicateDetectionMode:()=>yn,Formatter:()=>De,FunctionCall:()=>$,IdentifierString:()=>x,InlineQuery:()=>ke,InsertQuery:()=>We,InsertQueryParser:()=>xn,LiteralValue:()=>D,ParameterExpression:()=>b,ParenExpression:()=>z,PostgresJsonQueryBuilder:()=>En,QualifiedName:()=>Ie,QueryBuilder:()=>it,RawString:()=>L,SchemaCollector:()=>Et,SchemaManager:()=>dt,SelectQueryParser:()=>J,SelectValueCollector:()=>be,SelectableColumnCollector:()=>Ne,SimpleSelectQuery:()=>I,SqlFormatter:()=>Ze,SqlParamInjector:()=>gn,SqlSchemaValidator:()=>bn,StringSpecifierExpression:()=>Qe,SwitchCaseArgument:()=>he,TableSchema:()=>xt,TableSourceCollector:()=>vt,TupleExpression:()=>ve,TypeValue:()=>Se,UnaryExpression:()=>X,UpstreamSelectQueryFinder:()=>tt,VALID_PRESETS:()=>ei,ValueList:()=>K,ValuesQuery:()=>ne,WindowFrameBound:()=>fn,WindowFrameBoundStatic:()=>He,WindowFrameBoundaryValue:()=>Ge,WindowFrameExpression:()=>Te,WindowFrameSpec:()=>Ae,WindowFrameType:()=>dn,createJsonMappingFromSchema:()=>ii,createSchemaManager:()=>ti,createTableColumnResolver:()=>ni});module.exports=Qn(ri);var C=class{constructor(){this.comments=null}getKind(){return this.constructor.kind}accept(e){return e.visit(this)}toSqlString(e){return this.accept(e)}};var We=class extends C{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var ke=class extends C{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},K=class extends C{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},S=class extends C{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof x?this.qualifiedName.name:new x(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(e,t){super();let n=typeof t=="string"?new x(t):t;this.qualifiedName=new Ie(kn(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},$=class extends C{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,i){super(),this.qualifiedName=new Ie(e,t),this.argument=n,this.over=i}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},dn=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(dn||{}),fn=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(fn||{}),He=class extends C{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},Ge=class extends C{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},Ae=class extends C{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Te=class extends C{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},X=class extends C{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new L(e),this.expression=t}},y=class extends C{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new L(t),this.right=n}},D=class extends C{static{this.kind=Symbol("LiteralExpression")}constructor(e){super(),this.value=e}},b=class extends C{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new L(e),this.value=t,this.index=null}},he=class extends C{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},de=class extends C{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},L=class extends C{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},x=class extends C{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},z=class extends C{static{this.kind=Symbol("ParenExpression")}constructor(e){super(),this.expression=e}},ae=class extends C{static{this.kind=Symbol("CastExpression")}constructor(e,t){super(),this.input=e,this.castType=t}},re=class extends C{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},fe=class extends C{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},we=class extends C{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},Ce=class extends C{static{this.kind=Symbol("BetweenExpression")}constructor(e,t,n,i){super(),this.expression=e,this.lower=t,this.upper=n,this.negated=i}},Qe=class extends C{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new L(e),this.value=new D(t)}},Se=class extends C{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new Ie(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof L?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}},ve=class extends C{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}};function kn(o){if(o==null)return null;if(typeof o=="string")return o.trim()===""?null:[new x(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 x(t))}else{let e=o.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var Ie=class extends C{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=kn(e),typeof t=="string"?this.name=new L(t):this.name=t}toString(){let e=this.name instanceof L?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 C{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new x(t):null}},j=class extends C{static{this.kind=Symbol("SelectClause")}constructor(e,t=null){super(),this.items=e,this.distinct=t}},rt=class extends C{static{this.kind=Symbol("Distinct")}constructor(){super()}},st=class extends C{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},se=class extends C{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},Ve=class extends C{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},ye=class extends C{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new x(e),this.expression=t}},Je=class extends C{static{this.kind=Symbol("WindowsClause")}constructor(e){super(),this.windows=e}};var xe=class extends C{static{this.kind=Symbol("OrderByClause")}constructor(e){super(),this.order=e}},Le=class extends C{static{this.kind=Symbol("OrderByItem")}constructor(e,t,n){super(),this.value=e,this.sortDirection=t===null?"asc":t,this.nullsPosition=n}},le=class extends C{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},ue=class extends C{static{this.kind=Symbol("HavingClause")}constructor(e){super(),this.condition=e}},V=class extends C{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof x?this.qualifiedName.name:new x(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(e,t){super();let n=typeof t=="string"?new x(t):t;this.qualifiedName=new Ie(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof L?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof L?this.qualifiedName.name.value:this.qualifiedName.name.name}},je=class extends C{static{this.kind=Symbol("FunctionSource")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"name"in e){let n=e;this.qualifiedName=new Ie(n.namespaces,n.name)}else this.qualifiedName=new Ie(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},Be=class extends C{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},q=class extends C{static{this.kind=Symbol("SubQuerySource")}constructor(e){super(),this.query=e}},A=class extends C{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 V?this.datasource.getSourceName():null}},ce=class extends C{static{this.kind=Symbol("JoinOnClause")}constructor(e){super(),this.condition=e}},Ee=class extends C{static{this.kind=Symbol("JoinUsingClause")}constructor(e){super(),this.condition=e}},pe=class extends C{static{this.kind=Symbol("JoinItem")}constructor(e,t,n,i){super(),this.joinType=new L(e),this.source=t,this.condition=n,this.lateral=i}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof V?this.source.table.name:null}},B=class extends C{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 V?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 C{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new M(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},ee=class extends C{static{this.kind=Symbol("WithClause")}constructor(e,t){super(),this.recursive=e,this.tables=t}},me=class extends C{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var Ue=class extends C{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},Ke=class extends C{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},Ye=class extends C{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var Fe=class extends C{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},M=class extends C{static{this.kind=Symbol("SourceAliasExpression")}constructor(e,t){super(),this.table=new x(e),this.columns=t!==null?t.map(n=>new x(n)):null}},gt=class extends C{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new x(t):t)}},qe=class extends C{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 C{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 x(n.column):n.column;this.qualifiedName=new Ie(n.namespaces,i)}else{let n=typeof e=="string"?new x(e):e;this.qualifiedName=new Ie(null,n)}this.value=t}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof x?this.qualifiedName.name:new x(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},ot=class extends C{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 V?this.source.datasource.table.name:null}},Me=class extends C{constructor(e,t){super(),this.source=e,this.columns=t.map(n=>new x(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 oe=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
|
+
"use strict";var hn=Object.defineProperty;var An=Object.getOwnPropertyDescriptor;var Qn=Object.getOwnPropertyNames;var Bn=Object.prototype.hasOwnProperty;var Vn=(o,e)=>{for(var t in e)hn(o,t,{get:e[t],enumerable:!0})},Rn=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Qn(e))!Bn.call(o,i)&&i!==t&&hn(o,i,{get:()=>e[i],enumerable:!(n=An(e,i))||n.enumerable});return o};var $n=o=>Rn(hn({},"__esModule",{value:!0}),o);var oi={};Vn(oi,{ArrayExpression:()=>we,ArrayQueryExpression:()=>Ce,BetweenExpression:()=>ve,BinaryExpression:()=>y,BinarySelectQuery:()=>_,CTECollector:()=>G,CTENormalizer:()=>$e,CaseExpression:()=>re,CaseKeyValuePair:()=>fe,CastExpression:()=>le,ColumnReference:()=>S,DuplicateDetectionMode:()=>yn,Formatter:()=>Je,FunctionCall:()=>$,IdentifierString:()=>E,InlineQuery:()=>Ie,InsertQuery:()=>je,InsertQueryParser:()=>xn,LiteralValue:()=>D,ParameterExpression:()=>k,ParenExpression:()=>z,PostgresJsonQueryBuilder:()=>En,QualifiedName:()=>Oe,QueryBuilder:()=>it,RawString:()=>L,SchemaCollector:()=>Et,SchemaManager:()=>dt,SelectQueryParser:()=>U,SelectValueCollector:()=>ke,SelectableColumnCollector:()=>Te,SimpleSelectQuery:()=>b,SqlFormatter:()=>Ze,SqlPaginationInjector:()=>kn,SqlParamInjector:()=>gn,SqlSchemaValidator:()=>Tn,SqlSortInjector:()=>bn,StringSpecifierExpression:()=>Be,SwitchCaseArgument:()=>de,TableSchema:()=>xt,TableSourceCollector:()=>vt,TupleExpression:()=>ye,TypeValue:()=>xe,UnaryExpression:()=>X,UpstreamSelectQueryFinder:()=>tt,VALID_PRESETS:()=>ni,ValueList:()=>J,ValuesQuery:()=>ne,WindowFrameBound:()=>fn,WindowFrameBoundStatic:()=>He,WindowFrameBoundaryValue:()=>Ge,WindowFrameExpression:()=>Pe,WindowFrameSpec:()=>Ae,WindowFrameType:()=>dn,createJsonMappingFromSchema:()=>si,createSchemaManager:()=>ii,createTableColumnResolver:()=>ri});module.exports=$n(oi);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 je=class extends v{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var Ie=class extends v{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},J=class extends v{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},S=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 Oe(In(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},$=class extends v{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,i){super(),this.qualifiedName=new Oe(e,t),this.argument=n,this.over=i}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},dn=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(dn||{}),fn=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(fn||{}),He=class extends v{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},Ge=class extends v{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},Ae=class extends v{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Pe=class extends v{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},X=class extends v{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new L(e),this.expression=t}},y=class extends v{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new L(t),this.right=n}},D=class extends v{static{this.kind=Symbol("LiteralExpression")}constructor(e){super(),this.value=e}},k=class extends v{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new L(e),this.value=t,this.index=null}},de=class extends v{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},fe=class extends v{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},L=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}},re=class extends v{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},we=class extends v{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},Ce=class extends v{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},ve=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}},Be=class extends v{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new L(e),this.value=new D(t)}},xe=class extends v{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new Oe(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof L?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}},ye=class extends v{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}};function In(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 Oe=class extends v{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=In(e),typeof t=="string"?this.name=new L(t):this.name=t}toString(){let e=this.name instanceof L?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 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}},rt=class extends v{static{this.kind=Symbol("Distinct")}constructor(){super()}},st=class extends v{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},se=class extends v{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},Ve=class extends v{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},Se=class extends v{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new E(e),this.expression=t}},Me=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}},Ee=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 Oe(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof L?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof L?this.qualifiedName.name.value:this.qualifiedName.name.name}},Ue=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 Oe(n.namespaces,n.name)}else this.qualifiedName=new Oe(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},Re=class extends v{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},M=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}},ge=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 L(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}},Z=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}},ee=class extends v{static{this.kind=Symbol("WithClause")}constructor(e,t){super(),this.recursive=e,this.tables=t}},oe=class extends v{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var Qe=class extends v{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},Ke=class extends v{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},Ye=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}},gt=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 Oe(n.namespaces,i)}else{let n=typeof e=="string"?new E(e):e;this.qualifiedName=new Oe(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 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}},qe=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 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&&!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 H=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
|
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 H=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 H{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 Le=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 Fe=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 Wn=[["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"]],jn=new Fe(Wn),wn=new Le(jn),kt=class extends H{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===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 Tt=class extends H{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 H{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
|
7
|
-
${this.getDebugPositionInfo(t)}`);return this.position++,this.input.slice(t+1,this.position-1)}};var
|
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 oe.readWhiteSpaceAndComment(this.input,this.position)}getDebugPositionInfo(e){return oe.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 x(s),newIndex:i,lastTokenType:a}}static parse(e){let n=new T(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 Vt=class{static parseFromLexeme(e,t){let{namespaces:n,name:i,newIndex:r}=ge.parseFromLexeme(e,t);return{value:new S(n,i),newIndex:r}}};var ft=class{static parseFromLexeme(e,t){let n=t,i=e[n].value,r,s=wn.parse(i.toLowerCase(),0);if(s){let l=new L(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 D(r),newIndex:n}}};var Bt=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=J.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 ke(i.value),newIndex:n}}else{let i=g.parseArgument(4,8,e,t);return n=i.newIndex,{value:new z(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=g.parseFromLexeme(e,n);return n=r.newIndex,{value:new X(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 b(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 Qe(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=g.parseFromLexeme(e,n);return{value:new X(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=g.parseFromLexeme(e,n);n=i.newIndex;let r=this.parseSwitchCaseArgument(e,n,[]);return n=r.newIndex,{value:new re(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 re(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=g.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 he(r,s),newIndex:i}}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,i=g.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=g.parseFromLexeme(e,n);return n=r.newIndex,{value:new de(i.value,r.value),newIndex:n}}};var at=class{static parse(e){let n=new T(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 xe(i),newIndex:n}}static parseItem(e,t){let n=t,i=g.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 Le(r,s,a),newIndex:n}}};var Ut=class{static parse(e){let n=new T(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=g.parseFromLexeme(e,n);for(i.push(r.value),n=r.newIndex;n<e.length&&e[n].type&16;){n++;let s=g.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 Ve(i[0]),newIndex:n}:{value:new Ve(new K(i)),newIndex:n}}};var lt=class{static parse(e){let n=new T(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 Te(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 Ae(r,a,u),newIndex:n}}else{let s=this.parseFrameBoundary(e,n),a=s.value;return n=s.newIndex,{value:new Ae(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 He(r),newIndex:n+1}}else if(n<e.length&&e[n].type&1){let i=g.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 Ge(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 wt=class{static parse(e){let n=new T(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 x(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 Xe=class{static parseArrayExpression(e,t){let n=t;if(n+1<e.length&&e[n+1].type&512){n++;let i=g.parseArgument(512,1024,e,n);return n=i.newIndex,{value:new fe(i.value),newIndex:n}}else if(n+1<e.length&&e[n+1].type&4){n++,n++;let i=J.parseFromLexeme(e,n);return n=i.newIndex,n++,{value:new we(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 h=this.parseTypeValue(e,s);return s=h.newIndex,{value:new ae(n,h.value),newIndex:s}}let l=g.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=g.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 Ce(n,s.value,a.value,i),newIndex:r}}static parseBetweenUpperBound(e,t){return g.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=g.parseArgument(4,8,e,n);if(n=a.newIndex,n<e.length&&e[n].value==="over"){let l=wt.parseFromLexeme(e,n);return n=l.newIndex,{value:new $(r,s.name,a.value,l.value),newIndex:n}}else return{value:new $(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=g.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:h,required:v}of n)if(i<e.length&&e[i].type&128&&e[i].value===h)if(i++,i<e.length&&e[i].type&8192){let f=this.parseTypeValue(e,i);u=new y(u,h,f.value),i=f.newIndex}else{let f=g.parseFromLexeme(e,i);u=new y(u,h,f.value),i=f.newIndex}else if(v)throw new Error(`Keyword '${h}' is required at index ${i}`);if(i<e.length&&e[i].type&8)if(i++,i<e.length&&e[i].value==="over"){i++;let h=wt.parseFromLexeme(e,i);return i=h.newIndex,{value:new $(s,a.name,u,h.value),newIndex:i}}else return{value:new $(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=g.parseArgument(4,8,e,n);return n=a.newIndex,{value:new Se(i,new L(r.name),a.value),newIndex:n}}else return{value:new Se(i,new L(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,h)=>{let v=h+r===n?">":" ",f=Q[u.type]||u.type;return`${v} ${h+r}:${u.value} [${f}]`}).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 H{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 H{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 Un=new Fe([["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"]]),Kn=new Fe([["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"]]),Dn=new Le(Un),Jn=new Le(Kn);var Ot=class extends H{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=Dn.parse(this.input,this.position),n!==null?(this.position=n.newPosition,this.createLexeme(2,n.keyword)):null)}};var Mn=new Fe([["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"]]),_n=new Fe([["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"]]),qn=new Le(_n),Cn=new Le(Mn),Lt=class extends H{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=qn.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 zn=new Set(["e'","E'","x'","X'","b'","B'"]),Hn=new Set(["u&'","U&'"]),Ft=class extends H{tryRead(e){let t=this.position;return this.canRead(1)&&zn.has(this.input.slice(t,t+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(t,this.position))):this.canRead(2)&&Hn.has(this.input.slice(t,t+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(t,this.position))):null}};var Gn=new Fe([["grouping","sets"],["array"]]),Yn=new Le(Gn),Nt=class extends H{tryRead(e){if(this.isEndOfInput())return null;let t=Yn.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 Xn=new Fe([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),Zn=new Le(Xn),At=class extends H{tryRead(e){if(this.isEndOfInput())return null;let t=Zn.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 H{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 be=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}=be.parseFromLexeme(e,t);return{value:new S(n,i),newIndex:r}}};var ft=class{static parseFromLexeme(e,t){let n=t,i=e[n].value,r,s=wn.parse(i.toLowerCase(),0);if(s){let l=new L(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 D(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=U.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 Ie(i.value),newIndex:n}}else{let i=g.parseArgument(4,8,e,t);return n=i.newIndex,{value:new z(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=g.parseFromLexeme(e,n);return n=r.newIndex,{value:new X(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 k(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 Be(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=g.parseFromLexeme(e,n);return{value:new X(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=g.parseFromLexeme(e,n);n=i.newIndex;let r=this.parseSwitchCaseArgument(e,n,[]);return n=r.newIndex,{value:new re(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 re(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=g.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 de(r,s),newIndex:i}}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,i=g.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=g.parseFromLexeme(e,n);return n=r.newIndex,{value:new fe(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 ue(i),newIndex:n}}static parseItem(e,t){let n=t,i=g.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 Ee(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=g.parseFromLexeme(e,n);for(i.push(r.value),n=r.newIndex;n<e.length&&e[n].type&16;){n++;let s=g.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 Ve(i[0]),newIndex:n}:{value:new Ve(new J(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 Pe(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 Ae(r,a,u),newIndex:n}}else{let s=this.parseFrameBoundary(e,n),a=s.value;return n=s.newIndex,{value:new Ae(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 He(r),newIndex:n+1}}else if(n<e.length&&e[n].type&1){let i=g.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 Ge(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 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 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 Xe=class{static parseArrayExpression(e,t){let n=t;if(n+1<e.length&&e[n+1].type&512){n++;let i=g.parseArgument(512,1024,e,n);return n=i.newIndex,{value:new we(i.value),newIndex:n}}else if(n+1<e.length&&e[n+1].type&4){n++,n++;let i=U.parseFromLexeme(e,n);return n=i.newIndex,n++,{value:new Ce(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=g.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=g.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 ve(n,s.value,a.value,i),newIndex:r}}static parseBetweenUpperBound(e,t){return g.parseFromLexeme(e,t,!1,!1)}static parseFunctionCall(e,t){let n=t,i=be.parseFromLexeme(e,n),r=i.namespaces,s=i.name;if(n=i.newIndex,n<e.length&&e[n].type&4){let a=g.parseArgument(4,8,e,n);if(n=a.newIndex,n<e.length&&e[n].value==="over"){let l=wt.parseFromLexeme(e,n);return n=l.newIndex,{value:new $(r,s.name,a.value,l.value),newIndex:n}}else return{value:new $(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=be.parseFromLexeme(e,i),s=r.namespaces,a=r.name;if(i=r.newIndex,i<e.length&&e[i].type&4){i++;let l=g.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=g.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=wt.parseFromLexeme(e,i);return i=m.newIndex,{value:new $(s,a.name,u,m.value),newIndex:i}}else return{value:new $(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}=be.parseFromLexeme(e,n);if(n=s,n<e.length&&e[n].type&4){let a=g.parseArgument(4,8,e,n);return n=a.newIndex,{value:new xe(i,new L(r.name),a.value),newIndex:n}}else return{value:new xe(i,new L(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,m)=>{let w=m+r===n?">":" ",d=Q[u.type]||u.type;return`${w} ${m+r}:${u.value} [${d}]`}).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 Ct=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 g=class{static parse(e){let n=new T(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 v=e[s].value;if(!i&&v.toLowerCase()==="and"||!r&&v.toLowerCase()==="or")break;let f=Ct.getPrecedence(v);if(f<n)break;if(s++,Ct.isBetweenOperator(v)){let m=Xe.parseBetweenExpression(e,s,u,v.toLowerCase().includes("not"));u=m.value,s=m.newIndex;continue}if(v==="::"){let m=Xe.parseTypeValue(e,s);u=new ae(u,m.value),s=m.newIndex;continue}let p=f+1,E=this.parseExpressionWithPrecedence(e,s,p,i,r);s=E.newIndex,u=new y(u,v,E.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=Vt.parseFromLexeme(e,n);if(r.newIndex>=e.length)return r;if(e[r.newIndex].type&1){let a=ft.parseFromLexeme(e,r.newIndex);return{value:new X(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?Xe.parseFromLexeme(e,n):{value:new S(r,s),newIndex:a}}else{if(i.type&1)return ft.parseFromLexeme(e,n);if(i.type&4)return Bt.parseFromLexeme(e,n);if(i.type&2048)return Xe.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}=ge.parseFromLexeme(e,n);return{value:new S(r,s),newIndex:a}}else if(i.type&8192){let{namespaces:r,name:s,newIndex:a}=ge.parseFromLexeme(e,n);return{value:new Se(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 K([]),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 K(s),newIndex:r};throw new Error(`Missing closing parenthesis at index ${r}`)}throw new Error(`Expected opening parenthesis at index ${i}`)}};var G=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(I.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(_.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ne.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(x.kind,e=>this.visitIdentifierString(e)),this.handlers.set(L.kind,e=>this.visitRawString(e)),this.handlers.set(S.kind,e=>this.visitColumnReference(e)),this.handlers.set(b.kind,e=>this.visitParameterExpression(e)),this.handlers.set(D.kind,e=>this.visitLiteralValue(e)),this.handlers.set(A.kind,e=>this.visitSourceExpression(e)),this.handlers.set(V.kind,e=>this.visitTableSource(e)),this.handlers.set(je.kind,e=>this.visitFunctionSource(e)),this.handlers.set(Be.kind,e=>this.visitParenSource(e)),this.handlers.set(q.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(ke.kind,e=>this.visitInlineQuery(e)),this.handlers.set(B.kind,e=>this.visitFromClause(e)),this.handlers.set(pe.kind,e=>this.visitJoinClause(e)),this.handlers.set(ce.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Ee.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(se.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(X.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(re.kind,e=>this.visitCaseExpression(e)),this.handlers.set(de.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(he.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(Ce.kind,e=>this.visitBetweenExpression(e)),this.handlers.set($.kind,e=>this.visitFunctionCall(e)),this.handlers.set(fe.kind,e=>this.visitArrayExpression(e)),this.handlers.set(we.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(ve.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ae.kind,e=>this.visitCastExpression(e)),this.handlers.set(Te.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Ae.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Se.kind,e=>this.visitTypeValue(e)),this.handlers.set(K.kind,e=>this.visitValueList(e)),this.handlers.set(Qe.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(j.kind,e=>this.visitSelectClause(e)),this.handlers.set(le.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ue.kind,e=>this.visitHavingClause(e)),this.handlers.set(xe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(ye.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(me.kind,e=>this.visitLimitClause(e)),this.handlers.set(Fe.kind,e=>this.visitForClause(e)),this.handlers.set(Le.kind,e=>this.visitOrderByItem(e)),this.handlers.set(Ve.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(I.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(_.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ne.kind,e=>this.visitValuesQuery(e)),this.handlers.set(W.kind,e=>this.visitSelectItem(e)),this.handlers.set(x.kind,e=>this.visitIdentifierString(e)),this.handlers.set(L.kind,e=>this.visitRawString(e)),this.handlers.set(S.kind,e=>this.visitColumnReference(e)),this.handlers.set(b.kind,e=>this.visitParameterExpression(e)),this.handlers.set(D.kind,e=>this.visitLiteralValue(e)),this.handlers.set(A.kind,e=>this.visitSourceExpression(e)),this.handlers.set(V.kind,e=>this.visitTableSource(e)),this.handlers.set(Be.kind,e=>this.visitParenSource(e)),this.handlers.set(q.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(ke.kind,e=>this.visitInlineQuery(e)),this.handlers.set(B.kind,e=>this.visitFromClause(e)),this.handlers.set(pe.kind,e=>this.visitJoinClause(e)),this.handlers.set(ce.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Ee.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(se.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(X.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(re.kind,e=>this.visitCaseExpression(e)),this.handlers.set(de.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(he.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(Ce.kind,e=>this.visitBetweenExpression(e)),this.handlers.set($.kind,e=>this.visitFunctionCall(e)),this.handlers.set(fe.kind,e=>this.visitArrayExpression(e)),this.handlers.set(we.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(ve.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ae.kind,e=>this.visitCastExpression(e)),this.handlers.set(Te.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Ae.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Se.kind,e=>this.visitTypeValue(e)),this.handlers.set(j.kind,e=>this.visitSelectClause(e)),this.handlers.set(le.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ue.kind,e=>this.visitHavingClause(e)),this.handlers.set(xe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(ye.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(me.kind,e=>this.visitLimitClause(e)),this.handlers.set(Fe.kind,e=>this.visitForClause(e)),this.handlers.set(Le.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 ne(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 B(t,n)}visitSubQuerySource(e){let t=this.visit(e.query);return new q(t)}visitInlineQuery(e){let t=this.visit(e.selectQuery);return new ke(t)}visitJoinClause(e){let t=this.visit(e.source),n=e.condition?this.visit(e.condition):null;return new pe(e.joinType.value,t,n,e.lateral)}visitJoinOnClause(e){let t=this.visit(e.condition);return new ce(t)}visitJoinUsingClause(e){let t=this.visit(e.condition);return new Ee(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 le(t)}visitHavingClause(e){let t=this.visit(e.condition);return new ue(t)}visitOrderByClause(e){let t=e.order.map(n=>this.visit(n));return new xe(t)}visitWindowFrameClause(e){let t=this.visit(e.expression);return new ye(e.name.name,t)}visitLimitClause(e){let t=this.visit(e.value);return new me(t)}visitForClause(e){return new Fe(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 X(e.operator.value,t)}visitCaseExpression(e){let t=e.condition?this.visit(e.condition):null,n=this.visit(e.switchCase);return new re(t,n)}visitSwitchCaseArgument(e){let t=e.cases.map(i=>this.visit(i)),n=e.elseValue?this.visit(e.elseValue):null;return new he(t,n)}visitCaseKeyValuePair(e){let t=this.visit(e.key),n=this.visit(e.value);return new de(t,n)}visitBetweenExpression(e){let t=this.visit(e.expression),n=this.visit(e.lower),i=this.visit(e.upper);return new Ce(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 $(e.namespaces,e.name,t,n)}visitArrayExpression(e){let t=this.visit(e.expression);return new fe(t)}visitArrayQueryExpression(e){let t=this.visit(e.query);return new we(t)}visitTupleExpression(e){let t=e.values.map(n=>this.visit(n));return new ve(t)}visitCastExpression(e){let t=this.visit(e.input),n=this.visit(e.castType);return new ae(t,n)}visitTypeValue(e){let t=e.argument?this.visit(e.argument):null;return new Se(e.namespaces,e.name,t)}visitSelectItem(e){let t=this.visit(e.value);return new 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 Be(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 Te(t,n,i)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new Le(t,e.sortDirection,e.nullsPosition)}};var vt=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(I.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(_.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ne.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(B.kind,t=>this.visitFromClause(t)),this.handlers.set(pe.kind,t=>this.visitJoinClause(t)),this.handlers.set(ce.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(V.kind,t=>this.visitTableSource(t)),this.handlers.set(je.kind,t=>this.visitFunctionSource(t)),this.handlers.set(Be.kind,t=>this.visitParenSource(t)),this.handlers.set(q.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(ke.kind,t=>this.visitInlineQuery(t)),e||(this.handlers.set(se.kind,t=>this.visitWhereClause(t)),this.handlers.set(le.kind,t=>this.visitGroupByClause(t)),this.handlers.set(ue.kind,t=>this.visitHavingClause(t)),this.handlers.set(xe.kind,t=>this.visitOrderByClause(t)),this.handlers.set(ye.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(me.kind,t=>this.visitLimitClause(t)),this.handlers.set(Ue.kind,t=>this.visitOffsetClause(t)),this.handlers.set(Ke.kind,t=>this.visitFetchClause(t)),this.handlers.set(Fe.kind,t=>this.visitForClause(t)),this.handlers.set(Le.kind,t=>this.visitOrderByItem(t)),this.handlers.set(j.kind,t=>this.visitSelectClause(t)),this.handlers.set(W.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(X.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(re.kind,t=>this.visitCaseExpression(t)),this.handlers.set(de.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(he.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(Ce.kind,t=>this.visitBetweenExpression(t)),this.handlers.set($.kind,t=>this.visitFunctionCall(t)),this.handlers.set(fe.kind,t=>this.visitArrayExpression(t)),this.handlers.set(we.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(ve.kind,t=>this.visitTupleExpression(t)),this.handlers.set(ae.kind,t=>this.visitCastExpression(t)),this.handlers.set(K.kind,t=>this.visitValueList(t)),this.handlers.set(Qe.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 L?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof L?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 G;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===b.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 qt=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var Dt=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 C{static{this.kind=Symbol("UpdateQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.updateClause=e.updateClause,this.setClause=e.setClause instanceof qe?e.setClause:new qe(e.setClause),this.whereClause=e.whereClause??null,this.fromClause=e.fromClause??null,this.returningClause=e.returning??null}};var be=class o{constructor(e=null,t=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=e??null,this.commonTableCollector=new G,this.commonTables=[],this.initialCommonTables=t,this.handlers=new Map,this.handlers.set(I.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(B.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 V){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 Be)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 C{static{this.kind=Symbol("CreateTableQuery")}constructor(e){super(),this.tableName=new x(e.tableName),this.isTemporary=e.isTemporary??!1,this.asSelectQuery=e.asSelectQuery}getSelectQuery(){let e;return this.asSelectQuery?e=new be().collect(this.asSelectQuery).map(i=>new W(i.value,i.name)):e=[new W(new L("*"))],new I({selectClause:new j(e),fromClause:new B(new A(new V(null,this.tableName.name),null),null)})}getCountQuery(){return new I({selectClause:new j([new W(new $(null,"count",new S(null,"*"),null))]),fromClause:new B(new A(new V(null,this.tableName.name),null),null)})}};var Tn={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"}},Jt=class o{constructor(e){this.handlers=new Map;this.index=1;e?.preset&&(e={...e.preset,...e}),this.parameterDecorator=new Dt({prefix:typeof e?.parameterSymbol=="string"?e.parameterSymbol:e?.parameterSymbol?.start??":",suffix:typeof e?.parameterSymbol=="object"?e.parameterSymbol.end:"",style:e?.parameterStyle??"named"}),this.identifierDecorator=new qt({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.handlers.set(K.kind,t=>this.visitValueList(t)),this.handlers.set(S.kind,t=>this.visitColumnReference(t)),this.handlers.set(Ie.kind,t=>this.visitQualifiedName(t)),this.handlers.set($.kind,t=>this.visitFunctionCall(t)),this.handlers.set(X.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(y.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(D.kind,t=>this.visitLiteralValue(t)),this.handlers.set(b.kind,t=>this.visitParameterExpression(t)),this.handlers.set(he.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(de.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(L.kind,t=>this.visitRawString(t)),this.handlers.set(x.kind,t=>this.visitIdentifierString(t)),this.handlers.set(z.kind,t=>this.visitParenExpression(t)),this.handlers.set(ae.kind,t=>this.visitCastExpression(t)),this.handlers.set(re.kind,t=>this.visitCaseExpression(t)),this.handlers.set(fe.kind,t=>this.visitArrayExpression(t)),this.handlers.set(we.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(Ce.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(Qe.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(Se.kind,t=>this.visitTypeValue(t)),this.handlers.set(ve.kind,t=>this.visitTupleExpression(t)),this.handlers.set(ke.kind,t=>this.visitInlineQuery(t)),this.handlers.set(Te.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(Ae.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(He.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(Ge.kind,t=>this.visitWindowFrameBoundaryValue(t)),this.handlers.set(Ve.kind,t=>this.visitPartitionByClause(t)),this.handlers.set(xe.kind,t=>this.visitOrderByClause(t)),this.handlers.set(Le.kind,t=>this.visitOrderByItem(t)),this.handlers.set(W.kind,t=>this.visitSelectItem(t)),this.handlers.set(j.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(V.kind,t=>this.visitTableSource(t)),this.handlers.set(je.kind,t=>this.visitFunctionSource(t)),this.handlers.set(A.kind,t=>this.visitSourceExpression(t)),this.handlers.set(M.kind,t=>this.visitSourceAliasExpression(t)),this.handlers.set(B.kind,t=>this.visitFromClause(t)),this.handlers.set(pe.kind,t=>this.visitJoinClause(t)),this.handlers.set(ce.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(Ee.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(se.kind,t=>this.visitWhereClause(t)),this.handlers.set(le.kind,t=>this.visitGroupByClause(t)),this.handlers.set(ue.kind,t=>this.visitHavingClause(t)),this.handlers.set(Je.kind,t=>this.visitWindowClause(t)),this.handlers.set(ye.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(me.kind,t=>this.visitLimitClause(t)),this.handlers.set(Ue.kind,t=>this.visitOffsetClause(t)),this.handlers.set(Ke.kind,t=>this.visitFetchClause(t)),this.handlers.set(Ye.kind,t=>this.visitFetchExpression(t)),this.handlers.set(Fe.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(I.kind,t=>this.visitSimpleQuery(t)),this.handlers.set(q.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(_.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ne.kind,t=>this.visitValuesQuery(t)),this.handlers.set(ve.kind,t=>this.visitTupleExpression(t)),this.handlers.set(We.kind,t=>this.visitInsertQuery(t)),this.handlers.set(Me.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(qe.kind,t=>this.visitSetClause(t)),this.handlers.set(_e.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 x?(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 V){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 yt=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 _t=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 yt(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 yt(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 ei=["mysql","postgres","sqlserver","sqlite"],Ze=class{constructor(e={}){let t=e.preset?Tn[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 Jt(n),this.printer=new _t(e)}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var De=class{constructor(){this.sqlFormatter=new Ze({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(e,t=null){return t&&(this.sqlFormatter=new Ze(t)),this.sqlFormatter.format(e).formattedSql}formatWithParameters(e,t=null){t&&(this.sqlFormatter=new Ze(t));let n=this.sqlFormatter.format(e);return{sql:n.formattedSql,params:n.params}}visit(e){return this.format(e)}};var Mt=class{constructor(){this.sourceCollector=new vt(!0),this.cteCollector=new G,this.formatter=new De}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 h of l)if(h.table.name===a){n.add(a);break}i.has(a)||i.set(a,new Set);let u=this.cteCollector.collect(s.query);for(let h of u){let v=h.aliasExpression.table.name;t.has(v)&&(i.get(a).add(v),r.has(v)||r.set(v,new Set),r.get(v).add(a))}}return{tableMap:t,recursiveCTEs:n,dependencies:i}}sortCommonTables(e,t,n,i){let r=[],s=[],a=new Set,l=new Set,u=h=>{if(a.has(h))return;if(l.has(h))throw new Error(`Circular reference detected in CTE: ${h}`);l.add(h);let v=i.get(h)||new Set;for(let f of v)u(f);l.delete(h),a.add(h),n.has(h)?r.push(t.get(h)):s.push(t.get(h))};for(let h of e){let v=h.aliasExpression.table.name;a.has(v)||u(v)}return[...r,...s]}};var zt=class{constructor(){this.nameConflictResolver=new Mt,this.cteCollector=new G}inject(e,t){if(t.length===0)return e;t.push(...this.cteCollector.collect(e));let n=this.nameConflictResolver.build(t);if(e instanceof I)return this.injectIntoSimpleQuery(e,n);if(e instanceof _)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 I)return this.injectIntoSimpleQuery(e.left,t),e;if(e.left instanceof _)return this.injectIntoBinaryQuery(e.left,t),e;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var Re=class{constructor(){}static normalize(e){let n=new G().collect(e);return n.length===0?e:(new ut().execute(e),new zt().inject(e,n))}};var yn=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))(yn||{}),Ne=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 G,this.commonTables=[],this.duplicateDetection=n,this.options=i||{},this.handlers=new Map,this.handlers.set(I.kind,r=>this.visitSimpleSelectQuery(r)),this.handlers.set(j.kind,r=>this.visitSelectClause(r)),this.handlers.set(B.kind,r=>this.visitFromClause(r)),this.handlers.set(se.kind,r=>this.visitWhereClause(r)),this.handlers.set(le.kind,r=>this.visitGroupByClause(r)),this.handlers.set(ue.kind,r=>this.visitHavingClause(r)),this.handlers.set(xe.kind,r=>this.visitOrderByClause(r)),this.handlers.set(ye.kind,r=>this.visitWindowFrameClause(r)),this.handlers.set(me.kind,r=>this.visitLimitClause(r)),this.handlers.set(Ue.kind,r=>this.offsetClause(r)),this.handlers.set(Ke.kind,r=>this.visitFetchClause(r)),this.handlers.set(ce.kind,r=>this.visitJoinOnClause(r)),this.handlers.set(Ee.kind,r=>this.visitJoinUsingClause(r)),this.handlers.set(S.kind,r=>this.visitColumnReference(r)),this.handlers.set(y.kind,r=>this.visitBinaryExpression(r)),this.handlers.set(X.kind,r=>this.visitUnaryExpression(r)),this.handlers.set($.kind,r=>this.visitFunctionCall(r)),this.handlers.set(z.kind,r=>this.visitParenExpression(r)),this.handlers.set(re.kind,r=>this.visitCaseExpression(r)),this.handlers.set(ae.kind,r=>this.visitCastExpression(r)),this.handlers.set(Ce.kind,r=>this.visitBetweenExpression(r)),this.handlers.set(fe.kind,r=>this.visitArrayExpression(r)),this.handlers.set(we.kind,r=>this.visitArrayQueryExpression(r)),this.handlers.set(K.kind,r=>this.visitValueList(r)),this.handlers.set(ye.kind,r=>this.visitWindowFrameClause(r)),this.handlers.set(Te.kind,r=>this.visitWindowFrameExpression(r)),this.handlers.set(Ve.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 I))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 be(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 T(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 V(t,n.name),newIndex:i}}static parseFunctionSource(e,t){let n=t.newIndex,{namespaces:i,name:r}=t,s=g.parseArgument(4,8,e,n);n=s.newIndex;let a=r.name;return{value:new je({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}=J.parseFromLexeme(e,n);return n=r,{value:new q(i),newIndex:n}}};var tt=class{constructor(e,t){this.options=t||{},this.tableColumnResolver=e,this.columnCollector=new Ne(this.tableColumnResolver)}find(e,t){let n=typeof t=="string"?[t]:t,r=new G().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,h=null;if(u instanceof V)h=this.handleTableSource(u,t,n),a++;else if(u instanceof q)h=this.handleSubQuerySource(u,t,n),a++;else{if(u instanceof ne)continue;s=!1;break}if(h===null){s=!1;break}r.push(h)}return s&&r.length===a?r.flat():null}findUpstream(e,t,n){if(e instanceof I){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 _){let i=this.findUpstream(e.left,t,n),r=this.findUpstream(e.right,t,n);return[...i,...r]}return[]}};var nt=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 M(i,r),newIndex:n}}return{value:new M(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 $e=class{static parse(e){let n=new T(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=nt.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=nt.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 it=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 ne?o.buildSimpleQuery(r):r,i=new _(n(e[0]),t,n(e[1]));Re.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 I)return e;if(e instanceof _)return o.buildSimpleBinaryQuery(e);if(e instanceof ne)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 M("bq",null)),i=new B(n,null),r=o.createSelectAllClause(),s=new I({selectClause:r,fromClause:i});return Re.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 M("vq",e.columnAliases)),r=new B(i,null),s=e.columnAliases.map(l=>new W(new S("vq",l),l)),a=new j(s,null);return new I({selectClause:a,fromClause:r})}static createSelectAllClause(){let e=new S(null,"*"),t=new W(e,"*");return new j([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 be().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 Ct=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 g=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 w=e[s].value;if(!i&&w.toLowerCase()==="and"||!r&&w.toLowerCase()==="or")break;let d=Ct.getPrecedence(w);if(d<n)break;if(s++,Ct.isBetweenOperator(w)){let h=Xe.parseBetweenExpression(e,s,u,w.toLowerCase().includes("not"));u=h.value,s=h.newIndex;continue}if(w==="::"){let h=Xe.parseTypeValue(e,s);u=new le(u,h.value),s=h.newIndex;continue}let p=d+1,x=this.parseExpressionWithPrecedence(e,s,p,i,r);s=x.newIndex,u=new y(u,w,x.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=ft.parseFromLexeme(e,r.newIndex);return{value:new X(e[n].value,a.value),newIndex:a.newIndex}}return r}else if(i.type&64){let{namespaces:r,name:s,newIndex:a}=be.parseFromLexeme(e,n);return e[a-1].type&10240?Xe.parseFromLexeme(e,n):{value:new S(r,s),newIndex:a}}else{if(i.type&1)return ft.parseFromLexeme(e,n);if(i.type&4)return Vt.parseFromLexeme(e,n);if(i.type&2048)return Xe.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}=be.parseFromLexeme(e,n);return{value:new S(r,s),newIndex:a}}else if(i.type&8192){let{namespaces:r,name:s,newIndex:a}=be.parseFromLexeme(e,n);return{value:new xe(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 J([]),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 J(s),newIndex:r};throw new Error(`Missing closing parenthesis at index ${r}`)}throw new Error(`Expected opening parenthesis at index ${i}`)}};var G=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(b.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(_.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ne.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(L.kind,e=>this.visitRawString(e)),this.handlers.set(S.kind,e=>this.visitColumnReference(e)),this.handlers.set(k.kind,e=>this.visitParameterExpression(e)),this.handlers.set(D.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(Ue.kind,e=>this.visitFunctionSource(e)),this.handlers.set(Re.kind,e=>this.visitParenSource(e)),this.handlers.set(M.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Ie.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(ge.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(se.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(X.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(re.kind,e=>this.visitCaseExpression(e)),this.handlers.set(fe.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(de.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ve.kind,e=>this.visitBetweenExpression(e)),this.handlers.set($.kind,e=>this.visitFunctionCall(e)),this.handlers.set(we.kind,e=>this.visitArrayExpression(e)),this.handlers.set(Ce.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(ye.kind,e=>this.visitTupleExpression(e)),this.handlers.set(le.kind,e=>this.visitCastExpression(e)),this.handlers.set(Pe.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Ae.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(xe.kind,e=>this.visitTypeValue(e)),this.handlers.set(J.kind,e=>this.visitValueList(e)),this.handlers.set(Be.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(Se.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Ne.kind,e=>this.visitForClause(e)),this.handlers.set(Ee.kind,e=>this.visitOrderByItem(e)),this.handlers.set(Ve.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(b.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(_.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ne.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(L.kind,e=>this.visitRawString(e)),this.handlers.set(S.kind,e=>this.visitColumnReference(e)),this.handlers.set(k.kind,e=>this.visitParameterExpression(e)),this.handlers.set(D.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(Re.kind,e=>this.visitParenSource(e)),this.handlers.set(M.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Ie.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(ge.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(se.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(X.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(re.kind,e=>this.visitCaseExpression(e)),this.handlers.set(fe.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(de.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ve.kind,e=>this.visitBetweenExpression(e)),this.handlers.set($.kind,e=>this.visitFunctionCall(e)),this.handlers.set(we.kind,e=>this.visitArrayExpression(e)),this.handlers.set(Ce.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(ye.kind,e=>this.visitTupleExpression(e)),this.handlers.set(le.kind,e=>this.visitCastExpression(e)),this.handlers.set(Pe.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Ae.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(xe.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(Se.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Ne.kind,e=>this.visitForClause(e)),this.handlers.set(Ee.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 Me(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 ne(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 M(t)}visitInlineQuery(e){let t=this.visit(e.selectQuery);return new Ie(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 ge(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 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 Se(e.name.name,t)}visitLimitClause(e){let t=this.visit(e.value);return new oe(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 X(e.operator.value,t)}visitCaseExpression(e){let t=e.condition?this.visit(e.condition):null,n=this.visit(e.switchCase);return new re(t,n)}visitSwitchCaseArgument(e){let t=e.cases.map(i=>this.visit(i)),n=e.elseValue?this.visit(e.elseValue):null;return new de(t,n)}visitCaseKeyValuePair(e){let t=this.visit(e.key),n=this.visit(e.value);return new fe(t,n)}visitBetweenExpression(e){let t=this.visit(e.expression),n=this.visit(e.lower),i=this.visit(e.upper);return new ve(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 $(e.namespaces,e.name,t,n)}visitArrayExpression(e){let t=this.visit(e.expression);return new we(t)}visitArrayQueryExpression(e){let t=this.visit(e.query);return new Ce(t)}visitTupleExpression(e){let t=e.values.map(n=>this.visit(n));return new ye(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 xe(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 Re(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 Pe(t,n,i)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new Ee(t,e.sortDirection,e.nullsPosition)}};var vt=class{constructor(e=!0){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.cteNames=new Set;this.isRootVisit=!0;this.selectableOnly=e,this.handlers=new Map,this.handlers.set(b.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(_.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ne.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(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(ge.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(Ue.kind,t=>this.visitFunctionSource(t)),this.handlers.set(Re.kind,t=>this.visitParenSource(t)),this.handlers.set(M.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(Ie.kind,t=>this.visitInlineQuery(t)),e||(this.handlers.set(se.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(Se.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(oe.kind,t=>this.visitLimitClause(t)),this.handlers.set(Qe.kind,t=>this.visitOffsetClause(t)),this.handlers.set(Ke.kind,t=>this.visitFetchClause(t)),this.handlers.set(Ne.kind,t=>this.visitForClause(t)),this.handlers.set(Ee.kind,t=>this.visitOrderByItem(t)),this.handlers.set(j.kind,t=>this.visitSelectClause(t)),this.handlers.set(W.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(X.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(re.kind,t=>this.visitCaseExpression(t)),this.handlers.set(fe.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(de.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(ve.kind,t=>this.visitBetweenExpression(t)),this.handlers.set($.kind,t=>this.visitFunctionCall(t)),this.handlers.set(we.kind,t=>this.visitArrayExpression(t)),this.handlers.set(Ce.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(ye.kind,t=>this.visitTupleExpression(t)),this.handlers.set(le.kind,t=>this.visitCastExpression(t)),this.handlers.set(J.kind,t=>this.visitValueList(t)),this.handlers.set(Be.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 L?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof L?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 G;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===k.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 Dt=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var Jt=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 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 ke=class o{constructor(e=null,t=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=e??null,this.commonTableCollector=new G,this.commonTables=[],this.initialCommonTables=t,this.handlers=new Map,this.handlers.set(b.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 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 M){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 Re)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 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 ke().collect(this.asSelectQuery).map(i=>new W(i.value,i.name)):e=[new W(new L("*"))],new b({selectClause:new j(e),fromClause:new V(new A(new B(null,this.tableName.name),null),null)})}getCountQuery(){return new b({selectClause:new j([new W(new $(null,"count",new S(null,"*"),null))]),fromClause:new V(new A(new B(null,this.tableName.name),null),null)})}};var Ln={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 Jt({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 Dt({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.handlers.set(J.kind,t=>this.visitValueList(t)),this.handlers.set(S.kind,t=>this.visitColumnReference(t)),this.handlers.set(Oe.kind,t=>this.visitQualifiedName(t)),this.handlers.set($.kind,t=>this.visitFunctionCall(t)),this.handlers.set(X.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(y.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(D.kind,t=>this.visitLiteralValue(t)),this.handlers.set(k.kind,t=>this.visitParameterExpression(t)),this.handlers.set(de.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(fe.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(L.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(re.kind,t=>this.visitCaseExpression(t)),this.handlers.set(we.kind,t=>this.visitArrayExpression(t)),this.handlers.set(Ce.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(ve.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(Be.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(xe.kind,t=>this.visitTypeValue(t)),this.handlers.set(ye.kind,t=>this.visitTupleExpression(t)),this.handlers.set(Ie.kind,t=>this.visitInlineQuery(t)),this.handlers.set(Pe.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(Ae.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(He.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(Ge.kind,t=>this.visitWindowFrameBoundaryValue(t)),this.handlers.set(Ve.kind,t=>this.visitPartitionByClause(t)),this.handlers.set(ue.kind,t=>this.visitOrderByClause(t)),this.handlers.set(Ee.kind,t=>this.visitOrderByItem(t)),this.handlers.set(W.kind,t=>this.visitSelectItem(t)),this.handlers.set(j.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(Ue.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(ge.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(se.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(Me.kind,t=>this.visitWindowClause(t)),this.handlers.set(Se.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(oe.kind,t=>this.visitLimitClause(t)),this.handlers.set(Qe.kind,t=>this.visitOffsetClause(t)),this.handlers.set(Ke.kind,t=>this.visitFetchClause(t)),this.handlers.set(Ye.kind,t=>this.visitFetchExpression(t)),this.handlers.set(Ne.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(b.kind,t=>this.visitSimpleQuery(t)),this.handlers.set(M.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(_.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ne.kind,t=>this.visitValuesQuery(t)),this.handlers.set(ye.kind,t=>this.visitTupleExpression(t)),this.handlers.set(je.kind,t=>this.visitInsertQuery(t)),this.handlers.set(qe.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(De.kind,t=>this.visitSetClause(t)),this.handlers.set(_e.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 yt=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 _t=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 yt(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 yt(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 ni=["mysql","postgres","sqlserver","sqlite"],Ze=class{constructor(e={}){let t=e.preset?Ln[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 _t(e)}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var Je=class{constructor(){this.sqlFormatter=new Ze({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(e,t=null){return t&&(this.sqlFormatter=new Ze(t)),this.sqlFormatter.format(e).formattedSql}formatWithParameters(e,t=null){t&&(this.sqlFormatter=new Ze(t));let n=this.sqlFormatter.format(e);return{sql:n.formattedSql,params:n.params}}visit(e){return this.format(e)}};var qt=class{constructor(){this.sourceCollector=new vt(!0),this.cteCollector=new G,this.formatter=new Je}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 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 zt=class{constructor(){this.nameConflictResolver=new qt,this.cteCollector=new G}inject(e,t){if(t.length===0)return e;t.push(...this.cteCollector.collect(e));let n=this.nameConflictResolver.build(t);if(e instanceof b)return this.injectIntoSimpleQuery(e,n);if(e instanceof _)return this.injectIntoBinaryQuery(e,n);throw new Error("Unsupported query type")}injectIntoSimpleQuery(e,t){if(e.withClause)throw new Error("The query already has a WITH clause. Please remove it before injecting new CTEs.");return e.withClause=t,e}injectIntoBinaryQuery(e,t){if(e.left instanceof b)return this.injectIntoSimpleQuery(e.left,t),e;if(e.left instanceof _)return this.injectIntoBinaryQuery(e.left,t),e;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var $e=class{constructor(){}static normalize(e){let n=new G().collect(e);return n.length===0?e:(new ut().execute(e),new zt().inject(e,n))}};var yn=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))(yn||{}),Te=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 G,this.commonTables=[],this.duplicateDetection=n,this.options=i||{},this.handlers=new Map,this.handlers.set(b.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(se.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(Se.kind,r=>this.visitWindowFrameClause(r)),this.handlers.set(oe.kind,r=>this.visitLimitClause(r)),this.handlers.set(Qe.kind,r=>this.offsetClause(r)),this.handlers.set(Ke.kind,r=>this.visitFetchClause(r)),this.handlers.set(me.kind,r=>this.visitJoinOnClause(r)),this.handlers.set(ge.kind,r=>this.visitJoinUsingClause(r)),this.handlers.set(S.kind,r=>this.visitColumnReference(r)),this.handlers.set(y.kind,r=>this.visitBinaryExpression(r)),this.handlers.set(X.kind,r=>this.visitUnaryExpression(r)),this.handlers.set($.kind,r=>this.visitFunctionCall(r)),this.handlers.set(z.kind,r=>this.visitParenExpression(r)),this.handlers.set(re.kind,r=>this.visitCaseExpression(r)),this.handlers.set(le.kind,r=>this.visitCastExpression(r)),this.handlers.set(ve.kind,r=>this.visitBetweenExpression(r)),this.handlers.set(we.kind,r=>this.visitArrayExpression(r)),this.handlers.set(Ce.kind,r=>this.visitArrayQueryExpression(r)),this.handlers.set(J.kind,r=>this.visitValueList(r)),this.handlers.set(Se.kind,r=>this.visitWindowFrameClause(r)),this.handlers.set(Pe.kind,r=>this.visitWindowFrameExpression(r)),this.handlers.set(Ve.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 b))throw new Error("Root visit must be a SimpleSelectQuery");this.reset(),this.isRootVisit=!1,this.commonTables=this.commonTableCollector.collect(e);try{this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}visitSimpleSelectQuery(e){if(e.selectClause&&e.selectClause.accept(this),e.fromClause&&e.fromClause.accept(this),e.whereClause&&e.whereClause.accept(this),e.groupByClause&&e.groupByClause.accept(this),e.havingClause&&e.havingClause.accept(this),e.windowClause)for(let t of e.windowClause.windows)t.accept(this);e.orderByClause&&e.orderByClause.accept(this),e.limitClause&&e.limitClause.accept(this),e.offsetClause&&e.offsetClause.accept(this),e.fetchClause&&e.fetchClause.accept(this),e.forClause&&e.forClause.accept(this)}visitSelectClause(e){for(let t of e.items)t.identifier&&this.addSelectValueAsUnique(t.identifier.name,t.value),t.value.accept(this)}visitFromClause(e){let n=new ke(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=be.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=be.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=g.parseArgument(4,8,e,n);n=s.newIndex;let a=r.name;return{value:new Ue({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}=U.parseFromLexeme(e,n);return n=r,{value:new M(i),newIndex:n}}};var tt=class{constructor(e,t){this.options=t||{},this.tableColumnResolver=e,this.columnCollector=new Te(this.tableColumnResolver)}find(e,t){let n=typeof t=="string"?[t]:t,r=new G().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 M)m=this.handleSubQuerySource(u,t,n),a++;else{if(u instanceof ne)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 b){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 _){let i=this.findUpstream(e.left,t,n),r=this.findUpstream(e.right,t,n);return[...i,...r]}return[]}};var nt=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 We=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=nt.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=nt.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 it=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 ne?o.buildSimpleQuery(r):r,i=new _(n(e[0]),t,n(e[1]));$e.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 b)return e;if(e instanceof _)return o.buildSimpleBinaryQuery(e);if(e instanceof ne)return o.buildSimpleValuesQuery(e);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(e){let t=new M(e),n=new A(t,new q("bq",null)),i=new V(n,null),r=o.createSelectAllClause(),s=new b({selectClause:r,fromClause:i});return $e.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 M(e),i=new A(n,new q("vq",e.columnAliases)),r=new V(i,null),s=e.columnAliases.map(l=>new W(new S("vq",l),l)),a=new j(s,null);return new b({selectClause:a,fromClause:r})}static createSelectAllClause(){let e=new S(null,"*"),t=new W(e,"*");return new j([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 ke().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=$e.parse(t);return new We({insertClause:new Me(a,n),selectQuery:e})}static buildUpdateQuery(e,t,n,i){let r=new ot($e.parse(n)),s=Array.isArray(i)?i:[i],l=new be().collect(e),h=new G().collect(e);new ut().execute(e);for(let w of s)if(!l.some(Y=>Y.name===w))throw new Error(`Primary key column '${w}' is not present in selectQuery select list.`);let f=r.getSourceAliasName();if(!f)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let E=l.filter(w=>!s.includes(w.name)).map(w=>new _e(w.name,new S(f,w.name))),m=new qe(E),F=new B(e.toSource(t),null),k=null;for(let w of s){let Y=new y(new S(f,w),"=",new S(t,w));k=k?new y(k,"and",Y):Y}let N=new se(k);return new pt({updateClause:r,setClause:m,fromClause:F,whereClause:N,withClause:h.length>0?new ee(!1,h):void 0})}};var ze=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 I=class extends C{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 it.buildBinaryQuery([this,t],e)}appendWhereRaw(e){let t=g.parse(e);this.appendWhere(t)}appendWhere(e){this.whereClause?this.whereClause.condition=new y(this.whereClause.condition,"and",e):this.whereClause=new se(e)}appendHavingRaw(e){let t=g.parse(e);this.appendHaving(t)}appendHaving(e){this.havingClause?this.havingClause.condition=new y(this.havingClause.condition,"and",e):this.havingClause=new ue(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 M(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 Ne(i).collect(this),l=null,u=0,h=t.getAliasName();if(!h)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let p of a)if(r.some(E=>E==p.name)){let E=new y(p.value,"=",new S([h],p.name));l?l=new y(l,"and",E):l=E,u++}if(!l||u!==r.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${r.join(", ")}`);let v=new ce(l),f=new pe(e,t,v,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(f):this.fromClause.joins=[f]),Re.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 M(e,null))}appendWith(e){let t=Array.isArray(e)?e:[e];this.withClause?this.withClause.tables.push(...t):this.withClause=new ee(!1,t),Re.normalize(this)}appendWithRaw(e,t){let n=J.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 De().visit(i.value),a=t(s);i.value=g.parse(a)}appendWhereExpr(e,t,n){if(n&&n.upstream){let r=new tt().find(this,[e]),s=new Ne,a=new De;for(let l of r){let u=s.collect(l).filter(v=>v.name===e).map(v=>v.value);if(u.length!==1)throw new Error(`Expected exactly one expression for column '${e}'`);let h=a.format(u[0]);l.appendWhereRaw(t(h))}}else{let i=new Ne,r=new De,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 _=class o extends C{static{this.kind=Symbol("BinarySelectQuery")}constructor(e,t,n){super(),this.left=e,this.operator=new L(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 L(e),this.right=t,Re.normalize(this),this}unionRaw(e){let t=J.parse(e);return this.union(t)}unionAllRaw(e){let t=J.parse(e);return this.unionAll(t)}intersectRaw(e){let t=J.parse(e);return this.intersect(t)}intersectAllRaw(e){let t=J.parse(e);return this.intersectAll(t)}exceptRaw(e){let t=J.parse(e);return this.except(t)}exceptAllRaw(e){let t=J.parse(e);return this.exceptAll(t)}toSource(e="subq"){return new A(new q(this),new M(e,null))}setParameter(e,t){return ze.set(this,e,t),this}};var ne=class extends C{static{this.kind=Symbol("ValuesQuery")}constructor(e,t=null){super(),this.tuples=e,this.columnAliases=t}toSimpleSelectQuery(){return it.buildSimpleQuery(this)}setParameter(e,t){return ze.set(this,e,t),this}};var Ht=class{static parse(e){let n=new T(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=g.parseArgument(4,8,e,n);i=new st(a.value),n=a.newIndex}let r=[],s=Gt.parseItem(e,n);for(r.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let a=Gt.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}}},Gt=class{static parse(e){let n=new T(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=g.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 Yt=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="on"){n++;let i=g.parseFromLexeme(e,n);return n=i.newIndex,{value:new ce(i.value),newIndex:n}}return null}};var Xt=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="using"){n++;let i=g.parseArgument(4,8,e,n),r=i.value;return n=i.newIndex,{value:new Ee(r),newIndex:n}}return null}};var Zt=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=$e.parseFromLexeme(e,n);if(n=a.newIndex,n<e.length){let u=Yt.tryParse(e,n);if(u)return{value:new pe(i,a.value,u.value,s),newIndex:u.newIndex};let h=Xt.tryParse(e,n);if(h)return{value:new pe(i,a.value,h.value,s),newIndex:h.newIndex}}return{value:new pe(i,a.value,null,s),newIndex:n}}};var en=class{static parse(e){let n=new T(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=$e.parseFromLexeme(e,n);n=i.newIndex;let r=Zt.tryParse(e,n);return n=r?.newIndex||n,r!==null?{value:new B(i.value,r.value),newIndex:n}:{value:new B(i.value,null),newIndex:n}}};var tn=class{static parse(e){let n=new T(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=g.parseFromLexeme(e,n);return{value:new se(i.value),newIndex:i.newIndex}}};var nn=class{static parse(e){let n=new T(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 le(i),newIndex:n}}static parseItem(e,t){let n=t,i=g.parseFromLexeme(e,n),r=i.value;return n=i.newIndex,{value:r,newIndex:n}}};var rn=class{static parse(e){let n=new T(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=g.parseFromLexeme(e,n);return{value:new ue(i.value),newIndex:i.newIndex}}};var sn=class{static parse(e){let n=new T(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 ye(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 on=class{static parse(e){let n=new T(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=g.parseFromLexeme(e,n);return n=i.newIndex,{value:new me(i.value),newIndex:n}}};var an=class{static parse(e){let n=new T(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 Fe(r),newIndex:n}}};var St=class{static parse(e){let n=new T(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=nt.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=J.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 ht=class{static parse(e){let n=new T(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=St.parseFromLexeme(e,n);for(r.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let a=St.parseFromLexeme(e,n);r.push(a.value),n=a.newIndex}return{value:new ee(i,r),newIndex:n}}};var ln=class{static parse(e){let n=new T(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 ne(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 ve([]),newIndex:n};let r=g.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=g.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 ve(i),newIndex:n}}};var un=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=Sn.parseFromLexeme(e,n),r=i.value;return n=i.newIndex,{value:new Ke(r),newIndex:n}}},Sn=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 D(1),a="rows only",n++,{value:new Ye(i,s,a),newIndex:n};let l=g.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 Ye(i,s,a),newIndex:n}}};var cn=class{static parse(e){let n=new T(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=g.parseFromLexeme(e,n);return n=i.newIndex,n<e.length&&(e[n].value==="row"||e[n].value==="rows")&&n++,{value:new Ue(i.value),newIndex:n}}};var J=class{static parse(e){let n=new T(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 _(s,a,u.value),n=u.newIndex}else if(l==="values"){let u=this.parseValuesQuery(e,n);s=new _(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=Ht.parseFromLexeme(e,n);n=r.newIndex;let s=null;n<e.length&&e[n].value==="from"&&(s=en.parseFromLexeme(e,n),n=s.newIndex);let a=null;n<e.length&&e[n].value==="where"&&(a=tn.parseFromLexeme(e,n),n=a.newIndex);let l=null;n<e.length&&e[n].value==="group by"&&(l=nn.parseFromLexeme(e,n),n=l.newIndex);let u=null;n<e.length&&e[n].value==="having"&&(u=rn.parseFromLexeme(e,n),n=u.newIndex);let h=null;n<e.length&&e[n].value==="window"&&(h=sn.parseFromLexeme(e,n),n=h.newIndex);let v=null;n<e.length&&e[n].value==="order by"&&(v=at.parseFromLexeme(e,n),n=v.newIndex);let f=null;n<e.length&&e[n].value==="limit"&&(f=on.parseFromLexeme(e,n),n=f.newIndex);let p=null;n<e.length&&e[n].value==="offset"&&(p=cn.parseFromLexeme(e,n),n=p.newIndex);let E=null;n<e.length&&e[n].value==="fetch"&&(E=un.parseFromLexeme(e,n),n=E.newIndex);let m=null;return n<e.length&&e[n].value.toLowerCase()==="for"&&(m=an.parseFromLexeme(e,n),n=m.newIndex),{value:new I({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:v?v.value:null,windowClause:h?h.value:null,limitClause:f?f.value:null,offsetClause:p?p.value:null,fetchClause:E?E.value:null,forClause:m?m.value:null}),newIndex:n}}static parseValuesQuery(e,t){let n=ln.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}};var xn=class{static parse(e){let n=new T(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=$e.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=J.parseFromLexeme(e,n);if(i)if(a.value instanceof I)a.value.withClause=i;else throw new Error("WITH clause is not supported in this context.");return n=a.newIndex,{value:new We({insertClause:new Me(r.value,s),selectQuery:a.value}),newIndex:n}}};var pn=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,h)=>h-u);for(let u of l){let h=a.get(u),v=`${o.CTE_OBJECT_PREFIX}${u}`,f=this.buildDepthCte(h,r,v,n,t);i.push(f),r=v}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 h=t.get(a);if(!h)throw new Error(`Parent entity ${a} not found during depth calculation for ${r}`);let v=!1;if(h.isRoot)v=!0;else{let f=e.nestedEntities.find(p=>p.id===a);if(f)f.relationshipType==="object"&&(v=!0);else throw new Error(`Parent entity ${a} (ancestor of ${r}) has no definition in mapping.nestedEntities and is not root.`)}if(v&&l++,h.isRoot)break;a=h.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 x(o.WILDCARD_COLUMN)))];for(let{entity:l}of e){let u=this.buildEntityJsonColumn(l,i,r);s.push(u)}let a=new I({selectClause:new j(s),fromClause:new B(new A(new V(null,new x(t)),null),null)});return new Z(a,new M(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 D(i)),t.push(new S(null,new x(r))),n.push(new y(new S(null,new x(r)),"is",new D(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 D(s.propertyName));let l=`${a.name.toLowerCase()}${o.JSON_COLUMN_SUFFIX}`;t.push(new S(null,new x(l)))}})}createJsonObject(e,t=!1){let n=t?"jsonb_build_object":"json_build_object";return new $(null,new L(n),new K(e),null)}buildNullCondition(e){return e.reduce((t,n)=>t?new y(t,"and",n):n)}createCaseExpression(e,t){return new re(null,new he([new de(e,new D(null))],t))}};var mn=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((h,v)=>v-h);for(let h of u){let v=l.get(h),{cte:f,newCteAlias:p}=this.buildDepthCte(v,s,r,h,i);r.push(f),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(E=>{Object.values(E.entity.columns).forEach(m=>s.add(m))});let a=n.find(E=>E.aliasExpression.table.name===t)?.query;if(!a)throw new Error(`CTE not found: ${t}`);let l=new be(null,n).collect(a),u=[],h=[];l.forEach(E=>{s.has(E.name)||(h.push(new W(new S(null,new x(E.name)),E.name)),u.push(new S(null,new x(E.name))))});for(let E of e){let m=this.buildAggregationDetailsForArrayEntity(E.entity,r.nestedEntities,new Map,r.useJsonb);h.push(new W(m.jsonAgg,E.entity.propertyName))}let v=`${o.CTE_ARRAY_PREFIX}${i}`,f=new I({selectClause:new j(h),fromClause:new B(new A(new V(null,new x(t)),null),null),groupByClause:u.length>0?new le(u):null});return{cte:new Z(f,new M(v,null),null),newCteAlias:v}}buildAggregationDetailsForArrayEntity(e,t,n,i=!1){let r=i?"jsonb_build_object":"json_build_object",s=[];Object.entries(e.columns).forEach(([v,f])=>{s.push(new D(v)),s.push(new S(null,new x(f)))}),t.filter(v=>v.parentId===e.id).forEach(v=>{if(s.push(new D(v.propertyName)),v.relationshipType==="object"){let f=`${v.name.toLowerCase()}_json`;s.push(new S(null,new x(f)))}else v.relationshipType==="array"&&s.push(new S(null,new x(v.propertyName)))});let l=new $(null,new L(r),new K(s),null),u=i?"jsonb_agg":"json_agg";return{jsonAgg:new $(null,new L(u),new K([l]),null)}}};var En=class{constructor(){this.selectValueCollector=new be(null),this.objectEntityCteBuilder=new pn,this.arrayEntityCteBuilder=new mn}validateMapping(e,t){let i=new be().collect(e),r=new Set(i.map(u=>u.name));for(let u in t.rootEntity.columns){let h=t.rootEntity.columns[u];if(!r.has(h))throw new Error(`Validation Error: Column "${h}" 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 h in u.columns){let v=u.columns[h];if(!r.has(v))throw new Error(`Validation Error: Column "${v}" for JSON key "${h}" 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 h=t.nestedEntities.filter(p=>p.parentId===u);if(h.filter(p=>p.relationshipType==="array").length>1){let p=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(E=>E.id===u)?.name;throw new Error(`Validation Error: Parent entity "${p}" (ID: ${u}) has multiple direct array children. This is not supported.`)}let f=new Set;for(let p of h){if(f.has(p.propertyName)){let E=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(m=>m.id===u)?.name;throw new Error(`Validation Error: Parent entity "${E}" (ID: ${u}) has duplicate property name "${p.propertyName}" for its children.`)}f.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(h=>a.set(h.id,{...h,isRoot:!1,propertyName:h.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 M(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),h=new Z(new I({selectClause:new j([u]),fromClause:new B(new A(new V(null,new x(t)),null),null)}),new M(s,null),null);r.push(h);let v=i.useJsonb?"jsonb_agg":"json_agg",f=new $(null,new L(v),new K([new S(null,new x(i.rootName))]),null);return new I({withClause:new ee(!1,r),selectClause:new j([new W(f,`${i.rootName}_array`)]),fromClause:new B(new A(new V(null,new x(s)),null),null)})}else{let l=this.buildEntityJsonObject(a,null,i.nestedEntities,n,i.useJsonb),u=new W(l,i.rootName),h=new Z(new I({selectClause:new j([u]),fromClause:new B(new A(new V(null,new x(t)),null),null)}),new M(s,null),null);return r.push(h),new I({withClause:new ee(!1,r),selectClause:new j([new W(new S(null,new x(i.rootName)),i.rootName)]),fromClause:new B(new A(new V(null,new x(s)),null),null),limitClause:new me(new D(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,h])=>{a.push(new D(u)),a.push(new S(null,new x(h)))}),n.filter(u=>u.parentId===e.id).forEach(u=>{let h=i.get(u.id);if(h)if(a.push(new D(u.propertyName)),u.relationshipType==="object"){let v=`${h.name.toLowerCase()}_json`;a.push(new S(null,new x(v)))}else u.relationshipType==="array"&&a.push(new S(null,new x(u.propertyName)))}),new $(null,new L(s),new K(a),null)}};var xt=class{constructor(e,t){this.name=e,this.columns=t}},Et=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(I.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(_.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 I||e instanceof _))throw new Error(`Unsupported SQL component type for schema collection. Received: ${e.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let t=new G;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 xt(t,Array.from(n).sort()))}handleTableSource(e,t,n){if(e.datasource instanceof V){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 Ne(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 V?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 V?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 xt(e,r);this.tableSchemas.push(s)}};var gn=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=J.parse(e));let n=new tt(this.tableColumnResolver,this.options),i=new Ne(this.tableColumnResolver),r=f=>this.options.ignoreCaseAndUnderscore?f.toLowerCase().replace(/_/g,""):f,s=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"];for(let[f,p]of Object.entries(t)){if(p===void 0)continue;if(p!==null&&typeof p=="object"&&!Array.isArray(p)&&"or"in p){let m=p.or;if(m&&m.length>0){let F=m.map(d=>d.column||f).filter((d,w,Y)=>Y.indexOf(d)===w),k=null;for(let d of F){let w=n.find(e,d);if(w.length>0){k=w[0];break}}if(!k)throw new Error(`None of the OR condition columns [${F.join(", ")}] found in query`);let N=i.collect(k);l(k,f,m,r,N,i);continue}}if(p!==null&&typeof p=="object"&&!Array.isArray(p)&&"and"in p){let m=p.and;if(m&&m.length>0){let F=m.map(d=>d.column||f).filter((d,w,Y)=>Y.indexOf(d)===w),k=null;for(let d of F){let w=n.find(e,d);if(w.length>0){k=w[0];break}}if(!k)throw new Error(`None of the AND condition columns [${F.join(", ")}] found in query`);let N=i.collect(k);a(k,f,m,r,N,i);continue}}if(p!==null&&typeof p=="object"&&!Array.isArray(p)&&"column"in p&&!("or"in p)){let m=p.column;if(m){let F=n.find(e,m);if(F.length===0)throw new Error(`Explicit column '${m}' not found in query`);for(let k of F){let d=i.collect(k).find(w=>r(w.name)===r(m));if(!d)throw new Error(`Explicit column '${m}' not found in query`);p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.getPrototypeOf(p)===Object.prototype&&u(p,s,f),v(k,d.value,f,p)}continue}}let E=n.find(e,f);if(E.length===0)throw new Error(`Column '${f}' not found in query`);for(let m of E){let F=i.collect(m),k=F.find(Y=>r(Y.name)===r(f));if(!k)throw new Error(`Column '${f}' not found in query`);let N=k.value;p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.getPrototypeOf(p)===Object.prototype&&u(p,s,f);let d=N,w=f;if(p!==null&&typeof p=="object"&&!Array.isArray(p)&&"column"in p){let Y=p.column;if(Y){let ie=F.find(O=>r(O.name)===r(Y));ie&&(d=ie.value,w=Y)}}p===null||typeof p!="object"||Array.isArray(p)||p instanceof Date?h(m,d,w,p):v(m,d,w,p)}}function a(f,p,E,m,F,k){for(let N=0;N<E.length;N++){let d=E[N],w=d.column||p,Y=F.find(O=>m(O.name)===m(w));if(!Y)throw new Error(`Column '${w}' not found in query for AND condition`);let ie=Y.value;if("="in d&&d["="]!==void 0){let O=`${p}_and_${N}_eq`,P=new b(O,d["="]);f.appendWhere(new y(ie,"=",P))}if("min"in d&&d.min!==void 0){let O=`${p}_and_${N}_min`,P=new b(O,d.min);f.appendWhere(new y(ie,">=",P))}if("max"in d&&d.max!==void 0){let O=`${p}_and_${N}_max`,P=new b(O,d.max);f.appendWhere(new y(ie,"<=",P))}if("like"in d&&d.like!==void 0){let O=`${p}_and_${N}_like`,P=new b(O,d.like);f.appendWhere(new y(ie,"like",P))}if("ilike"in d&&d.ilike!==void 0){let O=`${p}_and_${N}_ilike`,P=new b(O,d.ilike);f.appendWhere(new y(ie,"ilike",P))}if("in"in d&&d.in!==void 0){let P=d.in.map((R,U)=>new b(`${p}_and_${N}_in_${U}`,R));f.appendWhere(new y(ie,"in",new z(new K(P))))}if("any"in d&&d.any!==void 0){let O=`${p}_and_${N}_any`,P=new b(O,d.any);f.appendWhere(new y(ie,"=",new $(null,"any",P,null)))}if("<"in d&&d["<"]!==void 0){let O=`${p}_and_${N}_lt`,P=new b(O,d["<"]);f.appendWhere(new y(ie,"<",P))}if(">"in d&&d[">"]!==void 0){let O=`${p}_and_${N}_gt`,P=new b(O,d[">"]);f.appendWhere(new y(ie,">",P))}if("!="in d&&d["!="]!==void 0){let O=`${p}_and_${N}_neq`,P=new b(O,d["!="]);f.appendWhere(new y(ie,"!=",P))}if("<>"in d&&d["<>"]!==void 0){let O=`${p}_and_${N}_ne`,P=new b(O,d["<>"]);f.appendWhere(new y(ie,"<>",P))}if("<="in d&&d["<="]!==void 0){let O=`${p}_and_${N}_le`,P=new b(O,d["<="]);f.appendWhere(new y(ie,"<=",P))}if(">="in d&&d[">="]!==void 0){let O=`${p}_and_${N}_ge`,P=new b(O,d[">="]);f.appendWhere(new y(ie,">=",P))}}}function l(f,p,E,m,F,k){let N=[];for(let d=0;d<E.length;d++){let w=E[d],Y=w.column||p,ie=F.find(R=>m(R.name)===m(Y));if(!ie)throw new Error(`Column '${Y}' not found in query for OR condition`);let O=ie.value,P=[];if("="in w&&w["="]!==void 0){let R=`${p}_or_${d}_eq`,U=new b(R,w["="]);P.push(new y(O,"=",U))}if("min"in w&&w.min!==void 0){let R=`${p}_or_${d}_min`,U=new b(R,w.min);P.push(new y(O,">=",U))}if("max"in w&&w.max!==void 0){let R=`${p}_or_${d}_max`,U=new b(R,w.max);P.push(new y(O,"<=",U))}if("like"in w&&w.like!==void 0){let R=`${p}_or_${d}_like`,U=new b(R,w.like);P.push(new y(O,"like",U))}if("ilike"in w&&w.ilike!==void 0){let R=`${p}_or_${d}_ilike`,U=new b(R,w.ilike);P.push(new y(O,"ilike",U))}if("in"in w&&w.in!==void 0){let U=w.in.map((In,Pn)=>new b(`${p}_or_${d}_in_${Pn}`,In));P.push(new y(O,"in",new z(new K(U))))}if("any"in w&&w.any!==void 0){let R=`${p}_or_${d}_any`,U=new b(R,w.any);P.push(new y(O,"=",new $(null,"any",U,null)))}if("<"in w&&w["<"]!==void 0){let R=`${p}_or_${d}_lt`,U=new b(R,w["<"]);P.push(new y(O,"<",U))}if(">"in w&&w[">"]!==void 0){let R=`${p}_or_${d}_gt`,U=new b(R,w[">"]);P.push(new y(O,">",U))}if("!="in w&&w["!="]!==void 0){let R=`${p}_or_${d}_neq`,U=new b(R,w["!="]);P.push(new y(O,"!=",U))}if("<>"in w&&w["<>"]!==void 0){let R=`${p}_or_${d}_ne`,U=new b(R,w["<>"]);P.push(new y(O,"<>",U))}if("<="in w&&w["<="]!==void 0){let R=`${p}_or_${d}_le`,U=new b(R,w["<="]);P.push(new y(O,"<=",U))}if(">="in w&&w[">="]!==void 0){let R=`${p}_or_${d}_ge`,U=new b(R,w[">="]);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 d=N[0];for(let w=1;w<N.length;w++)d=new y(d,"or",N[w]);f.appendWhere(new z(d))}}function u(f,p,E){Object.keys(f).forEach(m=>{if(!p.includes(m))throw new Error(`Unsupported operator '${m}' for state key '${E}'`)})}function h(f,p,E,m){let F=new b(E,m);f.appendWhere(new y(p,"=",F))}function v(f,p,E,m){let F=[];if("="in m){let k=new b(E,m["="]);F.push(new y(p,"=",k))}if("min"in m){let k=new b(E+"_min",m.min);F.push(new y(p,">=",k))}if("max"in m){let k=new b(E+"_max",m.max);F.push(new y(p,"<=",k))}if("like"in m){let k=new b(E+"_like",m.like);F.push(new y(p,"like",k))}if("ilike"in m){let k=new b(E+"_ilike",m.ilike);F.push(new y(p,"ilike",k))}if("in"in m){let N=m.in.map((d,w)=>new b(`${E}_in_${w}`,d));F.push(new y(p,"in",new z(new K(N))))}if("any"in m){let k=new b(E+"_any",m.any);F.push(new y(p,"=",new $(null,"any",k,null)))}if("<"in m){let k=new b(E+"_lt",m["<"]);F.push(new y(p,"<",k))}if(">"in m){let k=new b(E+"_gt",m[">"]);F.push(new y(p,">",k))}if("!="in m){let k=new b(E+"_neq",m["!="]);F.push(new y(p,"!=",k))}if("<>"in m){let k=new b(E+"_ne",m["<>"]);F.push(new y(p,"<>",k))}if("<="in m){let k=new b(E+"_le",m["<="]);F.push(new y(p,"<=",k))}if(">="in m){let k=new b(E+"_ge",m[">="]);F.push(new y(p,">=",k))}if(F.length===1)f.appendWhere(F[0]);else if(F.length>1){let k=F[0];for(let N=1;N<F.length;N++)k=new y(k,"and",F[N]);f.appendWhere(new z(k))}}return e}};var bn=class{static validate(e,t){let n=typeof e=="string"?J.parse(e):e,i=Array.isArray(t)?l=>{let u=t.find(h=>h.name===l);return u?u.columns:[]}:t,s=new Et(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 h=l.columns.filter(v=>!u.includes(v));h.length>0&&a.push(`Table '${l.name}' contains undefined columns: ${h.join(", ")}.`)}if(a.length>0)throw new Error(a.join(`
|
15
|
-
`))}};var dt=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,
|
14
|
+
Detected column names: [${n.join(", ")}]`);let a=We.parse(t);return new je({insertClause:new qe(a,n),selectQuery:e})}static buildUpdateQuery(e,t,n,i){let r=new ot(We.parse(n)),s=Array.isArray(i)?i:[i],l=new ke().collect(e),m=new G().collect(e);new ut().execute(e);for(let C of s)if(!l.some(Y=>Y.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 x=l.filter(C=>!s.includes(C.name)).map(C=>new _e(C.name,new S(d,C.name))),h=new De(x),F=new V(e.toSource(t),null),T=null;for(let C of s){let Y=new y(new S(d,C),"=",new S(t,C));T=T?new y(T,"and",Y):Y}let N=new se(T);return new pt({updateClause:r,setClause:h,fromClause:F,whereClause:N,withClause:m.length>0?new ee(!1,m):void 0})}};var ze=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 b=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 it.buildBinaryQuery([this,t],e)}appendWhereRaw(e){let t=g.parse(e);this.appendWhere(t)}appendWhere(e){this.whereClause?this.whereClause.condition=new y(this.whereClause.condition,"and",e):this.whereClause=new se(e)}appendHavingRaw(e){let t=g.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=et.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 Te(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(x=>x==p.name)){let x=new y(p.value,"=",new S([m],p.name));l?l=new y(l,"and",x):l=x,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]),$e.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 M(this),new q(e,null))}appendWith(e){let t=Array.isArray(e)?e:[e];this.withClause?this.withClause.tables.push(...t):this.withClause=new ee(!1,t),$e.normalize(this)}appendWithRaw(e,t){let n=U.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 Je().visit(i.value),a=t(s);i.value=g.parse(a)}appendWhereExpr(e,t,n){if(n&&n.upstream){let r=new tt().find(this,[e]),s=new Te,a=new Je;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 Te,r=new Je,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 _=class o extends v{static{this.kind=Symbol("BinarySelectQuery")}constructor(e,t,n){super(),this.left=e,this.operator=new L(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 L(e),this.right=t,$e.normalize(this),this}unionRaw(e){let t=U.parse(e);return this.union(t)}unionAllRaw(e){let t=U.parse(e);return this.unionAll(t)}intersectRaw(e){let t=U.parse(e);return this.intersect(t)}intersectAllRaw(e){let t=U.parse(e);return this.intersectAll(t)}exceptRaw(e){let t=U.parse(e);return this.except(t)}exceptAllRaw(e){let t=U.parse(e);return this.exceptAll(t)}toSource(e="subq"){return new A(new M(this),new q(e,null))}setParameter(e,t){return ze.set(this,e,t),this}};var ne=class extends v{static{this.kind=Symbol("ValuesQuery")}constructor(e,t=null){super(),this.tuples=e,this.columnAliases=t}toSimpleSelectQuery(){return it.buildSimpleQuery(this)}setParameter(e,t){return ze.set(this,e,t),this}};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 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=g.parseArgument(4,8,e,n);i=new st(a.value),n=a.newIndex}let r=[],s=Gt.parseItem(e,n);for(r.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let a=Gt.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}}},Gt=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=g.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 Yt=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="on"){n++;let i=g.parseFromLexeme(e,n);return n=i.newIndex,{value:new me(i.value),newIndex:n}}return null}};var Xt=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="using"){n++;let i=g.parseArgument(4,8,e,n),r=i.value;return n=i.newIndex,{value:new ge(r),newIndex:n}}return null}};var Zt=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=We.parseFromLexeme(e,n);if(n=a.newIndex,n<e.length){let u=Yt.tryParse(e,n);if(u)return{value:new he(i,a.value,u.value,s),newIndex:u.newIndex};let m=Xt.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 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 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=We.parseFromLexeme(e,n);n=i.newIndex;let r=Zt.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 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 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=g.parseFromLexeme(e,n);return{value:new se(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 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=g.parseFromLexeme(e,n),r=i.value;return n=i.newIndex,{value:r,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 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=g.parseFromLexeme(e,n);return{value:new pe(i.value),newIndex:i.newIndex}}};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 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 Se(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 Me(i),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 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=g.parseFromLexeme(e,n);return n=i.newIndex,{value:new oe(i.value),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 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 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 CommonTable definition is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t,i=nt.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=U.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 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=St.parseFromLexeme(e,n);for(r.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let a=St.parseFromLexeme(e,n);r.push(a.value),n=a.newIndex}return{value:new ee(i,r),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 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 ne(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 ye([]),newIndex:n};let r=g.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=g.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 ye(i),newIndex:n}}};var un=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=Sn.parseFromLexeme(e,n),r=i.value;return n=i.newIndex,{value:new Ke(r),newIndex:n}}},Sn=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 D(1),a="rows only",n++,{value:new Ye(i,s,a),newIndex:n};let l=g.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 Ye(i,s,a),newIndex:n}}};var cn=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=g.parseFromLexeme(e,n);return n=i.newIndex,n<e.length&&(e[n].value==="row"||e[n].value==="rows")&&n++,{value:new Qe(i.value),newIndex:n}}};var U=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 _(s,a,u.value),n=u.newIndex}else if(l==="values"){let u=this.parseValuesQuery(e,n);s=new _(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=Ht.parseFromLexeme(e,n);n=r.newIndex;let s=null;n<e.length&&e[n].value==="from"&&(s=en.parseFromLexeme(e,n),n=s.newIndex);let a=null;n<e.length&&e[n].value==="where"&&(a=tn.parseFromLexeme(e,n),n=a.newIndex);let l=null;n<e.length&&e[n].value==="group by"&&(l=nn.parseFromLexeme(e,n),n=l.newIndex);let u=null;n<e.length&&e[n].value==="having"&&(u=rn.parseFromLexeme(e,n),n=u.newIndex);let m=null;n<e.length&&e[n].value==="window"&&(m=sn.parseFromLexeme(e,n),n=m.newIndex);let w=null;n<e.length&&e[n].value==="order by"&&(w=at.parseFromLexeme(e,n),n=w.newIndex);let d=null;n<e.length&&e[n].value==="limit"&&(d=on.parseFromLexeme(e,n),n=d.newIndex);let p=null;n<e.length&&e[n].value==="offset"&&(p=cn.parseFromLexeme(e,n),n=p.newIndex);let x=null;n<e.length&&e[n].value==="fetch"&&(x=un.parseFromLexeme(e,n),n=x.newIndex);let h=null;return n<e.length&&e[n].value.toLowerCase()==="for"&&(h=an.parseFromLexeme(e,n),n=h.newIndex),{value:new b({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:x?x.value:null,forClause:h?h.value:null}),newIndex:n}}static parseValuesQuery(e,t){let n=ln.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}};var xn=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=We.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=U.parseFromLexeme(e,n);if(i)if(a.value instanceof b)a.value.withClause=i;else throw new Error("WITH clause is not supported in this context.");return n=a.newIndex,{value:new je({insertClause:new qe(r.value,s),selectQuery:a.value}),newIndex:n}}};var pn=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 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 b({selectClause:new j(s),fromClause:new V(new A(new B(null,new E(t)),null),null)});return new Z(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 W(l,u)}prepareEntityColumns(e){let t=[],n=[];return Object.entries(e.columns).forEach(([i,r])=>{t.push(new D(i)),t.push(new S(null,new E(r))),n.push(new y(new S(null,new E(r)),"is",new D(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 D(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 $(null,new L(n),new J(e),null)}buildNullCondition(e){return e.reduce((t,n)=>t?new y(t,"and",n):n)}createCaseExpression(e,t){return new re(null,new de([new fe(e,new D(null))],t))}};var mn=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(x=>{Object.values(x.entity.columns).forEach(h=>s.add(h))});let a=n.find(x=>x.aliasExpression.table.name===t)?.query;if(!a)throw new Error(`CTE not found: ${t}`);let l=new ke(null,n).collect(a),u=[],m=[];l.forEach(x=>{s.has(x.name)||(m.push(new W(new S(null,new E(x.name)),x.name)),u.push(new S(null,new E(x.name))))});for(let x of e){let h=this.buildAggregationDetailsForArrayEntity(x.entity,r.nestedEntities,new Map,r.useJsonb);m.push(new W(h.jsonAgg,x.entity.propertyName))}let w=`${o.CTE_ARRAY_PREFIX}${i}`,d=new b({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 Z(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 D(w)),s.push(new S(null,new E(d)))}),t.filter(w=>w.parentId===e.id).forEach(w=>{if(s.push(new D(w.propertyName)),w.relationshipType==="object"){let d=`${w.name.toLowerCase()}_json`;s.push(new S(null,new E(d)))}else w.relationshipType==="array"&&s.push(new S(null,new E(w.propertyName)))});let l=new $(null,new L(r),new J(s),null),u=i?"jsonb_agg":"json_agg";return{jsonAgg:new $(null,new L(u),new J([l]),null)}}};var En=class{constructor(){this.selectValueCollector=new ke(null),this.objectEntityCteBuilder=new pn,this.arrayEntityCteBuilder=new mn}validateMapping(e,t){let i=new ke().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(x=>x.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 x=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(h=>h.id===u)?.name;throw new Error(`Validation Error: Parent entity "${x}" (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 Z(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 W(l,i.rootName),m=new Z(new b({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 $(null,new L(w),new J([new S(null,new E(i.rootName))]),null);return new b({withClause:new ee(!1,r),selectClause:new j([new W(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 W(l,i.rootName),m=new Z(new b({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 b({withClause:new ee(!1,r),selectClause:new j([new W(new S(null,new E(i.rootName)),i.rootName)]),fromClause:new V(new A(new B(null,new E(s)),null),null),limitClause:new oe(new D(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 D(u)),a.push(new S(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 D(u.propertyName)),u.relationshipType==="object"){let w=`${m.name.toLowerCase()}_json`;a.push(new S(null,new E(w)))}else u.relationshipType==="array"&&a.push(new S(null,new E(u.propertyName)))}),new $(null,new L(s),new J(a),null)}};var xt=class{constructor(e,t){this.name=e,this.columns=t}},Et=class{constructor(e=null){this.tableColumnResolver=e;this.tableSchemas=[];this.visitedNodes=new Set;this.commonTables=[];this.running=!1;this.handlers=new Map,this.handlers.set(b.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(_.kind,t=>this.visitBinarySelectQuery(t))}collect(e){return this.visit(e),this.tableSchemas}visit(e){if(this.running){this.visitNode(e);return}this.reset(),this.running=!0;try{if(!(e instanceof b||e instanceof _))throw new Error(`Unsupported SQL component type for schema collection. Received: ${e.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let t=new G;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 xt(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 Te(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 M&&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 M&&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 xt(e,r);this.tableSchemas.push(s)}};var gn=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=U.parse(e));let n=new tt(this.tableColumnResolver,this.options),i=new Te(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 F=h.map(f=>f.column||d).filter((f,C,Y)=>Y.indexOf(f)===C),T=null;for(let f of F){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 [${F.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 F=h.map(f=>f.column||d).filter((f,C,Y)=>Y.indexOf(f)===C),T=null;for(let f of F){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 [${F.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 F=n.find(e,h);if(F.length===0)throw new Error(`Explicit column '${h}' not found in query`);for(let T of F){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 x=n.find(e,d);if(x.length===0)throw new Error(`Column '${d}' not found in query`);for(let h of x){let F=i.collect(h),T=F.find(Y=>r(Y.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 Y=p.column;if(Y){let ie=F.find(O=>r(O.name)===r(Y));ie&&(f=ie.value,C=Y)}}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,x,h,F,T){for(let N=0;N<x.length;N++){let f=x[N],C=f.column||p,Y=F.find(O=>h(O.name)===h(C));if(!Y)throw new Error(`Column '${C}' not found in query for AND condition`);let ie=Y.value;if("="in f&&f["="]!==void 0){let O=`${p}_and_${N}_eq`,P=new k(O,f["="]);d.appendWhere(new y(ie,"=",P))}if("min"in f&&f.min!==void 0){let O=`${p}_and_${N}_min`,P=new k(O,f.min);d.appendWhere(new y(ie,">=",P))}if("max"in f&&f.max!==void 0){let O=`${p}_and_${N}_max`,P=new k(O,f.max);d.appendWhere(new y(ie,"<=",P))}if("like"in f&&f.like!==void 0){let O=`${p}_and_${N}_like`,P=new k(O,f.like);d.appendWhere(new y(ie,"like",P))}if("ilike"in f&&f.ilike!==void 0){let O=`${p}_and_${N}_ilike`,P=new k(O,f.ilike);d.appendWhere(new y(ie,"ilike",P))}if("in"in f&&f.in!==void 0){let P=f.in.map((R,K)=>new k(`${p}_and_${N}_in_${K}`,R));d.appendWhere(new y(ie,"in",new z(new J(P))))}if("any"in f&&f.any!==void 0){let O=`${p}_and_${N}_any`,P=new k(O,f.any);d.appendWhere(new y(ie,"=",new $(null,"any",P,null)))}if("<"in f&&f["<"]!==void 0){let O=`${p}_and_${N}_lt`,P=new k(O,f["<"]);d.appendWhere(new y(ie,"<",P))}if(">"in f&&f[">"]!==void 0){let O=`${p}_and_${N}_gt`,P=new k(O,f[">"]);d.appendWhere(new y(ie,">",P))}if("!="in f&&f["!="]!==void 0){let O=`${p}_and_${N}_neq`,P=new k(O,f["!="]);d.appendWhere(new y(ie,"!=",P))}if("<>"in f&&f["<>"]!==void 0){let O=`${p}_and_${N}_ne`,P=new k(O,f["<>"]);d.appendWhere(new y(ie,"<>",P))}if("<="in f&&f["<="]!==void 0){let O=`${p}_and_${N}_le`,P=new k(O,f["<="]);d.appendWhere(new y(ie,"<=",P))}if(">="in f&&f[">="]!==void 0){let O=`${p}_and_${N}_ge`,P=new k(O,f[">="]);d.appendWhere(new y(ie,">=",P))}}}function l(d,p,x,h,F,T){let N=[];for(let f=0;f<x.length;f++){let C=x[f],Y=C.column||p,ie=F.find(R=>h(R.name)===h(Y));if(!ie)throw new Error(`Column '${Y}' not found in query for OR condition`);let O=ie.value,P=[];if("="in C&&C["="]!==void 0){let R=`${p}_or_${f}_eq`,K=new k(R,C["="]);P.push(new y(O,"=",K))}if("min"in C&&C.min!==void 0){let R=`${p}_or_${f}_min`,K=new k(R,C.min);P.push(new y(O,">=",K))}if("max"in C&&C.max!==void 0){let R=`${p}_or_${f}_max`,K=new k(R,C.max);P.push(new y(O,"<=",K))}if("like"in C&&C.like!==void 0){let R=`${p}_or_${f}_like`,K=new k(R,C.like);P.push(new y(O,"like",K))}if("ilike"in C&&C.ilike!==void 0){let R=`${p}_or_${f}_ilike`,K=new k(R,C.ilike);P.push(new y(O,"ilike",K))}if("in"in C&&C.in!==void 0){let K=C.in.map((Fn,Nn)=>new k(`${p}_or_${f}_in_${Nn}`,Fn));P.push(new y(O,"in",new z(new J(K))))}if("any"in C&&C.any!==void 0){let R=`${p}_or_${f}_any`,K=new k(R,C.any);P.push(new y(O,"=",new $(null,"any",K,null)))}if("<"in C&&C["<"]!==void 0){let R=`${p}_or_${f}_lt`,K=new k(R,C["<"]);P.push(new y(O,"<",K))}if(">"in C&&C[">"]!==void 0){let R=`${p}_or_${f}_gt`,K=new k(R,C[">"]);P.push(new y(O,">",K))}if("!="in C&&C["!="]!==void 0){let R=`${p}_or_${f}_neq`,K=new k(R,C["!="]);P.push(new y(O,"!=",K))}if("<>"in C&&C["<>"]!==void 0){let R=`${p}_or_${f}_ne`,K=new k(R,C["<>"]);P.push(new y(O,"<>",K))}if("<="in C&&C["<="]!==void 0){let R=`${p}_or_${f}_le`,K=new k(R,C["<="]);P.push(new y(O,"<=",K))}if(">="in C&&C[">="]!==void 0){let R=`${p}_or_${f}_ge`,K=new k(R,C[">="]);P.push(new y(O,">=",K))}if(P.length>0){let R=P[0];for(let K=1;K<P.length;K++)R=new y(R,"and",P[K]);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,x){Object.keys(d).forEach(h=>{if(!p.includes(h))throw new Error(`Unsupported operator '${h}' for state key '${x}'`)})}function m(d,p,x,h){let F=new k(x,h);d.appendWhere(new y(p,"=",F))}function w(d,p,x,h){let F=[];if("="in h){let T=new k(x,h["="]);F.push(new y(p,"=",T))}if("min"in h){let T=new k(x+"_min",h.min);F.push(new y(p,">=",T))}if("max"in h){let T=new k(x+"_max",h.max);F.push(new y(p,"<=",T))}if("like"in h){let T=new k(x+"_like",h.like);F.push(new y(p,"like",T))}if("ilike"in h){let T=new k(x+"_ilike",h.ilike);F.push(new y(p,"ilike",T))}if("in"in h){let N=h.in.map((f,C)=>new k(`${x}_in_${C}`,f));F.push(new y(p,"in",new z(new J(N))))}if("any"in h){let T=new k(x+"_any",h.any);F.push(new y(p,"=",new $(null,"any",T,null)))}if("<"in h){let T=new k(x+"_lt",h["<"]);F.push(new y(p,"<",T))}if(">"in h){let T=new k(x+"_gt",h[">"]);F.push(new y(p,">",T))}if("!="in h){let T=new k(x+"_neq",h["!="]);F.push(new y(p,"!=",T))}if("<>"in h){let T=new k(x+"_ne",h["<>"]);F.push(new y(p,"<>",T))}if("<="in h){let T=new k(x+"_le",h["<="]);F.push(new y(p,"<=",T))}if(">="in h){let T=new k(x+"_ge",h[">="]);F.push(new y(p,">=",T))}if(F.length===1)d.appendWhere(F[0]);else if(F.length>1){let T=F[0];for(let N=1;N<F.length;N++)T=new y(T,"and",F[N]);d.appendWhere(new z(T))}}return e}};var bn=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=U.parse(e)),!(e instanceof b))throw new Error("Complex queries are not supported for ORDER BY removal");return new b({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=U.parse(e)),!(e instanceof b))throw new Error("Complex queries are not supported for sorting");let i=new Te(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 x=new Ee(w,d,p);r.push(x)}let s=[];e.orderByClause?s=[...e.orderByClause.order,...r]:s=r;let a=s.length>0?new ue(s):null;return new b({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 kn=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=U.parse(e)),!(e instanceof b))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 D(t.pageSize)),r=n>0?new Qe(new D(n)):null;return new b({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=U.parse(e)),!(e instanceof b))throw new Error("Complex queries are not supported for pagination removal");return new b({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 Tn=class{static validate(e,t){let n=typeof e=="string"?U.parse(e):e,i=Array.isArray(t)?l=>{let u=t.find(m=>m.name===l);return u?u.columns:[]}:t,s=new Et(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 dt=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,m])=>{a[u]=m.jsonAlias||m.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 ii(o){return new dt(o)}function ri(o){return new dt(o).createTableColumnResolver()}function si(o,e){return new dt(o).createJsonMapping(e)}
|
16
16
|
//# sourceMappingURL=index.min.js.map
|