rawsql-ts 0.11.17-beta → 0.11.19-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index.min.js +16 -16
- package/dist/esm/index.min.js.map +4 -4
- package/dist/esm/src/index.d.ts +2 -0
- package/dist/esm/src/index.js +2 -0
- package/dist/esm/src/index.js.map +1 -1
- package/dist/esm/src/transformers/CTERenamer.d.ts +144 -0
- package/dist/esm/src/transformers/CTERenamer.js +342 -0
- package/dist/esm/src/transformers/CTERenamer.js.map +1 -0
- package/dist/esm/src/transformers/ColumnReferenceCollector.d.ts +162 -0
- package/dist/esm/src/transformers/ColumnReferenceCollector.js +464 -0
- package/dist/esm/src/transformers/ColumnReferenceCollector.js.map +1 -0
- package/dist/esm/tsconfig.browser.tsbuildinfo +1 -1
- package/dist/index.min.js +16 -16
- package/dist/index.min.js.map +4 -4
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +2 -0
- package/dist/src/index.js.map +1 -1
- package/dist/src/transformers/CTERenamer.d.ts +144 -0
- package/dist/src/transformers/CTERenamer.js +346 -0
- package/dist/src/transformers/CTERenamer.js.map +1 -0
- package/dist/src/transformers/ColumnReferenceCollector.d.ts +162 -0
- package/dist/src/transformers/ColumnReferenceCollector.js +468 -0
- package/dist/src/transformers/ColumnReferenceCollector.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +3 -6
package/dist/esm/index.min.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var f=class{constructor(){this.comments=null}getKind(){return this.constructor.kind}accept(e){return e.visit(this)}toSqlString(e){return this.accept(e)}};var Ge=class extends f{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var Fe=class extends f{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},_=class extends f{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},v=class extends f{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 Re(or(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},U=class extends f{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,r,i=null){super(),this.qualifiedName=new Re(e,t),this.argument=n,this.over=r,this.withinGroup=i}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},ir=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(ir||{}),sr=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(sr||{}),ct=class extends f{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},pt=class extends f{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},je=class extends f{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Qe=class extends f{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},re=class extends f{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new V(e),this.expression=t}},y=class extends f{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new V(t),this.right=n}},G=class extends f{static{this.kind=Symbol("LiteralExpression")}constructor(e,t){super(),this.value=e,this.isDollarString=t}},T=class extends f{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new V(e),this.value=t,this.index=null}},ye=class extends f{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},we=class extends f{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},V=class extends f{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},x=class extends f{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},Z=class extends f{static{this.kind=Symbol("ParenExpression")}constructor(e){super(),this.expression=e}},ue=class extends f{static{this.kind=Symbol("CastExpression")}constructor(e,t){super(),this.input=e,this.castType=t}},le=class extends f{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},ge=class extends f{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},Se=class extends f{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},ve=class extends f{static{this.kind=Symbol("BetweenExpression")}constructor(e,t,n,r){super(),this.expression=e,this.lower=t,this.upper=n,this.negated=r}},Me=class extends f{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new V(e),this.value=new G(t)}},Ee=class extends f{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new Re(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof V?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}},be=class extends f{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}},Ye=class extends f{static{this.kind=Symbol("ArraySliceExpression")}constructor(e,t,n){super(),this.array=e,this.startIndex=t,this.endIndex=n}},Xe=class extends f{static{this.kind=Symbol("ArrayIndexExpression")}constructor(e,t){super(),this.array=e,this.index=t}};function or(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 Re=class extends f{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=or(e),typeof t=="string"?this.name=new V(t):this.name=t}toString(){let e=this.name instanceof V?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(t=>t.name).join(".")+"."+e:e}};var j=class extends f{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new x(t):null}},J=class extends f{static{this.kind=Symbol("SelectClause")}constructor(e,t=null,n=[]){super(),this.items=e,this.distinct=t,this.hints=n}},mt=class extends f{static{this.kind=Symbol("Distinct")}constructor(){super()}},dt=class extends f{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},ie=class extends f{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},Pe=class extends f{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},Ce=class extends f{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new x(e),this.expression=t}},Ze=class extends f{static{this.kind=Symbol("WindowsClause")}constructor(e){super(),this.windows=e}};var ce=class extends f{static{this.kind=Symbol("OrderByClause")}constructor(e){super(),this.order=e}},xe=class extends f{static{this.kind=Symbol("OrderByItem")}constructor(e,t,n){super(),this.value=e,this.sortDirection=t===null?"asc":t,this.nullsPosition=n}},pe=class extends f{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},me=class extends f{static{this.kind=Symbol("HavingClause")}constructor(e){super(),this.condition=e}},R=class extends f{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 Re(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof V?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof V?this.qualifiedName.name.value:this.qualifiedName.name.name}},qe=class extends f{static{this.kind=Symbol("FunctionSource")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"name"in e){let n=e;this.qualifiedName=new Re(n.namespaces,n.name)}else this.qualifiedName=new Re(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},Ue=class extends f{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},z=class extends f{static{this.kind=Symbol("SubQuerySource")}constructor(e){super(),this.query=e}},M=class extends f{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 R?this.datasource.getSourceName():null}},de=class extends f{static{this.kind=Symbol("JoinOnClause")}constructor(e){super(),this.condition=e}},Te=class extends f{static{this.kind=Symbol("JoinUsingClause")}constructor(e){super(),this.condition=e}},he=class extends f{static{this.kind=Symbol("JoinItem")}constructor(e,t,n,r){super(),this.joinType=new V(e),this.source=t,this.condition=n,this.lateral=r}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof R?this.source.table.name:null}},D=class extends f{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 R?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}},ee=class extends f{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new Y(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},ne=class extends f{static{this.kind=Symbol("WithClause")}constructor(e,t){super(),this.recursive=e,this.tables=t}},se=class extends f{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var De=class extends f{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},Ke=class extends f{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},ot=class extends f{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var Be=class extends f{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},Y=class extends f{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}},Ut=class extends f{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new x(t):t)}},He=class extends f{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof et?t:new et(t.column,t.value))}},et=class extends f{static{this.kind=Symbol("SetClauseItem")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"column"in e){let n=e,r=typeof n.column=="string"?new x(n.column):n.column;this.qualifiedName=new Re(n.namespaces,r)}else{let n=typeof e=="string"?new x(e):e;this.qualifiedName=new Re(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()}},ht=class extends f{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 R?this.source.datasource.table.name:null}},tt=class extends f{constructor(e,t){super(),this.source=e,this.columns=t.map(n=>new x(n))}};var $=(d=>(d[d.None=0]="None",d[d.Literal=1]="Literal",d[d.Operator=2]="Operator",d[d.OpenParen=4]="OpenParen",d[d.CloseParen=8]="CloseParen",d[d.Comma=16]="Comma",d[d.Dot=32]="Dot",d[d.Identifier=64]="Identifier",d[d.Command=128]="Command",d[d.Parameter=256]="Parameter",d[d.OpenBracket=512]="OpenBracket",d[d.CloseBracket=1024]="CloseBracket",d[d.Function=2048]="Function",d[d.StringSpecifier=4096]="StringSpecifier",d[d.Type=8192]="Type",d))($||{});var H=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||t===63}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||t===63}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),r=Math.min(e.length,t+5),i=e.slice(n,r),s=" ".repeat(t-n)+"^";return`${i}
|
|
1
|
+
var f=class{constructor(){this.comments=null}getKind(){return this.constructor.kind}accept(e){return e.visit(this)}toSqlString(e){return this.accept(e)}};var Ye=class extends f{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var Se=class extends f{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},K=class extends f{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},v=class extends f{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 Ve(lr(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},j=class extends f{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,r,i=null){super(),this.qualifiedName=new Ve(e,t),this.argument=n,this.over=r,this.withinGroup=i}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},or=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(or||{}),ar=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(ar||{}),dt=class extends f{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},ht=class extends f{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},Je=class extends f{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Ee=class extends f{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},te=class extends f{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new V(e),this.expression=t}},C=class extends f{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new V(t),this.right=n}},G=class extends f{static{this.kind=Symbol("LiteralExpression")}constructor(e,t){super(),this.value=e,this.isDollarString=t}},T=class extends f{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new V(e),this.value=t,this.index=null}},be=class extends f{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},xe=class extends f{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},V=class extends f{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},x=class extends f{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},H=class extends f{static{this.kind=Symbol("ParenExpression")}constructor(e){super(),this.expression=e}},ae=class extends f{static{this.kind=Symbol("CastExpression")}constructor(e,t){super(),this.input=e,this.castType=t}},ie=class extends f{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},fe=class extends f{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},Ce=class extends f{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},ye=class extends f{static{this.kind=Symbol("BetweenExpression")}constructor(e,t,n,r){super(),this.expression=e,this.lower=t,this.upper=n,this.negated=r}},We=class extends f{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new V(e),this.value=new G(t)}},Te=class extends f{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new Ve(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof V?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}},ke=class extends f{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}},Ze=class extends f{static{this.kind=Symbol("ArraySliceExpression")}constructor(e,t,n){super(),this.array=e,this.startIndex=t,this.endIndex=n}},et=class extends f{static{this.kind=Symbol("ArrayIndexExpression")}constructor(e,t){super(),this.array=e,this.index=t}};function lr(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 Ve=class extends f{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=lr(e),typeof t=="string"?this.name=new V(t):this.name=t}toString(){let e=this.name instanceof V?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(t=>t.name).join(".")+"."+e:e}};var q=class extends f{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new x(t):null}},J=class extends f{static{this.kind=Symbol("SelectClause")}constructor(e,t=null,n=[]){super(),this.items=e,this.distinct=t,this.hints=n}},ft=class extends f{static{this.kind=Symbol("Distinct")}constructor(){super()}},Ct=class extends f{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},se=class extends f{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},Qe=class extends f{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},ve=class extends f{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new x(e),this.expression=t}},_e=class extends f{static{this.kind=Symbol("WindowsClause")}constructor(e){super(),this.windows=e}};var le=class extends f{static{this.kind=Symbol("OrderByClause")}constructor(e){super(),this.order=e}},Ie=class extends f{static{this.kind=Symbol("OrderByItem")}constructor(e,t,n){super(),this.value=e,this.sortDirection=t===null?"asc":t,this.nullsPosition=n}},ue=class extends f{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},ce=class extends f{static{this.kind=Symbol("HavingClause")}constructor(e){super(),this.condition=e}},B=class extends f{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 Ve(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof V?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof V?this.qualifiedName.name.value:this.qualifiedName.name.name}},ze=class extends f{static{this.kind=Symbol("FunctionSource")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"name"in e){let n=e;this.qualifiedName=new Ve(n.namespaces,n.name)}else this.qualifiedName=new Ve(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},Ue=class extends f{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},_=class extends f{static{this.kind=Symbol("SubQuerySource")}constructor(e){super(),this.query=e}},$=class extends f{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}},pe=class extends f{static{this.kind=Symbol("JoinOnClause")}constructor(e){super(),this.condition=e}},we=class extends f{static{this.kind=Symbol("JoinUsingClause")}constructor(e){super(),this.condition=e}},me=class extends f{static{this.kind=Symbol("JoinItem")}constructor(e,t,n,r){super(),this.joinType=new V(e),this.source=t,this.condition=n,this.lateral=r}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof B?this.source.table.name:null}},D=class extends f{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}},X=class extends f{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new Z(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},ne=class extends f{static{this.kind=Symbol("WithClause")}constructor(e,t){super(),this.recursive=e,this.tables=t}},oe=class extends f{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var Le=class extends f{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},De=class extends f{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},ut=class extends f{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var Ne=class extends f{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},Z=class extends f{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}},Ut=class extends f{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new x(t):t)}},Xe=class extends f{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof tt?t:new tt(t.column,t.value))}},tt=class extends f{static{this.kind=Symbol("SetClauseItem")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"column"in e){let n=e,r=typeof n.column=="string"?new x(n.column):n.column;this.qualifiedName=new Ve(n.namespaces,r)}else{let n=typeof e=="string"?new x(e):e;this.qualifiedName=new Ve(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()}},yt=class extends f{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}},nt=class extends f{constructor(e,t){super(),this.source=e,this.columns=t.map(n=>new x(n))}};var M=(d=>(d[d.None=0]="None",d[d.Literal=1]="Literal",d[d.Operator=2]="Operator",d[d.OpenParen=4]="OpenParen",d[d.CloseParen=8]="CloseParen",d[d.Comma=16]="Comma",d[d.Dot=32]="Dot",d[d.Identifier=64]="Identifier",d[d.Command=128]="Command",d[d.Parameter=256]="Parameter",d[d.OpenBracket=512]="OpenBracket",d[d.CloseBracket=1024]="CloseBracket",d[d.Function=2048]="Function",d[d.StringSpecifier=4096]="StringSpecifier",d[d.Type=8192]="Type",d))(M||{});var Y=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||t===63}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||t===63}static isNamedParameterPrefix(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===64||t===58||t===36}};var de=class o{static getDebugPositionInfo(e,t){let n=Math.max(0,t-5),r=Math.min(e.length,t+5),i=e.slice(n,r),s=" ".repeat(t-n)+"^";return`${i}
|
|
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 r=e.charCodeAt(t);if(r!==32&&r!==9&&r!==10&&r!==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 r=e.slice(n+2,t).trim();return{newPosition:t,comment:r}}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 r=e.slice(n+2,t-2).replace(/\r/g,"").split(`
|
|
3
3
|
`);for(let i=0;i<r.length;i++)r[i]=r[i].trim();for(;r.length>0&&r[0]==="";)r.shift();for(;r.length>0&&r[r.length-1]==="";)r.pop();return{newPosition:t,comments:r}}t++}throw new Error(`Block comment is not closed. position: ${t}`)}return{newPosition:t,comments:null}}static readWhiteSpaceAndComment(e,t){let n=[],r=e.length;for(;t<r;){let i=t;if(t=o.skipWhiteSpace(e,t),t!==i)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&&!
|
|
5
|
-
${this.getDebugPositionInfo(e)}`);return this.input[e]==="."?"0"+this.input.slice(e,this.position):this.input.slice(e,this.position)}readMoneyDigit(){let e=this.position,t=!1;for(;this.canRead();){let n=this.input[this.position];if(n==="."&&!t)t=!0;else if(!(n===","&&!t)){if(!
|
|
4
|
+
${o.getDebugPositionInfo(e,t)}`);return n}static tryReadRegularIdentifier(e,t){let n=t;for(;t<e.length&&!Y.isDelimiter(e[t]);)t++;if(n===t)return null;for(;t+1<e.length&&e[t]==="["&&e[t+1]==="]";){let r=e.slice(0,n).trim();if(r===""||/[)]$/.test(r)||/\b(select|from|where|and|or|set|values|insert|update|delete)\s*$/i.test(r))break;t+=2}return{identifier:e.slice(n,t),newPosition:t}}};var re=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,r,i){let s={type:e,value:e===128||e===2||e===2048?t.toLowerCase():t,comments:n};return r!==void 0&&i!==void 0&&(s.position={startPosition:r,endPosition:i}),s}createLexemeWithPosition(e,t,n,r=null){return this.createLexeme(e,t,r,n,n+t.length)}getDebugPositionInfo(e){return de.getDebugPositionInfo(this.input,e)}};var qt=class extends re{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="*")return this.position++,this.createLexeme(64,t);let n=de.readRegularIdentifier(this.input,this.position);return this.position=n.newPosition,this.createLexeme(64,n.identifier)}};var Ae=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=de.tryReadRegularIdentifier(e,t);if(n===null)return null;let r=this.trie.pushLexeme(n.identifier.toLowerCase());if(r===0)return null;if(r===3)return{keyword:n.identifier,newPosition:n.newPosition};let i=n.identifier;if(t=de.readWhiteSpaceAndComment(e,n.newPosition).position,this.isEndOfInput(e,t))return r===2?{keyword:i,newPosition:t}:null;for(;this.canParse(e,t);){let s=r,a=de.tryReadRegularIdentifier(e,t);if(a!==null){if(r=this.trie.pushLexeme(a.identifier.toLowerCase()),r===0){if(s===2)break;return null}if(i+=" "+a.identifier,t=de.readWhiteSpaceAndComment(e,a.newPosition).position,r===3)break}else{if(s===2)break;return null}}return{keyword:i,newPosition:t}}};var Be=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 xr=[["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"]],Tr=new Be(xr),Hn=new Ae(Tr),Kt=class extends re{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)&&Y.isDigit(this.input[this.position+1]))return this.createLexeme(1,this.readDigit());if(t==="'"){let r=this.readSingleQuotedString(!1);return this.createLexeme(1,r)}if(Y.isDigit(t))return this.createLexeme(1,this.readDigit());if(t==="$"&&this.isDollarQuotedString())return this.createLexeme(1,this.readDollarQuotedString());if(t==="$"&&this.canRead(1)&&Y.isDigit(this.input[this.position+1])){let r=this.position+1,i=!1;for(;r<this.input.length&&(Y.isDigit(this.input[r])||this.input[r]===","||this.input[r]===".");){if(this.input[r]==="."||this.input[r]===","){i=!0;break}r++}if(i){let s=this.position;this.position++;let a=this.readMoneyDigit();return this.createLexeme(1,"$"+a)}}if((t==="+"||t==="-")&&this.determineSignOrOperator(e)==="sign"){let r=t;this.position++;let i=this.position;for(;this.canRead()&&Y.isWhitespace(this.input[this.position]);)this.position++;if(this.canRead()&&(Y.isDigit(this.input[this.position])||this.input[this.position]==="."&&this.canRead(1)&&Y.isDigit(this.input[this.position+1])))return this.createLexeme(1,r==="-"?r+this.readDigit():this.readDigit());this.position=i-1}return null}tryReadKeyword(){let e=Hn.parse(this.input,this.position);return e?(this.position=e.newPosition,this.createLexeme(1,e.keyword)):null}determineSignOrOperator(e){return e===null?"sign":e.type&1||e.type&64||e.type&256||e.type&8?"operator":"sign"}readDigit(){let e=this.position,t=!1,n=!1;if(this.canRead(1)&&this.input[this.position]==="0"&&"xbo".includes(this.input[this.position+1].toLowerCase())){let r=this.input[this.position+1].toLowerCase();this.position+=2;let i=r==="x";for(;this.canRead();){let s=this.input[this.position];if(Y.isDigit(s)||i&&Y.isHexChar(s))this.position++;else break}return this.input.slice(e,this.position)}for(this.input[e]==="."&&(t=!0,this.position++);this.canRead();){let r=this.input[this.position];if(r==="."&&!t)t=!0;else if((r==="e"||r==="E")&&!n)n=!0,this.canRead(1)&&(this.input[this.position+1]==="+"||this.input[this.position+1]==="-")&&this.position++;else if(!Y.isDigit(r))break;this.position++}if(e===this.position)throw new Error(`Unexpected character. position: ${e}
|
|
5
|
+
${this.getDebugPositionInfo(e)}`);return this.input[e]==="."?"0"+this.input.slice(e,this.position):this.input.slice(e,this.position)}readMoneyDigit(){let e=this.position,t=!1;for(;this.canRead();){let n=this.input[this.position];if(n==="."&&!t)t=!0;else if(!(n===","&&!t)){if(!Y.isDigit(n))break}this.position++}if(e===this.position)throw new Error(`Unexpected character. position: ${e}
|
|
6
6
|
${this.getDebugPositionInfo(e)}`);return this.input.slice(e,this.position)}readSingleQuotedString(e){let t=this.position,n=!1;for(this.read("'");this.canRead();){let r=this.input[this.position];if(this.position++,r==="\\"&&this.canRead(1)){this.position++;continue}else if(r==="'"){n=!0;break}}if(n===!1)throw new Error(`Single quote is not closed. position: ${t}
|
|
7
|
-
${this.getDebugPositionInfo(t)}`);return e?this.input.slice(t,this.position):this.input.slice(t+1,this.position-1)}isDollarQuotedString(){if(!this.canRead(1))return!1;if(this.input[this.position+1]==="$")return!0;let e=this.position+1;for(;e<this.input.length;){let t=this.input[e];if(t==="$")return!0;if(!this.isAlphanumeric(t)&&t!=="_")return!1;e++}return!1}readDollarQuotedString(){let e=this.position;this.position++;let t="";for(;this.canRead()&&this.input[this.position]!=="$";)t+=this.input[this.position],this.position++;if(!this.canRead())throw new Error(`Unexpected end of input while reading dollar-quoted string tag at position ${e}`);this.position++;let n="$"+t+"$",r=n,i="";for(;this.canRead();){if(this.input.substring(this.position,this.position+r.length)===r)return this.position+=r.length,n+i+r;i+=this.input[this.position],this.position++}throw new Error(`Unclosed dollar-quoted string starting at position ${e}. Expected closing tag: ${r}`)}isAlphanumeric(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}};var Kt=class extends te{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 r=this.input.slice(n,this.position);if(r.length===0)throw new Error("Empty parameter name is not allowed: found ${} at position "+(n-2));return this.position++,this.createLexeme(256,"${"+r+"}")}let t=this.input[this.position];if(H.isNamedParameterPrefix(t)){if(this.canRead(1)&&H.isOperatorSymbol(this.input[this.position+1])||t===":"&&this.isInArraySliceContext()||t==="$"&&this.isDollarQuotedString())return null;if(t==="$"&&this.canRead(1)&&H.isDigit(this.input[this.position+1])){let i=this.position+1,s=!1;for(;i<this.input.length&&(H.isDigit(this.input[i])||this.input[i]===","||this.input[i]===".");){if(this.input[i]==="."||this.input[i]===","){s=!0;break}i++}if(s)return null}this.position++;let n=this.position;for(;this.canRead()&&!H.isDelimiter(this.input[this.position]);)this.position++;let r=this.input.slice(n,this.position);return this.createLexeme(256,t+r)}if(t==="?"){if(this.canRead(1)){let n=this.input[this.position+1];if(n==="|"||n==="&")return null}return e&&(e.type&64||e.type&1)?null:(this.position++,this.createLexeme(256,t))}return null}isInArraySliceContext(){let e=this.position-1,t=0,n=0;for(;e>=0;){let r=this.input[e];if(r==="]")t++;else if(r==="["){if(t--,t<0){if(e>0){let i=this.input[e-1];if(/[a-zA-Z0-9_)\]]/.test(i))return!0}if(e===0)return!1;break}}else r===")"?n++:r==="("&&n--;e--}return!1}isDollarQuotedString(){if(!this.canRead(1))return!1;if(this.input[this.position+1]==="$")return!0;let e=this.position+1;for(;e<this.input.length;){let t=this.input[e];if(t==="$")return!0;if(!this.isAlphanumeric(t)&&t!=="_")return!1;e++}return!1}isAlphanumeric(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}};var _t=class o extends te{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 zt=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 r of this.readers)if(n=r.tryRead(t),n){this.position=r.getPosition();break}for(let r of this.readers)r.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 br=new Le([["and"],["or"],["is"],["is","not"],["is","distinct","from"],["is","not","distinct","from"],["like"],["ilike"],["in"],["exists"],["between"],["not","like"],["not","ilike"],["not","in"],["not","exists"],["not","between"],["escape"],["uescape"],["similar","to"],["not","similar","to"],["similar"],["placing"],["rlike"],["regexp"],["mod"],["xor"],["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"]]),xr=new Le([["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"]]),Tr=new Oe(br),kr=new Oe(xr);var Gt=class extends te{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(H.isOperatorSymbol(t)){let r=this.position;for(;this.canRead()&&H.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 i=this.input.slice(r,this.position);return this.createLexeme(2,i)}let n=kr.parse(this.input,this.position);return n!==null?(this.position=n.newPosition,this.createLexeme(8258,n.keyword)):(n=Tr.parse(this.input,this.position),n!==null?(this.position=n.newPosition,this.createLexeme(2,n.keyword)):null)}};var Ir=new Le([["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"]]),Nr=new Le([["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"],["within","group"],["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"]]),Pr=new Oe(Nr),Gn=new Oe(Ir),Ht=class extends te{tryRead(e){if(this.isEndOfInput())return null;let t=Gn.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(128,t.keyword);let n=Pr.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 r=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(r,this.position-2).trim()+" */");this.position++}throw new Error(`Block comment is not closed. position: ${this.position}`)}return null}};var Or=new Set(["e'","E'","x'","X'","b'","B'"]),Lr=new Set(["u&'","U&'"]),Yt=class extends te{tryRead(e){let t=this.position;return this.canRead(1)&&Or.has(this.input.slice(t,t+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(t,this.position))):this.canRead(2)&&Lr.has(this.input.slice(t,t+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(t,this.position))):null}};var Ar=new Le([["grouping","sets"],["array"]]),Fr=new Oe(Ar),Xt=class extends te{tryRead(e){if(this.isEndOfInput())return null;let t=Fr.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(2048,t.keyword);let n=oe.tryReadRegularIdentifier(this.input,this.position);if(!n)return null;this.position=n.newPosition;var r=oe.readWhiteSpaceAndComment(this.input,this.position).position-this.position;return this.canRead(r)&&this.input[this.position+r]==="("?this.createLexeme(2048,n.identifier):null}};var Qr=new Le([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),Rr=new Oe(Qr),Zt=class extends te{tryRead(e){if(this.isEndOfInput())return null;let t=Rr.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=oe.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 en=class extends te{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==="["&&this.isSqlServerBracketIdentifier(e)){let n=this.readEscapedIdentifier("]");return this.createLexeme(64,n)}return null}isSqlServerBracketIdentifier(e){if(e?.value==="array")return!1;let t=this.position+1,n=t;for(;n<this.input.length&&this.input[n]!=="]";){let i=this.input[n];if(i===":"||i===","||i==="+"||i==="-"||i==="*"||i==="/"||i==="("||i===")")return!1;n++}if(n>=this.input.length)return!1;let r=this.input.slice(t,n).trim();return r===""?!1:/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$/.test(r)}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}
|
|
8
|
-
${this.getDebugPositionInfo(t)}`);return this.position++,this.input.slice(t+1,this.position-1)}};var P=class{constructor(e){this.input=e,this.position=0,this.readerManager=new
|
|
9
|
-
${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&&i.push(...l.lines):((i.length>0||l.lines.length>0)&&this.addCommentsToToken(a,i,l.lines),i=[]),t[n++]=a,s=a}if(i.length>0&&n>0){let a=t[n-1];a.comments===null&&(a.comments=[]),a.comments.push(...i)}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 ke=class o{static parseFromLexeme(e,t){let{identifiers:n,newIndex:r}=o.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:i,name:s}=o.extractNamespacesAndName(n),a=0;return r>t&&(a=e[r-1].type),{namespaces:i,name:new x(s),newIndex:r,lastTokenType:a}}static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The name is complete but additional tokens were found.`);return{namespaces:r.namespaces,name:r.name}}static parseEscapedOrDotSeparatedIdentifiers(e,t){let n=t,r=[];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(r.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)r.push(e[n].value),n++;else if(e[n].type&2048)r.push(e[n].value),n++;else if(e[n].type&8192)r.push(e[n].value),n++;else if(e[n].value==="*"){r.push(e[n].value),n++;break}if(n<e.length&&e[n].type&32)n++;else break}return{identifiers:r,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 tn=class{static parseFromLexeme(e,t){let{namespaces:n,name:r,newIndex:i}=ke.parseFromLexeme(e,t);return{value:new v(n,r),newIndex:i}}};var Pt=class{static parseFromLexeme(e,t){let n=t,r=e[n].value,i,s=zn.parse(r.toLowerCase(),0);if(s){let a=new V(s.keyword);return n++,{value:a,newIndex:n}}if(/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(r))return i=Number(r),n++,{value:new G(i),newIndex:n};{let a=/^\$[^$]*\$[\s\S]*\$[^$]*\$$/.test(r);return a?i=r:r.startsWith("'")&&r.endsWith("'")?i=r.slice(1,-1):i=r,n++,{value:new G(i,a),newIndex:n}}}};var nn=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 r=A.parseFromLexeme(e,n);if(n=r.newIndex,n>=e.length||e[n].type!==8)throw new Error(`Expected ')' at index ${n}, but found ${e[n].value}`);return n++,{value:new Fe(r.value),newIndex:n}}else{let r=k.parseArgument(4,8,e,t);return n=r.newIndex,{value:new Z(r.value),newIndex:n}}}};var rn=class{static parseFromLexeme(e,t){let n=t;if(n<e.length&&e[n].type&2){let r=e[n].value;if(n++,r==="*")return{value:new v(null,"*"),newIndex:n};let i=k.parseFromLexeme(e,n);return n=i.newIndex,{value:new re(r,i.value),newIndex:n}}throw new Error(`Invalid unary expression at index ${t}: ${e[t].value}`)}};var sn=class{static parseFromLexeme(e,t){let n=t,r=e[n].value;r.startsWith("${")&&r.endsWith("}")?r=r.slice(2,-1):r=r.slice(1);let i=new T(r);return n++,{value:i,newIndex:n}}};var on=class{static parseFromLexeme(e,t){let n=t,r=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 i=e[n].value;return n++,{value:new Me(r,i),newIndex:n}}};var an=class{static parseFromLexeme(e,t){let n=t,r=e[n];return r.value==="case"?(n++,this.parseCaseExpression(e,n)):r.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 r=e[n].value;n++;let i=k.parseFromLexeme(e,n);return{value:new re(r,i.value),newIndex:i.newIndex}}throw new Error(`Invalid modifier unary expression at index ${n}, Lexeme: ${e[n].value}`)}static parseCaseExpression(e,t){let n=t,r=k.parseFromLexeme(e,n);n=r.newIndex;let i=this.parseSwitchCaseArgument(e,n,[]);return n=i.newIndex,{value:new le(r.value,i.value),newIndex:n}}static parseCaseWhenExpression(e,t){let n=t,r=this.parseCaseConditionValuePair(e,n);n=r.newIndex;let i=[r.value],s=this.parseSwitchCaseArgument(e,n,i);return n=s.newIndex,{value:new le(null,s.value),newIndex:n}}static parseSwitchCaseArgument(e,t,n){let r=t,i=[...n],s=null;for(;r<e.length&&this.isCommandWithValue(e[r],"when");){r++;let l=this.parseCaseConditionValuePair(e,r);r=l.newIndex,i.push(l.value)}if(r<e.length&&this.isCommandWithValue(e[r],"else")){r++;let l=k.parseFromLexeme(e,r);s=l.value,r=l.newIndex}if(r<e.length&&this.isCommandWithValue(e[r],"end"))r++;else throw new Error(`The CASE expression requires 'end' keyword at the end (index ${r})`);if(i.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${r})`);return{value:new ye(i,s),newIndex:r}}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,r=k.parseFromLexeme(e,n);if(n=r.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 i=k.parseFromLexeme(e,n);return n=i.newIndex,{value:new we(r.value,i.value),newIndex:n}}};var nt=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The ORDER BY clause is complete but there are additional tokens.`);return r.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 r=[],i=this.parseItem(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=this.parseItem(e,n);r.push(s.value),n=s.newIndex}if(r.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 ce(r),newIndex:n}}static parseItem(e,t){let n=t,r=k.parseFromLexeme(e,n),i=r.value;if(n=r.newIndex,n>=e.length)return{value:i,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:i,newIndex:n}:{value:new xe(i,s,a),newIndex:n}}};var ln=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The PARTITION BY clause is complete but there are additional tokens.`);return r.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 r=[],i=k.parseFromLexeme(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=k.parseFromLexeme(e,n);r.push(s.value),n=s.newIndex}if(r.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 r.length===1?{value:new Pe(r[0]),newIndex:n}:{value:new Pe(new _(r)),newIndex:n}}};var ft=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The window frame expression is complete but there are additional tokens.`);return r.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 r=null,i=null,s=null;if(n<e.length&&e[n].value==="partition by"){let a=ln.parseFromLexeme(e,n);r=a.value,n=a.newIndex}if(n<e.length&&e[n].value==="order by"){let a=nt.parseFromLexeme(e,n);i=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 Qe(r,i,s),newIndex:n}}static isFrameTypeKeyword(e){let t=e;return t==="rows"||t==="range"||t==="groups"}static parseFrameSpec(e,t){let n=t,r=e[n].value,i;switch(r){case"rows":i="rows";break;case"range":i="range";break;case"groups":i="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 je(i,a,u),newIndex:n}}else{let s=this.parseFrameBoundary(e,n),a=s.value;return n=s.newIndex,{value:new je(i,a,null),newIndex:n}}}static parseFrameBoundary(e,t){let n=t;if(n<e.length&&e[n].type&128){let r=e[n].value,i;switch(r){case"current row":i="current row";break;case"unbounded preceding":i="unbounded preceding";break;case"unbounded following":i="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 ct(i),newIndex:n+1}}else if(n<e.length&&e[n].type&1){let r=k.parseFromLexeme(e,n);if(n=r.newIndex,n<e.length&&e[n].type&128){let i=e[n].value,s;if(i==="preceding")s=!1;else if(i==="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 pt(r.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 Ot=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The OVER expression is complete but there are additional tokens.`);return r.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 r=e[n].value;return n++,{value:new x(r),newIndex:n}}if(e[n].type&4)return ft.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 Ve=class o extends Error{constructor(t,n,r){super(t);this.index=n;this.context=r;this.name="ParseError"}static fromUnparsedLexemes(t,n,r){let i=Math.max(0,n-2),s=Math.min(t.length,n+3),a=t.slice(i,s).map((u,c)=>{let m=c+i===n?">":" ",h=$[u.type]||u.type;return`${m} ${c+i}:${u.value} [${h}]`}).join(`
|
|
7
|
+
${this.getDebugPositionInfo(t)}`);return e?this.input.slice(t,this.position):this.input.slice(t+1,this.position-1)}isDollarQuotedString(){if(!this.canRead(1))return!1;if(this.input[this.position+1]==="$")return!0;let e=this.position+1;for(;e<this.input.length;){let t=this.input[e];if(t==="$")return!0;if(!this.isAlphanumeric(t)&&t!=="_")return!1;e++}return!1}readDollarQuotedString(){let e=this.position;this.position++;let t="";for(;this.canRead()&&this.input[this.position]!=="$";)t+=this.input[this.position],this.position++;if(!this.canRead())throw new Error(`Unexpected end of input while reading dollar-quoted string tag at position ${e}`);this.position++;let n="$"+t+"$",r=n,i="";for(;this.canRead();){if(this.input.substring(this.position,this.position+r.length)===r)return this.position+=r.length,n+i+r;i+=this.input[this.position],this.position++}throw new Error(`Unclosed dollar-quoted string starting at position ${e}. Expected closing tag: ${r}`)}isAlphanumeric(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}};var _t=class extends re{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 r=this.input.slice(n,this.position);if(r.length===0)throw new Error("Empty parameter name is not allowed: found ${} at position "+(n-2));return this.position++,this.createLexeme(256,"${"+r+"}")}let t=this.input[this.position];if(Y.isNamedParameterPrefix(t)){if(this.canRead(1)&&Y.isOperatorSymbol(this.input[this.position+1])||t===":"&&this.isInArraySliceContext()||t==="$"&&this.isDollarQuotedString())return null;if(t==="$"&&this.canRead(1)&&Y.isDigit(this.input[this.position+1])){let i=this.position+1,s=!1;for(;i<this.input.length&&(Y.isDigit(this.input[i])||this.input[i]===","||this.input[i]===".");){if(this.input[i]==="."||this.input[i]===","){s=!0;break}i++}if(s)return null}this.position++;let n=this.position;for(;this.canRead()&&!Y.isDelimiter(this.input[this.position]);)this.position++;let r=this.input.slice(n,this.position);return this.createLexeme(256,t+r)}if(t==="?"){if(this.canRead(1)){let n=this.input[this.position+1];if(n==="|"||n==="&")return null}return e&&(e.type&64||e.type&1)?null:(this.position++,this.createLexeme(256,t))}return null}isInArraySliceContext(){let e=this.position-1,t=0,n=0;for(;e>=0;){let r=this.input[e];if(r==="]")t++;else if(r==="["){if(t--,t<0){if(e>0){let i=this.input[e-1];if(/[a-zA-Z0-9_)\]]/.test(i))return!0}if(e===0)return!1;break}}else r===")"?n++:r==="("&&n--;e--}return!1}isDollarQuotedString(){if(!this.canRead(1))return!1;if(this.input[this.position+1]==="$")return!0;let e=this.position+1;for(;e<this.input.length;){let t=this.input[e];if(t==="$")return!0;if(!this.isAlphanumeric(t)&&t!=="_")return!1;e++}return!1}isAlphanumeric(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}};var zt=class o extends re{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 Gt=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 r of this.readers)if(n=r.tryRead(t),n){this.position=r.getPosition();break}for(let r of this.readers)r.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 kr=new Be([["and"],["or"],["is"],["is","not"],["is","distinct","from"],["is","not","distinct","from"],["like"],["ilike"],["in"],["exists"],["between"],["not","like"],["not","ilike"],["not","in"],["not","exists"],["not","between"],["escape"],["uescape"],["similar","to"],["not","similar","to"],["similar"],["placing"],["rlike"],["regexp"],["mod"],["xor"],["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"]]),Ir=new Be([["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"]]),Nr=new Ae(kr),Pr=new Ae(Ir);var Ht=class extends re{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(Y.isOperatorSymbol(t)){let r=this.position;for(;this.canRead()&&Y.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 i=this.input.slice(r,this.position);return this.createLexeme(2,i)}let n=Pr.parse(this.input,this.position);return n!==null?(this.position=n.newPosition,this.createLexeme(8258,n.keyword)):(n=Nr.parse(this.input,this.position),n!==null?(this.position=n.newPosition,this.createLexeme(2,n.keyword)):null)}};var Or=new Be([["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"]]),Fr=new Be([["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"],["within","group"],["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"]]),Qr=new Ae(Fr),Yn=new Ae(Or),Yt=class extends re{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(128,t.keyword);let n=Qr.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 r=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(r,this.position-2).trim()+" */");this.position++}throw new Error(`Block comment is not closed. position: ${this.position}`)}return null}};var Lr=new Set(["e'","E'","x'","X'","b'","B'"]),Ar=new Set(["u&'","U&'"]),Xt=class extends re{tryRead(e){let t=this.position;return this.canRead(1)&&Lr.has(this.input.slice(t,t+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(t,this.position))):this.canRead(2)&&Ar.has(this.input.slice(t,t+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(t,this.position))):null}};var Br=new Be([["grouping","sets"],["array"]]),Rr=new Ae(Br),Zt=class extends re{tryRead(e){if(this.isEndOfInput())return null;let t=Rr.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(2048,t.keyword);let n=de.tryReadRegularIdentifier(this.input,this.position);if(!n)return null;this.position=n.newPosition;var r=de.readWhiteSpaceAndComment(this.input,this.position).position-this.position;return this.canRead(r)&&this.input[this.position+r]==="("?this.createLexeme(2048,n.identifier):null}};var Vr=new Be([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),$r=new Ae(Vr),en=class extends re{tryRead(e){if(this.isEndOfInput())return null;let t=$r.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=de.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 tn=class extends re{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==="["&&this.isSqlServerBracketIdentifier(e)){let n=this.readEscapedIdentifier("]");return this.createLexeme(64,n)}return null}isSqlServerBracketIdentifier(e){if(e?.value==="array")return!1;let t=this.position+1,n=t;for(;n<this.input.length&&this.input[n]!=="]";){let i=this.input[n];if(i===":"||i===","||i==="+"||i==="-"||i==="*"||i==="/"||i==="("||i===")")return!1;n++}if(n>=this.input.length)return!1;let r=this.input.slice(t,n).trim();return r===""?!1:/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$/.test(r)}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}
|
|
8
|
+
${this.getDebugPositionInfo(t)}`);return this.position++,this.input.slice(t+1,this.position-1)}};var P=class{constructor(e){this.input=e,this.position=0,this.readerManager=new Gt(e).register(new tn(e)).register(new _t(e)).register(new Xt(e)).register(new Kt(e)).register(new zt(e)).register(new Yt(e)).register(new Ht(e)).register(new en(e)).register(new Zt(e)).register(new qt(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,r=this.readComment(),i=r.lines;this.position=r.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}
|
|
9
|
+
${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&&i.push(...l.lines):((i.length>0||l.lines.length>0)&&this.addCommentsToToken(a,i,l.lines),i=[]),t[n++]=a,s=a}if(i.length>0&&n>0){let a=t[n-1];a.comments===null&&(a.comments=[]),a.comments.push(...i)}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 de.readWhiteSpaceAndComment(this.input,this.position)}getDebugPositionInfo(e){return de.getDebugPositionInfo(this.input,e)}};var Pe=class o{static parseFromLexeme(e,t){let{identifiers:n,newIndex:r}=o.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:i,name:s}=o.extractNamespacesAndName(n),a=0;return r>t&&(a=e[r-1].type),{namespaces:i,name:new x(s),newIndex:r,lastTokenType:a}}static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The name is complete but additional tokens were found.`);return{namespaces:r.namespaces,name:r.name}}static parseEscapedOrDotSeparatedIdentifiers(e,t){let n=t,r=[];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(r.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)r.push(e[n].value),n++;else if(e[n].type&2048)r.push(e[n].value),n++;else if(e[n].type&8192)r.push(e[n].value),n++;else if(e[n].value==="*"){r.push(e[n].value),n++;break}if(n<e.length&&e[n].type&32)n++;else break}return{identifiers:r,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 nn=class{static parseFromLexeme(e,t){let{namespaces:n,name:r,newIndex:i}=Pe.parseFromLexeme(e,t);return{value:new v(n,r),newIndex:i}}};var Ot=class{static parseFromLexeme(e,t){let n=t,r=e[n].value,i,s=Hn.parse(r.toLowerCase(),0);if(s){let a=new V(s.keyword);return n++,{value:a,newIndex:n}}if(/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(r))return i=Number(r),n++,{value:new G(i),newIndex:n};{let a=/^\$[^$]*\$[\s\S]*\$[^$]*\$$/.test(r);return a?i=r:r.startsWith("'")&&r.endsWith("'")?i=r.slice(1,-1):i=r,n++,{value:new G(i,a),newIndex:n}}}};var rn=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 r=Q.parseFromLexeme(e,n);if(n=r.newIndex,n>=e.length||e[n].type!==8)throw new Error(`Expected ')' at index ${n}, but found ${e[n].value}`);return n++,{value:new Se(r.value),newIndex:n}}else{let r=k.parseArgument(4,8,e,t);return n=r.newIndex,{value:new H(r.value),newIndex:n}}}};var sn=class{static parseFromLexeme(e,t){let n=t;if(n<e.length&&e[n].type&2){let r=e[n].value;if(n++,r==="*")return{value:new v(null,"*"),newIndex:n};let i=k.parseFromLexeme(e,n);return n=i.newIndex,{value:new te(r,i.value),newIndex:n}}throw new Error(`Invalid unary expression at index ${t}: ${e[t].value}`)}};var on=class{static parseFromLexeme(e,t){let n=t,r=e[n].value;r.startsWith("${")&&r.endsWith("}")?r=r.slice(2,-1):r=r.slice(1);let i=new T(r);return n++,{value:i,newIndex:n}}};var an=class{static parseFromLexeme(e,t){let n=t,r=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 i=e[n].value;return n++,{value:new We(r,i),newIndex:n}}};var ln=class{static parseFromLexeme(e,t){let n=t,r=e[n];return r.value==="case"?(n++,this.parseCaseExpression(e,n)):r.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 r=e[n].value;n++;let i=k.parseFromLexeme(e,n);return{value:new te(r,i.value),newIndex:i.newIndex}}throw new Error(`Invalid modifier unary expression at index ${n}, Lexeme: ${e[n].value}`)}static parseCaseExpression(e,t){let n=t,r=k.parseFromLexeme(e,n);n=r.newIndex;let i=this.parseSwitchCaseArgument(e,n,[]);return n=i.newIndex,{value:new ie(r.value,i.value),newIndex:n}}static parseCaseWhenExpression(e,t){let n=t,r=this.parseCaseConditionValuePair(e,n);n=r.newIndex;let i=[r.value],s=this.parseSwitchCaseArgument(e,n,i);return n=s.newIndex,{value:new ie(null,s.value),newIndex:n}}static parseSwitchCaseArgument(e,t,n){let r=t,i=[...n],s=null;for(;r<e.length&&this.isCommandWithValue(e[r],"when");){r++;let l=this.parseCaseConditionValuePair(e,r);r=l.newIndex,i.push(l.value)}if(r<e.length&&this.isCommandWithValue(e[r],"else")){r++;let l=k.parseFromLexeme(e,r);s=l.value,r=l.newIndex}if(r<e.length&&this.isCommandWithValue(e[r],"end"))r++;else throw new Error(`The CASE expression requires 'end' keyword at the end (index ${r})`);if(i.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${r})`);return{value:new be(i,s),newIndex:r}}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,r=k.parseFromLexeme(e,n);if(n=r.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 i=k.parseFromLexeme(e,n);return n=i.newIndex,{value:new xe(r.value,i.value),newIndex:n}}};var rt=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The ORDER BY clause is complete but there are additional tokens.`);return r.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 r=[],i=this.parseItem(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=this.parseItem(e,n);r.push(s.value),n=s.newIndex}if(r.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 le(r),newIndex:n}}static parseItem(e,t){let n=t,r=k.parseFromLexeme(e,n),i=r.value;if(n=r.newIndex,n>=e.length)return{value:i,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:i,newIndex:n}:{value:new Ie(i,s,a),newIndex:n}}};var un=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The PARTITION BY clause is complete but there are additional tokens.`);return r.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 r=[],i=k.parseFromLexeme(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=k.parseFromLexeme(e,n);r.push(s.value),n=s.newIndex}if(r.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 r.length===1?{value:new Qe(r[0]),newIndex:n}:{value:new Qe(new K(r)),newIndex:n}}};var wt=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The window frame expression is complete but there are additional tokens.`);return r.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 r=null,i=null,s=null;if(n<e.length&&e[n].value==="partition by"){let a=un.parseFromLexeme(e,n);r=a.value,n=a.newIndex}if(n<e.length&&e[n].value==="order by"){let a=rt.parseFromLexeme(e,n);i=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 Ee(r,i,s),newIndex:n}}static isFrameTypeKeyword(e){let t=e;return t==="rows"||t==="range"||t==="groups"}static parseFrameSpec(e,t){let n=t,r=e[n].value,i;switch(r){case"rows":i="rows";break;case"range":i="range";break;case"groups":i="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 Je(i,a,u),newIndex:n}}else{let s=this.parseFrameBoundary(e,n),a=s.value;return n=s.newIndex,{value:new Je(i,a,null),newIndex:n}}}static parseFrameBoundary(e,t){let n=t;if(n<e.length&&e[n].type&128){let r=e[n].value,i;switch(r){case"current row":i="current row";break;case"unbounded preceding":i="unbounded preceding";break;case"unbounded following":i="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 dt(i),newIndex:n+1}}else if(n<e.length&&e[n].type&1){let r=k.parseFromLexeme(e,n);if(n=r.newIndex,n<e.length&&e[n].type&128){let i=e[n].value,s;if(i==="preceding")s=!1;else if(i==="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 ht(r.value,s),newIndex:n}}else throw new Error(`Syntax error at position ${n}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`)}throw new Error(`Syntax error at position ${n}: Expected a valid frame boundary component.`)}};var Ft=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The OVER expression is complete but there are additional tokens.`);return r.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 r=e[n].value;return n++,{value:new x(r),newIndex:n}}if(e[n].type&4)return wt.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 $e=class o extends Error{constructor(t,n,r){super(t);this.index=n;this.context=r;this.name="ParseError"}static fromUnparsedLexemes(t,n,r){let i=Math.max(0,n-2),s=Math.min(t.length,n+3),a=t.slice(i,s).map((u,c)=>{let m=c+i===n?">":" ",h=M[u.type]||u.type;return`${m} ${c+i}:${u.value} [${h}]`}).join(`
|
|
10
10
|
`),l=`${r} Unparsed lexeme remains at index ${n}: ${t[n].value}
|
|
11
11
|
Context:
|
|
12
|
-
${a}`;return new o(l,n,a)}};var $e=class{static parseArrayExpression(e,t){let n=t;if(n+1<e.length&&e[n+1].type&512){n++;let r=k.parseArgument(512,1024,e,n);return n=r.newIndex,{value:new ge(r.value),newIndex:n}}else if(n+1<e.length&&e[n+1].type&4){n++,n++;let r=A.parseFromLexeme(e,n);return n=r.newIndex,n++,{value:new Se(r.value),newIndex:n}}throw new Error(`Invalid ARRAY syntax at index ${n}, expected ARRAY[... or ARRAY(...)`)}static parseFromLexeme(e,t){let n=t,r=e[n];return r.value==="array"?this.parseArrayExpression(e,n):r.value==="substring"||r.value==="overlay"?this.parseKeywordFunction(e,n,[{key:"from",required:!1},{key:"for",required:!1}]):r.value==="cast"?this.parseKeywordFunction(e,n,[{key:"as",required:!0}]):r.value==="trim"?this.parseKeywordFunction(e,n,[{key:"from",required:!1}]):this.parseFunctionCall(e,n)}static tryParseBinaryExpression(e,t,n,r=!0,i=!0){let s=t;if(s<e.length&&e[s].type&2){let a=e[s].value.toLowerCase();if(!r&&a==="and"||!i&&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 c=this.parseTypeValue(e,s);return s=c.newIndex,{value:new ue(n,c.value),newIndex:s}}let l=k.parseFromLexeme(e,s);return s=l.newIndex,{value:new y(n,a,l.value),newIndex:s}}return null}static parseBetweenExpression(e,t,n,r){let i=t,s=k.parseFromLexeme(e,i,!1);if(i=s.newIndex,i<e.length&&e[i].type&2&&e[i].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${i}`);i++;let a=this.parseBetweenUpperBound(e,i);return i=a.newIndex,{value:new ve(n,s.value,a.value,r),newIndex:i}}static parseBetweenUpperBound(e,t){return k.parseFromLexeme(e,t,!1,!1)}static parseFunctionCall(e,t){let n=t,r=ke.parseFromLexeme(e,n),i=r.namespaces,s=r.name;if(n=r.newIndex,n<e.length&&e[n].type&4){let a=k.parseArgument(4,8,e,n);n=a.newIndex;let l=null;if(n<e.length&&e[n].value==="within group"){let u=this.parseWithinGroupClause(e,n);l=u.value,n=u.newIndex}if(n<e.length&&e[n].value==="over"){let u=Ot.parseFromLexeme(e,n);return n=u.newIndex,{value:new U(i,s.name,a.value,u.value,l),newIndex:n}}else return{value:new U(i,s.name,a.value,null,l),newIndex:n}}else throw Ve.fromUnparsedLexemes(e,n,`Expected opening parenthesis after function name '${s.name}'.`)}static parseKeywordFunction(e,t,n){let r=t,i=ke.parseFromLexeme(e,r),s=i.namespaces,a=i.name;if(r=i.newIndex,r<e.length&&e[r].type&4){r++;let l=k.parseFromLexeme(e,r),u=l.value;if(r=l.newIndex,r<e.length&&e[r].type&16)return this.parseFunctionCall(e,t);for(let{key:c,required:m}of n)if(r<e.length&&e[r].type&128&&e[r].value===c)if(r++,r<e.length&&e[r].type&8192){let h=this.parseTypeValue(e,r);u=new y(u,c,h.value),r=h.newIndex}else{let h=k.parseFromLexeme(e,r);u=new y(u,c,h.value),r=h.newIndex}else if(m)throw Ve.fromUnparsedLexemes(e,r,`Keyword '${c}' is required for ${a.name} function.`);if(r<e.length&&e[r].type&8){r++;let c=null;if(r<e.length&&e[r].value==="within group"){let m=this.parseWithinGroupClause(e,r);c=m.value,r=m.newIndex}if(r<e.length&&e[r].value==="over"){r++;let m=Ot.parseFromLexeme(e,r);return r=m.newIndex,{value:new U(s,a.name,u,m.value,c),newIndex:r}}else return{value:new U(s,a.name,u,null,c),newIndex:r}}else throw Ve.fromUnparsedLexemes(e,r,`Missing closing parenthesis for function '${a.name}'.`)}else throw Ve.fromUnparsedLexemes(e,r,`Missing opening parenthesis for function '${a.name}'.`)}static parseTypeValue(e,t){let n=t,{namespaces:r,name:i,newIndex:s}=ke.parseFromLexeme(e,n);if(n=s,n<e.length&&e[n].type&4){let a=k.parseArgument(4,8,e,n);return n=a.newIndex,{value:new Ee(r,new V(i.name),a.value),newIndex:n}}else return{value:new Ee(r,new V(i.name)),newIndex:n}}static parseWithinGroupClause(e,t){let n=t;if(n>=e.length||e[n].value!=="within group")throw new Error(`Expected 'WITHIN GROUP' at index ${n}`);if(n++,n>=e.length||!(e[n].type&4))throw new Error(`Expected '(' after 'WITHIN GROUP' at index ${n}`);n++;let r=nt.parseFromLexeme(e,n);if(n=r.newIndex,n>=e.length||!(e[n].type&8))throw new Error(`Expected ')' after WITHIN GROUP ORDER BY clause at index ${n}`);return n++,{value:r.value,newIndex:n}}};var at=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,"similar to":10,"not similar to":10,in:10,"not in":10,is:10,"is not":10,"->":10,"->>":10,"#>":10,"#>>":10,"@>":10,"<@":10,"?":10,"?|":10,"?&":10,"~":10,"~*":10,"!~":10,"!~*":10,rlike:10,regexp:10,mod:30,xor:2,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","similar to","in","not in","->","->>","#>","#>>","@>","<@","?","?|","?&","~","~*","!~","!~*","rlike","regexp"].includes(t)}};var k=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw Ve.fromUnparsedLexemes(n,r.newIndex,"[ValueParser]");return r.value}static parseFromLexeme(e,t,n=!0,r=!0){return this.parseExpressionWithPrecedence(e,t,0,n,r)}static parseExpressionWithPrecedence(e,t,n,r=!0,i=!0){let s=t,a=e[s].comments,l=this.parseItem(e,s);l.value.comments=a,s=l.newIndex;let u=l.value,c=this.parseArrayAccess(e,s,u);for(u=c.value,s=c.newIndex;s<e.length&&e[s].type&2;){let h=e[s].value;if(!r&&h.toLowerCase()==="and"||!i&&h.toLowerCase()==="or")break;let w=at.getPrecedence(h);if(w<n)break;if(s++,at.isBetweenOperator(h)){let C=$e.parseBetweenExpression(e,s,u,h.toLowerCase().includes("not"));u=C.value,s=C.newIndex;continue}if(h==="::"){let C=$e.parseTypeValue(e,s);u=new ue(u,C.value),s=C.newIndex;continue}let b=w+1,d=this.parseExpressionWithPrecedence(e,s,b,r,i);s=d.newIndex,u=new y(u,h,d.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 r=e[n];if(r.type&64&&r.type&2&&r.type&8192){if(n+1<e.length&&e[n+1].type&4)if(this.isTypeConstructor(e,n+1,r.value)){let a=$e.parseTypeValue(e,n);return{value:a.value,newIndex:a.newIndex}}else return $e.parseFromLexeme(e,n);let i=tn.parseFromLexeme(e,n);if(i.newIndex>=e.length)return i;if(e[i.newIndex].type&1){let a=Pt.parseFromLexeme(e,i.newIndex);return{value:new re(e[n].value,a.value),newIndex:a.newIndex}}return i}else if(r.type&64){let{namespaces:i,name:s,newIndex:a}=ke.parseFromLexeme(e,n);if(e[a-1].type&2048)return $e.parseFromLexeme(e,n);if(e[a-1].type&8192)if(a<e.length&&e[a].type&4)if(this.isTypeConstructor(e,a,s.name)){let u=$e.parseTypeValue(e,n);return{value:u.value,newIndex:u.newIndex}}else return $e.parseFromLexeme(e,n);else return{value:new Ee(i,s),newIndex:a};return{value:new v(i,s),newIndex:a}}else{if(r.type&1)return Pt.parseFromLexeme(e,n);if(r.type&4)return nn.parseFromLexeme(e,n);if(r.type&2048)return $e.parseFromLexeme(e,n);if(r.type&2)return rn.parseFromLexeme(e,n);if(r.type&256)return sn.parseFromLexeme(e,n);if(r.type&4096)return on.parseFromLexeme(e,n);if(r.type&128)return an.parseFromLexeme(e,n);if(r.type&512){let{namespaces:i,name:s,newIndex:a}=ke.parseFromLexeme(e,n);return{value:new v(i,s),newIndex:a}}else if(r.type&8192){let{namespaces:i,name:s,newIndex:a}=ke.parseFromLexeme(e,n);if(a<e.length&&e[a].type&4)if(this.isTypeConstructor(e,a,s.name)){let l=$e.parseTypeValue(e,n);return{value:l.value,newIndex:l.newIndex}}else return $e.parseFromLexeme(e,n);else return{value:new Ee(i,s),newIndex:a}}}throw Ve.fromUnparsedLexemes(e,n,"[ValueParser] Invalid lexeme.")}static parseArgument(e,t,n,r){let i=r,s=[];if(i<n.length&&n[i].type===e){if(i++,i<n.length&&n[i].type===t)return i++,{value:new _([]),newIndex:i};if(i<n.length&&n[i].value==="*"){let l=new v(null,"*");if(i++,i<n.length&&n[i].type===t)return i++,{value:l,newIndex:i};throw Ve.fromUnparsedLexemes(n,i,"Expected closing parenthesis after wildcard '*'.")}let a=this.parseFromLexeme(n,i);for(i=a.newIndex,s.push(a.value);i<n.length&&n[i].type&16;){i++;let l=this.parseFromLexeme(n,i);i=l.newIndex,s.push(l.value)}if(i<n.length&&n[i].type===t)return i++,s.length===1?{value:s[0],newIndex:i}:{value:new _(s),newIndex:i};throw Ve.fromUnparsedLexemes(n,i,"Missing closing parenthesis.")}throw Ve.fromUnparsedLexemes(n,r,"Expected opening parenthesis.")}static parseArrayAccess(e,t,n){let r=t,i=n;for(;r<e.length&&e[r].type&512&&!this.isSqlServerBracketIdentifier(e,r);){if(r++,r>=e.length)throw new Error(`Expected array index or slice after '[' at index ${r-1}`);if(e[r].type&1024)throw new Error(`Empty array access brackets not supported at index ${r}`);let s=null,a=!1;if(e[r].type&2&&e[r].value===":")a=!0,r++;else{let l=at.getPrecedence(":"),u=this.parseExpressionWithPrecedence(e,r,l+1);s=u.value,r=u.newIndex,r<e.length&&e[r].type&2&&e[r].value===":"&&(a=!0,r++)}if(a){let l=null;if(r<e.length&&!(e[r].type&1024)){let u=at.getPrecedence(":"),c=this.parseExpressionWithPrecedence(e,r,u+1);l=c.value,r=c.newIndex}if(r>=e.length||!(e[r].type&1024))throw new Error(`Expected ']' after array slice at index ${r}`);r++,i=new Ye(i,s,l)}else{if(!s){let l=this.parseFromLexeme(e,r);s=l.value,r=l.newIndex}if(r>=e.length||!(e[r].type&1024))throw new Error(`Expected ']' after array index at index ${r}`);r++,i=new Xe(i,s)}}return{value:i,newIndex:r}}static isSqlServerBracketIdentifier(e,t){let n=t+1;if(n>=e.length)return!1;for(;n<e.length&&!(e[n].type&1024);){let s=e[n];if(s.type&64||s.type&2&&s.value==="."){n++;continue}return!1}if(n>=e.length)return!1;let r=n;if(r+1<e.length){let s=e[r+1];if(s.type&2&&s.value===".")return!0}n=t+1;let i=!0;for(;n<r;){let s=e[n];if(!(s.type&64||s.type&2&&s.value===".")){i=!1;break}n++}return i}static isTypeConstructor(e,t,n){let r=["NUMERIC","DECIMAL","VARCHAR","CHAR","CHARACTER","TIMESTAMP","TIME","INTERVAL"],i=n.toUpperCase();if(r.includes(i))return!0;if(i==="DATE"){let s=t+1;if(s<e.length){let a=e[s];return!(a.type&1&&typeof a.value=="string"&&isNaN(Number(a.value)))}}return!1}};var X=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(E.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(K.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ae.kind,e=>this.visitValuesQuery(e)),this.handlers.set(ne.kind,e=>this.visitWithClause(e)),this.handlers.set(ee.kind,e=>this.visitCommonTable(e)),this.handlers.set(j.kind,e=>this.visitSelectItem(e)),this.handlers.set(x.kind,e=>this.visitIdentifierString(e)),this.handlers.set(V.kind,e=>this.visitRawString(e)),this.handlers.set(v.kind,e=>this.visitColumnReference(e)),this.handlers.set(T.kind,e=>this.visitParameterExpression(e)),this.handlers.set(G.kind,e=>this.visitLiteralValue(e)),this.handlers.set(M.kind,e=>this.visitSourceExpression(e)),this.handlers.set(R.kind,e=>this.visitTableSource(e)),this.handlers.set(qe.kind,e=>this.visitFunctionSource(e)),this.handlers.set(Ue.kind,e=>this.visitParenSource(e)),this.handlers.set(z.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Fe.kind,e=>this.visitInlineQuery(e)),this.handlers.set(D.kind,e=>this.visitFromClause(e)),this.handlers.set(he.kind,e=>this.visitJoinClause(e)),this.handlers.set(de.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Te.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(ie.kind,e=>this.visitWhereClause(e)),this.handlers.set(Z.kind,e=>this.visitParenExpression(e)),this.handlers.set(y.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(re.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(le.kind,e=>this.visitCaseExpression(e)),this.handlers.set(we.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(ye.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ve.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(U.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ge.kind,e=>this.visitArrayExpression(e)),this.handlers.set(Se.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(be.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ue.kind,e=>this.visitCastExpression(e)),this.handlers.set(Qe.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(je.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Ee.kind,e=>this.visitTypeValue(e)),this.handlers.set(_.kind,e=>this.visitValueList(e)),this.handlers.set(Me.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(J.kind,e=>this.visitSelectClause(e)),this.handlers.set(pe.kind,e=>this.visitGroupByClause(e)),this.handlers.set(me.kind,e=>this.visitHavingClause(e)),this.handlers.set(ce.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Ce.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(se.kind,e=>this.visitLimitClause(e)),this.handlers.set(Be.kind,e=>this.visitForClause(e)),this.handlers.set(xe.kind,e=>this.visitOrderByItem(e)),this.handlers.set(Pe.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",r=e.constructor?.name||"unknown";throw new Error(`[CTECollector] No handler for ${r} 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 Ct=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(E.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(K.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ae.kind,e=>this.visitValuesQuery(e)),this.handlers.set(j.kind,e=>this.visitSelectItem(e)),this.handlers.set(x.kind,e=>this.visitIdentifierString(e)),this.handlers.set(V.kind,e=>this.visitRawString(e)),this.handlers.set(v.kind,e=>this.visitColumnReference(e)),this.handlers.set(T.kind,e=>this.visitParameterExpression(e)),this.handlers.set(G.kind,e=>this.visitLiteralValue(e)),this.handlers.set(M.kind,e=>this.visitSourceExpression(e)),this.handlers.set(R.kind,e=>this.visitTableSource(e)),this.handlers.set(Ue.kind,e=>this.visitParenSource(e)),this.handlers.set(z.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Fe.kind,e=>this.visitInlineQuery(e)),this.handlers.set(D.kind,e=>this.visitFromClause(e)),this.handlers.set(he.kind,e=>this.visitJoinClause(e)),this.handlers.set(de.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Te.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(ie.kind,e=>this.visitWhereClause(e)),this.handlers.set(Z.kind,e=>this.visitParenExpression(e)),this.handlers.set(y.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(re.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(le.kind,e=>this.visitCaseExpression(e)),this.handlers.set(we.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(ye.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ve.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(U.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ge.kind,e=>this.visitArrayExpression(e)),this.handlers.set(Se.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(be.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ue.kind,e=>this.visitCastExpression(e)),this.handlers.set(Qe.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(je.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Ee.kind,e=>this.visitTypeValue(e)),this.handlers.set(_.kind,e=>this.visitValueList(e)),this.handlers.set(Ye.kind,e=>this.visitArraySliceExpression(e)),this.handlers.set(Xe.kind,e=>this.visitArrayIndexExpression(e)),this.handlers.set(Me.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(J.kind,e=>this.visitSelectClause(e)),this.handlers.set(pe.kind,e=>this.visitGroupByClause(e)),this.handlers.set(me.kind,e=>this.visitHavingClause(e)),this.handlers.set(ce.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Ce.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(se.kind,e=>this.visitLimitClause(e)),this.handlers.set(Be.kind,e=>this.visitForClause(e)),this.handlers.set(xe.kind,e=>this.visitOrderByItem(e)),this.handlers.set(Pe.kind,e=>this.visitPartitionByClause(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",r=e.constructor?.name||"unknown";throw new Error(`[CTEDisabler] No handler for ${r} 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 Ze(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 ae(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(r=>this.visit(r)):null;return new D(t,n)}visitSubQuerySource(e){let t=this.visit(e.query);return new z(t)}visitInlineQuery(e){let t=this.visit(e.selectQuery);return new Fe(t)}visitJoinClause(e){let t=this.visit(e.source),n=e.condition?this.visit(e.condition):null;return new he(e.joinType.value,t,n,e.lateral)}visitJoinOnClause(e){let t=this.visit(e.condition);return new de(t)}visitJoinUsingClause(e){let t=this.visit(e.condition);return new Te(t)}visitWhereClause(e){let t=this.visit(e.condition);return new ie(t)}visitGroupByClause(e){let t=e.grouping.map(n=>this.visit(n));return new pe(t)}visitHavingClause(e){let t=this.visit(e.condition);return new me(t)}visitOrderByClause(e){let t=e.order.map(n=>this.visit(n));return new ce(t)}visitWindowFrameClause(e){let t=this.visit(e.expression);return new Ce(e.name.name,t)}visitLimitClause(e){let t=this.visit(e.value);return new se(t)}visitForClause(e){return new Be(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 re(e.operator.value,t)}visitCaseExpression(e){let t=e.condition?this.visit(e.condition):null,n=this.visit(e.switchCase);return new le(t,n)}visitSwitchCaseArgument(e){let t=e.cases.map(r=>this.visit(r)),n=e.elseValue?this.visit(e.elseValue):null;return new ye(t,n)}visitCaseKeyValuePair(e){let t=this.visit(e.key),n=this.visit(e.value);return new we(t,n)}visitBetweenExpression(e){let t=this.visit(e.expression),n=this.visit(e.lower),r=this.visit(e.upper);return new ve(t,n,r,e.negated)}visitFunctionCall(e){let t=e.argument?this.visit(e.argument):null,n=e.over?this.visit(e.over):null;return new U(e.namespaces,e.name,t,n)}visitArrayExpression(e){let t=this.visit(e.expression);return new ge(t)}visitArrayQueryExpression(e){let t=this.visit(e.query);return new Se(t)}visitTupleExpression(e){let t=e.values.map(n=>this.visit(n));return new be(t)}visitCastExpression(e){let t=this.visit(e.input),n=this.visit(e.castType);return new ue(t,n)}visitTypeValue(e){let t=e.argument?this.visit(e.argument):null;return new Ee(e.namespaces,e.name,t)}visitSelectItem(e){let t=this.visit(e.value);return new j(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 M(t,n)}visitTableSource(e){return e}visitParenSource(e){let t=this.visit(e.source);return new Ue(t)}visitParameterExpression(e){return e}visitWindowFrameExpression(e){let t=e.partition?this.visit(e.partition):null,n=e.order?this.visit(e.order):null,r=e.frameSpec?this.visit(e.frameSpec):null;return new Qe(t,n,r)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new xe(t,e.sortDirection,e.nullsPosition)}visitValueList(e){let t=e.values.map(n=>this.visit(n));return new _(t)}visitArraySliceExpression(e){return e}visitArrayIndexExpression(e){return e}visitStringSpecifierExpression(e){return e}visitPartitionByClause(e){let t=this.visit(e.value);return new Pe(t)}};var yt=class{constructor(e=!0){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.cteNames=new Set;this.isRootVisit=!0;this.selectableOnly=e,this.handlers=new Map,this.handlers.set(E.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(K.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ae.kind,t=>this.visitValuesQuery(t)),this.handlers.set(ne.kind,t=>this.visitWithClause(t)),this.handlers.set(ee.kind,t=>this.visitCommonTable(t)),this.handlers.set(D.kind,t=>this.visitFromClause(t)),this.handlers.set(he.kind,t=>this.visitJoinClause(t)),this.handlers.set(de.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(Te.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(M.kind,t=>this.visitSourceExpression(t)),this.handlers.set(R.kind,t=>this.visitTableSource(t)),this.handlers.set(qe.kind,t=>this.visitFunctionSource(t)),this.handlers.set(Ue.kind,t=>this.visitParenSource(t)),this.handlers.set(z.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(Fe.kind,t=>this.visitInlineQuery(t)),e||(this.handlers.set(ie.kind,t=>this.visitWhereClause(t)),this.handlers.set(pe.kind,t=>this.visitGroupByClause(t)),this.handlers.set(me.kind,t=>this.visitHavingClause(t)),this.handlers.set(ce.kind,t=>this.visitOrderByClause(t)),this.handlers.set(Ce.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(se.kind,t=>this.visitLimitClause(t)),this.handlers.set(De.kind,t=>this.visitOffsetClause(t)),this.handlers.set(Ke.kind,t=>this.visitFetchClause(t)),this.handlers.set(Be.kind,t=>this.visitForClause(t)),this.handlers.set(xe.kind,t=>this.visitOrderByItem(t)),this.handlers.set(J.kind,t=>this.visitSelectClause(t)),this.handlers.set(j.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(re.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(le.kind,t=>this.visitCaseExpression(t)),this.handlers.set(we.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(ye.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(ve.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(U.kind,t=>this.visitFunctionCall(t)),this.handlers.set(ge.kind,t=>this.visitArrayExpression(t)),this.handlers.set(Se.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(be.kind,t=>this.visitTupleExpression(t)),this.handlers.set(ue.kind,t=>this.visitCastExpression(t)),this.handlers.set(_.kind,t=>this.visitValueList(t)),this.handlers.set(Me.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 V?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof V?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 X;t.visit(e);let n=t.getCommonTables();for(let r of n)this.cteNames.add(r.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 rt=class extends f{static{this.kind=Symbol("HintClause")}constructor(e){super(),this.hintContent=e}getFullHint(){return"/*+ "+this.hintContent+" */"}static isHintClause(e){let t=e.trim();return t.length>=5&&t.substring(0,3)==="/*+"&&t.substring(t.length-2)==="*/"}static extractHintContent(e){let t=e.trim();if(!this.isHintClause(t))throw new Error("Not a valid hint clause: "+e);return t.slice(3,-2).trim()}};var p=class{constructor(e,t="",n=""){this.innerTokens=[];this.type=e,this.text=t,this.containerType=n}};var it=class{static collect(e){let t=[];function n(r){if(!(!r||typeof r!="object")){r.constructor&&r.constructor.kind===T.kind&&t.push(r);for(let i of Object.keys(r)){let s=r[i];Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&s.constructor&&s.constructor.kind&&n(s)}}}return n(e),t}};var un=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var cn=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 wt=class extends f{static{this.kind=Symbol("UpdateQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.updateClause=e.updateClause,this.setClause=e.setClause instanceof He?e.setClause:new He(e.setClause),this.whereClause=e.whereClause??null,this.fromClause=e.fromClause??null,this.returningClause=e.returning??null}};var Ae=class o{constructor(e=null,t=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=e??null,this.commonTableCollector=new X,this.commonTables=[],this.initialCommonTables=t,this.handlers=new Map,this.handlers.set(E.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(J.kind,n=>this.visitSelectClause(n)),this.handlers.set(M.kind,n=>this.visitSourceExpression(n)),this.handlers.set(D.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(r=>r.name==="*");if(t.length===0)return;if(this.selectValues.some(r=>r.value instanceof v&&r.value.namespaces===null)){e.fromClause&&this.processFromClause(e.fromClause,!0),this.selectValues=this.selectValues.filter(r=>r.name!=="*");return}let n=t.filter(r=>r.value instanceof v&&r.value.namespaces).map(r=>r.value.getNamespace());if(e.fromClause){let r=e.fromClause.getSourceAliasName();if(r&&n.includes(r)&&this.processFromClause(e.fromClause,!1),e.fromClause.joins)for(let i of e.fromClause.joins){let s=i.getSourceAliasName();s&&n.includes(s)&&this.processJoinClause(i)}}this.selectValues=this.selectValues.filter(r=>r.name!=="*")}processFromClause(e,t){if(e){let n=e.getSourceAliasName();if(this.processSourceExpression(n,e.source),e.joins&&t)for(let r of e.joins)this.processJoinClause(r)}}processJoinClause(e){let t=e.getSourceAliasName();this.processSourceExpression(t,e.source)}processSourceExpression(e,t){let n=this.commonTables.find(r=>r.aliasExpression.table.name===e);if(n){let r=this.commonTables.filter(a=>a.aliasExpression.table.name!==e);new o(this.tableColumnResolver,r).collect(n.query).forEach(a=>{this.addSelectValueAsUnique(a.name,new v(e?[e]:null,a.name))})}else new o(this.tableColumnResolver,this.commonTables).collect(t).forEach(s=>{this.addSelectValueAsUnique(s.name,new v(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 v){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 v(t?[t]:null,n.name))});return}else if(e.datasource instanceof R){if(this.tableColumnResolver){let t=e.datasource.getSourceName();this.tableColumnResolver(t).forEach(n=>{this.addSelectValueAsUnique(n,new v([t],n))})}return}else if(e.datasource instanceof z){let t=e.getAliasName();new o(this.tableColumnResolver,this.commonTables).collect(e.datasource.query).forEach(i=>{this.addSelectValueAsUnique(i.name,new v(t?[t]:null,i.name))});return}else if(e.datasource instanceof Ue)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 gt=class extends f{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 Ae().collect(this.asSelectQuery).map(r=>new j(r.value,r.name)):e=[new j(new V("*"))],new E({selectClause:new J(e),fromClause:new D(new M(new R(null,this.tableName.name),null),null)})}getCountQuery(){return new E({selectClause:new J([new j(new U(null,"count",new v(null,"*"),null))]),fromClause:new D(new M(new R(null,this.tableName.name),null),null)})}};var ur={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"}},pn=class o{constructor(e){this.handlers=new Map;this.index=1;e?.preset&&(e={...e.preset,...e}),this.parameterDecorator=new cn({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 un({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.handlers.set(_.kind,t=>this.visitValueList(t)),this.handlers.set(v.kind,t=>this.visitColumnReference(t)),this.handlers.set(Re.kind,t=>this.visitQualifiedName(t)),this.handlers.set(U.kind,t=>this.visitFunctionCall(t)),this.handlers.set(re.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(y.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(G.kind,t=>this.visitLiteralValue(t)),this.handlers.set(T.kind,t=>this.visitParameterExpression(t)),this.handlers.set(ye.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(we.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(V.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(ue.kind,t=>this.visitCastExpression(t)),this.handlers.set(le.kind,t=>this.visitCaseExpression(t)),this.handlers.set(ge.kind,t=>this.visitArrayExpression(t)),this.handlers.set(Se.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(Ye.kind,t=>this.visitArraySliceExpression(t)),this.handlers.set(Xe.kind,t=>this.visitArrayIndexExpression(t)),this.handlers.set(ve.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(Me.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(Ee.kind,t=>this.visitTypeValue(t)),this.handlers.set(be.kind,t=>this.visitTupleExpression(t)),this.handlers.set(Fe.kind,t=>this.visitInlineQuery(t)),this.handlers.set(Qe.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(je.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(ct.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(pt.kind,t=>this.visitWindowFrameBoundaryValue(t)),this.handlers.set(Pe.kind,t=>this.visitPartitionByClause(t)),this.handlers.set(ce.kind,t=>this.visitOrderByClause(t)),this.handlers.set(xe.kind,t=>this.visitOrderByItem(t)),this.handlers.set(j.kind,t=>this.visitSelectItem(t)),this.handlers.set(J.kind,t=>this.visitSelectClause(t)),this.handlers.set(mt.kind,t=>this.visitDistinct(t)),this.handlers.set(dt.kind,t=>this.visitDistinctOn(t)),this.handlers.set(rt.kind,t=>this.visitHintClause(t)),this.handlers.set(R.kind,t=>this.visitTableSource(t)),this.handlers.set(qe.kind,t=>this.visitFunctionSource(t)),this.handlers.set(M.kind,t=>this.visitSourceExpression(t)),this.handlers.set(Y.kind,t=>this.visitSourceAliasExpression(t)),this.handlers.set(D.kind,t=>this.visitFromClause(t)),this.handlers.set(he.kind,t=>this.visitJoinClause(t)),this.handlers.set(de.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(Te.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(ie.kind,t=>this.visitWhereClause(t)),this.handlers.set(pe.kind,t=>this.visitGroupByClause(t)),this.handlers.set(me.kind,t=>this.visitHavingClause(t)),this.handlers.set(Ze.kind,t=>this.visitWindowClause(t)),this.handlers.set(Ce.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(se.kind,t=>this.visitLimitClause(t)),this.handlers.set(De.kind,t=>this.visitOffsetClause(t)),this.handlers.set(Ke.kind,t=>this.visitFetchClause(t)),this.handlers.set(ot.kind,t=>this.visitFetchExpression(t)),this.handlers.set(Be.kind,t=>this.visitForClause(t)),this.handlers.set(ne.kind,t=>this.visitWithClause(t)),this.handlers.set(ee.kind,t=>this.visitCommonTable(t)),this.handlers.set(E.kind,t=>this.visitSimpleQuery(t)),this.handlers.set(z.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(K.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ae.kind,t=>this.visitValuesQuery(t)),this.handlers.set(be.kind,t=>this.visitTupleExpression(t)),this.handlers.set(Ge.kind,t=>this.visitInsertQuery(t)),this.handlers.set(tt.kind,t=>this.visitInsertClause(t)),this.handlers.set(wt.kind,t=>this.visitUpdateQuery(t)),this.handlers.set(ht.kind,t=>this.visitUpdateClause(t)),this.handlers.set(He.kind,t=>this.visitSetClause(t)),this.handlers.set(et.kind,t=>this.visitSetClauseItem(t)),this.handlers.set(Ut.kind,t=>this.visitReturningClause(t)),this.handlers.set(gt.kind,t=>this.visitCreateTableQuery(t))}static{this.SPACE_TOKEN=new p(10," ")}static{this.COMMA_TOKEN=new p(3,",")}static{this.ARGUMENT_SPLIT_COMMA_TOKEN=new p(11,",")}static{this.PAREN_OPEN_TOKEN=new p(4,"(")}static{this.PAREN_CLOSE_TOKEN=new p(4,")")}static{this.DOT_TOKEN=new p(8,".")}visitBinarySelectQuery(e){let t=new p(0,"");return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,e.operator.value,"BinarySelectQueryOperator")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}static commaSpaceTokens(){return[o.COMMA_TOKEN,o.SPACE_TOKEN]}static argumentCommaSpaceTokens(){return[o.ARGUMENT_SPLIT_COMMA_TOKEN,o.SPACE_TOKEN]}visitQualifiedName(e){let t=new p(0,"","QualifiedName");if(e.namespaces)for(let n=0;n<e.namespaces.length;n++)t.innerTokens.push(e.namespaces[n].accept(this)),t.innerTokens.push(o.DOT_TOKEN);return t.innerTokens.push(e.name.accept(this)),t}visitPartitionByClause(e){let t=new p(1,"partition by","PartitionByClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOrderByClause(e){let t=new p(1,"order by","OrderByClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.order.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(this.visit(e.order[n]));return t}visitOrderByItem(e){let t=new p(0,"","OrderByItem");return t.innerTokens.push(this.visit(e.value)),e.sortDirection&&e.sortDirection!=="asc"&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"desc"))),e.nullsPosition&&(e.nullsPosition==="first"?(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"nulls first"))):e.nullsPosition==="last"&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"nulls last")))),t}parse(e){this.index=1;let t=this.visit(e),n=it.collect(e).sort((i,s)=>(i.index??0)-(s.index??0)),r=this.parameterDecorator.style;if(r==="named"){let i={};for(let s of n){let a=s.name.value;if(i.hasOwnProperty(a)){if(i[a]!==s.value)throw new Error(`Duplicate parameter name '${a}' with different values detected during query composition.`);continue}i[a]=s.value}return{token:t,params:i}}else if(r==="indexed"){let i=n.map(s=>s.value);return{token:t,params:i}}else if(r==="anonymous"){let i=n.map(s=>s.value);return{token:t,params:i}}return{token:t,params:[]}}visit(e){let t=this.handlers.get(e.getKind());if(t){let n=t(e);return this.addCommentsToToken(n,e.comments),n}throw new Error(`[SqlPrintTokenParser] No handler for kind: ${e.getKind().toString()}`)}addCommentsToToken(e,t){if(!t||t.length===0)return;let n=this.createCommentBlocks(t);n.length>0&&this.insertCommentBlocksWithSpacing(e,n)}createCommentBlocks(e){let t=[];for(let n of e)n.trim()&&t.push(this.createSingleCommentBlock(n));return t}createSingleCommentBlock(e){let t=new p(0,"","CommentBlock"),n=new p(6,this.formatBlockComment(e));t.innerTokens.push(n);let r=new p(12,"");t.innerTokens.push(r);let i=new p(10," ");return t.innerTokens.push(i),t}insertCommentBlocksWithSpacing(e,t){if(e.innerTokens.unshift(...t),this.shouldAddSeparatorSpace(e.containerType)){let r=new p(10," ");e.innerTokens.splice(t.length,0,r),e.innerTokens.length>t.length+1&&e.innerTokens[t.length+1].type===10&&e.innerTokens.splice(t.length+1,1)}else e.innerTokens.length>t.length&&e.innerTokens[t.length].type===10&&e.innerTokens.splice(t.length,1)}shouldAddSeparatorSpace(e){return this.isClauseLevelContainer(e)}isClauseLevelContainer(e){switch(e){case"SelectClause":case"FromClause":case"WhereClause":case"GroupByClause":case"HavingClause":case"OrderByClause":case"LimitClause":case"OffsetClause":case"WithClause":case"SimpleSelectQuery":return!0;default:return!1}}formatBlockComment(e){return`/* ${e} */`}visitValueList(e){let t=new p(0,"","ValueList");for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...o.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t}visitColumnReference(e){let t=new p(0,"","ColumnReference");return t.innerTokens.push(e.qualifiedName.accept(this)),t}visitFunctionCall(e){let t=new p(0,"","FunctionCall");return t.innerTokens.push(e.qualifiedName.accept(this)),t.innerTokens.push(o.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),e.over&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"over")),e.over instanceof 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 p(0,"","UnaryExpression");return t.innerTokens.push(this.visit(e.operator)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.expression)),t}visitBinaryExpression(e){let t=new p(0,"","BinaryExpression");return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(5,e.operator.value)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}visitLiteralValue(e){let t;return typeof e.value=="string"?e.isDollarString?t=e.value:t=`'${e.value.replace(/'/g,"''")}'`:e.value===null?t="null":t=e.value.toString(),new p(2,t,"LiteralValue")}visitParameterExpression(e){e.index=this.index;let t=this.parameterDecorator.decorate(e.name.value,e.index),n=new p(7,t);return this.index++,n}visitSwitchCaseArgument(e){let t=new p(0,"","SwitchCaseArgument");for(let n of e.cases)t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(n.accept(this));return e.elseValue&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.createElseToken(e.elseValue))),t}createElseToken(e){let t=new p(0,"","ElseClause");t.innerTokens.push(new p(1,"else")),t.innerTokens.push(o.SPACE_TOKEN);let n=new p(0,"","CaseElseValue");return n.innerTokens.push(this.visit(e)),t.innerTokens.push(n),t}visitCaseKeyValuePair(e){let t=new p(0,"","CaseKeyValuePair");t.innerTokens.push(new p(1,"when")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.key)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"then")),t.innerTokens.push(o.SPACE_TOKEN);let n=new p(0,"","CaseThenValue");return n.innerTokens.push(this.visit(e.value)),t.innerTokens.push(n),t}visitRawString(e){return new p(2,e.value,"RawString")}visitIdentifierString(e){let t=e.name==="*"?e.name:this.identifierDecorator.decorate(e.name);return new p(2,t,"IdentifierString")}visitParenExpression(e){let t=new p(0,"","ParenExpression");return t.innerTokens.push(o.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitCastExpression(e){let t=new p(0,"","CastExpression");return t.innerTokens.push(this.visit(e.input)),t.innerTokens.push(new p(5,"::")),t.innerTokens.push(this.visit(e.castType)),t}visitCaseExpression(e){let t=new p(0,"","CaseExpression");return t.innerTokens.push(new p(1,"case")),e.condition&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition))),t.innerTokens.push(this.visit(e.switchCase)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"end")),t}visitArrayExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(new p(1,"array")),t.innerTokens.push(new p(4,"[")),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(new p(4,"]")),t}visitArrayQueryExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(new p(1,"array")),t.innerTokens.push(new p(4,"(")),t.innerTokens.push(this.visit(e.query)),t.innerTokens.push(new p(4,")")),t}visitArraySliceExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(this.visit(e.array)),t.innerTokens.push(new p(4,"[")),e.startIndex&&t.innerTokens.push(this.visit(e.startIndex)),t.innerTokens.push(new p(5,":")),e.endIndex&&t.innerTokens.push(this.visit(e.endIndex)),t.innerTokens.push(new p(4,"]")),t}visitArrayIndexExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(this.visit(e.array)),t.innerTokens.push(new p(4,"[")),t.innerTokens.push(this.visit(e.index)),t.innerTokens.push(new p(4,"]")),t}visitBetweenExpression(e){let t=new p(0,"","BetweenExpression");return t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(o.SPACE_TOKEN),e.negated&&(t.innerTokens.push(new p(1,"not")),t.innerTokens.push(o.SPACE_TOKEN)),t.innerTokens.push(new p(1,"between")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.lower)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"and")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.upper)),t}visitStringSpecifierExpression(e){let t=e.specifier.accept(this).text,n=e.value.accept(this).text;return new p(2,t+n,"StringSpecifierExpression")}visitTypeValue(e){let t=new p(0,"","TypeValue");return t.innerTokens.push(e.qualifiedName.accept(this)),e.argument&&(t.innerTokens.push(o.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN)),t}visitTupleExpression(e){let t=new p(0,"","TupleExpression");t.innerTokens.push(o.PAREN_OPEN_TOKEN);for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...o.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitWindowFrameExpression(e){let t=new p(0,"","WindowFrameExpression"),n=!0;return e.partition&&(t.innerTokens.push(this.visit(e.partition)),n=!1),e.order&&(n?n=!1:t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.order))),e.frameSpec&&(n?n=!1:t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.frameSpec))),t}visitWindowFrameSpec(e){let t=new p(0,"","WindowFrameSpec");return t.innerTokens.push(new p(1,e.frameType)),e.endBound===null?(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this))):(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"between")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"and")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.endBound.accept(this))),t}visitWindowFrameBoundaryValue(e){let t=new p(0,"","WindowFrameBoundaryValue");return t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,e.isFollowing?"following":"preceding")),t}visitWindowFrameBoundStatic(e){return new p(1,e.bound)}visitSelectItem(e){let t=new p(0,"","SelectItem");if(t.innerTokens.push(this.visit(e.value)),!e.identifier)return t;if(e.value instanceof v){let n=e.value.column.name;if(e.identifier.name===n)return t}return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.identifier)),t}visitSelectClause(e){let t=new p(1,"select","SelectClause"),n="select";for(let r of e.hints)n+=" "+this.visit(r).text;if(e.distinct){let r=e.distinct.accept(this);if(r.innerTokens&&r.innerTokens.length>0){let i=r.text;for(let s of r.innerTokens)i+=this.flattenTokenText(s);n+=" "+i}else n+=" "+r.text}t.text=n,t.innerTokens.push(o.SPACE_TOKEN);for(let r=0;r<e.items.length;r++)r>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[r]));return t}flattenTokenText(e){let t=e.text;if(e.innerTokens)for(let n of e.innerTokens)t+=this.flattenTokenText(n);return t}visitHintClause(e){return new p(2,e.getFullHint())}visitDistinct(e){return new p(1,"distinct")}visitDistinctOn(e){let t=new p(0,"","DistinctOn");return t.innerTokens.push(new p(1,"distinct on")),t.innerTokens.push(o.PAREN_OPEN_TOKEN),t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitTableSource(e){let t="";Array.isArray(e.namespaces)&&e.namespaces.length>0&&(t=e.namespaces.map(r=>r.accept(this).text).join(".")+"."),t+=e.table.accept(this).text;let n=new p(2,t);return e.identifier&&(e.identifier.name,e.table.name),n}visitSourceExpression(e){let t=new p(0,"","SourceExpression");if(t.innerTokens.push(e.datasource.accept(this)),!e.aliasExpression)return t;if(e.datasource instanceof R){let n=e.datasource.table.name;return e.aliasExpression.table.name===n||(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this))),t}else return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this)),t}visitFromClause(e){let t=new p(1,"from","FromClause");if(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.joins)for(let n=0;n<e.joins.length;n++)t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.joins[n]));return t}visitJoinClause(e){let t=new p(0,"","JoinClause");return t.innerTokens.push(new p(1,e.joinType.value)),e.lateral&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"lateral"))),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.condition&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition))),t}visitJoinOnClause(e){let t=new p(0,"","JoinOnClause");return t.innerTokens.push(new p(1,"on")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitJoinUsingClause(e){let t=new p(0,"","JoinUsingClause");return t.innerTokens.push(new p(1,"using")),t.innerTokens.push(o.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.condition)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitFunctionSource(e){let t=new p(0,"","FunctionSource");return t.innerTokens.push(e.qualifiedName.accept(this)),t.innerTokens.push(o.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitSourceAliasExpression(e){let t=new p(0,"","SourceAliasExpression");if(t.innerTokens.push(this.visit(e.table)),e.columns){t.innerTokens.push(o.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...o.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));t.innerTokens.push(o.PAREN_CLOSE_TOKEN)}return t}visitWhereClause(e){let t=new p(1,"where","WhereClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitGroupByClause(e){let t=new p(1,"group by","GroupByClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.grouping.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(this.visit(e.grouping[n]));return t}visitHavingClause(e){let t=new p(1,"having","HavingClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitWindowClause(e){let t=new p(1,"window","WindowClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.windows.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(this.visit(e.windows[n]));return t}visitWindowFrameClause(e){let t=new p(0,"","WindowFrameClause");return t.innerTokens.push(e.name.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(o.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitLimitClause(e){let t=new p(1,"limit","LimitClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOffsetClause(e){let t=new p(1,"offset","OffsetClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitFetchClause(e){let t=new p(1,"fetch","FetchClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.expression)),t}visitFetchExpression(e){let t=new p(0,"","FetchExpression");return t.innerTokens.push(new p(1,e.type)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.count.accept(this)),e.unit&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,e.unit))),t}visitForClause(e){let t=new p(1,"for","ForClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,e.lockMode)),t}visitWithClause(e){let t=new p(1,"with","WithClause");t.innerTokens.push(o.SPACE_TOKEN),e.recursive&&(t.innerTokens.push(new p(1,"recursive")),t.innerTokens.push(o.SPACE_TOKEN));for(let n=0;n<e.tables.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(e.tables[n].accept(this));return t.innerTokens.push(o.SPACE_TOKEN),t}visitCommonTable(e){let t=new p(0,"","CommonTable");t.innerTokens.push(e.aliasExpression.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),e.materialized!==null&&(e.materialized?t.innerTokens.push(new p(1,"materialized")):t.innerTokens.push(new p(1,"not materialized")),t.innerTokens.push(o.SPACE_TOKEN)),t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new p(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitSimpleQuery(e){let t=new p(0,"","SimpleSelectQuery");return e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(e.selectClause.accept(this)),e.fromClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this)),e.whereClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.groupByClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.groupByClause.accept(this))),e.havingClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.havingClause.accept(this))),e.orderByClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.orderByClause.accept(this))),e.windowClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.windowClause.accept(this))),e.limitClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.limitClause.accept(this))),e.offsetClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.offsetClause.accept(this))),e.fetchClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.fetchClause.accept(this))),e.forClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.forClause.accept(this)))),t}visitSubQuerySource(e){let t=new p(0,"");t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new p(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitValuesQuery(e){let t=new p(1,"values","ValuesQuery");t.innerTokens.push(o.SPACE_TOKEN);let n=new p(0,"","Values");for(let r=0;r<e.tuples.length;r++)r>0&&n.innerTokens.push(...o.commaSpaceTokens()),n.innerTokens.push(e.tuples[r].accept(this));return t.innerTokens.push(n),t}visitInlineQuery(e){let t=new p(0,"");t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new p(0,"","InlineQuery");return n.innerTokens.push(e.selectQuery.accept(this)),t.innerTokens.push(n),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitInsertQuery(e){let t=new p(0,"","InsertQuery");return t.innerTokens.push(this.visit(e.insertClause)),e.selectQuery&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.selectQuery))),t}visitInsertClause(e){let t=new p(0,"");if(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"insert into")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),e.columns.length>0){t.innerTokens.push(o.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(e.columns[n].accept(this));t.innerTokens.push(o.PAREN_CLOSE_TOKEN)}return t}visitUpdateQuery(e){let t=new p(0,"","UpdateQuery");return e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(e.updateClause.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.setClause.accept(this)),e.fromClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this))),e.whereClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.returningClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.returningClause.accept(this))),t}visitUpdateClause(e){let t=new p(1,"update","UpdateClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t}visitSetClause(e){let t=new p(1,"set","SelectClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.items.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[n]));return t}visitSetClauseItem(e){let t=new p(0,"","SetClauseItem");return t.innerTokens.push(e.column.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(5,"=")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.value.accept(this)),t}visitReturningClause(e){let t=new p(1,"returning","ReturningClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));return t}visitCreateTableQuery(e){let t=new p(1,e.isTemporary?"create temporary table":"create table","CreateTableQuery");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.tableName.accept(this)),e.asSelectQuery&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.asSelectQuery.accept(this))),t}};var Lt=class{constructor(e=" ",t=0,n=`\r
|
|
13
|
-
`){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 Hn(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.")}},Hn=class{constructor(e,t){this.level=e,this.text=t}};var mn=class o{constructor(e){this.insideWithClause=!1;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.exportComment=e?.exportComment??!1,this.strictCommentPlacement=e?.strictCommentPlacement??!1,this.withClauseStyle=e?.withClauseStyle??"standard",this.linePrinter=new Lt(this.indentChar,this.indentSize,this.newline),this.indentIncrementContainers=new Set(e?.indentIncrementContainerTypes??["SelectClause","FromClause","WhereClause","GroupByClause","HavingClause","WindowFrameExpression","PartitionByClause","OrderByClause","WindowClause","LimitClause","OffsetClause","SubQuerySource","BinarySelectQueryOperator","Values","WithClause","SwitchCaseArgument","CaseKeyValuePair","CaseThenValue","ElseClause","CaseElseValue","SimpleSelectQuery"])}print(e,t=0){return this.linePrinter=new Lt(this.indentChar,this.indentSize,this.newline),this.insideWithClause=!1,this.linePrinter.lines.length>0&&t!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=t),this.appendToken(e,t,void 0),this.linePrinter.print()}appendToken(e,t,n){let r=this.insideWithClause;if(e.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"&&(this.insideWithClause=!0),this.shouldSkipToken(e))return;let i=this.linePrinter.getCurrentLine();if(e.type===1)this.handleKeywordToken(e,t);else if(e.type===3)this.handleCommaToken(e,t,n);else if(e.type===5&&e.text.toLowerCase()==="and")this.handleAndOperatorToken(e,t);else if(e.containerType==="JoinClause")this.handleJoinClauseToken(e,t);else if(e.type===6)this.exportComment&&this.linePrinter.appendText(e.text);else if(e.type===10)this.handleSpaceToken(e,n);else if(e.type===12)this.handleCommentNewlineToken(e,t);else if(e.containerType==="CommonTable"&&this.withClauseStyle==="cte-oneline"){this.handleCteOnelineToken(e,t);return}else this.linePrinter.appendText(e.text);if(e.keywordTokens&&e.keywordTokens.length>0)for(let a=0;a<e.keywordTokens.length;a++){let l=e.keywordTokens[a];this.appendToken(l,t,e.containerType)}let s=t;!this.isOnelineMode()&&i.text!==""&&this.indentIncrementContainers.has(e.containerType)&&(this.insideWithClause&&this.withClauseStyle==="full-oneline"||(s++,this.linePrinter.appendNewline(s)));for(let a=0;a<e.innerTokens.length;a++){let l=e.innerTokens[a];this.appendToken(l,s,e.containerType)}if(e.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"){this.insideWithClause=!1,this.linePrinter.appendNewline(t);return}s!==t&&(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t))}shouldSkipToken(e){return e.type===12?!1:(!e.innerTokens||e.innerTokens.length===0)&&e.text===""}applyKeywordCase(e){return this.keywordCase==="upper"?e.toUpperCase():this.keywordCase==="lower"?e.toLowerCase():e}handleKeywordToken(e,t){let n=this.applyKeywordCase(e.text);this.linePrinter.appendText(n)}handleCommaToken(e,t,n){let r=e.text;this.insideWithClause&&this.withClauseStyle==="full-oneline"?this.linePrinter.appendText(r):this.withClauseStyle==="cte-oneline"&&n==="WithClause"?(this.linePrinter.appendText(r),this.linePrinter.appendNewline(t)):this.commaBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)):this.commaBreak==="after"?(this.linePrinter.appendText(r),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t)):this.linePrinter.appendText(r)}handleAndOperatorToken(e,t){let n=this.applyKeywordCase(e.text);this.andBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(n)):this.andBreak==="after"?(this.linePrinter.appendText(n),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t)):this.linePrinter.appendText(n)}handleJoinClauseToken(e,t){let n=this.applyKeywordCase(e.text);this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(n)}handleSpaceToken(e,t){this.shouldSkipCommentBlockSpace(t)||this.linePrinter.appendText(e.text)}shouldSkipCommentBlockSpace(e){return e==="CommentBlock"&&this.insideWithClause&&this.withClauseStyle==="full-oneline"}handleCommentNewlineToken(e,t){this.shouldSkipCommentNewline()||this.isOnelineMode()||this.linePrinter.appendNewline(t)}shouldSkipCommentNewline(){return this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.withClauseStyle==="cte-oneline"}isOnelineMode(){return this.newline===" "}handleCteOnelineToken(e,t){let r=this.createCteOnelinePrinter().print(e,t),i=this.cleanDuplicateSpaces(r);this.linePrinter.appendText(i)}createCteOnelinePrinter(){return new o({indentChar:"",indentSize:0,newline:" ",commaBreak:this.commaBreak,andBreak:this.andBreak,keywordCase:this.keywordCase,exportComment:this.exportComment,strictCommentPlacement:this.strictCommentPlacement,withClauseStyle:"standard"})}cleanDuplicateSpaces(e){return e.replace(/\s{2,}/g," ")}};var vu=["mysql","postgres","sqlserver","sqlite"],We=class{constructor(e={}){let t=e.preset?ur[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 pn(n),this.printer=new mn(e)}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var st=class{constructor(){this.sqlFormatter=new We({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(e,t=null){return t&&(this.sqlFormatter=new We(t)),this.sqlFormatter.format(e).formattedSql}formatWithParameters(e,t=null){t&&(this.sqlFormatter=new We(t));let n=this.sqlFormatter.format(e);return{sql:n.formattedSql,params:n.params}}visit(e){return this.format(e)}};var dn=class{constructor(){this.sourceCollector=new yt(!0),this.cteCollector=new X,this.formatter=new st}build(e){if(e.length===0)return new ne(!1,e);let t=this.resolveDuplicateNames(e),{tableMap:n,recursiveCTEs:r,dependencies:i}=this.buildDependencyGraph(t),s=this.sortCommonTables(t,n,r,i);return new ne(r.size>0,s)}resolveDuplicateNames(e){let t=new Map;for(let r of e){let i=r.aliasExpression.table.name;t.has(i)||t.set(i,[]),t.get(i).push(r)}let n=[];for(let[r,i]of t.entries()){if(i.length===1){n.push(i[0]);continue}let s=i.map(l=>this.formatter.format(l.query));if(new Set(s).size===1)n.push(i[0]);else throw new Error(`CTE name conflict detected: '${r}' 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,r=new Map,i=new Map;for(let s of e){let a=s.aliasExpression.table.name,l=this.sourceCollector.collect(s.query);for(let c of l)if(c.table.name===a){n.add(a);break}r.has(a)||r.set(a,new Set);let u=this.cteCollector.collect(s.query);for(let c of u){let m=c.aliasExpression.table.name;t.has(m)&&(r.get(a).add(m),i.has(m)||i.set(m,new Set),i.get(m).add(a))}}return{tableMap:t,recursiveCTEs:n,dependencies:r}}sortCommonTables(e,t,n,r){let i=[],s=[],a=new Set,l=new Set,u=c=>{if(a.has(c))return;if(l.has(c))throw new Error(`Circular reference detected in CTE: ${c}`);l.add(c);let m=r.get(c)||new Set;for(let h of m)u(h);l.delete(c),a.add(c),n.has(c)?i.push(t.get(c)):s.push(t.get(c))};for(let c of e){let m=c.aliasExpression.table.name;a.has(m)||u(m)}return[...i,...s]}};var hn=class{constructor(){this.nameConflictResolver=new dn,this.cteCollector=new X}inject(e,t){if(t.length===0)return e;t.push(...this.cteCollector.collect(e));let n=this.nameConflictResolver.build(t);if(e instanceof E)return this.injectIntoSimpleQuery(e,n);if(e instanceof K)return this.injectIntoBinaryQuery(e,n);throw new Error("Unsupported query type")}injectIntoSimpleQuery(e,t){if(e.withClause)throw new Error("The query already has a WITH clause. Please remove it before injecting new CTEs.");return e.withClause=t,e}injectIntoBinaryQuery(e,t){if(e.left instanceof E)return this.injectIntoSimpleQuery(e.left,t),e;if(e.left instanceof K)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 X().collect(e);return n.length===0?e:(new Ct().execute(e),new hn().inject(e,n))}};var cr=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))(cr||{}),Ie=class{constructor(e,t=!1,n="columnNameOnly",r){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=null;this.commonTables=[];this.tableColumnResolver=e??null,this.includeWildCard=t,this.commonTableCollector=new X,this.commonTables=[],this.duplicateDetection=n,this.options=r||{},this.handlers=new Map,this.handlers.set(E.kind,i=>this.visitSimpleSelectQuery(i)),this.handlers.set(J.kind,i=>this.visitSelectClause(i)),this.handlers.set(D.kind,i=>this.visitFromClause(i)),this.handlers.set(ie.kind,i=>this.visitWhereClause(i)),this.handlers.set(pe.kind,i=>this.visitGroupByClause(i)),this.handlers.set(me.kind,i=>this.visitHavingClause(i)),this.handlers.set(ce.kind,i=>this.visitOrderByClause(i)),this.handlers.set(Ce.kind,i=>this.visitWindowFrameClause(i)),this.handlers.set(se.kind,i=>this.visitLimitClause(i)),this.handlers.set(De.kind,i=>this.offsetClause(i)),this.handlers.set(Ke.kind,i=>this.visitFetchClause(i)),this.handlers.set(de.kind,i=>this.visitJoinOnClause(i)),this.handlers.set(Te.kind,i=>this.visitJoinUsingClause(i)),this.handlers.set(v.kind,i=>this.visitColumnReference(i)),this.handlers.set(y.kind,i=>this.visitBinaryExpression(i)),this.handlers.set(re.kind,i=>this.visitUnaryExpression(i)),this.handlers.set(U.kind,i=>this.visitFunctionCall(i)),this.handlers.set(Z.kind,i=>this.visitParenExpression(i)),this.handlers.set(le.kind,i=>this.visitCaseExpression(i)),this.handlers.set(ue.kind,i=>this.visitCastExpression(i)),this.handlers.set(ve.kind,i=>this.visitBetweenExpression(i)),this.handlers.set(ge.kind,i=>this.visitArrayExpression(i)),this.handlers.set(Se.kind,i=>this.visitArrayQueryExpression(i)),this.handlers.set(_.kind,i=>this.visitValueList(i)),this.handlers.set(Ce.kind,i=>this.visitWindowFrameClause(i)),this.handlers.set(Qe.kind,i=>this.visitWindowFrameExpression(i)),this.handlers.set(Pe.kind,i=>this.visitPartitionByClause(i))}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 r=n?n+"."+e:e;this.selectValues.some(i=>{let s="";return i.value&&typeof i.value.getNamespace=="function"&&(s=i.value.getNamespace()||""),(s?s+"."+i.name:i.name)===r})||this.selectValues.push({name:e,value:t})}}visit(e){if(!this.isRootVisit){this.visitNode(e);return}if(!(e instanceof E))throw new Error("Root visit requires a SimpleSelectQuery. Decompose compound queries before collecting columns.");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 Ae(this.tableColumnResolver,this.commonTables).collect(e);for(let r of n)this.addSelectValueAsUnique(r.name,r.value);if(e.joins)for(let r of e.joins)r.condition&&r.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 lt=class o{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The source component is complete but there are additional tokens.`);return r.value}static parseTableSourceFromLexemes(e,t){let n=ke.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 r=ke.parseFromLexeme(e,n);return r.lastTokenType&2048?o.parseFunctionSource(e,r):o.parseTableSource(r)}static parseTableSource(e){let{namespaces:t,name:n,newIndex:r}=e;return{value:new R(t,n.name),newIndex:r}}static parseFunctionSource(e,t){let n=t.newIndex,{namespaces:r,name:i}=t,s=k.parseArgument(4,8,e,n);n=s.newIndex;let a=i.name;return{value:new qe({namespaces:r,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 r=e[n].value;if(r==="select"||r==="values"||r==="with"){let i=this.parseSubQuerySource(e,n);if(n=i.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:i.value,newIndex:n}}else if(e[n].type==4){let i=this.parseParenSource(e,n);if(n=i.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:i.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:r,newIndex:i}=A.parseFromLexeme(e,n);return n=i,{value:new z(r),newIndex:n}}};var At=class extends Error{constructor(t){super(`CTE '${t}' already exists in the query`);this.cteName=t;this.name="DuplicateCTEError"}},St=class extends Error{constructor(t,n){super(`Invalid CTE name '${t}': ${n}`);this.cteName=t;this.name="InvalidCTENameError"}},Ft=class extends Error{constructor(t){super(`CTE '${t}' not found in the query`);this.cteName=t;this.name="CTENotFoundError"}};var vt=class{constructor(e,t){this.options=t||{},this.tableColumnResolver=e,this.columnCollector=new Ie(this.tableColumnResolver)}find(e,t){let n=typeof t=="string"?[t]:t,i=new X().collect(e),s=new Map;for(let a of i)s.set(a.getSourceAliasName(),a);return this.findUpstream(e,n,s)}handleTableSource(e,t,n){let r=n.get(e.table.name);if(r){let i=new Map(n);i.delete(e.table.name);let s=this.findUpstream(r.query,t,i);return s.length===0?null:s}return null}handleSubQuerySource(e,t,n){let r=this.findUpstream(e.query,t,n);return r.length===0?null:r}processFromClauseBranches(e,t,n){let r=e.getSources();if(r.length===0)return null;let i=[],s=!0,a=0;for(let l of r){let u=l.datasource,c=null;if(u instanceof R)c=this.handleTableSource(u,t,n),a++;else if(u instanceof z)c=this.handleSubQuerySource(u,t,n),a++;else{if(u instanceof ae)continue;s=!1;break}if(c===null){s=!1;break}i.push(c)}return s&&i.length===a?i.flat():null}findUpstream(e,t,n){if(e instanceof E){let r=e.fromClause;if(r){let c=this.processFromClauseBranches(r,t,n);if(c&&c.length>0)return c}let i=this.columnCollector.collect(e).map(c=>c.name),s=this.collectCTEColumns(e,n),a=[...i,...s],l=c=>this.options.ignoreCaseAndUnderscore?c.toLowerCase().replace(/_/g,""):c;return t.every(c=>a.some(m=>l(m)===l(c)))?[e]:[]}else if(e instanceof K){let r=this.findUpstream(e.left,t,n),i=this.findUpstream(e.right,t,n);return[...r,...i]}return[]}collectCTEColumns(e,t){let n=[];if(e.withClause)for(let r of e.withClause.tables){let i=this.collectColumnsFromSelectQuery(r.query);n.push(...i)}return n}collectColumnsFromSelectQuery(e){if(e instanceof E)try{return this.columnCollector.collect(e).map(t=>t.name)}catch(t){return console.warn("Failed to collect columns from SimpleSelectQuery:",t),[]}else if(e instanceof K)return this.collectColumnsFromSelectQuery(e.left);return[]}};var ut=class{static parseFromLexeme(e,t){let n=t;if(n<e.length&&(e[n].type&64||e[n].type&2048)){let r=e[n].value;if(n++,n<e.length&&e[n].type&4){let i=[];for(n++;n<e.length&&e[n].type&64&&(i.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(i.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 Y(r,i),newIndex:n}}return{value:new Y(r,null),newIndex:n}}throw new Error(`Syntax error at position ${t}: Expected an identifier for table alias but found "${e[t]?.value||"end of input"}".`)}};var Je=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The source expression is complete but there are additional tokens.`);return r.value}static parseTableSourceFromLexemes(e,t){let n=lt.parseTableSourceFromLexemes(e,t);return{value:new M(n.value,null),newIndex:n.newIndex}}static parseFromLexeme(e,t){let n=t,r=lt.parseFromLexeme(e,n);if(n=r.newIndex,n<e.length){if(e[n].value==="as"){n++;let s=ut.parseFromLexeme(e,n);return n=s.newIndex,{value:new M(r.value,s.value),newIndex:n}}if(n<e.length&&this.isTokenTypeAliasCandidate(e[n].type)){let s=ut.parseFromLexeme(e,n);return n=s.newIndex,{value:new M(r.value,s.value),newIndex:n}}}return{value:new M(r.value,null),newIndex:n}}static isTokenTypeAliasCandidate(e){return(e&64)!==0||(e&2048)!==0}};var Ne=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=i=>i instanceof ae?o.buildSimpleQuery(i):i,r=new K(n(e[0]),t,n(e[1]));_e.normalize(r);for(let i=2;i<e.length;i++)r.appendSelectQuery(t,n(e[i]));return r}constructor(){}static buildSimpleQuery(e){if(e instanceof E)return e;if(e instanceof K)return o.buildSimpleBinaryQuery(e);if(e instanceof ae)return o.buildSimpleValuesQuery(e);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(e){let t=new z(e),n=new M(t,new Y("bq",null)),r=new D(n,null),i=o.createSelectAllClause(),s=new E({selectClause:i,fromClause:r});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 z(e),r=new M(n,new Y("vq",e.columnAliases)),i=new D(r,null),s=e.columnAliases.map(l=>new j(new v("vq",l),l)),a=new J(s,null);return new E({selectClause:a,fromClause:i})}static createSelectAllClause(){let e=new v(null,"*"),t=new j(e,"*");return new J([t],null)}static buildCreateTableQuery(e,t,n=!1){return new gt({tableName:t,isTemporary:n,asSelectQuery:e})}static buildInsertQuery(e,t){let n,r=e.selectClause.items.length;if(n=new Ae().collect(e).map(l=>l.name),!n.length||r!==n.length)throw new Error(`Columns cannot be inferred from the selectQuery. Make sure you are not using wildcards or unnamed columns.
|
|
12
|
+
${a}`;return new o(l,n,a)}};var Me=class{static parseArrayExpression(e,t){let n=t;if(n+1<e.length&&e[n+1].type&512){n++;let r=k.parseArgument(512,1024,e,n);return n=r.newIndex,{value:new fe(r.value),newIndex:n}}else if(n+1<e.length&&e[n+1].type&4){n++,n++;let r=Q.parseFromLexeme(e,n);return n=r.newIndex,n++,{value:new Ce(r.value),newIndex:n}}throw new Error(`Invalid ARRAY syntax at index ${n}, expected ARRAY[... or ARRAY(...)`)}static parseFromLexeme(e,t){let n=t,r=e[n];return r.value==="array"?this.parseArrayExpression(e,n):r.value==="substring"||r.value==="overlay"?this.parseKeywordFunction(e,n,[{key:"from",required:!1},{key:"for",required:!1}]):r.value==="cast"?this.parseKeywordFunction(e,n,[{key:"as",required:!0}]):r.value==="trim"?this.parseKeywordFunction(e,n,[{key:"from",required:!1}]):this.parseFunctionCall(e,n)}static tryParseBinaryExpression(e,t,n,r=!0,i=!0){let s=t;if(s<e.length&&e[s].type&2){let a=e[s].value.toLowerCase();if(!r&&a==="and"||!i&&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 c=this.parseTypeValue(e,s);return s=c.newIndex,{value:new ae(n,c.value),newIndex:s}}let l=k.parseFromLexeme(e,s);return s=l.newIndex,{value:new C(n,a,l.value),newIndex:s}}return null}static parseBetweenExpression(e,t,n,r){let i=t,s=k.parseFromLexeme(e,i,!1);if(i=s.newIndex,i<e.length&&e[i].type&2&&e[i].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${i}`);i++;let a=this.parseBetweenUpperBound(e,i);return i=a.newIndex,{value:new ye(n,s.value,a.value,r),newIndex:i}}static parseBetweenUpperBound(e,t){return k.parseFromLexeme(e,t,!1,!1)}static parseFunctionCall(e,t){let n=t,r=Pe.parseFromLexeme(e,n),i=r.namespaces,s=r.name;if(n=r.newIndex,n<e.length&&e[n].type&4){let a=k.parseArgument(4,8,e,n);n=a.newIndex;let l=null;if(n<e.length&&e[n].value==="within group"){let u=this.parseWithinGroupClause(e,n);l=u.value,n=u.newIndex}if(n<e.length&&e[n].value==="over"){let u=Ft.parseFromLexeme(e,n);return n=u.newIndex,{value:new j(i,s.name,a.value,u.value,l),newIndex:n}}else return{value:new j(i,s.name,a.value,null,l),newIndex:n}}else throw $e.fromUnparsedLexemes(e,n,`Expected opening parenthesis after function name '${s.name}'.`)}static parseKeywordFunction(e,t,n){let r=t,i=Pe.parseFromLexeme(e,r),s=i.namespaces,a=i.name;if(r=i.newIndex,r<e.length&&e[r].type&4){r++;let l=k.parseFromLexeme(e,r),u=l.value;if(r=l.newIndex,r<e.length&&e[r].type&16)return this.parseFunctionCall(e,t);for(let{key:c,required:m}of n)if(r<e.length&&e[r].type&128&&e[r].value===c)if(r++,r<e.length&&e[r].type&8192){let h=this.parseTypeValue(e,r);u=new C(u,c,h.value),r=h.newIndex}else{let h=k.parseFromLexeme(e,r);u=new C(u,c,h.value),r=h.newIndex}else if(m)throw $e.fromUnparsedLexemes(e,r,`Keyword '${c}' is required for ${a.name} function.`);if(r<e.length&&e[r].type&8){r++;let c=null;if(r<e.length&&e[r].value==="within group"){let m=this.parseWithinGroupClause(e,r);c=m.value,r=m.newIndex}if(r<e.length&&e[r].value==="over"){r++;let m=Ft.parseFromLexeme(e,r);return r=m.newIndex,{value:new j(s,a.name,u,m.value,c),newIndex:r}}else return{value:new j(s,a.name,u,null,c),newIndex:r}}else throw $e.fromUnparsedLexemes(e,r,`Missing closing parenthesis for function '${a.name}'.`)}else throw $e.fromUnparsedLexemes(e,r,`Missing opening parenthesis for function '${a.name}'.`)}static parseTypeValue(e,t){let n=t,{namespaces:r,name:i,newIndex:s}=Pe.parseFromLexeme(e,n);if(n=s,n<e.length&&e[n].type&4){let a=k.parseArgument(4,8,e,n);return n=a.newIndex,{value:new Te(r,new V(i.name),a.value),newIndex:n}}else return{value:new Te(r,new V(i.name)),newIndex:n}}static parseWithinGroupClause(e,t){let n=t;if(n>=e.length||e[n].value!=="within group")throw new Error(`Expected 'WITHIN GROUP' at index ${n}`);if(n++,n>=e.length||!(e[n].type&4))throw new Error(`Expected '(' after 'WITHIN GROUP' at index ${n}`);n++;let r=rt.parseFromLexeme(e,n);if(n=r.newIndex,n>=e.length||!(e[n].type&8))throw new Error(`Expected ')' after WITHIN GROUP ORDER BY clause at index ${n}`);return n++,{value:r.value,newIndex:n}}};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,"similar to":10,"not similar to":10,in:10,"not in":10,is:10,"is not":10,"->":10,"->>":10,"#>":10,"#>>":10,"@>":10,"<@":10,"?":10,"?|":10,"?&":10,"~":10,"~*":10,"!~":10,"!~*":10,rlike:10,regexp:10,mod:30,xor:2,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","similar to","in","not in","->","->>","#>","#>>","@>","<@","?","?|","?&","~","~*","!~","!~*","rlike","regexp"].includes(t)}};var k=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw $e.fromUnparsedLexemes(n,r.newIndex,"[ValueParser]");return r.value}static parseFromLexeme(e,t,n=!0,r=!0){return this.parseExpressionWithPrecedence(e,t,0,n,r)}static parseExpressionWithPrecedence(e,t,n,r=!0,i=!0){let s=t,a=e[s].comments,l=this.parseItem(e,s);l.value.comments=a,s=l.newIndex;let u=l.value,c=this.parseArrayAccess(e,s,u);for(u=c.value,s=c.newIndex;s<e.length&&e[s].type&2;){let h=e[s].value;if(!r&&h.toLowerCase()==="and"||!i&&h.toLowerCase()==="or")break;let w=ct.getPrecedence(h);if(w<n)break;if(s++,ct.isBetweenOperator(h)){let y=Me.parseBetweenExpression(e,s,u,h.toLowerCase().includes("not"));u=y.value,s=y.newIndex;continue}if(h==="::"){let y=Me.parseTypeValue(e,s);u=new ae(u,y.value),s=y.newIndex;continue}let b=w+1,d=this.parseExpressionWithPrecedence(e,s,b,r,i);s=d.newIndex,u=new C(u,h,d.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 r=e[n];if(r.type&64&&r.type&2&&r.type&8192){if(n+1<e.length&&e[n+1].type&4)if(this.isTypeConstructor(e,n+1,r.value)){let a=Me.parseTypeValue(e,n);return{value:a.value,newIndex:a.newIndex}}else return Me.parseFromLexeme(e,n);let i=nn.parseFromLexeme(e,n);if(i.newIndex>=e.length)return i;if(e[i.newIndex].type&1){let a=Ot.parseFromLexeme(e,i.newIndex);return{value:new te(e[n].value,a.value),newIndex:a.newIndex}}return i}else if(r.type&64){let{namespaces:i,name:s,newIndex:a}=Pe.parseFromLexeme(e,n);if(e[a-1].type&2048)return Me.parseFromLexeme(e,n);if(e[a-1].type&8192)if(a<e.length&&e[a].type&4)if(this.isTypeConstructor(e,a,s.name)){let u=Me.parseTypeValue(e,n);return{value:u.value,newIndex:u.newIndex}}else return Me.parseFromLexeme(e,n);else return{value:new Te(i,s),newIndex:a};return{value:new v(i,s),newIndex:a}}else{if(r.type&1)return Ot.parseFromLexeme(e,n);if(r.type&4)return rn.parseFromLexeme(e,n);if(r.type&2048)return Me.parseFromLexeme(e,n);if(r.type&2)return sn.parseFromLexeme(e,n);if(r.type&256)return on.parseFromLexeme(e,n);if(r.type&4096)return an.parseFromLexeme(e,n);if(r.type&128)return ln.parseFromLexeme(e,n);if(r.type&512){let{namespaces:i,name:s,newIndex:a}=Pe.parseFromLexeme(e,n);return{value:new v(i,s),newIndex:a}}else if(r.type&8192){let{namespaces:i,name:s,newIndex:a}=Pe.parseFromLexeme(e,n);if(a<e.length&&e[a].type&4)if(this.isTypeConstructor(e,a,s.name)){let l=Me.parseTypeValue(e,n);return{value:l.value,newIndex:l.newIndex}}else return Me.parseFromLexeme(e,n);else return{value:new Te(i,s),newIndex:a}}}throw $e.fromUnparsedLexemes(e,n,"[ValueParser] Invalid lexeme.")}static parseArgument(e,t,n,r){let i=r,s=[];if(i<n.length&&n[i].type===e){if(i++,i<n.length&&n[i].type===t)return i++,{value:new K([]),newIndex:i};if(i<n.length&&n[i].value==="*"){let l=new v(null,"*");if(i++,i<n.length&&n[i].type===t)return i++,{value:l,newIndex:i};throw $e.fromUnparsedLexemes(n,i,"Expected closing parenthesis after wildcard '*'.")}let a=this.parseFromLexeme(n,i);for(i=a.newIndex,s.push(a.value);i<n.length&&n[i].type&16;){i++;let l=this.parseFromLexeme(n,i);i=l.newIndex,s.push(l.value)}if(i<n.length&&n[i].type===t)return i++,s.length===1?{value:s[0],newIndex:i}:{value:new K(s),newIndex:i};throw $e.fromUnparsedLexemes(n,i,"Missing closing parenthesis.")}throw $e.fromUnparsedLexemes(n,r,"Expected opening parenthesis.")}static parseArrayAccess(e,t,n){let r=t,i=n;for(;r<e.length&&e[r].type&512&&!this.isSqlServerBracketIdentifier(e,r);){if(r++,r>=e.length)throw new Error(`Expected array index or slice after '[' at index ${r-1}`);if(e[r].type&1024)throw new Error(`Empty array access brackets not supported at index ${r}`);let s=null,a=!1;if(e[r].type&2&&e[r].value===":")a=!0,r++;else{let l=ct.getPrecedence(":"),u=this.parseExpressionWithPrecedence(e,r,l+1);s=u.value,r=u.newIndex,r<e.length&&e[r].type&2&&e[r].value===":"&&(a=!0,r++)}if(a){let l=null;if(r<e.length&&!(e[r].type&1024)){let u=ct.getPrecedence(":"),c=this.parseExpressionWithPrecedence(e,r,u+1);l=c.value,r=c.newIndex}if(r>=e.length||!(e[r].type&1024))throw new Error(`Expected ']' after array slice at index ${r}`);r++,i=new Ze(i,s,l)}else{if(!s){let l=this.parseFromLexeme(e,r);s=l.value,r=l.newIndex}if(r>=e.length||!(e[r].type&1024))throw new Error(`Expected ']' after array index at index ${r}`);r++,i=new et(i,s)}}return{value:i,newIndex:r}}static isSqlServerBracketIdentifier(e,t){let n=t+1;if(n>=e.length)return!1;for(;n<e.length&&!(e[n].type&1024);){let s=e[n];if(s.type&64||s.type&2&&s.value==="."){n++;continue}return!1}if(n>=e.length)return!1;let r=n;if(r+1<e.length){let s=e[r+1];if(s.type&2&&s.value===".")return!0}n=t+1;let i=!0;for(;n<r;){let s=e[n];if(!(s.type&64||s.type&2&&s.value===".")){i=!1;break}n++}return i}static isTypeConstructor(e,t,n){let r=["NUMERIC","DECIMAL","VARCHAR","CHAR","CHARACTER","TIMESTAMP","TIME","INTERVAL"],i=n.toUpperCase();if(r.includes(i))return!0;if(i==="DATE"){let s=t+1;if(s<e.length){let a=e[s];return!(a.type&1&&typeof a.value=="string"&&isNaN(Number(a.value)))}}return!1}};var ee=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(g.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(W.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(he.kind,e=>this.visitValuesQuery(e)),this.handlers.set(ne.kind,e=>this.visitWithClause(e)),this.handlers.set(X.kind,e=>this.visitCommonTable(e)),this.handlers.set(q.kind,e=>this.visitSelectItem(e)),this.handlers.set(x.kind,e=>this.visitIdentifierString(e)),this.handlers.set(V.kind,e=>this.visitRawString(e)),this.handlers.set(v.kind,e=>this.visitColumnReference(e)),this.handlers.set(T.kind,e=>this.visitParameterExpression(e)),this.handlers.set(G.kind,e=>this.visitLiteralValue(e)),this.handlers.set($.kind,e=>this.visitSourceExpression(e)),this.handlers.set(B.kind,e=>this.visitTableSource(e)),this.handlers.set(ze.kind,e=>this.visitFunctionSource(e)),this.handlers.set(Ue.kind,e=>this.visitParenSource(e)),this.handlers.set(_.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Se.kind,e=>this.visitInlineQuery(e)),this.handlers.set(D.kind,e=>this.visitFromClause(e)),this.handlers.set(me.kind,e=>this.visitJoinClause(e)),this.handlers.set(pe.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(we.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(H.kind,e=>this.visitParenExpression(e)),this.handlers.set(C.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ie.kind,e=>this.visitCaseExpression(e)),this.handlers.set(xe.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(be.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ye.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(j.kind,e=>this.visitFunctionCall(e)),this.handlers.set(fe.kind,e=>this.visitArrayExpression(e)),this.handlers.set(Ce.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(ke.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ae.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ee.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Je.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Te.kind,e=>this.visitTypeValue(e)),this.handlers.set(K.kind,e=>this.visitValueList(e)),this.handlers.set(We.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(J.kind,e=>this.visitSelectClause(e)),this.handlers.set(ue.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ce.kind,e=>this.visitHavingClause(e)),this.handlers.set(le.kind,e=>this.visitOrderByClause(e)),this.handlers.set(ve.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(Ie.kind,e=>this.visitOrderByItem(e)),this.handlers.set(Qe.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",r=e.constructor?.name||"unknown";throw new Error(`[CTECollector] No handler for ${r} 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 gt=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(g.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(W.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(he.kind,e=>this.visitValuesQuery(e)),this.handlers.set(q.kind,e=>this.visitSelectItem(e)),this.handlers.set(x.kind,e=>this.visitIdentifierString(e)),this.handlers.set(V.kind,e=>this.visitRawString(e)),this.handlers.set(v.kind,e=>this.visitColumnReference(e)),this.handlers.set(T.kind,e=>this.visitParameterExpression(e)),this.handlers.set(G.kind,e=>this.visitLiteralValue(e)),this.handlers.set($.kind,e=>this.visitSourceExpression(e)),this.handlers.set(B.kind,e=>this.visitTableSource(e)),this.handlers.set(Ue.kind,e=>this.visitParenSource(e)),this.handlers.set(_.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Se.kind,e=>this.visitInlineQuery(e)),this.handlers.set(D.kind,e=>this.visitFromClause(e)),this.handlers.set(me.kind,e=>this.visitJoinClause(e)),this.handlers.set(pe.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(we.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(H.kind,e=>this.visitParenExpression(e)),this.handlers.set(C.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ie.kind,e=>this.visitCaseExpression(e)),this.handlers.set(xe.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(be.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ye.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(j.kind,e=>this.visitFunctionCall(e)),this.handlers.set(fe.kind,e=>this.visitArrayExpression(e)),this.handlers.set(Ce.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(ke.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ae.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ee.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Je.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Te.kind,e=>this.visitTypeValue(e)),this.handlers.set(K.kind,e=>this.visitValueList(e)),this.handlers.set(Ze.kind,e=>this.visitArraySliceExpression(e)),this.handlers.set(et.kind,e=>this.visitArrayIndexExpression(e)),this.handlers.set(We.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(J.kind,e=>this.visitSelectClause(e)),this.handlers.set(ue.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ce.kind,e=>this.visitHavingClause(e)),this.handlers.set(le.kind,e=>this.visitOrderByClause(e)),this.handlers.set(ve.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(Ie.kind,e=>this.visitOrderByItem(e)),this.handlers.set(Qe.kind,e=>this.visitPartitionByClause(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",r=e.constructor?.name||"unknown";throw new Error(`[CTEDisabler] No handler for ${r} 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 _e(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 he(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(r=>this.visit(r)):null;return new D(t,n)}visitSubQuerySource(e){let t=this.visit(e.query);return new _(t)}visitInlineQuery(e){let t=this.visit(e.selectQuery);return new Se(t)}visitJoinClause(e){let t=this.visit(e.source),n=e.condition?this.visit(e.condition):null;return new me(e.joinType.value,t,n,e.lateral)}visitJoinOnClause(e){let t=this.visit(e.condition);return new pe(t)}visitJoinUsingClause(e){let t=this.visit(e.condition);return new we(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 ue(t)}visitHavingClause(e){let t=this.visit(e.condition);return new ce(t)}visitOrderByClause(e){let t=e.order.map(n=>this.visit(n));return new le(t)}visitWindowFrameClause(e){let t=this.visit(e.expression);return new ve(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 H(t)}visitBinaryExpression(e){let t=this.visit(e.left),n=this.visit(e.right);return new C(t,e.operator.value,n)}visitUnaryExpression(e){let t=this.visit(e.expression);return new te(e.operator.value,t)}visitCaseExpression(e){let t=e.condition?this.visit(e.condition):null,n=this.visit(e.switchCase);return new ie(t,n)}visitSwitchCaseArgument(e){let t=e.cases.map(r=>this.visit(r)),n=e.elseValue?this.visit(e.elseValue):null;return new be(t,n)}visitCaseKeyValuePair(e){let t=this.visit(e.key),n=this.visit(e.value);return new xe(t,n)}visitBetweenExpression(e){let t=this.visit(e.expression),n=this.visit(e.lower),r=this.visit(e.upper);return new ye(t,n,r,e.negated)}visitFunctionCall(e){let t=e.argument?this.visit(e.argument):null,n=e.over?this.visit(e.over):null;return new j(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 Ce(t)}visitTupleExpression(e){let t=e.values.map(n=>this.visit(n));return new ke(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 Te(e.namespaces,e.name,t)}visitSelectItem(e){let t=this.visit(e.value);return new q(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 $(t,n)}visitTableSource(e){return e}visitParenSource(e){let t=this.visit(e.source);return new Ue(t)}visitParameterExpression(e){return e}visitWindowFrameExpression(e){let t=e.partition?this.visit(e.partition):null,n=e.order?this.visit(e.order):null,r=e.frameSpec?this.visit(e.frameSpec):null;return new Ee(t,n,r)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new Ie(t,e.sortDirection,e.nullsPosition)}visitValueList(e){let t=e.values.map(n=>this.visit(n));return new K(t)}visitArraySliceExpression(e){return e}visitArrayIndexExpression(e){return e}visitStringSpecifierExpression(e){return e}visitPartitionByClause(e){let t=this.visit(e.value);return new Qe(t)}};var it=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(g.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(W.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(he.kind,t=>this.visitValuesQuery(t)),this.handlers.set(ne.kind,t=>this.visitWithClause(t)),this.handlers.set(X.kind,t=>this.visitCommonTable(t)),this.handlers.set(D.kind,t=>this.visitFromClause(t)),this.handlers.set(me.kind,t=>this.visitJoinClause(t)),this.handlers.set(pe.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(we.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set($.kind,t=>this.visitSourceExpression(t)),this.handlers.set(B.kind,t=>this.visitTableSource(t)),this.handlers.set(ze.kind,t=>this.visitFunctionSource(t)),this.handlers.set(Ue.kind,t=>this.visitParenSource(t)),this.handlers.set(_.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(Se.kind,t=>this.visitInlineQuery(t)),e||(this.handlers.set(se.kind,t=>this.visitWhereClause(t)),this.handlers.set(ue.kind,t=>this.visitGroupByClause(t)),this.handlers.set(ce.kind,t=>this.visitHavingClause(t)),this.handlers.set(le.kind,t=>this.visitOrderByClause(t)),this.handlers.set(ve.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(oe.kind,t=>this.visitLimitClause(t)),this.handlers.set(Le.kind,t=>this.visitOffsetClause(t)),this.handlers.set(De.kind,t=>this.visitFetchClause(t)),this.handlers.set(Ne.kind,t=>this.visitForClause(t)),this.handlers.set(Ie.kind,t=>this.visitOrderByItem(t)),this.handlers.set(J.kind,t=>this.visitSelectClause(t)),this.handlers.set(q.kind,t=>this.visitSelectItem(t)),this.handlers.set(H.kind,t=>this.visitParenExpression(t)),this.handlers.set(C.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(te.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(ie.kind,t=>this.visitCaseExpression(t)),this.handlers.set(xe.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(be.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(ye.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(j.kind,t=>this.visitFunctionCall(t)),this.handlers.set(fe.kind,t=>this.visitArrayExpression(t)),this.handlers.set(Ce.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(ke.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(We.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 V?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof V?e.qualifiedName.name.value:e.qualifiedName.name.name}collect(e){return this.visit(e),this.getTableSources()}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.selectableOnly||this.collectCTEs(e),this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}collectCTEs(e){let t=new ee;t.visit(e);let n=t.getCommonTables();for(let r of n)this.cteNames.add(r.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 st=class extends f{static{this.kind=Symbol("HintClause")}constructor(e){super(),this.hintContent=e}getFullHint(){return"/*+ "+this.hintContent+" */"}static isHintClause(e){let t=e.trim();return t.length>=5&&t.substring(0,3)==="/*+"&&t.substring(t.length-2)==="*/"}static extractHintContent(e){let t=e.trim();if(!this.isHintClause(t))throw new Error("Not a valid hint clause: "+e);return t.slice(3,-2).trim()}};var p=class{constructor(e,t="",n=""){this.innerTokens=[];this.type=e,this.text=t,this.containerType=n}};var ot=class{static collect(e){let t=[];function n(r){if(!(!r||typeof r!="object")){r.constructor&&r.constructor.kind===T.kind&&t.push(r);for(let i of Object.keys(r)){let s=r[i];Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&s.constructor&&s.constructor.kind&&n(s)}}}return n(e),t}};var cn=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var pn=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 St=class extends f{static{this.kind=Symbol("UpdateQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.updateClause=e.updateClause,this.setClause=e.setClause instanceof Xe?e.setClause:new Xe(e.setClause),this.whereClause=e.whereClause??null,this.fromClause=e.fromClause??null,this.returningClause=e.returning??null}};var Re=class o{constructor(e=null,t=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=e??null,this.commonTableCollector=new ee,this.commonTables=[],this.initialCommonTables=t,this.handlers=new Map,this.handlers.set(g.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(J.kind,n=>this.visitSelectClause(n)),this.handlers.set($.kind,n=>this.visitSourceExpression(n)),this.handlers.set(D.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(r=>r.name==="*");if(t.length===0)return;if(this.selectValues.some(r=>r.value instanceof v&&r.value.namespaces===null)){e.fromClause&&this.processFromClause(e.fromClause,!0),this.selectValues=this.selectValues.filter(r=>r.name!=="*");return}let n=t.filter(r=>r.value instanceof v&&r.value.namespaces).map(r=>r.value.getNamespace());if(e.fromClause){let r=e.fromClause.getSourceAliasName();if(r&&n.includes(r)&&this.processFromClause(e.fromClause,!1),e.fromClause.joins)for(let i of e.fromClause.joins){let s=i.getSourceAliasName();s&&n.includes(s)&&this.processJoinClause(i)}}this.selectValues=this.selectValues.filter(r=>r.name!=="*")}processFromClause(e,t){if(e){let n=e.getSourceAliasName();if(this.processSourceExpression(n,e.source),e.joins&&t)for(let r of e.joins)this.processJoinClause(r)}}processJoinClause(e){let t=e.getSourceAliasName();this.processSourceExpression(t,e.source)}processSourceExpression(e,t){let n=this.commonTables.find(r=>r.aliasExpression.table.name===e);if(n){let r=this.commonTables.filter(a=>a.aliasExpression.table.name!==e);new o(this.tableColumnResolver,r).collect(n.query).forEach(a=>{this.addSelectValueAsUnique(a.name,new v(e?[e]:null,a.name))})}else new o(this.tableColumnResolver,this.commonTables).collect(t).forEach(s=>{this.addSelectValueAsUnique(s.name,new v(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 v){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 v(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 v([t],n))})}return}else if(e.datasource instanceof _){let t=e.getAliasName();new o(this.tableColumnResolver,this.commonTables).collect(e.datasource.query).forEach(i=>{this.addSelectValueAsUnique(i.name,new v(t?[t]:null,i.name))});return}else if(e.datasource instanceof Ue)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 vt=class extends f{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 Re().collect(this.asSelectQuery).map(r=>new q(r.value,r.name)):e=[new q(new V("*"))],new g({selectClause:new J(e),fromClause:new D(new $(new B(null,this.tableName.name),null),null)})}getCountQuery(){return new g({selectClause:new J([new q(new j(null,"count",new v(null,"*"),null))]),fromClause:new D(new $(new B(null,this.tableName.name),null),null)})}};var pr={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"}},mn=class o{constructor(e){this.handlers=new Map;this.index=1;e?.preset&&(e={...e.preset,...e}),this.parameterDecorator=new pn({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 cn({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.handlers.set(K.kind,t=>this.visitValueList(t)),this.handlers.set(v.kind,t=>this.visitColumnReference(t)),this.handlers.set(Ve.kind,t=>this.visitQualifiedName(t)),this.handlers.set(j.kind,t=>this.visitFunctionCall(t)),this.handlers.set(te.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(C.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(G.kind,t=>this.visitLiteralValue(t)),this.handlers.set(T.kind,t=>this.visitParameterExpression(t)),this.handlers.set(be.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(xe.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(V.kind,t=>this.visitRawString(t)),this.handlers.set(x.kind,t=>this.visitIdentifierString(t)),this.handlers.set(H.kind,t=>this.visitParenExpression(t)),this.handlers.set(ae.kind,t=>this.visitCastExpression(t)),this.handlers.set(ie.kind,t=>this.visitCaseExpression(t)),this.handlers.set(fe.kind,t=>this.visitArrayExpression(t)),this.handlers.set(Ce.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(Ze.kind,t=>this.visitArraySliceExpression(t)),this.handlers.set(et.kind,t=>this.visitArrayIndexExpression(t)),this.handlers.set(ye.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(We.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(Te.kind,t=>this.visitTypeValue(t)),this.handlers.set(ke.kind,t=>this.visitTupleExpression(t)),this.handlers.set(Se.kind,t=>this.visitInlineQuery(t)),this.handlers.set(Ee.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(Je.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(dt.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(ht.kind,t=>this.visitWindowFrameBoundaryValue(t)),this.handlers.set(Qe.kind,t=>this.visitPartitionByClause(t)),this.handlers.set(le.kind,t=>this.visitOrderByClause(t)),this.handlers.set(Ie.kind,t=>this.visitOrderByItem(t)),this.handlers.set(q.kind,t=>this.visitSelectItem(t)),this.handlers.set(J.kind,t=>this.visitSelectClause(t)),this.handlers.set(ft.kind,t=>this.visitDistinct(t)),this.handlers.set(Ct.kind,t=>this.visitDistinctOn(t)),this.handlers.set(st.kind,t=>this.visitHintClause(t)),this.handlers.set(B.kind,t=>this.visitTableSource(t)),this.handlers.set(ze.kind,t=>this.visitFunctionSource(t)),this.handlers.set($.kind,t=>this.visitSourceExpression(t)),this.handlers.set(Z.kind,t=>this.visitSourceAliasExpression(t)),this.handlers.set(D.kind,t=>this.visitFromClause(t)),this.handlers.set(me.kind,t=>this.visitJoinClause(t)),this.handlers.set(pe.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(we.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(se.kind,t=>this.visitWhereClause(t)),this.handlers.set(ue.kind,t=>this.visitGroupByClause(t)),this.handlers.set(ce.kind,t=>this.visitHavingClause(t)),this.handlers.set(_e.kind,t=>this.visitWindowClause(t)),this.handlers.set(ve.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(oe.kind,t=>this.visitLimitClause(t)),this.handlers.set(Le.kind,t=>this.visitOffsetClause(t)),this.handlers.set(De.kind,t=>this.visitFetchClause(t)),this.handlers.set(ut.kind,t=>this.visitFetchExpression(t)),this.handlers.set(Ne.kind,t=>this.visitForClause(t)),this.handlers.set(ne.kind,t=>this.visitWithClause(t)),this.handlers.set(X.kind,t=>this.visitCommonTable(t)),this.handlers.set(g.kind,t=>this.visitSimpleQuery(t)),this.handlers.set(_.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(W.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(he.kind,t=>this.visitValuesQuery(t)),this.handlers.set(ke.kind,t=>this.visitTupleExpression(t)),this.handlers.set(Ye.kind,t=>this.visitInsertQuery(t)),this.handlers.set(nt.kind,t=>this.visitInsertClause(t)),this.handlers.set(St.kind,t=>this.visitUpdateQuery(t)),this.handlers.set(yt.kind,t=>this.visitUpdateClause(t)),this.handlers.set(Xe.kind,t=>this.visitSetClause(t)),this.handlers.set(tt.kind,t=>this.visitSetClauseItem(t)),this.handlers.set(Ut.kind,t=>this.visitReturningClause(t)),this.handlers.set(vt.kind,t=>this.visitCreateTableQuery(t))}static{this.SPACE_TOKEN=new p(10," ")}static{this.COMMA_TOKEN=new p(3,",")}static{this.ARGUMENT_SPLIT_COMMA_TOKEN=new p(11,",")}static{this.PAREN_OPEN_TOKEN=new p(4,"(")}static{this.PAREN_CLOSE_TOKEN=new p(4,")")}static{this.DOT_TOKEN=new p(8,".")}visitBinarySelectQuery(e){let t=new p(0,"");return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,e.operator.value,"BinarySelectQueryOperator")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}static commaSpaceTokens(){return[o.COMMA_TOKEN,o.SPACE_TOKEN]}static argumentCommaSpaceTokens(){return[o.ARGUMENT_SPLIT_COMMA_TOKEN,o.SPACE_TOKEN]}visitQualifiedName(e){let t=new p(0,"","QualifiedName");if(e.namespaces)for(let n=0;n<e.namespaces.length;n++)t.innerTokens.push(e.namespaces[n].accept(this)),t.innerTokens.push(o.DOT_TOKEN);return t.innerTokens.push(e.name.accept(this)),t}visitPartitionByClause(e){let t=new p(1,"partition by","PartitionByClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOrderByClause(e){let t=new p(1,"order by","OrderByClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.order.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(this.visit(e.order[n]));return t}visitOrderByItem(e){let t=new p(0,"","OrderByItem");return t.innerTokens.push(this.visit(e.value)),e.sortDirection&&e.sortDirection!=="asc"&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"desc"))),e.nullsPosition&&(e.nullsPosition==="first"?(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"nulls first"))):e.nullsPosition==="last"&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"nulls last")))),t}parse(e){this.index=1;let t=this.visit(e),n=ot.collect(e).sort((i,s)=>(i.index??0)-(s.index??0)),r=this.parameterDecorator.style;if(r==="named"){let i={};for(let s of n){let a=s.name.value;if(i.hasOwnProperty(a)){if(i[a]!==s.value)throw new Error(`Duplicate parameter name '${a}' with different values detected during query composition.`);continue}i[a]=s.value}return{token:t,params:i}}else if(r==="indexed"){let i=n.map(s=>s.value);return{token:t,params:i}}else if(r==="anonymous"){let i=n.map(s=>s.value);return{token:t,params:i}}return{token:t,params:[]}}visit(e){let t=this.handlers.get(e.getKind());if(t){let n=t(e);return this.addCommentsToToken(n,e.comments),n}throw new Error(`[SqlPrintTokenParser] No handler for kind: ${e.getKind().toString()}`)}addCommentsToToken(e,t){if(!t||t.length===0)return;let n=this.createCommentBlocks(t);n.length>0&&this.insertCommentBlocksWithSpacing(e,n)}createCommentBlocks(e){let t=[];for(let n of e)n.trim()&&t.push(this.createSingleCommentBlock(n));return t}createSingleCommentBlock(e){let t=new p(0,"","CommentBlock"),n=new p(6,this.formatBlockComment(e));t.innerTokens.push(n);let r=new p(12,"");t.innerTokens.push(r);let i=new p(10," ");return t.innerTokens.push(i),t}insertCommentBlocksWithSpacing(e,t){if(e.innerTokens.unshift(...t),this.shouldAddSeparatorSpace(e.containerType)){let r=new p(10," ");e.innerTokens.splice(t.length,0,r),e.innerTokens.length>t.length+1&&e.innerTokens[t.length+1].type===10&&e.innerTokens.splice(t.length+1,1)}else e.innerTokens.length>t.length&&e.innerTokens[t.length].type===10&&e.innerTokens.splice(t.length,1)}shouldAddSeparatorSpace(e){return this.isClauseLevelContainer(e)}isClauseLevelContainer(e){switch(e){case"SelectClause":case"FromClause":case"WhereClause":case"GroupByClause":case"HavingClause":case"OrderByClause":case"LimitClause":case"OffsetClause":case"WithClause":case"SimpleSelectQuery":return!0;default:return!1}}formatBlockComment(e){return`/* ${e} */`}visitValueList(e){let t=new p(0,"","ValueList");for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...o.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t}visitColumnReference(e){let t=new p(0,"","ColumnReference");return t.innerTokens.push(e.qualifiedName.accept(this)),t}visitFunctionCall(e){let t=new p(0,"","FunctionCall");return t.innerTokens.push(e.qualifiedName.accept(this)),t.innerTokens.push(o.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),e.over&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"over")),e.over instanceof 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 p(0,"","UnaryExpression");return t.innerTokens.push(this.visit(e.operator)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.expression)),t}visitBinaryExpression(e){let t=new p(0,"","BinaryExpression");return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(5,e.operator.value)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}visitLiteralValue(e){let t;return typeof e.value=="string"?e.isDollarString?t=e.value:t=`'${e.value.replace(/'/g,"''")}'`:e.value===null?t="null":t=e.value.toString(),new p(2,t,"LiteralValue")}visitParameterExpression(e){e.index=this.index;let t=this.parameterDecorator.decorate(e.name.value,e.index),n=new p(7,t);return this.index++,n}visitSwitchCaseArgument(e){let t=new p(0,"","SwitchCaseArgument");for(let n of e.cases)t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(n.accept(this));return e.elseValue&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.createElseToken(e.elseValue))),t}createElseToken(e){let t=new p(0,"","ElseClause");t.innerTokens.push(new p(1,"else")),t.innerTokens.push(o.SPACE_TOKEN);let n=new p(0,"","CaseElseValue");return n.innerTokens.push(this.visit(e)),t.innerTokens.push(n),t}visitCaseKeyValuePair(e){let t=new p(0,"","CaseKeyValuePair");t.innerTokens.push(new p(1,"when")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.key)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"then")),t.innerTokens.push(o.SPACE_TOKEN);let n=new p(0,"","CaseThenValue");return n.innerTokens.push(this.visit(e.value)),t.innerTokens.push(n),t}visitRawString(e){return new p(2,e.value,"RawString")}visitIdentifierString(e){let t=e.name==="*"?e.name:this.identifierDecorator.decorate(e.name);return new p(2,t,"IdentifierString")}visitParenExpression(e){let t=new p(0,"","ParenExpression");return t.innerTokens.push(o.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitCastExpression(e){let t=new p(0,"","CastExpression");return t.innerTokens.push(this.visit(e.input)),t.innerTokens.push(new p(5,"::")),t.innerTokens.push(this.visit(e.castType)),t}visitCaseExpression(e){let t=new p(0,"","CaseExpression");return t.innerTokens.push(new p(1,"case")),e.condition&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition))),t.innerTokens.push(this.visit(e.switchCase)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"end")),t}visitArrayExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(new p(1,"array")),t.innerTokens.push(new p(4,"[")),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(new p(4,"]")),t}visitArrayQueryExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(new p(1,"array")),t.innerTokens.push(new p(4,"(")),t.innerTokens.push(this.visit(e.query)),t.innerTokens.push(new p(4,")")),t}visitArraySliceExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(this.visit(e.array)),t.innerTokens.push(new p(4,"[")),e.startIndex&&t.innerTokens.push(this.visit(e.startIndex)),t.innerTokens.push(new p(5,":")),e.endIndex&&t.innerTokens.push(this.visit(e.endIndex)),t.innerTokens.push(new p(4,"]")),t}visitArrayIndexExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(this.visit(e.array)),t.innerTokens.push(new p(4,"[")),t.innerTokens.push(this.visit(e.index)),t.innerTokens.push(new p(4,"]")),t}visitBetweenExpression(e){let t=new p(0,"","BetweenExpression");return t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(o.SPACE_TOKEN),e.negated&&(t.innerTokens.push(new p(1,"not")),t.innerTokens.push(o.SPACE_TOKEN)),t.innerTokens.push(new p(1,"between")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.lower)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"and")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.upper)),t}visitStringSpecifierExpression(e){let t=e.specifier.accept(this).text,n=e.value.accept(this).text;return new p(2,t+n,"StringSpecifierExpression")}visitTypeValue(e){let t=new p(0,"","TypeValue");return t.innerTokens.push(e.qualifiedName.accept(this)),e.argument&&(t.innerTokens.push(o.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN)),t}visitTupleExpression(e){let t=new p(0,"","TupleExpression");t.innerTokens.push(o.PAREN_OPEN_TOKEN);for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...o.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitWindowFrameExpression(e){let t=new p(0,"","WindowFrameExpression"),n=!0;return e.partition&&(t.innerTokens.push(this.visit(e.partition)),n=!1),e.order&&(n?n=!1:t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.order))),e.frameSpec&&(n?n=!1:t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.frameSpec))),t}visitWindowFrameSpec(e){let t=new p(0,"","WindowFrameSpec");return t.innerTokens.push(new p(1,e.frameType)),e.endBound===null?(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this))):(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"between")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"and")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.endBound.accept(this))),t}visitWindowFrameBoundaryValue(e){let t=new p(0,"","WindowFrameBoundaryValue");return t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,e.isFollowing?"following":"preceding")),t}visitWindowFrameBoundStatic(e){return new p(1,e.bound)}visitSelectItem(e){let t=new p(0,"","SelectItem");if(t.innerTokens.push(this.visit(e.value)),!e.identifier)return t;if(e.value instanceof v){let n=e.value.column.name;if(e.identifier.name===n)return t}return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.identifier)),t}visitSelectClause(e){let t=new p(1,"select","SelectClause"),n="select";for(let r of e.hints)n+=" "+this.visit(r).text;if(e.distinct){let r=e.distinct.accept(this);if(r.innerTokens&&r.innerTokens.length>0){let i=r.text;for(let s of r.innerTokens)i+=this.flattenTokenText(s);n+=" "+i}else n+=" "+r.text}t.text=n,t.innerTokens.push(o.SPACE_TOKEN);for(let r=0;r<e.items.length;r++)r>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[r]));return t}flattenTokenText(e){let t=e.text;if(e.innerTokens)for(let n of e.innerTokens)t+=this.flattenTokenText(n);return t}visitHintClause(e){return new p(2,e.getFullHint())}visitDistinct(e){return new p(1,"distinct")}visitDistinctOn(e){let t=new p(0,"","DistinctOn");return t.innerTokens.push(new p(1,"distinct on")),t.innerTokens.push(o.PAREN_OPEN_TOKEN),t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitTableSource(e){let t="";Array.isArray(e.namespaces)&&e.namespaces.length>0&&(t=e.namespaces.map(r=>r.accept(this).text).join(".")+"."),t+=e.table.accept(this).text;let n=new p(2,t);return e.identifier&&(e.identifier.name,e.table.name),n}visitSourceExpression(e){let t=new p(0,"","SourceExpression");if(t.innerTokens.push(e.datasource.accept(this)),!e.aliasExpression)return t;if(e.datasource instanceof B){let n=e.datasource.table.name;return e.aliasExpression.table.name===n||(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this))),t}else return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this)),t}visitFromClause(e){let t=new p(1,"from","FromClause");if(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.joins)for(let n=0;n<e.joins.length;n++)t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.joins[n]));return t}visitJoinClause(e){let t=new p(0,"","JoinClause");return t.innerTokens.push(new p(1,e.joinType.value)),e.lateral&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"lateral"))),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.condition&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition))),t}visitJoinOnClause(e){let t=new p(0,"","JoinOnClause");return t.innerTokens.push(new p(1,"on")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitJoinUsingClause(e){let t=new p(0,"","JoinUsingClause");return t.innerTokens.push(new p(1,"using")),t.innerTokens.push(o.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.condition)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitFunctionSource(e){let t=new p(0,"","FunctionSource");return t.innerTokens.push(e.qualifiedName.accept(this)),t.innerTokens.push(o.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitSourceAliasExpression(e){let t=new p(0,"","SourceAliasExpression");if(t.innerTokens.push(this.visit(e.table)),e.columns){t.innerTokens.push(o.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...o.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));t.innerTokens.push(o.PAREN_CLOSE_TOKEN)}return t}visitWhereClause(e){let t=new p(1,"where","WhereClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitGroupByClause(e){let t=new p(1,"group by","GroupByClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.grouping.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(this.visit(e.grouping[n]));return t}visitHavingClause(e){let t=new p(1,"having","HavingClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitWindowClause(e){let t=new p(1,"window","WindowClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.windows.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(this.visit(e.windows[n]));return t}visitWindowFrameClause(e){let t=new p(0,"","WindowFrameClause");return t.innerTokens.push(e.name.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(o.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitLimitClause(e){let t=new p(1,"limit","LimitClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOffsetClause(e){let t=new p(1,"offset","OffsetClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitFetchClause(e){let t=new p(1,"fetch","FetchClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.expression)),t}visitFetchExpression(e){let t=new p(0,"","FetchExpression");return t.innerTokens.push(new p(1,e.type)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.count.accept(this)),e.unit&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,e.unit))),t}visitForClause(e){let t=new p(1,"for","ForClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,e.lockMode)),t}visitWithClause(e){let t=new p(1,"with","WithClause");t.innerTokens.push(o.SPACE_TOKEN),e.recursive&&(t.innerTokens.push(new p(1,"recursive")),t.innerTokens.push(o.SPACE_TOKEN));for(let n=0;n<e.tables.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(e.tables[n].accept(this));return t.innerTokens.push(o.SPACE_TOKEN),t}visitCommonTable(e){let t=new p(0,"","CommonTable");t.innerTokens.push(e.aliasExpression.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),e.materialized!==null&&(e.materialized?t.innerTokens.push(new p(1,"materialized")):t.innerTokens.push(new p(1,"not materialized")),t.innerTokens.push(o.SPACE_TOKEN)),t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new p(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitSimpleQuery(e){let t=new p(0,"","SimpleSelectQuery");return e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(e.selectClause.accept(this)),e.fromClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this)),e.whereClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.groupByClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.groupByClause.accept(this))),e.havingClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.havingClause.accept(this))),e.orderByClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.orderByClause.accept(this))),e.windowClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.windowClause.accept(this))),e.limitClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.limitClause.accept(this))),e.offsetClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.offsetClause.accept(this))),e.fetchClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.fetchClause.accept(this))),e.forClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.forClause.accept(this)))),t}visitSubQuerySource(e){let t=new p(0,"");t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new p(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitValuesQuery(e){let t=new p(1,"values","ValuesQuery");t.innerTokens.push(o.SPACE_TOKEN);let n=new p(0,"","Values");for(let r=0;r<e.tuples.length;r++)r>0&&n.innerTokens.push(...o.commaSpaceTokens()),n.innerTokens.push(e.tuples[r].accept(this));return t.innerTokens.push(n),t}visitInlineQuery(e){let t=new p(0,"");t.innerTokens.push(o.PAREN_OPEN_TOKEN);let n=new p(0,"","InlineQuery");return n.innerTokens.push(e.selectQuery.accept(this)),t.innerTokens.push(n),t.innerTokens.push(o.PAREN_CLOSE_TOKEN),t}visitInsertQuery(e){let t=new p(0,"","InsertQuery");return t.innerTokens.push(this.visit(e.insertClause)),e.selectQuery&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(this.visit(e.selectQuery))),t}visitInsertClause(e){let t=new p(0,"");if(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"insert into")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),e.columns.length>0){t.innerTokens.push(o.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(e.columns[n].accept(this));t.innerTokens.push(o.PAREN_CLOSE_TOKEN)}return t}visitUpdateQuery(e){let t=new p(0,"","UpdateQuery");return e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(e.updateClause.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.setClause.accept(this)),e.fromClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this))),e.whereClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.returningClause&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.returningClause.accept(this))),t}visitUpdateClause(e){let t=new p(1,"update","UpdateClause");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t}visitSetClause(e){let t=new p(1,"set","SelectClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.items.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[n]));return t}visitSetClauseItem(e){let t=new p(0,"","SetClauseItem");return t.innerTokens.push(e.column.accept(this)),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(5,"=")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.value.accept(this)),t}visitReturningClause(e){let t=new p(1,"returning","ReturningClause");t.innerTokens.push(o.SPACE_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...o.commaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));return t}visitCreateTableQuery(e){let t=new p(1,e.isTemporary?"create temporary table":"create table","CreateTableQuery");return t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.tableName.accept(this)),e.asSelectQuery&&(t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(o.SPACE_TOKEN),t.innerTokens.push(e.asSelectQuery.accept(this))),t}};var Qt=class{constructor(e=" ",t=0,n=`\r
|
|
13
|
+
`){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 Xn(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.")}},Xn=class{constructor(e,t){this.level=e,this.text=t}};var dn=class o{constructor(e){this.insideWithClause=!1;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.exportComment=e?.exportComment??!1,this.strictCommentPlacement=e?.strictCommentPlacement??!1,this.withClauseStyle=e?.withClauseStyle??"standard",this.linePrinter=new Qt(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","SimpleSelectQuery"])}print(e,t=0){return this.linePrinter=new Qt(this.indentChar,this.indentSize,this.newline),this.insideWithClause=!1,this.linePrinter.lines.length>0&&t!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=t),this.appendToken(e,t,void 0),this.linePrinter.print()}appendToken(e,t,n){let r=this.insideWithClause;if(e.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"&&(this.insideWithClause=!0),this.shouldSkipToken(e))return;let i=this.linePrinter.getCurrentLine();if(e.type===1)this.handleKeywordToken(e,t);else if(e.type===3)this.handleCommaToken(e,t,n);else if(e.type===5&&e.text.toLowerCase()==="and")this.handleAndOperatorToken(e,t);else if(e.containerType==="JoinClause")this.handleJoinClauseToken(e,t);else if(e.type===6)this.exportComment&&this.linePrinter.appendText(e.text);else if(e.type===10)this.handleSpaceToken(e,n);else if(e.type===12)this.handleCommentNewlineToken(e,t);else if(e.containerType==="CommonTable"&&this.withClauseStyle==="cte-oneline"){this.handleCteOnelineToken(e,t);return}else this.linePrinter.appendText(e.text);if(e.keywordTokens&&e.keywordTokens.length>0)for(let a=0;a<e.keywordTokens.length;a++){let l=e.keywordTokens[a];this.appendToken(l,t,e.containerType)}let s=t;!this.isOnelineMode()&&i.text!==""&&this.indentIncrementContainers.has(e.containerType)&&(this.insideWithClause&&this.withClauseStyle==="full-oneline"||(s++,this.linePrinter.appendNewline(s)));for(let a=0;a<e.innerTokens.length;a++){let l=e.innerTokens[a];this.appendToken(l,s,e.containerType)}if(e.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"){this.insideWithClause=!1,this.linePrinter.appendNewline(t);return}s!==t&&(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t))}shouldSkipToken(e){return e.type===12?!1:(!e.innerTokens||e.innerTokens.length===0)&&e.text===""}applyKeywordCase(e){return this.keywordCase==="upper"?e.toUpperCase():this.keywordCase==="lower"?e.toLowerCase():e}handleKeywordToken(e,t){let n=this.applyKeywordCase(e.text);this.linePrinter.appendText(n)}handleCommaToken(e,t,n){let r=e.text;this.insideWithClause&&this.withClauseStyle==="full-oneline"?this.linePrinter.appendText(r):this.withClauseStyle==="cte-oneline"&&n==="WithClause"?(this.linePrinter.appendText(r),this.linePrinter.appendNewline(t)):this.commaBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)):this.commaBreak==="after"?(this.linePrinter.appendText(r),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t)):this.linePrinter.appendText(r)}handleAndOperatorToken(e,t){let n=this.applyKeywordCase(e.text);this.andBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(n)):this.andBreak==="after"?(this.linePrinter.appendText(n),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t)):this.linePrinter.appendText(n)}handleJoinClauseToken(e,t){let n=this.applyKeywordCase(e.text);this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(n)}handleSpaceToken(e,t){this.shouldSkipCommentBlockSpace(t)||this.linePrinter.appendText(e.text)}shouldSkipCommentBlockSpace(e){return e==="CommentBlock"&&this.insideWithClause&&this.withClauseStyle==="full-oneline"}handleCommentNewlineToken(e,t){this.shouldSkipCommentNewline()||this.isOnelineMode()||this.linePrinter.appendNewline(t)}shouldSkipCommentNewline(){return this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.withClauseStyle==="cte-oneline"}isOnelineMode(){return this.newline===" "}handleCteOnelineToken(e,t){let r=this.createCteOnelinePrinter().print(e,t),i=this.cleanDuplicateSpaces(r);this.linePrinter.appendText(i)}createCteOnelinePrinter(){return new o({indentChar:"",indentSize:0,newline:" ",commaBreak:this.commaBreak,andBreak:this.andBreak,keywordCase:this.keywordCase,exportComment:this.exportComment,strictCommentPlacement:this.strictCommentPlacement,withClauseStyle:"standard"})}cleanDuplicateSpaces(e){return e.replace(/\s{2,}/g," ")}};var xu=["mysql","postgres","sqlserver","sqlite"],je=class{constructor(e={}){let t=e.preset?pr[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 mn(n),this.printer=new dn(e)}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var at=class{constructor(){this.sqlFormatter=new je({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(e,t=null){return t&&(this.sqlFormatter=new je(t)),this.sqlFormatter.format(e).formattedSql}formatWithParameters(e,t=null){t&&(this.sqlFormatter=new je(t));let n=this.sqlFormatter.format(e);return{sql:n.formattedSql,params:n.params}}visit(e){return this.format(e)}};var hn=class{constructor(){this.sourceCollector=new it(!0),this.cteCollector=new ee,this.formatter=new at}build(e){if(e.length===0)return new ne(!1,e);let t=this.resolveDuplicateNames(e),{tableMap:n,recursiveCTEs:r,dependencies:i}=this.buildDependencyGraph(t),s=this.sortCommonTables(t,n,r,i);return new ne(r.size>0,s)}resolveDuplicateNames(e){let t=new Map;for(let r of e){let i=r.aliasExpression.table.name;t.has(i)||t.set(i,[]),t.get(i).push(r)}let n=[];for(let[r,i]of t.entries()){if(i.length===1){n.push(i[0]);continue}let s=i.map(l=>this.formatter.format(l.query));if(new Set(s).size===1)n.push(i[0]);else throw new Error(`CTE name conflict detected: '${r}' 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,r=new Map,i=new Map;for(let s of e){let a=s.aliasExpression.table.name,l=this.sourceCollector.collect(s.query);for(let c of l)if(c.table.name===a){n.add(a);break}r.has(a)||r.set(a,new Set);let u=this.cteCollector.collect(s.query);for(let c of u){let m=c.aliasExpression.table.name;t.has(m)&&(r.get(a).add(m),i.has(m)||i.set(m,new Set),i.get(m).add(a))}}return{tableMap:t,recursiveCTEs:n,dependencies:r}}sortCommonTables(e,t,n,r){let i=[],s=[],a=new Set,l=new Set,u=c=>{if(a.has(c))return;if(l.has(c))throw new Error(`Circular reference detected in CTE: ${c}`);l.add(c);let m=r.get(c)||new Set;for(let h of m)u(h);l.delete(c),a.add(c),n.has(c)?i.push(t.get(c)):s.push(t.get(c))};for(let c of e){let m=c.aliasExpression.table.name;a.has(m)||u(m)}return[...i,...s]}};var fn=class{constructor(){this.nameConflictResolver=new hn,this.cteCollector=new ee}inject(e,t){if(t.length===0)return e;t.push(...this.cteCollector.collect(e));let n=this.nameConflictResolver.build(t);if(e instanceof g)return this.injectIntoSimpleQuery(e,n);if(e instanceof W)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 g)return this.injectIntoSimpleQuery(e.left,t),e;if(e.left instanceof W)return this.injectIntoBinaryQuery(e.left,t),e;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var Ge=class{constructor(){}static normalize(e){let n=new ee().collect(e);return n.length===0?e:(new gt().execute(e),new fn().inject(e,n))}};var mr=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))(mr||{}),Oe=class{constructor(e,t=!1,n="columnNameOnly",r){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=null;this.commonTables=[];this.tableColumnResolver=e??null,this.includeWildCard=t,this.commonTableCollector=new ee,this.commonTables=[],this.duplicateDetection=n,this.options=r||{},this.handlers=new Map,this.handlers.set(g.kind,i=>this.visitSimpleSelectQuery(i)),this.handlers.set(J.kind,i=>this.visitSelectClause(i)),this.handlers.set(D.kind,i=>this.visitFromClause(i)),this.handlers.set(se.kind,i=>this.visitWhereClause(i)),this.handlers.set(ue.kind,i=>this.visitGroupByClause(i)),this.handlers.set(ce.kind,i=>this.visitHavingClause(i)),this.handlers.set(le.kind,i=>this.visitOrderByClause(i)),this.handlers.set(ve.kind,i=>this.visitWindowFrameClause(i)),this.handlers.set(oe.kind,i=>this.visitLimitClause(i)),this.handlers.set(Le.kind,i=>this.offsetClause(i)),this.handlers.set(De.kind,i=>this.visitFetchClause(i)),this.handlers.set(pe.kind,i=>this.visitJoinOnClause(i)),this.handlers.set(we.kind,i=>this.visitJoinUsingClause(i)),this.handlers.set(v.kind,i=>this.visitColumnReference(i)),this.handlers.set(C.kind,i=>this.visitBinaryExpression(i)),this.handlers.set(te.kind,i=>this.visitUnaryExpression(i)),this.handlers.set(j.kind,i=>this.visitFunctionCall(i)),this.handlers.set(H.kind,i=>this.visitParenExpression(i)),this.handlers.set(ie.kind,i=>this.visitCaseExpression(i)),this.handlers.set(ae.kind,i=>this.visitCastExpression(i)),this.handlers.set(ye.kind,i=>this.visitBetweenExpression(i)),this.handlers.set(fe.kind,i=>this.visitArrayExpression(i)),this.handlers.set(Ce.kind,i=>this.visitArrayQueryExpression(i)),this.handlers.set(K.kind,i=>this.visitValueList(i)),this.handlers.set(ve.kind,i=>this.visitWindowFrameClause(i)),this.handlers.set(Ee.kind,i=>this.visitWindowFrameExpression(i)),this.handlers.set(Qe.kind,i=>this.visitPartitionByClause(i))}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 r=n?n+"."+e:e;this.selectValues.some(i=>{let s="";return i.value&&typeof i.value.getNamespace=="function"&&(s=i.value.getNamespace()||""),(s?s+"."+i.name:i.name)===r})||this.selectValues.push({name:e,value:t})}}visit(e){if(!this.isRootVisit){this.visitNode(e);return}if(!(e instanceof g))throw new Error("Root visit requires a SimpleSelectQuery. Decompose compound queries before collecting columns.");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 Re(this.tableColumnResolver,this.commonTables).collect(e);for(let r of n)this.addSelectValueAsUnique(r.name,r.value);if(e.joins)for(let r of e.joins)r.condition&&r.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 pt=class o{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The source component is complete but there are additional tokens.`);return r.value}static parseTableSourceFromLexemes(e,t){let n=Pe.parseFromLexeme(e,t);return this.parseTableSource(n)}static parseFromLexeme(e,t){let n=t;if(n<e.length&&e[n].type&4)return this.parseParenSource(e,n);let r=Pe.parseFromLexeme(e,n);return r.lastTokenType&2048?o.parseFunctionSource(e,r):o.parseTableSource(r)}static parseTableSource(e){let{namespaces:t,name:n,newIndex:r}=e;return{value:new B(t,n.name),newIndex:r}}static parseFunctionSource(e,t){let n=t.newIndex,{namespaces:r,name:i}=t,s=k.parseArgument(4,8,e,n);n=s.newIndex;let a=i.name;return{value:new ze({namespaces:r,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 r=e[n].value;if(r==="select"||r==="values"||r==="with"){let i=this.parseSubQuerySource(e,n);if(n=i.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:i.value,newIndex:n}}else if(e[n].type==4){let i=this.parseParenSource(e,n);if(n=i.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:i.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:r,newIndex:i}=Q.parseFromLexeme(e,n);return n=i,{value:new _(r),newIndex:n}}};var Lt=class extends Error{constructor(t){super(`CTE '${t}' already exists in the query`);this.cteName=t;this.name="DuplicateCTEError"}},Et=class extends Error{constructor(t,n){super(`Invalid CTE name '${t}': ${n}`);this.cteName=t;this.name="InvalidCTENameError"}},At=class extends Error{constructor(t){super(`CTE '${t}' not found in the query`);this.cteName=t;this.name="CTENotFoundError"}};var bt=class{constructor(e,t){this.options=t||{},this.tableColumnResolver=e,this.columnCollector=new Oe(this.tableColumnResolver)}find(e,t){let n=typeof t=="string"?[t]:t,i=new ee().collect(e),s=new Map;for(let a of i)s.set(a.getSourceAliasName(),a);return this.findUpstream(e,n,s)}handleTableSource(e,t,n){let r=n.get(e.table.name);if(r){let i=new Map(n);i.delete(e.table.name);let s=this.findUpstream(r.query,t,i);return s.length===0?null:s}return null}handleSubQuerySource(e,t,n){let r=this.findUpstream(e.query,t,n);return r.length===0?null:r}processFromClauseBranches(e,t,n){let r=e.getSources();if(r.length===0)return null;let i=[],s=!0,a=0;for(let l of r){let u=l.datasource,c=null;if(u instanceof B)c=this.handleTableSource(u,t,n),a++;else if(u instanceof _)c=this.handleSubQuerySource(u,t,n),a++;else{if(u instanceof he)continue;s=!1;break}if(c===null){s=!1;break}i.push(c)}return s&&i.length===a?i.flat():null}findUpstream(e,t,n){if(e instanceof g){let r=e.fromClause;if(r){let c=this.processFromClauseBranches(r,t,n);if(c&&c.length>0)return c}let i=this.columnCollector.collect(e).map(c=>c.name),s=this.collectCTEColumns(e,n),a=[...i,...s],l=c=>this.options.ignoreCaseAndUnderscore?c.toLowerCase().replace(/_/g,""):c;return t.every(c=>a.some(m=>l(m)===l(c)))?[e]:[]}else if(e instanceof W){let r=this.findUpstream(e.left,t,n),i=this.findUpstream(e.right,t,n);return[...r,...i]}return[]}collectCTEColumns(e,t){let n=[];if(e.withClause)for(let r of e.withClause.tables){let i=this.collectColumnsFromSelectQuery(r.query);n.push(...i)}return n}collectColumnsFromSelectQuery(e){if(e instanceof g)try{return this.columnCollector.collect(e).map(t=>t.name)}catch(t){return console.warn("Failed to collect columns from SimpleSelectQuery:",t),[]}else if(e instanceof W)return this.collectColumnsFromSelectQuery(e.left);return[]}};var mt=class{static parseFromLexeme(e,t){let n=t;if(n<e.length&&(e[n].type&64||e[n].type&2048)){let r=e[n].value;if(n++,n<e.length&&e[n].type&4){let i=[];for(n++;n<e.length&&e[n].type&64&&(i.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(i.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 Z(r,i),newIndex:n}}return{value:new Z(r,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 qe=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The source expression is complete but there are additional tokens.`);return r.value}static parseTableSourceFromLexemes(e,t){let n=pt.parseTableSourceFromLexemes(e,t);return{value:new $(n.value,null),newIndex:n.newIndex}}static parseFromLexeme(e,t){let n=t,r=pt.parseFromLexeme(e,n);if(n=r.newIndex,n<e.length){if(e[n].value==="as"){n++;let s=mt.parseFromLexeme(e,n);return n=s.newIndex,{value:new $(r.value,s.value),newIndex:n}}if(n<e.length&&this.isTokenTypeAliasCandidate(e[n].type)){let s=mt.parseFromLexeme(e,n);return n=s.newIndex,{value:new $(r.value,s.value),newIndex:n}}}return{value:new $(r.value,null),newIndex:n}}static isTokenTypeAliasCandidate(e){return(e&64)!==0||(e&2048)!==0}};var Fe=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=i=>i instanceof he?o.buildSimpleQuery(i):i,r=new W(n(e[0]),t,n(e[1]));Ge.normalize(r);for(let i=2;i<e.length;i++)r.appendSelectQuery(t,n(e[i]));return r}constructor(){}static buildSimpleQuery(e){if(e instanceof g)return e;if(e instanceof W)return o.buildSimpleBinaryQuery(e);if(e instanceof he)return o.buildSimpleValuesQuery(e);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(e){let t=new _(e),n=new $(t,new Z("bq",null)),r=new D(n,null),i=o.createSelectAllClause(),s=new g({selectClause:i,fromClause:r});return Ge.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 _(e),r=new $(n,new Z("vq",e.columnAliases)),i=new D(r,null),s=e.columnAliases.map(l=>new q(new v("vq",l),l)),a=new J(s,null);return new g({selectClause:a,fromClause:i})}static createSelectAllClause(){let e=new v(null,"*"),t=new q(e,"*");return new J([t],null)}static buildCreateTableQuery(e,t,n=!1){return new vt({tableName:t,isTemporary:n,asSelectQuery:e})}static buildInsertQuery(e,t){let n,r=e.selectClause.items.length;if(n=new Re().collect(e).map(l=>l.name),!n.length||r!==n.length)throw new Error(`Columns cannot be inferred from the selectQuery. Make sure you are not using wildcards or unnamed columns.
|
|
14
14
|
Select clause column count: ${r}, Columns with valid names: ${n.length}
|
|
15
|
-
Detected column names: [${n.join(", ")}]`);let a=Je.parse(t);return new Ge({insertClause:new tt(a,n),selectQuery:e})}static buildUpdateQuery(e,t,n,r){let i=new ht(Je.parse(n)),s=Array.isArray(r)?r:[r],l=new Ae().collect(e),c=new X().collect(e);new Ct().execute(e);for(let N of s)if(!l.some(Q=>Q.name===N))throw new Error(`Primary key column '${N}' is not present in selectQuery select list.`);let h=i.getSourceAliasName();if(!h)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let b=l.filter(N=>!s.includes(N.name)).map(N=>new et(N.name,new v(h,N.name))),d=new He(b),C=new D(e.toSource(t),null),F=null;for(let N of s){let Q=new y(new v(h,N),"=",new v(t,N));F=F?new y(F,"and",Q):Q}let S=new ie(F);return new wt({updateClause:i,setClause:d,fromClause:C,whereClause:S,withClause:c.length>0?new ne(!1,c):void 0})}};var ze=class{static set(e,t,n){let r=it.collect(e),i=!1;for(let s of r)s.name.value===t&&(s.value=n,i=!0);if(!i)throw new Error(`Parameter '${t}' not found in query.`)}};var E=class extends f{constructor(t){super();this.cteNameCache=new Set;this.withClause=t.withClause??null,this.selectClause=t.selectClause,this.fromClause=t.fromClause??null,this.whereClause=t.whereClause??null,this.groupByClause=t.groupByClause??null,this.havingClause=t.havingClause??null,this.orderByClause=t.orderByClause??null,this.windowClause=t.windowClause??null,this.limitClause=t.limitClause??null,this.offsetClause=t.offsetClause??null,this.fetchClause=t.fetchClause??null,this.forClause=t.forClause??null,this.initializeCTECache()}static{this.kind=Symbol("SelectQuery")}initializeCTECache(){if(this.cteNameCache.clear(),this.withClause?.tables)for(let t of this.withClause.tables)this.cteNameCache.add(t.aliasExpression.table.name)}toUnion(t){return this.toBinaryQuery("union",t)}toUnionAll(t){return this.toBinaryQuery("union all",t)}toIntersect(t){return this.toBinaryQuery("intersect",t)}toIntersectAll(t){return this.toBinaryQuery("intersect all",t)}toExcept(t){return this.toBinaryQuery("except",t)}toExceptAll(t){return this.toBinaryQuery("except all",t)}toBinaryQuery(t,n){return Ne.buildBinaryQuery([this,n],t)}appendWhereRaw(t){let n=k.parse(t);this.appendWhere(n)}appendWhere(t){this.whereClause?this.whereClause.condition=new y(this.whereClause.condition,"and",t):this.whereClause=new ie(t)}appendHavingRaw(t){let n=k.parse(t);this.appendHaving(n)}appendHaving(t){this.havingClause?this.havingClause.condition=new y(this.havingClause.condition,"and",t):this.havingClause=new me(t)}innerJoinRaw(t,n,r,i=null){this.joinSourceRaw("inner join",t,n,r,i)}leftJoinRaw(t,n,r,i=null){this.joinSourceRaw("left join",t,n,r,i)}rightJoinRaw(t,n,r,i=null){this.joinSourceRaw("right join",t,n,r,i)}innerJoin(t,n,r=null){this.joinSource("inner join",t,n,r)}leftJoin(t,n,r=null){this.joinSource("left join",t,n,r)}rightJoin(t,n,r=null){this.joinSource("right join",t,n,r)}joinSourceRaw(t,n,r,i,s=null){let a=lt.parse(n),l=new M(a,new Y(r,null));this.joinSource(t,l,i,s)}joinSource(t,n,r,i=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let s=Array.isArray(r)?r:[r],l=new Ie(i).collect(this),u=null,c=0,m=n.getAliasName();if(!m)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let b of l)if(s.some(d=>d==b.name)){let d=new y(b.value,"=",new v([m],b.name));u?u=new y(u,"and",d):u=d,c++}if(!u||c!==s.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${s.join(", ")}`);let h=new de(u),w=new he(t,n,h,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(w):this.fromClause.joins=[w]),_e.normalize(this)}toSource(t){if(!t||t.trim()==="")throw new Error("Alias is required for toSource(). Please specify a non-empty alias name.");return new M(new z(this),new Y(t,null))}appendWith(t){let n=Array.isArray(t)?t:[t];this.withClause?this.withClause.tables.push(...n):this.withClause=new ne(!1,n),_e.normalize(this)}appendWithRaw(t,n){let r=A.parse(t),i=new ee(r,n,null);this.appendWith(i)}overrideSelectItemExpr(t,n){let r=this.selectClause.items.filter(u=>u.identifier?.name===t);if(r.length===0)throw new Error(`Column ${t} not found in the query`);if(r.length>1)throw new Error(`Duplicate column name ${t} found in the query`);let i=r[0],a=new st().visit(i.value),l=n(a);i.value=k.parse(l)}appendWhereExpr(t,n,r){if(r&&r.upstream){let s=new vt().find(this,[t]),a=new Ie,l=new st;for(let u of s){let c=a.collect(u).filter(h=>h.name===t).map(h=>h.value);if(c.length!==1)throw new Error(`Expected exactly one expression for column '${t}'`);let m=l.format(c[0]);u.appendWhereRaw(n(m))}}else{let i=new Ie,s=new st,a=i.collect(this).filter(u=>u.name===t).map(u=>u.value);if(a.length!==1)throw new Error(`Expected exactly one expression for column '${t}'`);let l=s.format(a[0]);this.appendWhereRaw(n(l))}}setParameter(t,n){return ze.set(this,t,n),this}toSimpleQuery(){return this}addCTE(t,n,r){if(!t||t.trim()==="")throw new St(t,"name cannot be empty or whitespace-only");if(this.hasCTE(t))throw new At(t);let i=r?.materialized??null,s=new ee(n,t,i);return this.appendWith(s),this.cteNameCache.add(t),this}removeCTE(t){if(!this.hasCTE(t))throw new Ft(t);return this.withClause&&(this.withClause.tables=this.withClause.tables.filter(n=>n.aliasExpression.table.name!==t),this.withClause.tables.length===0&&(this.withClause=null)),this.cteNameCache.delete(t),this}hasCTE(t){return this.cteNameCache.has(t)}getCTENames(){return this.withClause?.tables.map(t=>t.aliasExpression.table.name)??[]}replaceCTE(t,n,r){if(!t||t.trim()==="")throw new St(t,"name cannot be empty or whitespace-only");this.hasCTE(t)&&this.removeCTE(t);let i=r?.materialized??null,s=new ee(n,t,i);return this.appendWith(s),this.cteNameCache.add(t),this}};var K=class o extends f{static{this.kind=Symbol("BinarySelectQuery")}constructor(e,t,n){super(),this.left=e,this.operator=new V(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 V(e),this.right=t,_e.normalize(this),this}unionRaw(e){let t=A.parse(e);return this.union(t)}unionAllRaw(e){let t=A.parse(e);return this.unionAll(t)}intersectRaw(e){let t=A.parse(e);return this.intersect(t)}intersectAllRaw(e){let t=A.parse(e);return this.intersectAll(t)}exceptRaw(e){let t=A.parse(e);return this.except(t)}exceptAllRaw(e){let t=A.parse(e);return this.exceptAll(t)}toSource(e="subq"){return new M(new z(this),new Y(e,null))}setParameter(e,t){return ze.set(this,e,t),this}toSimpleQuery(){return Ne.buildSimpleQuery(this)}};var ae=class extends f{static{this.kind=Symbol("ValuesQuery")}constructor(e,t=null){super(),this.tuples=e,this.columnAliases=t}toSimpleQuery(){return Ne.buildSimpleQuery(this)}setParameter(e,t){return ze.set(this,e,t),this}};var fn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The SELECT clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=null,i=n<e.length?e[n].comments: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.`);n++;let s=[];for(;n<e.length&&rt.isHintClause(e[n].value);){let u=rt.extractHintContent(e[n].value);s.push(new rt(u)),n++}if(n<e.length&&e[n].value==="distinct")n++,r=new mt;else if(n<e.length&&e[n].value==="distinct on"){n++;let u=k.parseArgument(4,8,e,n);r=new dt(u.value),n=u.newIndex}let a=[],l=Cn.parseItem(e,n);for(a.push(l.value),n=l.newIndex;n<e.length&&e[n].type&16;){n++;let u=Cn.parseItem(e,n);a.push(u.value),n=u.newIndex}if(a.length===0)throw new Error(`Syntax error at position ${t}: No select items found. The SELECT clause requires at least one expression to select.`);{let u=new J(a,r,s);return u.comments=i,{value:u,newIndex:n}}}},Cn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseItem(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The select item is complete but there are additional tokens.`);return r.value}static parseItem(e,t){let n=t,r=k.parseFromLexeme(e,n),i=r.value;if(n=r.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 j(i,s),newIndex:n}}else if(i instanceof v&&i.column.name!=="*")return{value:new j(i,i.column.name),newIndex:n};return{value:new j(i),newIndex:n}}};var yn=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="on"){n++;let r=k.parseFromLexeme(e,n);return n=r.newIndex,{value:new de(r.value),newIndex:n}}return null}};var wn=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="using"){n++;let r=k.parseArgument(4,8,e,n),i=r.value;return n=r.newIndex,{value:new Te(i),newIndex:n}}return null}};var gn=class{static tryParse(e,t){let n=t,r=[];for(;this.isJoinCommand(e,n);){let i=this.parseJoinClause(e,n);r.push(i.value),n=i.newIndex}return r.length>0?{value:r,newIndex:n}:null}static isJoinKeyword(e){return!!Gn.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,r=e[n].value===","?"cross join":e[n].value;n++;let i=this.parseLateral(e,n),s=i.value;n=i.newIndex;let a=Je.parseFromLexeme(e,n);if(n=a.newIndex,n<e.length){let u=yn.tryParse(e,n);if(u)return{value:new he(r,a.value,u.value,s),newIndex:u.newIndex};let c=wn.tryParse(e,n);if(c)return{value:new he(r,a.value,c.value,s),newIndex:c.newIndex}}return{value:new he(r,a.value,null,s),newIndex:n}}};var Et=class{static collectClauseComments(e,t,n){if(t>=e.length||e[t].value.toLowerCase()!==n.toLowerCase())return null;let r=[];e[t].comments&&r.push(...e[t].comments);let i=t-1;for(;i>=0;){let s=e[i];if(s.comments&&s.comments.length>0){let a=s.comments.filter(l=>{let u=l.toLowerCase();return u.includes(n.toLowerCase())||u.includes("\u306E")||u.includes("\u30B3\u30E1\u30F3\u30C8")});a.length>0&&(r.unshift(...a),s.comments=s.comments.filter(l=>!a.includes(l)),s.comments.length===0&&(s.comments=null));break}if(this.isSignificantSqlKeyword(s.value))break;i--}return r.length>0?r:null}static isSignificantSqlKeyword(e){return new Set(["select","from","where","group by","having","order by","limit","offset"]).has(e.toLowerCase())}};var Sn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The FROM clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=Et.collectClauseComments(e,n,"from");if(e[n].value!=="from")throw new Error(`Syntax error at position ${n}: Expected 'FROM' keyword but found "${e[n].value}". FROM clauses must start with the FROM keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FROM' keyword. The FROM clause requires a table reference.");let i=Je.parseFromLexeme(e,n);n=i.newIndex;let s=gn.tryParse(e,n);if(n=s?.newIndex||n,s!==null){let a=new D(i.value,s.value);return a.comments=r,{value:a,newIndex:n}}else{let a=new D(i.value,null);return a.comments=r,{value:a,newIndex:n}}}};var vn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The WHERE clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=Et.collectClauseComments(e,n,"where");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=k.parseFromLexeme(e,n),s=new ie(i.value);return s.comments=r,{value:s,newIndex:i.newIndex}}};var En=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The GROUP BY clause is complete but there are additional tokens.`);return r.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 r=[],i=this.parseItem(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=this.parseItem(e,n);r.push(s.value),n=s.newIndex}if(r.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 pe(r),newIndex:n}}static parseItem(e,t){let n=t,r=k.parseFromLexeme(e,n),i=r.value;return n=r.newIndex,{value:i,newIndex:n}}};var bn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The HAVING clause is complete but there are additional tokens.`);return r.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 r=k.parseFromLexeme(e,n);return{value:new me(r.value),newIndex:r.newIndex}}};var xn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The WINDOW clause is complete but there are additional tokens.`);return r.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 r=[];for(;n<e.length;){if(n>=e.length||e[n].type!==64)throw new Error("Syntax error: Expected window name after 'WINDOW' keyword.");let i=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=ft.parseFromLexeme(e,n);if(n=s.newIndex,r.push(new Ce(i,s.value)),n<e.length&&e[n].type&16)n++;else break}if(r.length===0)throw new Error("At least one WINDOW clause is required after WINDOW keyword.");return{value:new Ze(r),newIndex:n}}};var Tn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The LIMIT clause is complete but there are additional tokens.`);return r.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 r=k.parseFromLexeme(e,n);return n=r.newIndex,{value:new se(r.value),newIndex:n}}};var kn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The FOR clause is complete but there are additional tokens.`);return r.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 r=e[n].value,i;switch(r){case"update":i="update",n++;break;case"share":i="share",n++;break;case"key share":i="key share",n++;break;case"no key update":i="no key update",n++;break;default:throw new Error(`Syntax error at position ${n}: Invalid lock mode "${r}". Valid lock modes are: UPDATE, SHARE, KEY SHARE, NO KEY UPDATE.`)}return{value:new Be(i),newIndex:n}}};var Qt=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The CommonTable definition is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=n<e.length?e[n].comments:null,i=ut.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length&&e[n].value!=="as")throw new Error(`Syntax error at position ${n}: Expected 'AS' keyword after CTE name but found "${e[n].value}".`);n++;let s=null;if(n<e.length){let c=e[n].value;c==="materialized"?(s=!0,n++):c==="not materialized"&&(s=!1,n++)}if(n<e.length&&e[n].type!==4)throw new Error(`Syntax error at position ${n}: Expected '(' after CTE name but found "${e[n].value}".`);let a=e[n].comments;n++;let l=A.parseFromLexeme(e,n);if(n=l.newIndex,a&&a.length>0&&(l.value.comments?l.value.comments=[...a,...l.value.comments]:l.value.comments=a),n<e.length&&e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected ')' after CTE query but found "${e[n].value}".`);n++;let u=new ee(l.value,i.value,s);return u.comments=r,{value:u,newIndex:n}}};var bt=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The WITH clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=n<e.length?e[n].comments:null;if(n<e.length&&e[n].value.toLowerCase()==="with")n++;else throw new Error(`Syntax error at position ${n}: Expected WITH keyword.`);let i=n<e.length&&e[n].value.toLowerCase()==="recursive";i&&n++;let s=[],a=Qt.parseFromLexeme(e,n);for(s.push(a.value),n=a.newIndex;n<e.length&&e[n].type&16;){n++;let u=Qt.parseFromLexeme(e,n);s.push(u.value),n=u.newIndex}let l=new ne(i,s);return l.comments=r,{value:l,newIndex:n}}};var In=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The VALUES clause is complete but there are additional tokens.`);return r.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 r=[],i=this.parseTuple(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let a=this.parseTuple(e,n);r.push(a.value),n=a.newIndex}return{value:new ae(r),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 r=[];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 be([]),newIndex:n};let i=k.parseFromLexeme(e,n);for(r.push(i.value),n=i.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=k.parseFromLexeme(e,n);r.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 be(r),newIndex:n}}};var Nn=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 r=Yn.parseFromLexeme(e,n),i=r.value;return n=r.newIndex,{value:new Ke(i),newIndex:n}}},Yn=class{static parseFromLexeme(e,t){let n=t,r,i=e[n].value;if(i==="first")r="first";else if(i==="next")r="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 G(1),a="rows only",n++,{value:new ot(r,s,a),newIndex:n};let l=k.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 ot(r,s,a),newIndex:n}}};var Pn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The OFFSET clause is complete but there are additional tokens.`);return r.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 r=k.parseFromLexeme(e,n);return n=r.newIndex,n<e.length&&(e[n].value==="row"||e[n].value==="rows")&&n++,{value:new De(r.value),newIndex:n}}};var A=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`[SelectQueryParser] Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The SELECT query is complete but there are additional tokens.`);return r.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 r=e[n].value;if(!this.selectCommandSet.has(r)&&r!=="values")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' or 'VALUES' keyword but found "${e[n].value}".`);let i=this.selectCommandSet.has(r)?this.parseSimpleSelectQuery(e,n):this.parseValuesQuery(e,n),s=i.value;for(n=i.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 K(s,a,u.value),n=u.newIndex}else if(l==="values"){let u=this.parseValuesQuery(e,n);s=new K(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,r=null;n<e.length&&e[n].value==="with"&&(r=bt.parseFromLexeme(e,n),n=r.newIndex);let i=n<e.length?e[n].comments:null;if(n>=e.length||e[n].value!=="select")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword but found "${n<e.length?e[n].value:"end of input"}". SELECT queries must start with the SELECT keyword.`);let s=fn.parseFromLexeme(e,n);n=s.newIndex,i&&s.value.comments&&JSON.stringify(i)===JSON.stringify(s.value.comments)&&(s.value.comments=null);let a=null;n<e.length&&e[n].value==="from"&&(a=Sn.parseFromLexeme(e,n),n=a.newIndex);let l=null;n<e.length&&e[n].value==="where"&&(l=vn.parseFromLexeme(e,n),n=l.newIndex);let u=null;n<e.length&&e[n].value==="group by"&&(u=En.parseFromLexeme(e,n),n=u.newIndex);let c=null;n<e.length&&e[n].value==="having"&&(c=bn.parseFromLexeme(e,n),n=c.newIndex);let m=null;n<e.length&&e[n].value==="window"&&(m=xn.parseFromLexeme(e,n),n=m.newIndex);let h=null;n<e.length&&e[n].value==="order by"&&(h=nt.parseFromLexeme(e,n),n=h.newIndex);let w=null;n<e.length&&e[n].value==="limit"&&(w=Tn.parseFromLexeme(e,n),n=w.newIndex);let b=null;n<e.length&&e[n].value==="offset"&&(b=Pn.parseFromLexeme(e,n),n=b.newIndex);let d=null;n<e.length&&e[n].value==="fetch"&&(d=Nn.parseFromLexeme(e,n),n=d.newIndex);let C=null;n<e.length&&e[n].value.toLowerCase()==="for"&&(C=kn.parseFromLexeme(e,n),n=C.newIndex);let F=new E({withClause:r?r.value:null,selectClause:s.value,fromClause:a?a.value:null,whereClause:l?l.value:null,groupByClause:u?u.value:null,havingClause:c?c.value:null,orderByClause:h?h.value:null,windowClause:m?m.value:null,limitClause:w?w.value:null,offsetClause:b?b.value:null,fetchClause:d?d.value:null,forClause:C?C.value:null});return F.comments=i,{value:F,newIndex:n}}static parseValuesQuery(e,t){let n=In.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}};var pr=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The INSERT query is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=null;if(e[n].value==="with"){let l=bt.parseFromLexeme(e,n);r=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 i=Je.parseTableSourceFromLexemes(e,n);n=i.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=A.parseFromLexeme(e,n);if(r)if(a.value instanceof E)a.value.withClause=r;else throw new Error("WITH clause is not supported in this context.");return n=a.newIndex,{value:new Ge({insertClause:new tt(i.value,s),selectQuery:a.value}),newIndex:n}}};var xt=class o{constructor(){this.dependencyGraph=null;this.cteMap=new Map;this.sourceCollector=new yt(!0),this.cteCollector=new X}static{this.ERROR_MESSAGES={NOT_ANALYZED:"Must call analyzeDependencies first",CIRCULAR_REFERENCE:"Circular reference detected in CTE"}}analyzeDependencies(e){let t=this.cteCollector.collect(e);return this.buildCTEMap(t),this.dependencyGraph=this.buildDependencyGraph(t),this.dependencyGraph}getDependencies(e){this.ensureAnalyzed();let t=this.findNodeByName(e);return t?[...t.dependencies]:[]}getDependents(e){this.ensureAnalyzed();let t=this.findNodeByName(e);return t?[...t.dependents]:[]}hasCircularDependency(){this.ensureAnalyzed();try{return this.getExecutionOrder(),!1}catch(e){if(e instanceof Error&&e.message.includes(o.ERROR_MESSAGES.CIRCULAR_REFERENCE))return!0;throw e}}getExecutionOrder(){this.ensureAnalyzed();let e=new Set,t=new Set,n=[],r=new Map;for(let s of this.dependencyGraph.nodes)r.set(s.name,new Set(s.dependencies));let i=s=>{if(e.has(s))return;if(t.has(s))throw new Error(`${o.ERROR_MESSAGES.CIRCULAR_REFERENCE}: ${s}`);t.add(s);let a=r.get(s)||new Set;for(let l of a)i(l);t.delete(s),e.add(s),n.push(s)};for(let s of this.dependencyGraph.nodes)e.has(s.name)||i(s.name);return n}buildDependencyGraph(e){let t=[],n=[],r=new Map,i=new Map;for(let s of e){let a=o.getCTEName(s);r.set(a,new Set),i.set(a,new Set)}for(let s of e){let a=o.getCTEName(s),l=this.sourceCollector.collect(s.query);for(let u of l){let c=u.table.name;this.cteMap.has(c)&&c!==a&&(r.get(a).add(c),i.get(c).add(a),n.push({from:a,to:c}))}}for(let s of e){let a=o.getCTEName(s);t.push({name:a,cte:s,dependencies:Array.from(r.get(a)||new Set),dependents:Array.from(i.get(a)||new Set)})}return{nodes:t,edges:n}}ensureAnalyzed(){if(!this.dependencyGraph)throw new Error(o.ERROR_MESSAGES.NOT_ANALYZED)}buildCTEMap(e){this.cteMap.clear();for(let t of e){let n=o.getCTEName(t);this.cteMap.set(n,t)}}findNodeByName(e){return this.dependencyGraph?.nodes.find(t=>t.name===e)}static getCTEName(e){return e.aliasExpression.table.name}};var On=class{static addComment(e,t){e.comments||(e.comments=[]),e.comments.push(t)}static editComment(e,t,n){if(!e.comments||t<0||t>=e.comments.length)throw new Error(`Invalid comment index: ${t}. Component has ${e.comments?.length||0} comments.`);e.comments[t]=n}static deleteComment(e,t){if(!e.comments||t<0||t>=e.comments.length)throw new Error(`Invalid comment index: ${t}. Component has ${e.comments?.length||0} comments.`);e.comments.splice(t,1),e.comments.length===0&&(e.comments=null)}static deleteAllComments(e){e.comments=null}static getComments(e){return e.comments||[]}static findComponentsWithComment(e,t,n=!1){let r=[],i=n?t:t.toLowerCase(),s=a=>{a&&a instanceof f&&a.comments&&a.comments.some(l=>(n?l:l.toLowerCase()).includes(i))&&r.push(a);for(let l in a)a[l]&&typeof a[l]=="object"&&(Array.isArray(a[l])?a[l].forEach(s):s(a[l]))};return s(e),r}static replaceInComments(e,t,n,r=!1){let i=0,s=a=>{if(a&&a instanceof f&&a.comments)for(let l=0;l<a.comments.length;l++){let u=a.comments[l],c=r?"g":"gi",m=new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c),h=u.replace(m,n);h!==u&&(a.comments[l]=h,i++)}for(let l in a)a[l]&&typeof a[l]=="object"&&(Array.isArray(a[l])?a[l].forEach(s):s(a[l]))};return s(e),i}static countComments(e){let t=0,n=r=>{r&&r instanceof f&&r.comments&&(t+=r.comments.length);for(let i in r)r[i]&&typeof r[i]=="object"&&(Array.isArray(r[i])?r[i].forEach(n):n(r[i]))};return n(e),t}static getAllComments(e){let t=[],n=r=>{r&&r instanceof f&&r.comments&&r.comments.forEach((i,s)=>{t.push({comment:i,component:r,index:s})});for(let i in r)r[i]&&typeof r[i]=="object"&&(Array.isArray(r[i])?r[i].forEach(n):n(r[i]))};return n(e),t}};var Ln=class{constructor(e,t){this.name=e,this.columns=t}},An=class{constructor(e=null,t=!1){this.tableColumnResolver=e;this.allowWildcardWithoutResolver=t;this.tableSchemas=[];this.visitedNodes=new Set;this.commonTables=[];this.running=!1;this.handlers=new Map,this.handlers.set(E.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(K.kind,n=>this.visitBinarySelectQuery(n))}collect(e){return this.visit(e),this.tableSchemas}visit(e){if(this.running){this.visitNode(e);return}this.reset(),this.running=!0;try{if(!(e instanceof E||e instanceof K))throw new Error(`Unsupported SQL component type for schema collection. Received: ${e.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let t=new X;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(r=>n?.add(r))}this.tableSchemas=Array.from(e.entries()).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>new Ln(t,Array.from(n).sort()))}handleTableSource(e,t,n){if(e.datasource instanceof R){let r=e.datasource.getSourceName(),i=this.commonTables.filter(s=>s.getSourceAliasName()===r);if(i.length>0)i[0].query.accept(this);else{let s=e.getAliasName()??r;this.processCollectTableSchema(r,s,t,n)}}else throw new Error("Datasource is not an instance of TableSource")}visitSimpleSelectQuery(e){if(e.fromClause===null)return;let n=new Ie(this.tableColumnResolver,!0,"fullName").collect(e),r;if(this.allowWildcardWithoutResolver){let i=this.getSelectClauseColumns(e);r=n.filter(s=>s.value instanceof v).map(s=>s.value).filter(s=>{let a=s.getNamespace(),l=s.column.name;return i.some(u=>{if(u.value instanceof v){let c=u.value.getNamespace(),m=u.value.column.name;if(c===a&&m===l)return!0;if(m==="*"){if(this.allowWildcardWithoutResolver&&this.tableColumnResolver===null)return!1;if(c===""||c===a)return!0}}return!1})}).map(s=>({table:s.getNamespace(),column:s.column.name}))}else r=n.filter(i=>i.value instanceof v).map(i=>i.value).map(i=>({table:i.getNamespace(),column:i.column.name}));if(e.fromClause.joins!==null&&e.fromClause.joins.length>0){let i=r.filter(s=>s.table==="").map(s=>s.column);if(i.length>0)throw new Error(`Column reference(s) without table name found in query: ${i.join(", ")}`)}if(e.fromClause.source.datasource instanceof R?this.handleTableSource(e.fromClause.source,r,!0):e.fromClause.source.datasource instanceof z&&e.fromClause.source.datasource.query.accept(this),e.fromClause?.joins)for(let i of e.fromClause.joins)i.source.datasource instanceof R?this.handleTableSource(i.source,r,!1):i.source.datasource instanceof z&&i.source.datasource.query.accept(this)}visitBinarySelectQuery(e){this.visitNode(e.left),this.visitNode(e.right)}getSelectClauseColumns(e){if(!e.selectClause)return[];let t=[];for(let n of e.selectClause.items)if(n.value instanceof v){let r=n.value.column.name;t.push({name:r,value:n.value})}return t}processCollectTableSchema(e,t,n,r=!1){if(this.tableColumnResolver===null&&n.filter(l=>l.table===t||r&&l.table==="").filter(l=>l.column==="*").length>0&&!this.allowWildcardWithoutResolver){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 i=n.filter(a=>a.column!=="*").filter(a=>a.table===t||r&&a.table==="").map(a=>a.column),s=new Ln(e,i);this.tableSchemas.push(s)}};var Fn=class{static validate(e,t){let n=typeof e=="string"?A.parse(e):e,r=Array.isArray(t)?l=>{let u=t.find(c=>c.name===l);return u?u.columns:[]}:t,s=new An(r).collect(n),a=[];for(let l of s){let u=r(l.name);if(u.length===0){a.push(`Table '${l.name}' is not defined.`);continue}let c=l.columns.filter(m=>!u.includes(m));c.length>0&&a.push(`Table '${l.name}' contains undefined columns: ${c.join(", ")}.`)}if(a.length>0)throw new Error(a.join(`
|
|
16
|
-
`))}};var
|
|
15
|
+
Detected column names: [${n.join(", ")}]`);let a=qe.parse(t);return new Ye({insertClause:new nt(a,n),selectQuery:e})}static buildUpdateQuery(e,t,n,r){let i=new yt(qe.parse(n)),s=Array.isArray(r)?r:[r],l=new Re().collect(e),c=new ee().collect(e);new gt().execute(e);for(let N of s)if(!l.some(A=>A.name===N))throw new Error(`Primary key column '${N}' is not present in selectQuery select list.`);let h=i.getSourceAliasName();if(!h)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let b=l.filter(N=>!s.includes(N.name)).map(N=>new tt(N.name,new v(h,N.name))),d=new Xe(b),y=new D(e.toSource(t),null),L=null;for(let N of s){let A=new C(new v(h,N),"=",new v(t,N));L=L?new C(L,"and",A):A}let E=new se(L);return new St({updateClause:i,setClause:d,fromClause:y,whereClause:E,withClause:c.length>0?new ne(!1,c):void 0})}};var He=class{static set(e,t,n){let r=ot.collect(e),i=!1;for(let s of r)s.name.value===t&&(s.value=n,i=!0);if(!i)throw new Error(`Parameter '${t}' not found in query.`)}};var g=class extends f{constructor(t){super();this.cteNameCache=new Set;this.withClause=t.withClause??null,this.selectClause=t.selectClause,this.fromClause=t.fromClause??null,this.whereClause=t.whereClause??null,this.groupByClause=t.groupByClause??null,this.havingClause=t.havingClause??null,this.orderByClause=t.orderByClause??null,this.windowClause=t.windowClause??null,this.limitClause=t.limitClause??null,this.offsetClause=t.offsetClause??null,this.fetchClause=t.fetchClause??null,this.forClause=t.forClause??null,this.initializeCTECache()}static{this.kind=Symbol("SelectQuery")}initializeCTECache(){if(this.cteNameCache.clear(),this.withClause?.tables)for(let t of this.withClause.tables)this.cteNameCache.add(t.aliasExpression.table.name)}toUnion(t){return this.toBinaryQuery("union",t)}toUnionAll(t){return this.toBinaryQuery("union all",t)}toIntersect(t){return this.toBinaryQuery("intersect",t)}toIntersectAll(t){return this.toBinaryQuery("intersect all",t)}toExcept(t){return this.toBinaryQuery("except",t)}toExceptAll(t){return this.toBinaryQuery("except all",t)}toBinaryQuery(t,n){return Fe.buildBinaryQuery([this,n],t)}appendWhereRaw(t){let n=k.parse(t);this.appendWhere(n)}appendWhere(t){this.whereClause?this.whereClause.condition=new C(this.whereClause.condition,"and",t):this.whereClause=new se(t)}appendHavingRaw(t){let n=k.parse(t);this.appendHaving(n)}appendHaving(t){this.havingClause?this.havingClause.condition=new C(this.havingClause.condition,"and",t):this.havingClause=new ce(t)}innerJoinRaw(t,n,r,i=null){this.joinSourceRaw("inner join",t,n,r,i)}leftJoinRaw(t,n,r,i=null){this.joinSourceRaw("left join",t,n,r,i)}rightJoinRaw(t,n,r,i=null){this.joinSourceRaw("right join",t,n,r,i)}innerJoin(t,n,r=null){this.joinSource("inner join",t,n,r)}leftJoin(t,n,r=null){this.joinSource("left join",t,n,r)}rightJoin(t,n,r=null){this.joinSource("right join",t,n,r)}joinSourceRaw(t,n,r,i,s=null){let a=pt.parse(n),l=new $(a,new Z(r,null));this.joinSource(t,l,i,s)}joinSource(t,n,r,i=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let s=Array.isArray(r)?r:[r],l=new Oe(i).collect(this),u=null,c=0,m=n.getAliasName();if(!m)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let b of l)if(s.some(d=>d==b.name)){let d=new C(b.value,"=",new v([m],b.name));u?u=new C(u,"and",d):u=d,c++}if(!u||c!==s.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${s.join(", ")}`);let h=new pe(u),w=new me(t,n,h,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(w):this.fromClause.joins=[w]),Ge.normalize(this)}toSource(t){if(!t||t.trim()==="")throw new Error("Alias is required for toSource(). Please specify a non-empty alias name.");return new $(new _(this),new Z(t,null))}appendWith(t){let n=Array.isArray(t)?t:[t];this.withClause?this.withClause.tables.push(...n):this.withClause=new ne(!1,n),Ge.normalize(this)}appendWithRaw(t,n){let r=Q.parse(t),i=new X(r,n,null);this.appendWith(i)}overrideSelectItemExpr(t,n){let r=this.selectClause.items.filter(u=>u.identifier?.name===t);if(r.length===0)throw new Error(`Column ${t} not found in the query`);if(r.length>1)throw new Error(`Duplicate column name ${t} found in the query`);let i=r[0],a=new at().visit(i.value),l=n(a);i.value=k.parse(l)}appendWhereExpr(t,n,r){if(r&&r.upstream){let s=new bt().find(this,[t]),a=new Oe,l=new at;for(let u of s){let c=a.collect(u).filter(h=>h.name===t).map(h=>h.value);if(c.length!==1)throw new Error(`Expected exactly one expression for column '${t}'`);let m=l.format(c[0]);u.appendWhereRaw(n(m))}}else{let i=new Oe,s=new at,a=i.collect(this).filter(u=>u.name===t).map(u=>u.value);if(a.length!==1)throw new Error(`Expected exactly one expression for column '${t}'`);let l=s.format(a[0]);this.appendWhereRaw(n(l))}}setParameter(t,n){return He.set(this,t,n),this}toSimpleQuery(){return this}addCTE(t,n,r){if(!t||t.trim()==="")throw new Et(t,"name cannot be empty or whitespace-only");if(this.hasCTE(t))throw new Lt(t);let i=r?.materialized??null,s=new X(n,t,i);return this.appendWith(s),this.cteNameCache.add(t),this}removeCTE(t){if(!this.hasCTE(t))throw new At(t);return this.withClause&&(this.withClause.tables=this.withClause.tables.filter(n=>n.aliasExpression.table.name!==t),this.withClause.tables.length===0&&(this.withClause=null)),this.cteNameCache.delete(t),this}hasCTE(t){return this.cteNameCache.has(t)}getCTENames(){return this.withClause?.tables.map(t=>t.aliasExpression.table.name)??[]}replaceCTE(t,n,r){if(!t||t.trim()==="")throw new Et(t,"name cannot be empty or whitespace-only");this.hasCTE(t)&&this.removeCTE(t);let i=r?.materialized??null,s=new X(n,t,i);return this.appendWith(s),this.cteNameCache.add(t),this}};var W=class o extends f{static{this.kind=Symbol("BinarySelectQuery")}constructor(e,t,n){super(),this.left=e,this.operator=new V(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 V(e),this.right=t,Ge.normalize(this),this}unionRaw(e){let t=Q.parse(e);return this.union(t)}unionAllRaw(e){let t=Q.parse(e);return this.unionAll(t)}intersectRaw(e){let t=Q.parse(e);return this.intersect(t)}intersectAllRaw(e){let t=Q.parse(e);return this.intersectAll(t)}exceptRaw(e){let t=Q.parse(e);return this.except(t)}exceptAllRaw(e){let t=Q.parse(e);return this.exceptAll(t)}toSource(e="subq"){return new $(new _(this),new Z(e,null))}setParameter(e,t){return He.set(this,e,t),this}toSimpleQuery(){return Fe.buildSimpleQuery(this)}};var he=class extends f{static{this.kind=Symbol("ValuesQuery")}constructor(e,t=null){super(),this.tuples=e,this.columnAliases=t}toSimpleQuery(){return Fe.buildSimpleQuery(this)}setParameter(e,t){return He.set(this,e,t),this}};var Cn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The SELECT clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=null,i=n<e.length?e[n].comments: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.`);n++;let s=[];for(;n<e.length&&st.isHintClause(e[n].value);){let u=st.extractHintContent(e[n].value);s.push(new st(u)),n++}if(n<e.length&&e[n].value==="distinct")n++,r=new ft;else if(n<e.length&&e[n].value==="distinct on"){n++;let u=k.parseArgument(4,8,e,n);r=new Ct(u.value),n=u.newIndex}let a=[],l=yn.parseItem(e,n);for(a.push(l.value),n=l.newIndex;n<e.length&&e[n].type&16;){n++;let u=yn.parseItem(e,n);a.push(u.value),n=u.newIndex}if(a.length===0)throw new Error(`Syntax error at position ${t}: No select items found. The SELECT clause requires at least one expression to select.`);{let u=new J(a,r,s);return u.comments=i,{value:u,newIndex:n}}}},yn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseItem(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The select item is complete but there are additional tokens.`);return r.value}static parseItem(e,t){let n=t,r=k.parseFromLexeme(e,n),i=r.value;if(n=r.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 q(i,s),newIndex:n}}else if(i instanceof v&&i.column.name!=="*")return{value:new q(i,i.column.name),newIndex:n};return{value:new q(i),newIndex:n}}};var wn=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="on"){n++;let r=k.parseFromLexeme(e,n);return n=r.newIndex,{value:new pe(r.value),newIndex:n}}return null}};var gn=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="using"){n++;let r=k.parseArgument(4,8,e,n),i=r.value;return n=r.newIndex,{value:new we(i),newIndex:n}}return null}};var Sn=class{static tryParse(e,t){let n=t,r=[];for(;this.isJoinCommand(e,n);){let i=this.parseJoinClause(e,n);r.push(i.value),n=i.newIndex}return r.length>0?{value:r,newIndex:n}:null}static isJoinKeyword(e){return!!Yn.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,r=e[n].value===","?"cross join":e[n].value;n++;let i=this.parseLateral(e,n),s=i.value;n=i.newIndex;let a=qe.parseFromLexeme(e,n);if(n=a.newIndex,n<e.length){let u=wn.tryParse(e,n);if(u)return{value:new me(r,a.value,u.value,s),newIndex:u.newIndex};let c=gn.tryParse(e,n);if(c)return{value:new me(r,a.value,c.value,s),newIndex:c.newIndex}}return{value:new me(r,a.value,null,s),newIndex:n}}};var xt=class{static collectClauseComments(e,t,n){if(t>=e.length||e[t].value.toLowerCase()!==n.toLowerCase())return null;let r=[];e[t].comments&&r.push(...e[t].comments);let i=t-1;for(;i>=0;){let s=e[i];if(s.comments&&s.comments.length>0){let a=s.comments.filter(l=>{let u=l.toLowerCase();return u.includes(n.toLowerCase())||u.includes("\u306E")||u.includes("\u30B3\u30E1\u30F3\u30C8")});a.length>0&&(r.unshift(...a),s.comments=s.comments.filter(l=>!a.includes(l)),s.comments.length===0&&(s.comments=null));break}if(this.isSignificantSqlKeyword(s.value))break;i--}return r.length>0?r:null}static isSignificantSqlKeyword(e){return new Set(["select","from","where","group by","having","order by","limit","offset"]).has(e.toLowerCase())}};var vn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The FROM clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=xt.collectClauseComments(e,n,"from");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=qe.parseFromLexeme(e,n);n=i.newIndex;let s=Sn.tryParse(e,n);if(n=s?.newIndex||n,s!==null){let a=new D(i.value,s.value);return a.comments=r,{value:a,newIndex:n}}else{let a=new D(i.value,null);return a.comments=r,{value:a,newIndex:n}}}};var En=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The WHERE clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=xt.collectClauseComments(e,n,"where");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=k.parseFromLexeme(e,n),s=new se(i.value);return s.comments=r,{value:s,newIndex:i.newIndex}}};var bn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The GROUP BY clause is complete but there are additional tokens.`);return r.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 r=[],i=this.parseItem(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=this.parseItem(e,n);r.push(s.value),n=s.newIndex}if(r.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 ue(r),newIndex:n}}static parseItem(e,t){let n=t,r=k.parseFromLexeme(e,n),i=r.value;return n=r.newIndex,{value:i,newIndex:n}}};var xn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The HAVING clause is complete but there are additional tokens.`);return r.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 r=k.parseFromLexeme(e,n);return{value:new ce(r.value),newIndex:r.newIndex}}};var Tn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The WINDOW clause is complete but there are additional tokens.`);return r.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 r=[];for(;n<e.length;){if(n>=e.length||e[n].type!==64)throw new Error("Syntax error: Expected window name after 'WINDOW' keyword.");let i=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=wt.parseFromLexeme(e,n);if(n=s.newIndex,r.push(new ve(i,s.value)),n<e.length&&e[n].type&16)n++;else break}if(r.length===0)throw new Error("At least one WINDOW clause is required after WINDOW keyword.");return{value:new _e(r),newIndex:n}}};var kn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The LIMIT clause is complete but there are additional tokens.`);return r.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 r=k.parseFromLexeme(e,n);return n=r.newIndex,{value:new oe(r.value),newIndex:n}}};var In=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The FOR clause is complete but there are additional tokens.`);return r.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 r=e[n].value,i;switch(r){case"update":i="update",n++;break;case"share":i="share",n++;break;case"key share":i="key share",n++;break;case"no key update":i="no key update",n++;break;default:throw new Error(`Syntax error at position ${n}: Invalid lock mode "${r}". Valid lock modes are: UPDATE, SHARE, KEY SHARE, NO KEY UPDATE.`)}return{value:new Ne(i),newIndex:n}}};var Bt=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The CommonTable definition is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=n<e.length?e[n].comments:null,i=mt.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length&&e[n].value!=="as")throw new Error(`Syntax error at position ${n}: Expected 'AS' keyword after CTE name but found "${e[n].value}".`);n++;let s=null;if(n<e.length){let c=e[n].value;c==="materialized"?(s=!0,n++):c==="not materialized"&&(s=!1,n++)}if(n<e.length&&e[n].type!==4)throw new Error(`Syntax error at position ${n}: Expected '(' after CTE name but found "${e[n].value}".`);let a=e[n].comments;n++;let l=Q.parseFromLexeme(e,n);if(n=l.newIndex,a&&a.length>0&&(l.value.comments?l.value.comments=[...a,...l.value.comments]:l.value.comments=a),n<e.length&&e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected ')' after CTE query but found "${e[n].value}".`);n++;let u=new X(l.value,i.value,s);return u.comments=r,{value:u,newIndex:n}}};var Tt=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The WITH clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=n<e.length?e[n].comments:null;if(n<e.length&&e[n].value.toLowerCase()==="with")n++;else throw new Error(`Syntax error at position ${n}: Expected WITH keyword.`);let i=n<e.length&&e[n].value.toLowerCase()==="recursive";i&&n++;let s=[],a=Bt.parseFromLexeme(e,n);for(s.push(a.value),n=a.newIndex;n<e.length&&e[n].type&16;){n++;let u=Bt.parseFromLexeme(e,n);s.push(u.value),n=u.newIndex}let l=new ne(i,s);return l.comments=r,{value:l,newIndex:n}}};var Nn=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The VALUES clause is complete but there are additional tokens.`);return r.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 r=[],i=this.parseTuple(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let a=this.parseTuple(e,n);r.push(a.value),n=a.newIndex}return{value:new he(r),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 r=[];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 ke([]),newIndex:n};let i=k.parseFromLexeme(e,n);for(r.push(i.value),n=i.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=k.parseFromLexeme(e,n);r.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 ke(r),newIndex:n}}};var Pn=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 r=Zn.parseFromLexeme(e,n),i=r.value;return n=r.newIndex,{value:new De(i),newIndex:n}}},Zn=class{static parseFromLexeme(e,t){let n=t,r,i=e[n].value;if(i==="first")r="first";else if(i==="next")r="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 G(1),a="rows only",n++,{value:new ut(r,s,a),newIndex:n};let l=k.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 ut(r,s,a),newIndex:n}}};var On=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The OFFSET clause is complete but there are additional tokens.`);return r.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 r=k.parseFromLexeme(e,n);return n=r.newIndex,n<e.length&&(e[n].value==="row"||e[n].value==="rows")&&n++,{value:new Le(r.value),newIndex:n}}};var Q=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`[SelectQueryParser] Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The SELECT query is complete but there are additional tokens.`);return r.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 r=e[n].value;if(!this.selectCommandSet.has(r)&&r!=="values")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' or 'VALUES' keyword but found "${e[n].value}".`);let i=this.selectCommandSet.has(r)?this.parseSimpleSelectQuery(e,n):this.parseValuesQuery(e,n),s=i.value;for(n=i.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 W(s,a,u.value),n=u.newIndex}else if(l==="values"){let u=this.parseValuesQuery(e,n);s=new W(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,r=null;n<e.length&&e[n].value==="with"&&(r=Tt.parseFromLexeme(e,n),n=r.newIndex);let i=n<e.length?e[n].comments:null;if(n>=e.length||e[n].value!=="select")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword but found "${n<e.length?e[n].value:"end of input"}". SELECT queries must start with the SELECT keyword.`);let s=Cn.parseFromLexeme(e,n);n=s.newIndex,i&&s.value.comments&&JSON.stringify(i)===JSON.stringify(s.value.comments)&&(s.value.comments=null);let a=null;n<e.length&&e[n].value==="from"&&(a=vn.parseFromLexeme(e,n),n=a.newIndex);let l=null;n<e.length&&e[n].value==="where"&&(l=En.parseFromLexeme(e,n),n=l.newIndex);let u=null;n<e.length&&e[n].value==="group by"&&(u=bn.parseFromLexeme(e,n),n=u.newIndex);let c=null;n<e.length&&e[n].value==="having"&&(c=xn.parseFromLexeme(e,n),n=c.newIndex);let m=null;n<e.length&&e[n].value==="window"&&(m=Tn.parseFromLexeme(e,n),n=m.newIndex);let h=null;n<e.length&&e[n].value==="order by"&&(h=rt.parseFromLexeme(e,n),n=h.newIndex);let w=null;n<e.length&&e[n].value==="limit"&&(w=kn.parseFromLexeme(e,n),n=w.newIndex);let b=null;n<e.length&&e[n].value==="offset"&&(b=On.parseFromLexeme(e,n),n=b.newIndex);let d=null;n<e.length&&e[n].value==="fetch"&&(d=Pn.parseFromLexeme(e,n),n=d.newIndex);let y=null;n<e.length&&e[n].value.toLowerCase()==="for"&&(y=In.parseFromLexeme(e,n),n=y.newIndex);let L=new g({withClause:r?r.value:null,selectClause:s.value,fromClause:a?a.value:null,whereClause:l?l.value:null,groupByClause:u?u.value:null,havingClause:c?c.value:null,orderByClause:h?h.value:null,windowClause:m?m.value:null,limitClause:w?w.value:null,offsetClause:b?b.value:null,fetchClause:d?d.value:null,forClause:y?y.value:null});return L.comments=i,{value:L,newIndex:n}}static parseValuesQuery(e,t){let n=Nn.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}};var dr=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The INSERT query is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=null;if(e[n].value==="with"){let l=Tt.parseFromLexeme(e,n);r=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 i=qe.parseTableSourceFromLexemes(e,n);n=i.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=Q.parseFromLexeme(e,n);if(r)if(a.value instanceof g)a.value.withClause=r;else throw new Error("WITH clause is not supported in this context.");return n=a.newIndex,{value:new Ye({insertClause:new nt(i.value,s),selectQuery:a.value}),newIndex:n}}};var lt=class o{constructor(){this.dependencyGraph=null;this.cteMap=new Map;this.sourceCollector=new it(!0),this.cteCollector=new ee}static{this.ERROR_MESSAGES={NOT_ANALYZED:"Must call analyzeDependencies first",CIRCULAR_REFERENCE:"Circular reference detected in CTE"}}analyzeDependencies(e){let t=this.cteCollector.collect(e);return this.buildCTEMap(t),this.dependencyGraph=this.buildDependencyGraph(t),this.dependencyGraph}getDependencies(e){this.ensureAnalyzed();let t=this.findNodeByName(e);return t?[...t.dependencies]:[]}getDependents(e){this.ensureAnalyzed();let t=this.findNodeByName(e);return t?[...t.dependents]:[]}hasCircularDependency(){this.ensureAnalyzed();try{return this.getExecutionOrder(),!1}catch(e){if(e instanceof Error&&e.message.includes(o.ERROR_MESSAGES.CIRCULAR_REFERENCE))return!0;throw e}}getExecutionOrder(){this.ensureAnalyzed();let e=new Set,t=new Set,n=[],r=new Map;for(let s of this.dependencyGraph.nodes)r.set(s.name,new Set(s.dependencies));let i=s=>{if(e.has(s))return;if(t.has(s))throw new Error(`${o.ERROR_MESSAGES.CIRCULAR_REFERENCE}: ${s}`);t.add(s);let a=r.get(s)||new Set;for(let l of a)i(l);t.delete(s),e.add(s),n.push(s)};for(let s of this.dependencyGraph.nodes)e.has(s.name)||i(s.name);return n}buildDependencyGraph(e){let t=[],n=[],r=new Map,i=new Map;for(let s of e){let a=o.getCTEName(s);r.set(a,new Set),i.set(a,new Set)}for(let s of e){let a=o.getCTEName(s),l=this.sourceCollector.collect(s.query);for(let u of l){let c=u.table.name;this.cteMap.has(c)&&c!==a&&(r.get(a).add(c),i.get(c).add(a),n.push({from:a,to:c}))}}for(let s of e){let a=o.getCTEName(s);t.push({name:a,cte:s,dependencies:Array.from(r.get(a)||new Set),dependents:Array.from(i.get(a)||new Set)})}return{nodes:t,edges:n}}ensureAnalyzed(){if(!this.dependencyGraph)throw new Error(o.ERROR_MESSAGES.NOT_ANALYZED)}buildCTEMap(e){this.cteMap.clear();for(let t of e){let n=o.getCTEName(t);this.cteMap.set(n,t)}}findNodeByName(e){return this.dependencyGraph?.nodes.find(t=>t.name===e)}static getCTEName(e){return e.aliasExpression.table.name}};var Fn=class{static addComment(e,t){e.comments||(e.comments=[]),e.comments.push(t)}static editComment(e,t,n){if(!e.comments||t<0||t>=e.comments.length)throw new Error(`Invalid comment index: ${t}. Component has ${e.comments?.length||0} comments.`);e.comments[t]=n}static deleteComment(e,t){if(!e.comments||t<0||t>=e.comments.length)throw new Error(`Invalid comment index: ${t}. Component has ${e.comments?.length||0} comments.`);e.comments.splice(t,1),e.comments.length===0&&(e.comments=null)}static deleteAllComments(e){e.comments=null}static getComments(e){return e.comments||[]}static findComponentsWithComment(e,t,n=!1){let r=[],i=n?t:t.toLowerCase(),s=a=>{a&&a instanceof f&&a.comments&&a.comments.some(l=>(n?l:l.toLowerCase()).includes(i))&&r.push(a);for(let l in a)a[l]&&typeof a[l]=="object"&&(Array.isArray(a[l])?a[l].forEach(s):s(a[l]))};return s(e),r}static replaceInComments(e,t,n,r=!1){let i=0,s=a=>{if(a&&a instanceof f&&a.comments)for(let l=0;l<a.comments.length;l++){let u=a.comments[l],c=r?"g":"gi",m=new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c),h=u.replace(m,n);h!==u&&(a.comments[l]=h,i++)}for(let l in a)a[l]&&typeof a[l]=="object"&&(Array.isArray(a[l])?a[l].forEach(s):s(a[l]))};return s(e),i}static countComments(e){let t=0,n=r=>{r&&r instanceof f&&r.comments&&(t+=r.comments.length);for(let i in r)r[i]&&typeof r[i]=="object"&&(Array.isArray(r[i])?r[i].forEach(n):n(r[i]))};return n(e),t}static getAllComments(e){let t=[],n=r=>{r&&r instanceof f&&r.comments&&r.comments.forEach((i,s)=>{t.push({comment:i,component:r,index:s})});for(let i in r)r[i]&&typeof r[i]=="object"&&(Array.isArray(r[i])?r[i].forEach(n):n(r[i]))};return n(e),t}};var Qn=class{constructor(e,t){this.name=e,this.columns=t}},Ln=class{constructor(e=null,t=!1){this.tableColumnResolver=e;this.allowWildcardWithoutResolver=t;this.tableSchemas=[];this.visitedNodes=new Set;this.commonTables=[];this.running=!1;this.handlers=new Map,this.handlers.set(g.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(W.kind,n=>this.visitBinarySelectQuery(n))}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 g||e instanceof W))throw new Error(`Unsupported SQL component type for schema collection. Received: ${e.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let t=new ee;this.commonTables=t.collect(e),this.visitNode(e),this.consolidateTableSchemas()}finally{this.running=!1}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}reset(){this.tableSchemas=[],this.visitedNodes=new Set,this.commonTables=[]}consolidateTableSchemas(){let e=new Map;for(let t of this.tableSchemas)if(!e.has(t.name))e.set(t.name,new Set(t.columns));else{let n=e.get(t.name);t.columns.forEach(r=>n?.add(r))}this.tableSchemas=Array.from(e.entries()).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>new Qn(t,Array.from(n).sort()))}handleTableSource(e,t,n){if(e.datasource instanceof B){let r=e.datasource.getSourceName(),i=this.commonTables.filter(s=>s.getSourceAliasName()===r);if(i.length>0)i[0].query.accept(this);else{let s=e.getAliasName()??r;this.processCollectTableSchema(r,s,t,n)}}else throw new Error("Datasource is not an instance of TableSource")}visitSimpleSelectQuery(e){if(e.fromClause===null)return;let n=new Oe(this.tableColumnResolver,!0,"fullName").collect(e),r;if(this.allowWildcardWithoutResolver){let i=this.getSelectClauseColumns(e);r=n.filter(s=>s.value instanceof v).map(s=>s.value).filter(s=>{let a=s.getNamespace(),l=s.column.name;return i.some(u=>{if(u.value instanceof v){let c=u.value.getNamespace(),m=u.value.column.name;if(c===a&&m===l)return!0;if(m==="*"){if(this.allowWildcardWithoutResolver&&this.tableColumnResolver===null)return!1;if(c===""||c===a)return!0}}return!1})}).map(s=>({table:s.getNamespace(),column:s.column.name}))}else r=n.filter(i=>i.value instanceof v).map(i=>i.value).map(i=>({table:i.getNamespace(),column:i.column.name}));if(e.fromClause.joins!==null&&e.fromClause.joins.length>0){let i=r.filter(s=>s.table==="").map(s=>s.column);if(i.length>0)throw new Error(`Column reference(s) without table name found in query: ${i.join(", ")}`)}if(e.fromClause.source.datasource instanceof B?this.handleTableSource(e.fromClause.source,r,!0):e.fromClause.source.datasource instanceof _&&e.fromClause.source.datasource.query.accept(this),e.fromClause?.joins)for(let i of e.fromClause.joins)i.source.datasource instanceof B?this.handleTableSource(i.source,r,!1):i.source.datasource instanceof _&&i.source.datasource.query.accept(this)}visitBinarySelectQuery(e){this.visitNode(e.left),this.visitNode(e.right)}getSelectClauseColumns(e){if(!e.selectClause)return[];let t=[];for(let n of e.selectClause.items)if(n.value instanceof v){let r=n.value.column.name;t.push({name:r,value:n.value})}return t}processCollectTableSchema(e,t,n,r=!1){if(this.tableColumnResolver===null&&n.filter(l=>l.table===t||r&&l.table==="").filter(l=>l.column==="*").length>0&&!this.allowWildcardWithoutResolver){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 i=n.filter(a=>a.column!=="*").filter(a=>a.table===t||r&&a.table==="").map(a=>a.column),s=new Qn(e,i);this.tableSchemas.push(s)}};var An=class{static validate(e,t){let n=typeof e=="string"?Q.parse(e):e,r=Array.isArray(t)?l=>{let u=t.find(c=>c.name===l);return u?u.columns:[]}:t,s=new Ln(r).collect(n),a=[];for(let l of s){let u=r(l.name);if(u.length===0){a.push(`Table '${l.name}' is not defined.`);continue}let c=l.columns.filter(m=>!u.includes(m));c.length>0&&a.push(`Table '${l.name}' contains undefined columns: ${c.join(", ")}.`)}if(a.length>0)throw new Error(a.join(`
|
|
16
|
+
`))}};var Bn=class{constructor(e={}){this.knownCTENames=[];this.options=e,this.formatter=new je(e),this.dependencyAnalyzer=new lt}compose(e,t){if(e.length===0)return t;this.knownCTENames=e.map(m=>m.name);let n=e.map(m=>({name:m.name,query:this.extractPureQuery(m.query,m.name)})),r=this.buildTempQueryForAnalysis(n,t),i=this.dependencyAnalyzer.analyzeDependencies(r),s=this.sortCTEsByDependencies(n,i),a=this.detectRecursiveFromOriginalQueries(e),l=s.map(m=>`${m.name} as (${m.query})`),c=`${a?"with recursive":"with"} ${l.join(", ")} ${t}`;return this.options.validateSchema&&this.options.schema&&this.validateComposedQuery(c),this.formatFinalQuery(c)}extractPureQuery(e,t){if(!/^\s*with\s+/i.test(e)||/^\s*with\s+recursive\s+/i.test(e))return e;try{let i=Q.parse(e);if(i.withClause&&i.withClause.tables){let s=this.getKnownCTENames();if(i.withClause.tables.map(u=>this.getCTEName(u)).every(u=>s.includes(u))){let u=new g({selectClause:i.selectClause,fromClause:i.fromClause,whereClause:i.whereClause,groupByClause:i.groupByClause,havingClause:i.havingClause,orderByClause:i.orderByClause,windowClause:i.windowClause,limitClause:i.limitClause,offsetClause:i.offsetClause,fetchClause:i.fetchClause,forClause:i.forClause,withClause:void 0});return new je({identifierEscape:{start:"",end:""}}).format(u).formattedSql}}}catch{}return e}getKnownCTENames(){return this.knownCTENames||[]}getCTEName(e){return e.aliasExpression.table.name}extractCTEWithRegex(e,t){let n=new RegExp(`${t}\\s+as\\s*\\(`,"i"),r=e.match(n);if(!r)return e;let i=r.index+r[0].length,s=1,a=i;for(;a<e.length&&s>0;){let l=e[a];l==="("?s++:l===")"&&s--,a++}return s===0?e.substring(i,a-1).trim():e}buildTempQueryForAnalysis(e,t){let r=`with ${e.map(i=>`${i.name} as (${i.query})`).join(", ")} ${t}`;try{return Q.parse(r)}catch(i){throw new Error(`Failed to parse temporary query for dependency analysis: ${i}`)}}sortCTEsByDependencies(e,t){let n=new Map;return e.forEach(r=>n.set(r.name,r.query)),t.nodes.map(r=>({name:r.name,query:n.get(r.name)||""})).filter(r=>r.query!=="")}detectRecursiveFromOriginalQueries(e){return e.some(t=>t.query.toLowerCase().includes("with recursive"))}detectRecursiveCTEs(e){return e.withClause?this.formatter.format(e).formattedSql.toLowerCase().includes("with recursive"):!1}validateComposedQuery(e){try{let t=Q.parse(e),n=Object.entries(this.options.schema).map(([r,i])=>({name:r,columns:i}));An.validate(t,n)}catch(t){throw t instanceof Error?new Error(`Schema validation failed: ${t.message}`):t}}formatFinalQuery(e){if(this.options.preset||this.options.keywordCase)try{let t=Q.parse(e);return this.formatter.format(t).formattedSql}catch{return e}return e}};var hr=class o{static{this.ERROR_MESSAGES={CIRCULAR_REFERENCE:"Circular reference detected in non-recursive CTEs",PARSING_FAILED:"Failed to parse query for comment injection"}}static{this.COMMENT_TEXTS={AUTO_GENERATED:"Auto-generated by CTE decomposer",ORIGINAL_CTE:"Original CTE:",DEPENDENCIES:"Dependencies:",DEPENDENTS:"Dependents:",RECURSIVE_TYPE:"Type: Recursive CTE",NONE:"none"}}constructor(e={}){this.options=e,this.dependencyAnalyzer=new lt,this.cteCollector=new ee,this.formatter=new je(e)}decompose(e){let t=this.cteCollector.collect(e);if(t.length===0)return[];let n=this.findRecursiveCTEs(e,t),r=this.dependencyAnalyzer.analyzeDependencies(e);return this.validateCircularDependencies(n.length>0),this.processCTENodes(e,r.nodes,n)}synchronize(e,t){if(e.length===0)return[];let n={...this.options,addComments:void 0},i=new Bn(n).compose(e,t),s=Q.parse(i);return this.decompose(s)}validateCircularDependencies(e){if(this.dependencyAnalyzer.hasCircularDependency()&&!e)throw new Error(o.ERROR_MESSAGES.CIRCULAR_REFERENCE)}processCTENodes(e,t,n){let r=[];for(let i of t)n.includes(i.name)?r.push(this.createRecursiveCTE(i,e)):r.push(this.createStandardCTE(i,t));return r}createRecursiveCTE(e,t){let n=this.formatter.format(t).formattedSql,r=this.addCommentsToQuery(n,e.name,[],[],!0);return{name:e.name,query:r,dependencies:[],dependents:[],isRecursive:!0}}createStandardCTE(e,t){let n=this.buildExecutableQuery(e,t),r=this.addCommentsToQuery(n,e.name,e.dependencies,e.dependents,!1);return{name:e.name,query:r,dependencies:[...e.dependencies],dependents:[...e.dependents],isRecursive:!1}}buildExecutableQuery(e,t){let n=this.collectRequiredCTEs(e,t);if(n.length===0)return this.formatter.format(e.cte.query).formattedSql;let r=this.buildWithClause(n),i=this.formatter.format(e.cte.query).formattedSql;return`${r} ${i}`}collectRequiredCTEs(e,t){let n=new Set,r=[],i=new Map;for(let a of t)i.set(a.name,a);let s=a=>{if(n.has(a))return;n.add(a);let l=i.get(a);if(l){for(let u of l.dependencies)s(u);a!==e.name&&r.push(l)}};for(let a of e.dependencies)s(a);return r}buildWithClause(e){return e.length===0?"":`with ${e.map(n=>{let r=n.name,i=this.formatter.format(n.cte.query).formattedSql;return`${r} as (${i})`}).join(", ")}`}findRecursiveCTEs(e,t){return!e.withClause||!this.isRecursiveWithClause(e)?[]:t.map(n=>this.getCTEName(n))}isRecursiveWithClause(e){return this.formatter.format(e).formattedSql.toLowerCase().includes("with recursive")}addCommentsToQuery(e,t,n,r,i){if(this.options.addComments!==!0)return e;try{let s=Q.parse(e);return this.generateComments(t,n,r,i).forEach(u=>{Fn.addComment(s,u)}),new je({...this.options,exportComment:!0}).format(s).formattedSql}catch(s){return console.warn(`${o.ERROR_MESSAGES.PARSING_FAILED}: ${s}`),this.addTextCommentsToQuery(e,t,n,r,i)}}generateComments(e,t,n,r){let{AUTO_GENERATED:i,ORIGINAL_CTE:s,DEPENDENCIES:a,DEPENDENTS:l,RECURSIVE_TYPE:u,NONE:c}=o.COMMENT_TEXTS,m=[];m.push(i),m.push(`${s} ${e}`),r&&m.push(u);let h=t.length>0?t.join(", "):c;m.push(`${a} ${h}`);let w=n.length>0?n.join(", "):c;return m.push(`${l} ${w}`),m}addTextCommentsToQuery(e,t,n,r,i){return`${this.generateComments(t,n,r,i).map(l=>`-- ${l}`).join(`
|
|
17
17
|
`)}
|
|
18
|
-
${e}`}getCTEName(e){return e.aliasExpression.table.name}};var Rn=class o{constructor(){this.jsonColumnCounter=0;this.entityToJsonColumnMap=new Map;this.columnMappings=[]}static{this.CTE_OBJECT_PREFIX="cte_object_depth_"}static{this.WILDCARD_COLUMN="*"}buildObjectEntityCtes(e,t,n){this.jsonColumnCounter=0,this.entityToJsonColumnMap.clear(),this.columnMappings=[];let r=[e],i=e.aliasExpression.table.name,s=this.collectAndSortObjectEntities(n,t),a=this.groupEntitiesByDepth(s),l=Array.from(a.keys()).sort((u,c)=>c-u);for(let u of l){let c=a.get(u),m=`${o.CTE_OBJECT_PREFIX}${u}`,h=this.buildDepthCte(c,i,m,n,t);r.push(h),i=m}return{ctes:r,lastCteAlias:i,columnMappings:this.columnMappings}}generateUniqueJsonColumnName(e,t,n){this.jsonColumnCounter++;let r=`${e.toLowerCase()}_json_${this.jsonColumnCounter}`;return this.columnMappings.push({entityId:t,entityName:e,generatedColumnName:r,depth:n}),r}collectAndSortObjectEntities(e,t){let n=[],r=i=>{let s=t.get(i);if(!s)throw new Error(`Entity ${i} 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(i);a;){if(u.has(a))throw new Error(`Circular dependency detected: ${a} already visited in path for ${i}`);u.add(a);let c=t.get(a);if(!c)throw new Error(`Parent entity ${a} not found during depth calculation for ${i}`);let m=!1;if(c.isRoot)m=!0;else{let h=e.nestedEntities.find(w=>w.id===a);if(h)h.relationshipType==="object"&&(m=!0);else throw new Error(`Parent entity ${a} (ancestor of ${i}) has no definition in mapping.nestedEntities and is not root.`)}if(m&&l++,c.isRoot)break;a=c.parentId}return l};return e.nestedEntities.forEach(i=>{if(i.relationshipType==="object"){let s=t.get(i.id);s&&!s.isRoot&&n.push({entity:s,depth:r(i.id)})}}),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let r=n.depth;t.has(r)||t.set(r,[]),t.get(r).push(n)}),t}buildDepthCte(e,t,n,r,i){let s=[new j(new v(null,new x(o.WILDCARD_COLUMN)))];for(let{entity:l}of e){let u=this.buildEntityJsonColumn(l,r,i);s.push(u)}let a=new E({selectClause:new J(s),fromClause:new D(new M(new R(null,new x(t)),null),null)});return new ee(a,new Y(n,null),null)}buildEntityJsonColumn(e,t,n){let{jsonObjectArgs:r,nullChecks:i}=this.prepareEntityColumns(e);this.addChildObjectRelationships(e,r,t,n);let s=this.createJsonObject(r),a=this.buildNullCondition(i),l=this.createCaseExpression(a,s),u=this.calculateApproximateDepth(e,t),c=this.generateUniqueJsonColumnName(e.name,e.id,u);return this.entityToJsonColumnMap.set(e.id,c),new j(l,c)}calculateApproximateDepth(e,t){if(e.isRoot)return 0;if(!e.parentId)return 1;let n=1,r=e.parentId;for(;r&&r!==t.rootEntity.id;){let i=t.nestedEntities.find(s=>s.id===r);if(!i)break;n++,r=i.parentId}return n}prepareEntityColumns(e){let t=[],n=[];return Object.entries(e.columns).forEach(([r,i])=>{t.push(new G(r)),t.push(new v(null,new x(i))),n.push(new y(new v(null,new x(i)),"is",new G(null)))}),{jsonObjectArgs:t,nullChecks:n}}addChildObjectRelationships(e,t,n,r){n.nestedEntities.filter(s=>s.parentId===e.id&&s.relationshipType==="object").forEach(s=>{let a=r.get(s.id);if(a){t.push(new G(s.propertyName));let l=this.entityToJsonColumnMap.get(a.id);if(!l)throw new Error(`JSON column name not found for child entity: ${a.id}`);t.push(new v(null,new x(l)))}})}createJsonObject(e){let t="jsonb_build_object";return new U(null,new V(t),new _(e),null)}buildNullCondition(e){return e.reduce((t,n)=>t?new y(t,"and",n):n)}createCaseExpression(e,t){return new le(null,new ye([new we(e,new G(null))],t))}};var Bn=class o{static{this.CTE_ARRAY_PREFIX="cte_array_depth_"}static{this.JSON_FUNCTIONS={BUILD_OBJECT:"jsonb_build_object",AGGREGATE:"jsonb_agg"}}buildArrayEntityCtes(e,t,n,r,i){let s=[...e],a=t,l=this.collectAndSortArrayEntities(r,n);if(l.length===0)return{updatedCtes:s,lastCteAlias:a};let u=this.groupEntitiesByDepth(l),c=Array.from(u.keys()).sort((m,h)=>h-m);for(let m of c){let h=u.get(m),{cte:w,newCteAlias:b}=this.buildDepthCte(h,a,s,m,r,i);s.push(w),a=b}return{updatedCtes:s,lastCteAlias:a}}collectAndSortArrayEntities(e,t){let n=[],r=i=>{let s=t.get(i);return!s||s.isRoot?0:s.parentId?1+r(s.parentId):1};return e.nestedEntities.forEach(i=>{if(i.relationshipType==="array"){let s=t.get(i.id),a=t.get(i.parentId);if(!s||!a)throw new Error(`Configuration error: Array entity '${i.id}' or its parent '${i.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 '${i.name}'.`);let u=l[0];n.push({entity:s,parentEntity:a,parentIdColumnSqlName:u,depth:r(i.id)})}}),n.sort((i,s)=>s.depth-i.depth),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let r=n.depth;t.has(r)||t.set(r,[]),t.get(r).push(n)}),t}buildDepthCte(e,t,n,r,i,s){let a=new Set;e.forEach(S=>{Object.values(S.entity.columns).forEach(N=>a.add(N));let O=N=>{i.nestedEntities.filter(Q=>Q.parentId===N).forEach(Q=>{Object.values(Q.columns).forEach(g=>{let I=typeof g=="string"?g:g.column;a.add(I)}),O(Q.id)})};O(S.entity.id)});let l=n.find(S=>S.aliasExpression.table.name===t)?.query;if(!l)throw new Error(`CTE not found: ${t}`);let u=new Ae(null,n).collect(l),c=[],m=[],h=new Set;e.forEach(S=>{Object.values(S.entity.columns).forEach(O=>h.add(O))});let w=this.collectArrayEntityColumnsByDepth(i,r),b=new Set;s&&e.forEach(S=>{i.nestedEntities.filter(O=>O.parentId===S.entity.id&&O.relationshipType==="object").forEach(O=>{let N=s.find(Q=>Q.entityId===O.id);N&&b.add(N.generatedColumnName)})}),this.processSelectVariablesForGroupBy(u,a,w,r,m,c,b);for(let S of e){let O=this.buildAggregationDetailsForArrayEntity(S.entity,i.nestedEntities,new Map,s);m.push(new j(O.jsonAgg,S.entity.propertyName))}let d=`${o.CTE_ARRAY_PREFIX}${r}`,C=new E({selectClause:new J(m),fromClause:new D(new M(new R(null,new x(t)),null),null),groupByClause:c.length>0?new pe(c):null});return{cte:new ee(C,new Y(d,null),null),newCteAlias:d}}buildAggregationDetailsForArrayEntity(e,t,n,r){let i=o.JSON_FUNCTIONS.BUILD_OBJECT,s=[];Object.entries(e.columns).forEach(([h,w])=>{s.push(new G(h)),s.push(new v(null,new x(w)))}),t.filter(h=>h.parentId===e.id).forEach(h=>{let w=h.originalPropertyName||h.propertyName;if(s.push(new G(w)),h.relationshipType==="object"){if(!r)throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mappings not provided
|
|
18
|
+
${e}`}getCTEName(e){return e.aliasExpression.table.name}};var Rn=class{constructor(){this.columnReferences=[];this.visitedNodes=new Set;this.handlers=new Map,this.handlers.set(ne.kind,e=>this.visitWithClause(e)),this.handlers.set(X.kind,e=>this.visitCommonTable(e)),this.handlers.set(J.kind,e=>this.visitSelectClause(e)),this.handlers.set(D.kind,e=>this.visitFromClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(ue.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ce.kind,e=>this.visitHavingClause(e)),this.handlers.set(le.kind,e=>this.visitOrderByClause(e)),this.handlers.set(_e.kind,e=>this.visitWindowsClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Le.kind,e=>this.visitOffsetClause(e)),this.handlers.set(De.kind,e=>this.visitFetchClause(e)),this.handlers.set(Ne.kind,e=>this.visitForClause(e)),this.handlers.set(me.kind,e=>this.visitJoinClause(e)),this.handlers.set(pe.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(we.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set($.kind,e=>this.visitSourceExpression(e)),this.handlers.set(_.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(v.kind,e=>this.visitColumnReference(e)),this.handlers.set(C.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(j.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ie.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ae.kind,e=>this.visitCastExpression(e)),this.handlers.set(ye.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(H.kind,e=>this.visitParenExpression(e)),this.handlers.set(Se.kind,e=>this.visitInlineQuery(e)),this.handlers.set(fe.kind,e=>this.visitArrayExpression(e)),this.handlers.set(Ce.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(K.kind,e=>this.visitValueList(e)),this.handlers.set(Ee.kind,e=>this.visitWindowFrameExpression(e))}collect(e){return this.columnReferences=[],this.visitedNodes.clear(),e instanceof g?this.collectFromSimpleQuery(e):e instanceof W?this.collectFromSimpleQuery(e.toSimpleQuery()):e.accept(this),[...this.columnReferences]}collectFromSimpleQuery(e){if(e.withClause&&e.withClause.tables)for(let t of e.withClause.tables)this.collectFromSimpleQuery(t.query);if(this.collectFromSelectClause(e.selectClause),e.fromClause&&this.collectFromFromClause(e.fromClause),e.whereClause&&this.collectFromValueComponent(e.whereClause.condition),e.groupByClause&&e.groupByClause.grouping)for(let t of e.groupByClause.grouping)this.collectFromValueComponent(t);if(e.havingClause&&this.collectFromValueComponent(e.havingClause.condition),e.orderByClause&&e.orderByClause.order)for(let t of e.orderByClause.order)typeof t=="object"&&"value"in t&&t.value?this.collectFromValueComponent(t.value):this.collectFromValueComponent(t)}collectFromSelectClause(e){for(let t of e.items)this.collectFromValueComponent(t.value)}collectFromFromClause(e){if(this.collectFromSourceExpression(e.source),e.joins)for(let t of e.joins)this.collectFromSourceExpression(t.source),t.condition&&this.collectFromValueComponent(t.condition.condition)}collectFromSourceExpression(e){e.datasource instanceof _&&(e.datasource.query instanceof g?this.collectFromSimpleQuery(e.datasource.query):e.datasource.query instanceof W&&this.collectFromSimpleQuery(e.datasource.query.toSimpleQuery()))}collectFromValueComponent(e){if(e instanceof v)this.columnReferences.push(e);else if(e instanceof C)this.collectFromValueComponent(e.left),this.collectFromValueComponent(e.right);else if(e instanceof te)this.collectFromValueComponent(e.expression);else if(e instanceof j&&e.argument)this.collectFromValueComponent(e.argument);else if(e instanceof ie){if(e.condition&&this.collectFromValueComponent(e.condition),e.switchCase&&e.switchCase.cases)for(let t of e.switchCase.cases)this.collectFromValueComponent(t.key),this.collectFromValueComponent(t.value);e.switchCase&&e.switchCase.elseValue&&this.collectFromValueComponent(e.switchCase.elseValue)}else e instanceof H?this.collectFromValueComponent(e.expression):e instanceof Se&&(e.selectQuery instanceof g?this.collectFromSimpleQuery(e.selectQuery):e.selectQuery instanceof W&&this.collectFromSimpleQuery(e.selectQuery.toSimpleQuery()))}visit(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());t&&t(e)}visitSimpleSelectQuery(e){e.withClause&&e.withClause.accept(this),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.orderByClause&&e.orderByClause.accept(this),e.windowClause&&e.windowClause.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)}visitWithClause(e){for(let t of e.tables)t.accept(this)}visitCommonTable(e){e.query.accept(this)}visitSelectClause(e){for(let t of e.items)t.value.accept(this)}visitFromClause(e){if(e.source.accept(this),e.joins)for(let t of e.joins)t.accept(this)}visitWhereClause(e){e.condition.accept(this)}visitGroupByClause(e){if(e.grouping)for(let t of e.grouping)t.accept(this)}visitHavingClause(e){e.condition.accept(this)}visitOrderByClause(e){if(e.order)for(let t of e.order)typeof t=="object"&&"value"in t&&t.value?typeof t.value=="object"&&"accept"in t.value&&t.value.accept(this):typeof t=="object"&&"accept"in t&&t.accept(this)}visitWindowsClause(e){for(let t of e.windows)t.expression.accept(this)}visitLimitClause(e){e.value.accept(this)}visitOffsetClause(e){e.value.accept(this)}visitFetchClause(e){e.expression.accept(this)}visitForClause(e){}visitJoinClause(e){e.source.accept(this),e.condition&&e.condition.accept(this)}visitJoinOnClause(e){e.condition.accept(this)}visitJoinUsingClause(e){e.condition.accept(this)}visitSourceExpression(e){e.datasource.accept(this)}visitSubQuerySource(e){e.query.accept(this)}visitColumnReference(e){this.columnReferences.push(e)}visitBinaryExpression(e){e.left.accept(this),e.right.accept(this)}visitUnaryExpression(e){e.expression.accept(this)}visitFunctionCall(e){e.argument&&e.argument.accept(this)}visitCaseExpression(e){if(e.condition&&e.condition.accept(this),e.switchCase&&e.switchCase.cases)for(let t of e.switchCase.cases)t.key.accept(this),t.value.accept(this);e.switchCase&&e.switchCase.elseValue&&e.switchCase.elseValue.accept(this)}visitCastExpression(e){e.input.accept(this)}visitBetweenExpression(e){e.expression.accept(this),e.lower.accept(this),e.upper.accept(this)}visitParenExpression(e){e.expression.accept(this)}visitInlineQuery(e){e.selectQuery.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)}visitWindowFrameExpression(e){e.partition&&e.partition.accept(this),e.order&&e.order.accept(this)}};var Ke={nullQuery:"Query cannot be null or undefined",invalidOldName:"Old CTE name must be a non-empty string",invalidNewName:"New CTE name must be a non-empty string",sameNames:"Old and new CTE names cannot be the same",unsupportedQuery:"Unsupported query type for CTE renaming",cteNotExists:o=>`CTE '${o}' does not exist`,cteAlreadyExists:o=>`CTE '${o}' already exists`,cteNotFound:o=>`CTE '${o}' not found`},fr=class{constructor(){this.dependencyAnalyzer=new lt,this.columnReferenceCollector=new Rn,this.tableSourceCollector=new it}renameCTE(e,t,n){this.validateInputs(e,t,n);let r=t.trim(),i=n.trim();if(e instanceof g)this.renameInSimpleQuery(e,r,i);else if(e instanceof W)this.renameInBinaryQuery(e,r,i);else throw new Error(Ke.unsupportedQuery)}validateInputs(e,t,n){if(!e)throw new Error(Ke.nullQuery);if(!t||typeof t!="string"||t.trim()==="")throw new Error(Ke.invalidOldName);if(!n||typeof n!="string"||n.trim()==="")throw new Error(Ke.invalidNewName);if(t.trim()===n.trim())throw new Error(Ke.sameNames)}renameInSimpleQuery(e,t,n){let r=e.getCTENames();if(!r.includes(t))throw new Error(Ke.cteNotExists(t));if(r.includes(n))throw new Error(Ke.cteAlreadyExists(n));this.renameCTEDefinition(e,t,n),this.updateAllReferences(e,t,n)}renameInBinaryQuery(e,t,n){let r=e.toSimpleQuery(),i=[];if(r.withClause&&r.withClause.tables&&(i=r.withClause.tables.map(s=>s.aliasExpression.table.name)),!i.includes(t))throw new Error(Ke.cteNotExists(t));if(i.includes(n))throw new Error(Ke.cteAlreadyExists(n));this.renameCTEDefinition(r,t,n),r.withClause&&(e.withClause=r.withClause,e.left instanceof g&&(e.left.withClause=r.withClause)),this.renameInSelectQuery(e.left,t,n),this.renameInSelectQuery(e.right,t,n)}renameInSelectQuery(e,t,n){e instanceof g?this.updateAllReferences(e,t,n):e instanceof W&&(this.renameInSelectQuery(e.left,t,n),this.renameInSelectQuery(e.right,t,n))}renameCTEDefinition(e,t,n){if(!e.withClause||!e.withClause.tables)throw new Error(Ke.cteNotFound(t));let r=e.withClause.tables.find(i=>i.aliasExpression.table.name===t);if(!r)throw new Error(Ke.cteNotFound(t));r.aliasExpression.table.name=n}updateAllReferences(e,t,n){let r=this.columnReferenceCollector.collect(e);for(let s of r)if(s.namespaces&&s.namespaces.length>0){for(let a of s.namespaces)if(a.name===t){a.name=n;break}}let i=this.tableSourceCollector.collect(e);for(let s of i)s.getSourceName()===t&&(s.qualifiedName.name instanceof v||("name"in s.qualifiedName.name?s.qualifiedName.name.name=n:s.qualifiedName.name.value=n));this.updateTableSourcesInCTEs(e,t,n)}updateTableSourcesInCTEs(e,t,n){if(!(!e.withClause||!e.withClause.tables))for(let r of e.withClause.tables)this.updateTableSourcesInQuery(r.query,t,n)}updateTableSourcesInQuery(e,t,n){if(e.fromClause&&e.fromClause.source.datasource&&this.updateTableSource(e.fromClause.source.datasource,t,n),e.fromClause&&e.fromClause.joins)for(let r of e.fromClause.joins)r.source.datasource&&this.updateTableSource(r.source.datasource,t,n)}updateTableSource(e,t,n){if(!e||typeof e!="object")return;let r=e;if(typeof r.getSourceName=="function")try{if(r.getSourceName()===t&&r.qualifiedName&&typeof r.qualifiedName=="object"){let s=r.qualifiedName;if(s.name&&typeof s.name=="object"){let a=s.name;"name"in a&&typeof a.name=="string"?a.name=n:"value"in a&&typeof a.value=="string"&&(a.value=n)}}}catch(i){console.warn("Warning: Failed to update table source:",i)}}};var Vn=class o{constructor(){this.jsonColumnCounter=0;this.entityToJsonColumnMap=new Map;this.columnMappings=[]}static{this.CTE_OBJECT_PREFIX="cte_object_depth_"}static{this.WILDCARD_COLUMN="*"}buildObjectEntityCtes(e,t,n){this.jsonColumnCounter=0,this.entityToJsonColumnMap.clear(),this.columnMappings=[];let r=[e],i=e.aliasExpression.table.name,s=this.collectAndSortObjectEntities(n,t),a=this.groupEntitiesByDepth(s),l=Array.from(a.keys()).sort((u,c)=>c-u);for(let u of l){let c=a.get(u),m=`${o.CTE_OBJECT_PREFIX}${u}`,h=this.buildDepthCte(c,i,m,n,t);r.push(h),i=m}return{ctes:r,lastCteAlias:i,columnMappings:this.columnMappings}}generateUniqueJsonColumnName(e,t,n){this.jsonColumnCounter++;let r=`${e.toLowerCase()}_json_${this.jsonColumnCounter}`;return this.columnMappings.push({entityId:t,entityName:e,generatedColumnName:r,depth:n}),r}collectAndSortObjectEntities(e,t){let n=[],r=i=>{let s=t.get(i);if(!s)throw new Error(`Entity ${i} 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(i);a;){if(u.has(a))throw new Error(`Circular dependency detected: ${a} already visited in path for ${i}`);u.add(a);let c=t.get(a);if(!c)throw new Error(`Parent entity ${a} not found during depth calculation for ${i}`);let m=!1;if(c.isRoot)m=!0;else{let h=e.nestedEntities.find(w=>w.id===a);if(h)h.relationshipType==="object"&&(m=!0);else throw new Error(`Parent entity ${a} (ancestor of ${i}) has no definition in mapping.nestedEntities and is not root.`)}if(m&&l++,c.isRoot)break;a=c.parentId}return l};return e.nestedEntities.forEach(i=>{if(i.relationshipType==="object"){let s=t.get(i.id);s&&!s.isRoot&&n.push({entity:s,depth:r(i.id)})}}),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let r=n.depth;t.has(r)||t.set(r,[]),t.get(r).push(n)}),t}buildDepthCte(e,t,n,r,i){let s=[new q(new v(null,new x(o.WILDCARD_COLUMN)))];for(let{entity:l}of e){let u=this.buildEntityJsonColumn(l,r,i);s.push(u)}let a=new g({selectClause:new J(s),fromClause:new D(new $(new B(null,new x(t)),null),null)});return new X(a,new Z(n,null),null)}buildEntityJsonColumn(e,t,n){let{jsonObjectArgs:r,nullChecks:i}=this.prepareEntityColumns(e);this.addChildObjectRelationships(e,r,t,n);let s=this.createJsonObject(r),a=this.buildNullCondition(i),l=this.createCaseExpression(a,s),u=this.calculateApproximateDepth(e,t),c=this.generateUniqueJsonColumnName(e.name,e.id,u);return this.entityToJsonColumnMap.set(e.id,c),new q(l,c)}calculateApproximateDepth(e,t){if(e.isRoot)return 0;if(!e.parentId)return 1;let n=1,r=e.parentId;for(;r&&r!==t.rootEntity.id;){let i=t.nestedEntities.find(s=>s.id===r);if(!i)break;n++,r=i.parentId}return n}prepareEntityColumns(e){let t=[],n=[];return Object.entries(e.columns).forEach(([r,i])=>{t.push(new G(r)),t.push(new v(null,new x(i))),n.push(new C(new v(null,new x(i)),"is",new G(null)))}),{jsonObjectArgs:t,nullChecks:n}}addChildObjectRelationships(e,t,n,r){n.nestedEntities.filter(s=>s.parentId===e.id&&s.relationshipType==="object").forEach(s=>{let a=r.get(s.id);if(a){t.push(new G(s.propertyName));let l=this.entityToJsonColumnMap.get(a.id);if(!l)throw new Error(`JSON column name not found for child entity: ${a.id}`);t.push(new v(null,new x(l)))}})}createJsonObject(e){let t="jsonb_build_object";return new j(null,new V(t),new K(e),null)}buildNullCondition(e){return e.reduce((t,n)=>t?new C(t,"and",n):n)}createCaseExpression(e,t){return new ie(null,new be([new xe(e,new G(null))],t))}};var $n=class o{static{this.CTE_ARRAY_PREFIX="cte_array_depth_"}static{this.JSON_FUNCTIONS={BUILD_OBJECT:"jsonb_build_object",AGGREGATE:"jsonb_agg"}}buildArrayEntityCtes(e,t,n,r,i){let s=[...e],a=t,l=this.collectAndSortArrayEntities(r,n);if(l.length===0)return{updatedCtes:s,lastCteAlias:a};let u=this.groupEntitiesByDepth(l),c=Array.from(u.keys()).sort((m,h)=>h-m);for(let m of c){let h=u.get(m),{cte:w,newCteAlias:b}=this.buildDepthCte(h,a,s,m,r,i);s.push(w),a=b}return{updatedCtes:s,lastCteAlias:a}}collectAndSortArrayEntities(e,t){let n=[],r=i=>{let s=t.get(i);return!s||s.isRoot?0:s.parentId?1+r(s.parentId):1};return e.nestedEntities.forEach(i=>{if(i.relationshipType==="array"){let s=t.get(i.id),a=t.get(i.parentId);if(!s||!a)throw new Error(`Configuration error: Array entity '${i.id}' or its parent '${i.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 '${i.name}'.`);let u=l[0];n.push({entity:s,parentEntity:a,parentIdColumnSqlName:u,depth:r(i.id)})}}),n.sort((i,s)=>s.depth-i.depth),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let r=n.depth;t.has(r)||t.set(r,[]),t.get(r).push(n)}),t}buildDepthCte(e,t,n,r,i,s){let a=new Set;e.forEach(E=>{Object.values(E.entity.columns).forEach(N=>a.add(N));let O=N=>{i.nestedEntities.filter(A=>A.parentId===N).forEach(A=>{Object.values(A.columns).forEach(S=>{let I=typeof S=="string"?S:S.column;a.add(I)}),O(A.id)})};O(E.entity.id)});let l=n.find(E=>E.aliasExpression.table.name===t)?.query;if(!l)throw new Error(`CTE not found: ${t}`);let u=new Re(null,n).collect(l),c=[],m=[],h=new Set;e.forEach(E=>{Object.values(E.entity.columns).forEach(O=>h.add(O))});let w=this.collectArrayEntityColumnsByDepth(i,r),b=new Set;s&&e.forEach(E=>{i.nestedEntities.filter(O=>O.parentId===E.entity.id&&O.relationshipType==="object").forEach(O=>{let N=s.find(A=>A.entityId===O.id);N&&b.add(N.generatedColumnName)})}),this.processSelectVariablesForGroupBy(u,a,w,r,m,c,b);for(let E of e){let O=this.buildAggregationDetailsForArrayEntity(E.entity,i.nestedEntities,new Map,s);m.push(new q(O.jsonAgg,E.entity.propertyName))}let d=`${o.CTE_ARRAY_PREFIX}${r}`,y=new g({selectClause:new J(m),fromClause:new D(new $(new B(null,new x(t)),null),null),groupByClause:c.length>0?new ue(c):null});return{cte:new X(y,new Z(d,null),null),newCteAlias:d}}buildAggregationDetailsForArrayEntity(e,t,n,r){let i=o.JSON_FUNCTIONS.BUILD_OBJECT,s=[];Object.entries(e.columns).forEach(([h,w])=>{s.push(new G(h)),s.push(new v(null,new x(w)))}),t.filter(h=>h.parentId===e.id).forEach(h=>{let w=h.originalPropertyName||h.propertyName;if(s.push(new G(w)),h.relationshipType==="object"){if(!r)throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mappings not provided
|
|
19
19
|
|
|
20
20
|
\u{1F50D} Details:
|
|
21
21
|
- Entity ID: ${h.id}
|
|
@@ -31,7 +31,7 @@ ${e}`}getCTEName(e){return e.aliasExpression.table.name}};var Rn=class o{constru
|
|
|
31
31
|
\u{1F527} Check:
|
|
32
32
|
1. Ensure PostgresJsonQueryBuilder.buildJsonWithCteStrategy() passes columnMappings
|
|
33
33
|
2. Verify PostgresObjectEntityCteBuilder.buildObjectEntityCtes() returns columnMappings
|
|
34
|
-
3. Check that Model-driven mapping conversion generates unique entity IDs`);let b=r.find(d=>d.entityId===h.id);if(!b){let d=r.map(
|
|
34
|
+
3. Check that Model-driven mapping conversion generates unique entity IDs`);let b=r.find(d=>d.entityId===h.id);if(!b){let d=r.map(y=>`${y.entityId} \u2192 ${y.generatedColumnName}`).join(", ");throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mapping not found
|
|
35
35
|
|
|
36
36
|
\u{1F50D} Details:
|
|
37
37
|
- Looking for Entity ID: ${h.id}
|
|
@@ -49,14 +49,14 @@ ${e}`}getCTEName(e){return e.aliasExpression.table.name}};var Rn=class o{constru
|
|
|
49
49
|
\u{1F527} Check:
|
|
50
50
|
1. Model-driven mapping conversion generates consistent entity IDs
|
|
51
51
|
2. PostgresObjectEntityCteBuilder processes all entities correctly
|
|
52
|
-
3. Entity hierarchy and parentId relationships are correct`)}s.push(new v(null,new x(b.generatedColumnName)))}else h.relationshipType==="array"&&s.push(new v(null,new x(h.propertyName)))});let l=new U(null,new V(i),new _(s),null),u=o.JSON_FUNCTIONS.AGGREGATE,c=Object.values(e.columns)[0];return{jsonAgg:new U(null,new V(u),new _([l]),null)}}collectArrayEntityColumnsByDepth(e,t){let n=new Map,r=Math.max(t+3,5);for(let i=t;i<=r;i++)n.set(i,new Set);return e.nestedEntities.filter(i=>i.relationshipType==="array").forEach(i=>{let s=this.calculateEntityDepth(i,e);n.has(s)||n.set(s,new Set),this.addEntityColumnsToDepthSet(i,s,n),this.collectDescendantColumns(i.id,s,e,n)}),n}calculateEntityDepth(e,t){let n=0,r=e;for(;r.parentId&&r.parentId!==t.rootEntity.id;)n++,r=t.nestedEntities.find(i=>i.id===r.parentId)||r;return n}addEntityColumnsToDepthSet(e,t,n){Object.values(e.columns).forEach(r=>{let i=typeof r=="string"?r:r.column;n.get(t).add(i)})}collectDescendantColumns(e,t,n,r){n.nestedEntities.filter(i=>i.parentId===e).forEach(i=>{this.addEntityColumnsToDepthSet(i,t,r),this.collectDescendantColumns(i.id,t,n,r)})}processSelectVariablesForGroupBy(e,t,n,r,i,s,a){e.forEach(l=>{if(!t.has(l.name)){if(a&&a.has(l.name))return;this.shouldIncludeColumnInGroupBy(l.name,n,r)&&(i.push(new j(new v(null,new x(l.name)),l.name)),l.name.endsWith("_json")||s.push(new v(null,new x(l.name))))}})}shouldIncludeColumnInGroupBy(e,t,n){let r=e.endsWith("_json"),i=!0;for(let[s,a]of t.entries())if(s>=n&&a.has(e)){i=!1;break}return r&&e.startsWith("entity_")&&(i=this.shouldIncludeJsonColumn(e,n)),i}shouldIncludeJsonColumn(e,t){let n=e.match(/entity_(\d+)_json/);return n&&t>0?parseInt(n[1])<=2:!0}};var Vn=class{constructor(){this.selectValueCollector=new Ae(null),this.objectEntityCteBuilder=new Rn,this.arrayEntityCteBuilder=new Bn}validateMapping(e,t){let r=new Ae().collect(e),i=new Set(r.map(u=>u.name));for(let u in t.rootEntity.columns){let c=t.rootEntity.columns[u],m=typeof c=="string"?c:c.column;if(!i.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 c in u.columns){let m=u.columns[c],h=typeof m=="string"?m:m.column;if(!i.has(h))throw new Error(`Validation Error: Column "${h}" for JSON key "${c}" in nested entity "${u.name}" (ID: ${u.id}) not found in the query's select list.`)}}let l=new Set([t.rootEntity.id,...t.nestedEntities.map(u=>u.parentId)]);for(let u of l){let c=t.nestedEntities.filter(w=>w.parentId===u);if(c.filter(w=>w.relationshipType==="array").length>1){let w=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(b=>b.id===u)?.name;throw new Error(`Validation Error: Parent entity "${w}" (ID: ${u}) has multiple direct array children. This is not supported.`)}let h=new Set;for(let w of c){if(h.has(w.propertyName)){let b=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(d=>d.id===u)?.name;throw new Error(`Validation Error: Parent entity "${b}" (ID: ${u}) has duplicate property name "${w.propertyName}" for its children.`)}h.add(w.propertyName)}}}buildJsonQuery(e,t,n){if(n?.jsonb===!1)throw new Error("JSONB must be enabled for PostgreSQL GROUP BY compatibility. JSON type cannot be used in GROUP BY clauses. Please set jsonb: true or omit the jsonb option (defaults to true).");let r=e instanceof E?e:Ne.buildSimpleQuery(e);return this.buildJsonWithCteStrategy(r,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:r}=this.createInitialCte(e),i=[n],s=r,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);i=l.ctes,s=l.lastCteAlias;let u=l.columnMappings,c=this.arrayEntityCteBuilder.buildArrayEntityCtes(i,s,a,t,u);return i=c.updatedCtes,s=c.lastCteAlias,this.buildFinalSelectQuery(i,s,a,t,u)}createInitialCte(e){let t="origin_query";return{initialCte:new ee(e,new Y(t,null),null),initialCteAlias:t}}buildFinalSelectQuery(e,t,n,r,i){let s=[...e],a=`cte_root_${r.rootName.toLowerCase().replace(/[^a-z0-9_]/g,"_")}`,l=n.get(r.rootEntity.id);if(!l)throw new Error(`Root entity ${r.rootEntity.id} not found`);if(r.resultFormat==="array"||!r.resultFormat){let u=this.buildEntityJsonObject(l,null,r.nestedEntities,n,i),c=new j(u,r.rootName),m=new ee(new E({selectClause:new J([c]),fromClause:new D(new M(new R(null,new x(t)),null),null)}),new Y(a,null),null);s.push(m);let h="jsonb_agg",w=new U(null,new V(h),new _([new v(null,new x(r.rootName))]),null);return new E({withClause:new ne(!1,s),selectClause:new J([new j(w,`${r.rootName}_array`)]),fromClause:new D(new M(new R(null,new x(a)),null),null)})}else{let u=this.buildEntityJsonObject(l,null,r.nestedEntities,n,i),c=new j(u,r.rootName),m=new ee(new E({selectClause:new J([c]),fromClause:new D(new M(new R(null,new x(t)),null),null)}),new Y(a,null),null);return s.push(m),new E({withClause:new ne(!1,s),selectClause:new J([new j(new v(null,new x(r.rootName)),r.rootName)]),fromClause:new D(new M(new R(null,new x(a)),null),null),limitClause:new se(new G(1))})}}buildEntityJsonObject(e,t,n,r,i){let s="jsonb_build_object",a=[];return Object.entries(e.columns).forEach(([u,c])=>{let m=typeof c=="string"?c:c.column;a.push(new G(u)),a.push(new v(null,new x(m)))}),n.filter(u=>u.parentId===e.id).forEach(u=>{let c=r.get(u.id);if(c)if(a.push(new G(u.propertyName)),u.relationshipType==="object"){let m=i.find(h=>h.entityId===c.id);if(!m)throw new Error(`Column mapping not found for entity: ${c.id}`);a.push(new v(null,new x(m.generatedColumnName)))}else u.relationshipType==="array"&&a.push(new v(null,new x(u.propertyName)))}),new U(null,new V(s),new _(a),null)}};function Xn(o){let e=[],t=0,n={},r=()=>`entity_${++t}`,i=u=>(n[u]||(n[u]=0),n[u]++,n[u]===1?u:`${u}_${n[u]}`),s=(u,c=null)=>{let m={},h=[];for(let[w,b]of Object.entries(u))if(typeof b=="string")m[w]=b;else if("column"in b&&typeof b.column=="string"&&!("type"in b&&(b.type==="object"||b.type==="array"))){let d=b;typeof d=="object"&&"column"in d&&(m[w]=d.column,d.type==="string"&&e.push(d.column))}else if("from"in b&&typeof b.from=="string"&&!("type"in b&&(b.type==="object"||b.type==="array"))){let d=b;typeof d=="object"&&"from"in d&&(m[w]=d.from,d.type==="string"&&e.push(d.from))}else if("type"in b&&(b.type==="object"||b.type==="array")){let d=b,C=i(w),F=r(),S=s(d.structure,F);h.push({id:F,name:w.charAt(0).toUpperCase()+w.slice(1),parentId:c||"root",propertyName:C,originalPropertyName:w,relationshipType:d.type,columns:S.columns}),h.push(...S.nestedEntities.map(O=>({...O,parentId:O.parentId==="root"?F:O.parentId})))}return{columns:m,nestedEntities:h}},a=s(o.structure),l={rootName:"root",rootEntity:{id:"root",name:"Root",columns:a.columns},nestedEntities:a.nestedEntities};return l.typeInfo=o.typeInfo,{jsonMapping:l,typeProtection:{protectedStringFields:e}}}function $r(o){let e=[];return o.typeInfo?(o.typeInfo.interface||e.push("typeInfo.interface is required"),o.typeInfo.importPath||e.push("typeInfo.importPath is required")):e.push("typeInfo is required"),(!o.structure||typeof o.structure!="object")&&e.push("structure is required and must be an object"),e}function $n(o){let e={};for(let[t,n]of Object.entries(o))typeof n=="string"?e[t]=n:n&&typeof n=="object"?"column"in n?e[t]=n.column:"from"in n?e[t]=n.from:e[t]=t:e[t]=t;return e}function gf(o){if(!o)throw new Error("Input mapping is required");if(o.rootName&&o.rootEntity&&typeof o.rootEntity.columns=="object"&&!o.typeInfo&&!o.typeProtection&&!o.metadata&&Object.values(o.rootEntity.columns).every(t=>typeof t=="string"))return o;if(o.rootName&&o.rootEntity)return{rootName:o.rootName,rootEntity:{id:o.rootEntity.id||"root",name:o.rootEntity.name||o.rootName,columns:$n(o.rootEntity.columns||{})},nestedEntities:(o.nestedEntities||[]).map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:$n(e.columns||{})})),resultFormat:o.resultFormat,emptyResult:o.emptyResult};throw new Error("Unsupported mapping format")}function dr(o){return{rootName:o.rootName,rootEntity:{id:o.rootEntity.id,name:o.rootEntity.name,columns:$n(o.rootEntity.columns)},nestedEntities:o.nestedEntities.map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:$n(e.columns)})),resultFormat:o.resultFormat,emptyResult:o.emptyResult}}function hr(o){let e=[],t=[],n=[];if(o.typeProtection)return{protectedStringFields:o.typeProtection.protectedStringFields||[],dateFields:o.typeProtection.dateFields,numberFields:o.typeProtection.numberFields,customTransforms:o.typeProtection.customTransforms};for(let[r,i]of Object.entries(o.rootEntity.columns))if(typeof i=="object"&&i.type){let s=i.column;switch(i.type){case"string":e.push(s);break;case"date":t.push(s);break;case"number":n.push(s);break}}for(let r of o.nestedEntities)for(let[i,s]of Object.entries(r.columns))if(typeof s=="object"&&s.type){let a=s.column;switch(s.type){case"string":e.push(a);break;case"date":t.push(a);break;case"number":n.push(a);break}}return{protectedStringFields:e,dateFields:t.length>0?t:void 0,numberFields:n.length>0?n:void 0,customTransforms:void 0}}function nr(o){return o!=null&&typeof o=="object"}var Zn=class{detect(e){if(!nr(e))return!1;let t=e;if(!t||typeof t.rootName!="string"||!t.rootEntity||!Array.isArray(t.nestedEntities))return!1;if(t.typeInfo||t.typeProtection||t.metadata)return!0;let n=r=>!r||typeof r!="object"?!1:Object.values(r).some(i=>typeof i=="object"&&i!==null&&"column"in i);return n(t.rootEntity.columns)?!0:t.nestedEntities.some(r=>r&&typeof r=="object"&&n(r.columns))}convert(e){return{format:"enhanced",mapping:dr(e),typeProtection:hr(e),originalInput:e,metadata:{typeInfo:e.typeInfo,version:e.metadata?.version,description:e.metadata?.description}}}},er=class{detect(e){if(!nr(e))return!1;let t=e;return t&&t.typeInfo&&t.structure&&typeof t.typeInfo.interface=="string"}convert(e){let t=Xn(e);return{format:"model-driven",mapping:t.jsonMapping,typeProtection:t.typeProtection,originalInput:e,metadata:{typeInfo:e.typeInfo}}}},tr=class{detect(e){if(!nr(e))return!1;let t=e;if(!t||typeof t.rootName!="string"||!t.rootEntity||typeof t.rootEntity.columns!="object"||t.typeInfo||t.typeProtection||t.metadata)return!1;let n=r=>!r||typeof r!="object"?!1:Object.values(r).some(i=>typeof i=="object"&&i!==null&&"column"in i);return!(n(t.rootEntity.columns)||t.nestedEntities&&Array.isArray(t.nestedEntities)&&t.nestedEntities.some(i=>i&&typeof i=="object"&&n(i.columns)))}convert(e){return{format:"legacy",mapping:e,typeProtection:{protectedStringFields:[]},originalInput:e}}},Rt=class{constructor(){this.strategies=[new Zn,new er,new tr]}detectFormat(e){for(let t of this.strategies)if(t.detect(e))return t.convert(e).format;throw new Error("Unsupported JSON mapping format")}convert(e){for(let t of this.strategies)if(t.detect(e))return t.convert(e);throw new Error("Unsupported JSON mapping format: Unable to detect a compatible strategy for the provided input")}toLegacyMapping(e){return this.convert(e).mapping}getTypeProtection(e){return this.convert(e).typeProtection}validate(e){let t=[];if(!e||typeof e!="object")return t.push("Input must be an object"),t;(!("rootName"in e)||!e.rootName)&&t.push("rootName is required");try{let n=this.convert(e);if(n.mapping.rootName||t.push("rootName is required"),n.mapping.rootEntity?(n.mapping.rootEntity.id||t.push("rootEntity.id is required"),n.mapping.rootEntity.columns||t.push("rootEntity.columns is required")):t.push("rootEntity is required"),n.mapping.nestedEntities)for(let r of n.mapping.nestedEntities)r.id||t.push(`Nested entity missing id: ${r.propertyName}`),r.parentId||t.push(`Nested entity missing parentId: ${r.id}`),r.propertyName||t.push(`Nested entity missing propertyName: ${r.id}`)}catch(n){t.length===0&&t.push(`Conversion failed: ${n instanceof Error?n.message:String(n)}`)}return t}upgradeToEnhanced(e,t){return{rootName:e.rootName,rootEntity:{id:e.rootEntity.id,name:e.rootEntity.name,columns:e.rootEntity.columns},nestedEntities:e.nestedEntities.map(n=>({id:n.id,name:n.name,parentId:n.parentId,propertyName:n.propertyName,relationshipType:n.relationshipType||"object",columns:n.columns})),resultFormat:e.resultFormat,emptyResult:e.emptyResult,typeInfo:t,metadata:{version:"1.0",description:"Upgraded from legacy format"}}}};function rr(o){return o.typeInfo&&o.structure?"model-driven":o.rootName&&o.rootEntity?"unified":(o.columns||o.relationships,"legacy")}function Mr(o){let e={rootName:o.rootName||"root",rootEntity:{id:"root",name:o.rootName||"Root",columns:o.columns||{}},nestedEntities:[]};if(o.relationships&&typeof o.relationships=="object")for(let[t,n]of Object.entries(o.relationships)){let r=n;e.nestedEntities.push({id:t,name:t.charAt(0).toUpperCase()+t.slice(1),parentId:"root",propertyName:t,relationshipType:r.type==="hasMany"?"array":"object",columns:r.columns||{}})}return e}function Dr(o){if(console.warn("\u26A0\uFE0F DEPRECATED: processJsonMapping() is deprecated. Use JsonMappingConverter.convert() instead."),console.warn("Migration guide: https://github.com/mk3008/rawsql-ts/blob/main/docs/migration-guide.md"),(o.columns||o.relationships)&&!o.rootName&&!o.rootEntity)return{format:"legacy",jsonMapping:Mr(o),originalInput:o,metadata:{}};let t=new Rt().convert(o),n=t.format;return t.format==="legacy"&&o.rootName&&o.rootEntity&&(n="unified"),{format:n,jsonMapping:t.mapping,originalInput:o,metadata:{typeInfo:t.metadata?.typeInfo,typeProtection:t.typeProtection}}}function Wr(o){return console.warn("\u26A0\uFE0F DEPRECATED: unifyJsonMapping() is deprecated. Use JsonMappingConverter.toLegacyMapping() instead."),console.warn("Migration guide: https://github.com/mk3008/rawsql-ts/blob/main/docs/migration-guide.md"),new Rt().toLegacyMapping(o)}function jr(o){return rr(o)==="model-driven"}function Ur(o){return rr(o)==="unified"}function Jr(o){return rr(o)==="legacy"}var Mn=class{constructor(e={}){this.config={enableValueBasedDetection:!0,strictDateDetection:!1,...e}}transformResult(e){return e==null?e:Array.isArray(e)?e.map(t=>this.transformSingleObject(t)):this.transformSingleObject(e)}transformSingleObject(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.transformSingleObject(n));let t={};for(let[n,r]of Object.entries(e)){if(r==null){t[n]=r;continue}let i=this.config.columnTransformations?.[n];if(i){t[n]=this.applyTransformation(r,i);continue}if(this.config.enableValueBasedDetection){let a=this.detectValueBasedTransformation(r);if(a){t[n]=this.applyTransformation(r,a);continue}}let s=this.config.globalTransformations&&this.getGlobalTransformationForValue(r);if(s){t[n]=this.applyTransformation(r,s);continue}if(typeof r=="object"&&!Array.isArray(r)){t[n]=this.transformSingleObject(r);continue}if(Array.isArray(r)){t[n]=r.map(a=>typeof a=="object"?this.transformSingleObject(a):a);continue}t[n]=r}return t}detectValueBasedTransformation(e){return typeof e=="string"&&this.isDateString(e)?{sourceType:"TIMESTAMP",targetType:"Date",handleNull:!0,validator:t=>typeof t=="string"&&!isNaN(Date.parse(t))}:typeof e=="number"&&!Number.isSafeInteger(e)?{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return typeof t=="string"||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?(BigInt(t),!0):!1}catch{return!1}}}:typeof e=="string"&&/^\d{16,}$/.test(e)?{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return typeof t=="string"||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?(BigInt(t),!0):!1}catch{return!1}}}:null}getGlobalTransformationForValue(e){return this.config.globalTransformations,null}detectAndGetGlobalTransformation(e){return this.detectValueBasedTransformation(e)}isDateString(e){if(this.config.strictDateDetection){if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})?$/.test(e))return!1}else if(!/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})?)?$/.test(e))return!1;let t=new Date(e);return!isNaN(t.getTime())}applyTransformation(e,t){if(e==null)return t.handleNull!==!1?e:null;if(t.validator&&!t.validator(e))return console.warn(`TypeTransformationPostProcessor: Value validation failed for ${e}`),e;try{switch(t.targetType){case"Date":return new Date(e);case"bigint":if(typeof e=="number"){let n=Math.trunc(e);return BigInt(n.toString())}return BigInt(e);case"string":return e.toString();case"number":return typeof e=="string"?parseFloat(e):Number(e);case"object":return typeof e=="string"?JSON.parse(e):e;case"custom":if(t.customTransformer&&this.config.customTransformers?.[t.customTransformer])return this.config.customTransformers[t.customTransformer](e);break;default:return e}}catch(n){return console.warn(`TypeTransformationPostProcessor: Transformation failed for ${e}:`,n),e}return e}static createDefaultConfig(){return{enableValueBasedDetection:!0,strictDateDetection:!1,globalTransformations:{DATE:{sourceType:"DATE",targetType:"Date",handleNull:!0,validator:e=>typeof e=="string"&&!isNaN(Date.parse(e))},TIMESTAMP:{sourceType:"TIMESTAMP",targetType:"Date",handleNull:!0,validator:e=>typeof e=="string"&&!isNaN(Date.parse(e))},BIGINT:{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:e=>{try{return typeof e=="string"||typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?(BigInt(e),!0):!1}catch{return!1}}}}}}static createSafeConfig(e){return{enableValueBasedDetection:!1,strictDateDetection:!0,columnTransformations:e||{},globalTransformations:{DATE:{sourceType:"DATE",targetType:"Date",handleNull:!0,validator:t=>typeof t=="string"&&!isNaN(Date.parse(t))},TIMESTAMP:{sourceType:"TIMESTAMP",targetType:"Date",handleNull:!0,validator:t=>typeof t=="string"&&!isNaN(Date.parse(t))},BIGINT:{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return typeof t=="string"||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?(BigInt(t),!0):!1}catch{return!1}}}}}}};function Lf(o,e){return new Mn(e||Mn.createDefaultConfig()).transformResult(o)}var Af={toDate:o=>{if(o==null)return null;let e=new Date(o);return isNaN(e.getTime())?null:e},toBigInt:o=>{if(o==null)return null;try{return BigInt(o)}catch{return null}},toObject:o=>{if(o==null)return null;try{return JSON.parse(o)}catch{return null}}};var Tt=class{constructor(e,t,n,r,i){this.id=e;this.label=t;this.type=n;this.shape=r;this.details=i}},kt=class o extends Tt{constructor(t,n,r){super(t,n,r,r==="subquery"?"hexagon":"cylinder");this.annotations=new Set}addAnnotation(t){this.annotations.add(t)}hasAnnotation(t){return this.annotations.has(t)}getMermaidRepresentation(){return this.shape==="hexagon"?`${this.id}{{${this.label}}}`:`${this.id}[(${this.label})]`}static createTable(t){return new o(`table_${t}`,t,"table")}static createCTE(t){return new o(`cte_${t}`,`CTE:${t}`,"cte")}static createSubquery(t){return new o(`subquery_${t}`,`SubQuery:${t}`,"subquery")}},Dn=class o extends Tt{constructor(e,t,n=""){let r=n?`${n}_${t.toLowerCase().replace(/\s+/g,"_")}`:t.toLowerCase().replace(/\s+/g,"_");super(r,t,"process","hexagon")}getMermaidRepresentation(){return`${this.id}{{${this.label}}}`}static createWhere(e){return new o(`${e}_where`,"WHERE",e)}static createGroupBy(e){return new o(`${e}_group_by`,"GROUP BY",e)}static createHaving(e){return new o(`${e}_having`,"HAVING",e)}static createSelect(e){return new o(`${e}_select`,"SELECT",e)}static createOrderBy(e){return new o(`${e}_order_by`,"ORDER BY",e)}static createLimit(e,t=!1){let n=t?"LIMIT/OFFSET":"LIMIT";return new o(`${e}_limit`,n,e)}},Bt=class o extends Tt{constructor(e,t,n="diamond"){super(e,t,"operation",n)}getMermaidRepresentation(){switch(this.shape){case"rounded":return`${this.id}(${this.label})`;case"rectangle":return`${this.id}[${this.label}]`;case"hexagon":return`${this.id}{{${this.label}}}`;case"stadium":return`${this.id}([${this.label}])`;case"diamond":default:return`${this.id}{${this.label}}`}}static createJoin(e,t){let n,r=t.trim().toLowerCase();return r==="join"?n="INNER JOIN":r.endsWith(" join")?n=r.toUpperCase():n=r.toUpperCase()+" JOIN",new o(`join_${e}`,n,"rectangle")}static createUnion(e,t="UNION ALL"){return new o(`${t.toLowerCase().replace(/\s+/g,"_")}_${e}`,t.toUpperCase(),"rectangle")}static createSetOperation(e,t){let n=t.toUpperCase(),r=`${n.toLowerCase().replace(/\s+/g,"_")}_${e}`;return new o(r,n,"rectangle")}},Wn=class extends Tt{constructor(e="main"){let t=e==="main"?"Final Result":`${e} Result`;super(`${e}_output`,t,"output","stadium")}getMermaidRepresentation(){return`${this.id}([${this.label}])`}};var jn=class o{constructor(e,t,n){this.from=e;this.to=t;this.label=n}getMermaidRepresentation(){let e=this.label?` -->|${this.label}| `:" --> ";return`${this.from}${e}${this.to}`}static create(e,t,n){return new o(e,t,n)}static createWithNullability(e,t,n){let r=n?"NULLABLE":"NOT NULL";return new o(e,t,r)}},Un=class{constructor(){this.edges=[];this.connectionSet=new Set}add(e){let t=`${e.from}->${e.to}`;this.connectionSet.has(t)||(this.edges.push(e),this.connectionSet.add(t))}addConnection(e,t,n){this.add(jn.create(e,t,n))}addJoinConnection(e,t,n){this.add(jn.createWithNullability(e,t,n))}hasConnection(e,t){return this.connectionSet.has(`${e}->${t}`)}getAll(){return[...this.edges]}getMermaidRepresentation(){return this.edges.map(e=>e.getMermaidRepresentation()).join(`
|
|
53
|
-
`)}};var
|
|
52
|
+
3. Entity hierarchy and parentId relationships are correct`)}s.push(new v(null,new x(b.generatedColumnName)))}else h.relationshipType==="array"&&s.push(new v(null,new x(h.propertyName)))});let l=new j(null,new V(i),new K(s),null),u=o.JSON_FUNCTIONS.AGGREGATE,c=Object.values(e.columns)[0];return{jsonAgg:new j(null,new V(u),new K([l]),null)}}collectArrayEntityColumnsByDepth(e,t){let n=new Map,r=Math.max(t+3,5);for(let i=t;i<=r;i++)n.set(i,new Set);return e.nestedEntities.filter(i=>i.relationshipType==="array").forEach(i=>{let s=this.calculateEntityDepth(i,e);n.has(s)||n.set(s,new Set),this.addEntityColumnsToDepthSet(i,s,n),this.collectDescendantColumns(i.id,s,e,n)}),n}calculateEntityDepth(e,t){let n=0,r=e;for(;r.parentId&&r.parentId!==t.rootEntity.id;)n++,r=t.nestedEntities.find(i=>i.id===r.parentId)||r;return n}addEntityColumnsToDepthSet(e,t,n){Object.values(e.columns).forEach(r=>{let i=typeof r=="string"?r:r.column;n.get(t).add(i)})}collectDescendantColumns(e,t,n,r){n.nestedEntities.filter(i=>i.parentId===e).forEach(i=>{this.addEntityColumnsToDepthSet(i,t,r),this.collectDescendantColumns(i.id,t,n,r)})}processSelectVariablesForGroupBy(e,t,n,r,i,s,a){e.forEach(l=>{if(!t.has(l.name)){if(a&&a.has(l.name))return;this.shouldIncludeColumnInGroupBy(l.name,n,r)&&(i.push(new q(new v(null,new x(l.name)),l.name)),l.name.endsWith("_json")||s.push(new v(null,new x(l.name))))}})}shouldIncludeColumnInGroupBy(e,t,n){let r=e.endsWith("_json"),i=!0;for(let[s,a]of t.entries())if(s>=n&&a.has(e)){i=!1;break}return r&&e.startsWith("entity_")&&(i=this.shouldIncludeJsonColumn(e,n)),i}shouldIncludeJsonColumn(e,t){let n=e.match(/entity_(\d+)_json/);return n&&t>0?parseInt(n[1])<=2:!0}};var Mn=class{constructor(){this.selectValueCollector=new Re(null),this.objectEntityCteBuilder=new Vn,this.arrayEntityCteBuilder=new $n}validateMapping(e,t){let r=new Re().collect(e),i=new Set(r.map(u=>u.name));for(let u in t.rootEntity.columns){let c=t.rootEntity.columns[u],m=typeof c=="string"?c:c.column;if(!i.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 c in u.columns){let m=u.columns[c],h=typeof m=="string"?m:m.column;if(!i.has(h))throw new Error(`Validation Error: Column "${h}" for JSON key "${c}" in nested entity "${u.name}" (ID: ${u.id}) not found in the query's select list.`)}}let l=new Set([t.rootEntity.id,...t.nestedEntities.map(u=>u.parentId)]);for(let u of l){let c=t.nestedEntities.filter(w=>w.parentId===u);if(c.filter(w=>w.relationshipType==="array").length>1){let w=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(b=>b.id===u)?.name;throw new Error(`Validation Error: Parent entity "${w}" (ID: ${u}) has multiple direct array children. This is not supported.`)}let h=new Set;for(let w of c){if(h.has(w.propertyName)){let b=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(d=>d.id===u)?.name;throw new Error(`Validation Error: Parent entity "${b}" (ID: ${u}) has duplicate property name "${w.propertyName}" for its children.`)}h.add(w.propertyName)}}}buildJsonQuery(e,t,n){if(n?.jsonb===!1)throw new Error("JSONB must be enabled for PostgreSQL GROUP BY compatibility. JSON type cannot be used in GROUP BY clauses. Please set jsonb: true or omit the jsonb option (defaults to true).");let r=e instanceof g?e:Fe.buildSimpleQuery(e);return this.buildJsonWithCteStrategy(r,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:r}=this.createInitialCte(e),i=[n],s=r,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);i=l.ctes,s=l.lastCteAlias;let u=l.columnMappings,c=this.arrayEntityCteBuilder.buildArrayEntityCtes(i,s,a,t,u);return i=c.updatedCtes,s=c.lastCteAlias,this.buildFinalSelectQuery(i,s,a,t,u)}createInitialCte(e){let t="origin_query";return{initialCte:new X(e,new Z(t,null),null),initialCteAlias:t}}buildFinalSelectQuery(e,t,n,r,i){let s=[...e],a=`cte_root_${r.rootName.toLowerCase().replace(/[^a-z0-9_]/g,"_")}`,l=n.get(r.rootEntity.id);if(!l)throw new Error(`Root entity ${r.rootEntity.id} not found`);if(r.resultFormat==="array"||!r.resultFormat){let u=this.buildEntityJsonObject(l,null,r.nestedEntities,n,i),c=new q(u,r.rootName),m=new X(new g({selectClause:new J([c]),fromClause:new D(new $(new B(null,new x(t)),null),null)}),new Z(a,null),null);s.push(m);let h="jsonb_agg",w=new j(null,new V(h),new K([new v(null,new x(r.rootName))]),null);return new g({withClause:new ne(!1,s),selectClause:new J([new q(w,`${r.rootName}_array`)]),fromClause:new D(new $(new B(null,new x(a)),null),null)})}else{let u=this.buildEntityJsonObject(l,null,r.nestedEntities,n,i),c=new q(u,r.rootName),m=new X(new g({selectClause:new J([c]),fromClause:new D(new $(new B(null,new x(t)),null),null)}),new Z(a,null),null);return s.push(m),new g({withClause:new ne(!1,s),selectClause:new J([new q(new v(null,new x(r.rootName)),r.rootName)]),fromClause:new D(new $(new B(null,new x(a)),null),null),limitClause:new oe(new G(1))})}}buildEntityJsonObject(e,t,n,r,i){let s="jsonb_build_object",a=[];return Object.entries(e.columns).forEach(([u,c])=>{let m=typeof c=="string"?c:c.column;a.push(new G(u)),a.push(new v(null,new x(m)))}),n.filter(u=>u.parentId===e.id).forEach(u=>{let c=r.get(u.id);if(c)if(a.push(new G(u.propertyName)),u.relationshipType==="object"){let m=i.find(h=>h.entityId===c.id);if(!m)throw new Error(`Column mapping not found for entity: ${c.id}`);a.push(new v(null,new x(m.generatedColumnName)))}else u.relationshipType==="array"&&a.push(new v(null,new x(u.propertyName)))}),new j(null,new V(s),new K(a),null)}};function er(o){let e=[],t=0,n={},r=()=>`entity_${++t}`,i=u=>(n[u]||(n[u]=0),n[u]++,n[u]===1?u:`${u}_${n[u]}`),s=(u,c=null)=>{let m={},h=[];for(let[w,b]of Object.entries(u))if(typeof b=="string")m[w]=b;else if("column"in b&&typeof b.column=="string"&&!("type"in b&&(b.type==="object"||b.type==="array"))){let d=b;typeof d=="object"&&"column"in d&&(m[w]=d.column,d.type==="string"&&e.push(d.column))}else if("from"in b&&typeof b.from=="string"&&!("type"in b&&(b.type==="object"||b.type==="array"))){let d=b;typeof d=="object"&&"from"in d&&(m[w]=d.from,d.type==="string"&&e.push(d.from))}else if("type"in b&&(b.type==="object"||b.type==="array")){let d=b,y=i(w),L=r(),E=s(d.structure,L);h.push({id:L,name:w.charAt(0).toUpperCase()+w.slice(1),parentId:c||"root",propertyName:y,originalPropertyName:w,relationshipType:d.type,columns:E.columns}),h.push(...E.nestedEntities.map(O=>({...O,parentId:O.parentId==="root"?L:O.parentId})))}return{columns:m,nestedEntities:h}},a=s(o.structure),l={rootName:"root",rootEntity:{id:"root",name:"Root",columns:a.columns},nestedEntities:a.nestedEntities};return l.typeInfo=o.typeInfo,{jsonMapping:l,typeProtection:{protectedStringFields:e}}}function Dr(o){let e=[];return o.typeInfo?(o.typeInfo.interface||e.push("typeInfo.interface is required"),o.typeInfo.importPath||e.push("typeInfo.importPath is required")):e.push("typeInfo is required"),(!o.structure||typeof o.structure!="object")&&e.push("structure is required and must be an object"),e}function Wn(o){let e={};for(let[t,n]of Object.entries(o))typeof n=="string"?e[t]=n:n&&typeof n=="object"?"column"in n?e[t]=n.column:"from"in n?e[t]=n.from:e[t]=t:e[t]=t;return e}function $f(o){if(!o)throw new Error("Input mapping is required");if(o.rootName&&o.rootEntity&&typeof o.rootEntity.columns=="object"&&!o.typeInfo&&!o.typeProtection&&!o.metadata&&Object.values(o.rootEntity.columns).every(t=>typeof t=="string"))return o;if(o.rootName&&o.rootEntity)return{rootName:o.rootName,rootEntity:{id:o.rootEntity.id||"root",name:o.rootEntity.name||o.rootName,columns:Wn(o.rootEntity.columns||{})},nestedEntities:(o.nestedEntities||[]).map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:Wn(e.columns||{})})),resultFormat:o.resultFormat,emptyResult:o.emptyResult};throw new Error("Unsupported mapping format")}function Cr(o){return{rootName:o.rootName,rootEntity:{id:o.rootEntity.id,name:o.rootEntity.name,columns:Wn(o.rootEntity.columns)},nestedEntities:o.nestedEntities.map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:Wn(e.columns)})),resultFormat:o.resultFormat,emptyResult:o.emptyResult}}function yr(o){let e=[],t=[],n=[];if(o.typeProtection)return{protectedStringFields:o.typeProtection.protectedStringFields||[],dateFields:o.typeProtection.dateFields,numberFields:o.typeProtection.numberFields,customTransforms:o.typeProtection.customTransforms};for(let[r,i]of Object.entries(o.rootEntity.columns))if(typeof i=="object"&&i.type){let s=i.column;switch(i.type){case"string":e.push(s);break;case"date":t.push(s);break;case"number":n.push(s);break}}for(let r of o.nestedEntities)for(let[i,s]of Object.entries(r.columns))if(typeof s=="object"&&s.type){let a=s.column;switch(s.type){case"string":e.push(a);break;case"date":t.push(a);break;case"number":n.push(a);break}}return{protectedStringFields:e,dateFields:t.length>0?t:void 0,numberFields:n.length>0?n:void 0,customTransforms:void 0}}function ir(o){return o!=null&&typeof o=="object"}var tr=class{detect(e){if(!ir(e))return!1;let t=e;if(!t||typeof t.rootName!="string"||!t.rootEntity||!Array.isArray(t.nestedEntities))return!1;if(t.typeInfo||t.typeProtection||t.metadata)return!0;let n=r=>!r||typeof r!="object"?!1:Object.values(r).some(i=>typeof i=="object"&&i!==null&&"column"in i);return n(t.rootEntity.columns)?!0:t.nestedEntities.some(r=>r&&typeof r=="object"&&n(r.columns))}convert(e){return{format:"enhanced",mapping:Cr(e),typeProtection:yr(e),originalInput:e,metadata:{typeInfo:e.typeInfo,version:e.metadata?.version,description:e.metadata?.description}}}},nr=class{detect(e){if(!ir(e))return!1;let t=e;return t&&t.typeInfo&&t.structure&&typeof t.typeInfo.interface=="string"}convert(e){let t=er(e);return{format:"model-driven",mapping:t.jsonMapping,typeProtection:t.typeProtection,originalInput:e,metadata:{typeInfo:e.typeInfo}}}},rr=class{detect(e){if(!ir(e))return!1;let t=e;if(!t||typeof t.rootName!="string"||!t.rootEntity||typeof t.rootEntity.columns!="object"||t.typeInfo||t.typeProtection||t.metadata)return!1;let n=r=>!r||typeof r!="object"?!1:Object.values(r).some(i=>typeof i=="object"&&i!==null&&"column"in i);return!(n(t.rootEntity.columns)||t.nestedEntities&&Array.isArray(t.nestedEntities)&&t.nestedEntities.some(i=>i&&typeof i=="object"&&n(i.columns)))}convert(e){return{format:"legacy",mapping:e,typeProtection:{protectedStringFields:[]},originalInput:e}}},Rt=class{constructor(){this.strategies=[new tr,new nr,new rr]}detectFormat(e){for(let t of this.strategies)if(t.detect(e))return t.convert(e).format;throw new Error("Unsupported JSON mapping format")}convert(e){for(let t of this.strategies)if(t.detect(e))return t.convert(e);throw new Error("Unsupported JSON mapping format: Unable to detect a compatible strategy for the provided input")}toLegacyMapping(e){return this.convert(e).mapping}getTypeProtection(e){return this.convert(e).typeProtection}validate(e){let t=[];if(!e||typeof e!="object")return t.push("Input must be an object"),t;(!("rootName"in e)||!e.rootName)&&t.push("rootName is required");try{let n=this.convert(e);if(n.mapping.rootName||t.push("rootName is required"),n.mapping.rootEntity?(n.mapping.rootEntity.id||t.push("rootEntity.id is required"),n.mapping.rootEntity.columns||t.push("rootEntity.columns is required")):t.push("rootEntity is required"),n.mapping.nestedEntities)for(let r of n.mapping.nestedEntities)r.id||t.push(`Nested entity missing id: ${r.propertyName}`),r.parentId||t.push(`Nested entity missing parentId: ${r.id}`),r.propertyName||t.push(`Nested entity missing propertyName: ${r.id}`)}catch(n){t.length===0&&t.push(`Conversion failed: ${n instanceof Error?n.message:String(n)}`)}return t}upgradeToEnhanced(e,t){return{rootName:e.rootName,rootEntity:{id:e.rootEntity.id,name:e.rootEntity.name,columns:e.rootEntity.columns},nestedEntities:e.nestedEntities.map(n=>({id:n.id,name:n.name,parentId:n.parentId,propertyName:n.propertyName,relationshipType:n.relationshipType||"object",columns:n.columns})),resultFormat:e.resultFormat,emptyResult:e.emptyResult,typeInfo:t,metadata:{version:"1.0",description:"Upgraded from legacy format"}}}};function sr(o){return o.typeInfo&&o.structure?"model-driven":o.rootName&&o.rootEntity?"unified":(o.columns||o.relationships,"legacy")}function jr(o){let e={rootName:o.rootName||"root",rootEntity:{id:"root",name:o.rootName||"Root",columns:o.columns||{}},nestedEntities:[]};if(o.relationships&&typeof o.relationships=="object")for(let[t,n]of Object.entries(o.relationships)){let r=n;e.nestedEntities.push({id:t,name:t.charAt(0).toUpperCase()+t.slice(1),parentId:"root",propertyName:t,relationshipType:r.type==="hasMany"?"array":"object",columns:r.columns||{}})}return e}function Jr(o){if(console.warn("\u26A0\uFE0F DEPRECATED: processJsonMapping() is deprecated. Use JsonMappingConverter.convert() instead."),console.warn("Migration guide: https://github.com/mk3008/rawsql-ts/blob/main/docs/migration-guide.md"),(o.columns||o.relationships)&&!o.rootName&&!o.rootEntity)return{format:"legacy",jsonMapping:jr(o),originalInput:o,metadata:{}};let t=new Rt().convert(o),n=t.format;return t.format==="legacy"&&o.rootName&&o.rootEntity&&(n="unified"),{format:n,jsonMapping:t.mapping,originalInput:o,metadata:{typeInfo:t.metadata?.typeInfo,typeProtection:t.typeProtection}}}function Ur(o){return console.warn("\u26A0\uFE0F DEPRECATED: unifyJsonMapping() is deprecated. Use JsonMappingConverter.toLegacyMapping() instead."),console.warn("Migration guide: https://github.com/mk3008/rawsql-ts/blob/main/docs/migration-guide.md"),new Rt().toLegacyMapping(o)}function qr(o){return sr(o)==="model-driven"}function Kr(o){return sr(o)==="unified"}function _r(o){return sr(o)==="legacy"}var Dn=class{constructor(e={}){this.config={enableValueBasedDetection:!0,strictDateDetection:!1,...e}}transformResult(e){return e==null?e:Array.isArray(e)?e.map(t=>this.transformSingleObject(t)):this.transformSingleObject(e)}transformSingleObject(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.transformSingleObject(n));let t={};for(let[n,r]of Object.entries(e)){if(r==null){t[n]=r;continue}let i=this.config.columnTransformations?.[n];if(i){t[n]=this.applyTransformation(r,i);continue}if(this.config.enableValueBasedDetection){let a=this.detectValueBasedTransformation(r);if(a){t[n]=this.applyTransformation(r,a);continue}}let s=this.config.globalTransformations&&this.getGlobalTransformationForValue(r);if(s){t[n]=this.applyTransformation(r,s);continue}if(typeof r=="object"&&!Array.isArray(r)){t[n]=this.transformSingleObject(r);continue}if(Array.isArray(r)){t[n]=r.map(a=>typeof a=="object"?this.transformSingleObject(a):a);continue}t[n]=r}return t}detectValueBasedTransformation(e){return typeof e=="string"&&this.isDateString(e)?{sourceType:"TIMESTAMP",targetType:"Date",handleNull:!0,validator:t=>typeof t=="string"&&!isNaN(Date.parse(t))}:typeof e=="number"&&!Number.isSafeInteger(e)?{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return typeof t=="string"||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?(BigInt(t),!0):!1}catch{return!1}}}:typeof e=="string"&&/^\d{16,}$/.test(e)?{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return typeof t=="string"||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?(BigInt(t),!0):!1}catch{return!1}}}:null}getGlobalTransformationForValue(e){return this.config.globalTransformations,null}detectAndGetGlobalTransformation(e){return this.detectValueBasedTransformation(e)}isDateString(e){if(this.config.strictDateDetection){if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})?$/.test(e))return!1}else if(!/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})?)?$/.test(e))return!1;let t=new Date(e);return!isNaN(t.getTime())}applyTransformation(e,t){if(e==null)return t.handleNull!==!1?e:null;if(t.validator&&!t.validator(e))return console.warn(`TypeTransformationPostProcessor: Value validation failed for ${e}`),e;try{switch(t.targetType){case"Date":return new Date(e);case"bigint":if(typeof e=="number"){let n=Math.trunc(e);return BigInt(n.toString())}return BigInt(e);case"string":return e.toString();case"number":return typeof e=="string"?parseFloat(e):Number(e);case"object":return typeof e=="string"?JSON.parse(e):e;case"custom":if(t.customTransformer&&this.config.customTransformers?.[t.customTransformer])return this.config.customTransformers[t.customTransformer](e);break;default:return e}}catch(n){return console.warn(`TypeTransformationPostProcessor: Transformation failed for ${e}:`,n),e}return e}static createDefaultConfig(){return{enableValueBasedDetection:!0,strictDateDetection:!1,globalTransformations:{DATE:{sourceType:"DATE",targetType:"Date",handleNull:!0,validator:e=>typeof e=="string"&&!isNaN(Date.parse(e))},TIMESTAMP:{sourceType:"TIMESTAMP",targetType:"Date",handleNull:!0,validator:e=>typeof e=="string"&&!isNaN(Date.parse(e))},BIGINT:{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:e=>{try{return typeof e=="string"||typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?(BigInt(e),!0):!1}catch{return!1}}}}}}static createSafeConfig(e){return{enableValueBasedDetection:!1,strictDateDetection:!0,columnTransformations:e||{},globalTransformations:{DATE:{sourceType:"DATE",targetType:"Date",handleNull:!0,validator:t=>typeof t=="string"&&!isNaN(Date.parse(t))},TIMESTAMP:{sourceType:"TIMESTAMP",targetType:"Date",handleNull:!0,validator:t=>typeof t=="string"&&!isNaN(Date.parse(t))},BIGINT:{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return typeof t=="string"||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?(BigInt(t),!0):!1}catch{return!1}}}}}}};function Hf(o,e){return new Dn(e||Dn.createDefaultConfig()).transformResult(o)}var Yf={toDate:o=>{if(o==null)return null;let e=new Date(o);return isNaN(e.getTime())?null:e},toBigInt:o=>{if(o==null)return null;try{return BigInt(o)}catch{return null}},toObject:o=>{if(o==null)return null;try{return JSON.parse(o)}catch{return null}}};var kt=class{constructor(e,t,n,r,i){this.id=e;this.label=t;this.type=n;this.shape=r;this.details=i}},It=class o extends kt{constructor(t,n,r){super(t,n,r,r==="subquery"?"hexagon":"cylinder");this.annotations=new Set}addAnnotation(t){this.annotations.add(t)}hasAnnotation(t){return this.annotations.has(t)}getMermaidRepresentation(){return this.shape==="hexagon"?`${this.id}{{${this.label}}}`:`${this.id}[(${this.label})]`}static createTable(t){return new o(`table_${t}`,t,"table")}static createCTE(t){return new o(`cte_${t}`,`CTE:${t}`,"cte")}static createSubquery(t){return new o(`subquery_${t}`,`SubQuery:${t}`,"subquery")}},jn=class o extends kt{constructor(e,t,n=""){let r=n?`${n}_${t.toLowerCase().replace(/\s+/g,"_")}`:t.toLowerCase().replace(/\s+/g,"_");super(r,t,"process","hexagon")}getMermaidRepresentation(){return`${this.id}{{${this.label}}}`}static createWhere(e){return new o(`${e}_where`,"WHERE",e)}static createGroupBy(e){return new o(`${e}_group_by`,"GROUP BY",e)}static createHaving(e){return new o(`${e}_having`,"HAVING",e)}static createSelect(e){return new o(`${e}_select`,"SELECT",e)}static createOrderBy(e){return new o(`${e}_order_by`,"ORDER BY",e)}static createLimit(e,t=!1){let n=t?"LIMIT/OFFSET":"LIMIT";return new o(`${e}_limit`,n,e)}},Vt=class o extends kt{constructor(e,t,n="diamond"){super(e,t,"operation",n)}getMermaidRepresentation(){switch(this.shape){case"rounded":return`${this.id}(${this.label})`;case"rectangle":return`${this.id}[${this.label}]`;case"hexagon":return`${this.id}{{${this.label}}}`;case"stadium":return`${this.id}([${this.label}])`;case"diamond":default:return`${this.id}{${this.label}}`}}static createJoin(e,t){let n,r=t.trim().toLowerCase();return r==="join"?n="INNER JOIN":r.endsWith(" join")?n=r.toUpperCase():n=r.toUpperCase()+" JOIN",new o(`join_${e}`,n,"rectangle")}static createUnion(e,t="UNION ALL"){return new o(`${t.toLowerCase().replace(/\s+/g,"_")}_${e}`,t.toUpperCase(),"rectangle")}static createSetOperation(e,t){let n=t.toUpperCase(),r=`${n.toLowerCase().replace(/\s+/g,"_")}_${e}`;return new o(r,n,"rectangle")}},Jn=class extends kt{constructor(e="main"){let t=e==="main"?"Final Result":`${e} Result`;super(`${e}_output`,t,"output","stadium")}getMermaidRepresentation(){return`${this.id}([${this.label}])`}};var Un=class o{constructor(e,t,n){this.from=e;this.to=t;this.label=n}getMermaidRepresentation(){let e=this.label?` -->|${this.label}| `:" --> ";return`${this.from}${e}${this.to}`}static create(e,t,n){return new o(e,t,n)}static createWithNullability(e,t,n){let r=n?"NULLABLE":"NOT NULL";return new o(e,t,r)}},qn=class{constructor(){this.edges=[];this.connectionSet=new Set}add(e){let t=`${e.from}->${e.to}`;this.connectionSet.has(t)||(this.edges.push(e),this.connectionSet.add(t))}addConnection(e,t,n){this.add(Un.create(e,t,n))}addJoinConnection(e,t,n){this.add(Un.createWithNullability(e,t,n))}hasConnection(e,t){return this.connectionSet.has(`${e}->${t}`)}getAll(){return[...this.edges]}getMermaidRepresentation(){return this.edges.map(e=>e.getMermaidRepresentation()).join(`
|
|
53
|
+
`)}};var $t=class{constructor(){this.nodes=new Map;this.edges=new qn}addNode(e){this.nodes.set(e.id,e)}addEdge(e){this.edges.add(e)}addConnection(e,t,n){this.edges.addConnection(e,t,n)}hasNode(e){return this.nodes.has(e)}hasConnection(e,t){return this.edges.hasConnection(e,t)}getNode(e){return this.nodes.get(e)}getAllNodes(){return Array.from(this.nodes.values())}getAllEdges(){return this.edges.getAll()}generateMermaid(e="TD",t){let n=`flowchart ${e}
|
|
54
54
|
`;t&&(n+=` %% ${t}
|
|
55
55
|
`);let r=Array.from(this.nodes.values()).map(s=>` ${s.getMermaidRepresentation()}`).join(`
|
|
56
56
|
`);r&&(n+=r+`
|
|
57
57
|
`),this.nodes.size>0&&this.edges.getAll().length>0&&(n+=`
|
|
58
58
|
`);let i=this.edges.getMermaidRepresentation();return i&&(n+=` ${i}
|
|
59
|
-
`),n}getOrCreateTable(e){let t=`table_${e}`,n=this.nodes.get(t);return n||(n=kt.createTable(e),this.addNode(n)),n}getOrCreateCTE(e){let t=`cte_${e}`,n=this.nodes.get(t);return n||(n=kt.createCTE(e),this.addNode(n)),n}getOrCreateSubquery(e){let t=`subquery_${e}`,n=this.nodes.get(t);return n||(n=kt.createSubquery(e),this.addNode(n)),n}createProcessNode(e,t){let n=new Dn(t,e);return this.addNode(n),n}createJoinNode(e,t){let n=Bt.createJoin(e,t);return this.addNode(n),n}createSetOperationNode(e,t){let n=Bt.createSetOperation(e,t);return this.addNode(n),n}createOutputNode(e="main"){let t=new Wn(e);return this.addNode(t),t}};var $t=class{constructor(e){this.graph=e}processSource(e,t,n){if(e.datasource instanceof R)return this.processTableSource(e.datasource,t);if(e.datasource instanceof z)return this.processSubquerySource(e,t,n);throw new Error("Unsupported source type")}processTableSource(e,t){let n=e.getSourceName();return t.has(n)?this.graph.getOrCreateCTE(n).id:this.graph.getOrCreateTable(n).id}processSubquerySource(e,t,n){let r=e.aliasExpression?.table.name||"subquery",i=this.graph.getOrCreateSubquery(r),s=n(e.datasource.query,`subquery_${r}_internal`,t);return s&&!this.graph.hasConnection(s,i.id)&&this.graph.addConnection(s,i.id),i.id}extractTableNodeIds(e,t){let n=[],r=e.source;if(r.datasource instanceof R){let i=r.datasource.getSourceName();if(t.has(i)){let s=this.graph.getOrCreateCTE(i);n.push(s.id)}else{let s=this.graph.getOrCreateTable(i);n.push(s.id)}}if(e.joins&&e.joins.length>0)for(let i of e.joins){let s=i.source;if(s.datasource instanceof R){let a=s.datasource.getSourceName();if(t.has(a)){let l=this.graph.getOrCreateCTE(a);n.push(l.id)}else{let l=this.graph.getOrCreateTable(a);n.push(l.id)}}}return n}};var Mt=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t;this.joinIdCounter=0}resetJoinCounter(){this.joinIdCounter=0}getNextJoinId(){return String(++this.joinIdCounter)}processFromClause(e,t,n){let r=this.dataSourceHandler.processSource(e.source,t,n);return e.joins&&e.joins.length>0?this.processJoins(e.joins,r,t,n):r}processJoins(e,t,n,r){let i=t;for(let s of e){let a=this.dataSourceHandler.processSource(s.source,n,r),l=this.getNextJoinId(),u=this.graph.createJoinNode(l,s.joinType.value),{leftLabel:c,rightLabel:m}=this.getJoinNullabilityLabels(s.joinType.value);i&&!this.graph.hasConnection(i,u.id)&&this.graph.addConnection(i,u.id,c),a&&!this.graph.hasConnection(a,u.id)&&this.graph.addConnection(a,u.id,m),i=u.id}return i}getJoinNullabilityLabels(e){switch(e.toLowerCase()){case"left join":return{leftLabel:"NOT NULL",rightLabel:"NULLABLE"};case"right join":return{leftLabel:"NULLABLE",rightLabel:"NOT NULL"};case"inner join":case"join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};case"full join":case"full outer join":return{leftLabel:"NULLABLE",rightLabel:"NULLABLE"};case"cross join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};default:return{leftLabel:"",rightLabel:""}}}};var Dt=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t}processQueryClauses(e,t,n,r,i){return n}};var Wt=class{constructor(e){this.graph=e}processCTEs(e,t,n){for(let r=0;r<e.tables.length;r++){let s=e.tables[r].getSourceAliasName(),a=this.graph.getOrCreateCTE(s);t.add(s),e.recursive&&r===0&&a.addAnnotation("recursive")}for(let r=0;r<e.tables.length;r++){let i=e.tables[r],s=i.getSourceAliasName(),a=this.graph.getOrCreateCTE(s),l=n(i.query,`cte_${s}`,t);if(l&&!this.graph.hasConnection(l,a.id)){let c=e.recursive&&r===0?"RECURSIVE":void 0;this.graph.addConnection(l,a.id,c)}}}detectRecursiveReference(e,t){return e.toString().toLowerCase().includes(t.toLowerCase())}};var fr=class o{constructor(){this.graph=new Vt,this.dataSourceHandler=new $t(this.graph),this.joinHandler=new Mt(this.graph,this.dataSourceHandler),this.processHandler=new Dt(this.graph,this.dataSourceHandler),this.cteHandler=new Wt(this.graph)}generateMermaidFlow(e,t){this.graph=new Vt,this.dataSourceHandler=new $t(this.graph),this.joinHandler=new Mt(this.graph,this.dataSourceHandler),this.processHandler=new Dt(this.graph,this.dataSourceHandler),this.cteHandler=new Wt(this.graph),this.joinHandler.resetJoinCounter();let n=typeof e=="string"?A.parse(e):e,r=new Set;return this.processQuery(n,"main",r),this.graph.generateMermaid(t?.direction||"TD",t?.title)}static generate(e){return new o().generateMermaidFlow(e)}processQuery(e,t,n){if(e instanceof E)return this.processSimpleQuery(e,t,n);if(e instanceof K)return this.processBinaryQuery(e,t,n);throw new Error("Unsupported query type")}processSimpleQuery(e,t,n){e.withClause&&this.cteHandler.processCTEs(e.withClause,n,this.processQuery.bind(this));let r="";return e.fromClause&&(e.fromClause.joins&&e.fromClause.joins.length>0?r=this.joinHandler.processFromClause(e.fromClause,n,this.processQuery.bind(this)):r=this.dataSourceHandler.processSource(e.fromClause.source,n,this.processQuery.bind(this))),r&&(r=this.processHandler.processQueryClauses(e,t,r,n,this.processQuery.bind(this))),this.handleOutputNode(r,t)}processBinaryQuery(e,t,n){let r=this.flattenBinaryChain(e,e.operator.value);return r.length>2?this.processMultiPartOperation(r,e.operator.value,t,n):this.processSimpleBinaryOperation(e,t,n)}processSimpleBinaryOperation(e,t,n){let r=this.processQuery(e.left,`${t}_left`,n),i=this.processQuery(e.right,`${t}_right`,n),s=t==="main"?"main":t.replace(/^cte_/,""),a=this.graph.createSetOperationNode(s,e.operator.value);return r&&!this.graph.hasConnection(r,a.id)&&this.graph.addConnection(r,a.id),i&&!this.graph.hasConnection(i,a.id)&&this.graph.addConnection(i,a.id),a.id}processMultiPartOperation(e,t,n,r){let i=[],s=n==="main"?"main":n.replace(/^cte_/,""),a=this.graph.createSetOperationNode(s,t);for(let l=0;l<e.length;l++){let u=`${n}_part${l+1}`,c=this.processQuery(e[l],u,r);i.push(c)}for(let l of i)l&&!this.graph.hasConnection(l,a.id)&&this.graph.addConnection(l,a.id);return a.id}handleOutputNode(e,t){if(t==="main"){let n=this.graph.createOutputNode(t);return e&&this.graph.addConnection(e,n.id),n.id}return e}flattenBinaryChain(e,t){let n=[],r=i=>{i instanceof K&&i.operator.value===t?(r(i.left),r(i.right)):n.push(i)};return r(e),n}};var Jn=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=A.parse(e));let n=new vt(this.tableColumnResolver,this.options),r=new Ie(this.tableColumnResolver),i=d=>this.options.ignoreCaseAndUnderscore?d.toLowerCase().replace(/_/g,""):d,s=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"],a=Object.values(t);if(a.length>0&&a.every(d=>d===void 0)&&!this.options.allowAllUndefined)throw new Error("All parameters are undefined. This would result in fetching all records. Use allowAllUndefined: true option to explicitly allow this behavior.");for(let[d,C]of Object.entries(t))C!==void 0&&this.processStateParameter(d,C,e,n,r,i,s,m,c,w,b,h);function c(d,C,F,S,O,N){for(let Q=0;Q<F.length;Q++){let g=F[Q],I=g.column||C,Nt=O.find(B=>S(B.name)===S(I));if(!Nt)throw new Error(`Column '${I}' not found in query for AND condition`);let fe=Nt.value;if("="in g&&g["="]!==void 0){let B=`${C}_and_${Q}_eq`,L=new T(B,g["="]);d.appendWhere(new y(fe,"=",L))}if("min"in g&&g.min!==void 0){let B=`${C}_and_${Q}_min`,L=new T(B,g.min);d.appendWhere(new y(fe,">=",L))}if("max"in g&&g.max!==void 0){let B=`${C}_and_${Q}_max`,L=new T(B,g.max);d.appendWhere(new y(fe,"<=",L))}if("like"in g&&g.like!==void 0){let B=`${C}_and_${Q}_like`,L=new T(B,g.like);d.appendWhere(new y(fe,"like",L))}if("ilike"in g&&g.ilike!==void 0){let B=`${C}_and_${Q}_ilike`,L=new T(B,g.ilike);d.appendWhere(new y(fe,"ilike",L))}if("in"in g&&g.in!==void 0){let L=g.in.map((W,q)=>new T(`${C}_and_${Q}_in_${q}`,W));d.appendWhere(new y(fe,"in",new Z(new _(L))))}if("any"in g&&g.any!==void 0){let B=`${C}_and_${Q}_any`,L=new T(B,g.any);d.appendWhere(new y(fe,"=",new U(null,"any",L,null)))}if("<"in g&&g["<"]!==void 0){let B=`${C}_and_${Q}_lt`,L=new T(B,g["<"]);d.appendWhere(new y(fe,"<",L))}if(">"in g&&g[">"]!==void 0){let B=`${C}_and_${Q}_gt`,L=new T(B,g[">"]);d.appendWhere(new y(fe,">",L))}if("!="in g&&g["!="]!==void 0){let B=`${C}_and_${Q}_neq`,L=new T(B,g["!="]);d.appendWhere(new y(fe,"!=",L))}if("<>"in g&&g["<>"]!==void 0){let B=`${C}_and_${Q}_ne`,L=new T(B,g["<>"]);d.appendWhere(new y(fe,"<>",L))}if("<="in g&&g["<="]!==void 0){let B=`${C}_and_${Q}_le`,L=new T(B,g["<="]);d.appendWhere(new y(fe,"<=",L))}if(">="in g&&g[">="]!==void 0){let B=`${C}_and_${Q}_ge`,L=new T(B,g[">="]);d.appendWhere(new y(fe,">=",L))}}}function m(d,C,F,S,O,N){let Q=[];for(let g=0;g<F.length;g++){let I=F[g],Nt=I.column||C,fe=O.find(W=>S(W.name)===S(Nt));if(!fe)throw new Error(`Column '${Nt}' not found in query for OR condition`);let B=fe.value,L=[];if("="in I&&I["="]!==void 0){let W=`${C}_or_${g}_eq`,q=new T(W,I["="]);L.push(new y(B,"=",q))}if("min"in I&&I.min!==void 0){let W=`${C}_or_${g}_min`,q=new T(W,I.min);L.push(new y(B,">=",q))}if("max"in I&&I.max!==void 0){let W=`${C}_or_${g}_max`,q=new T(W,I.max);L.push(new y(B,"<=",q))}if("like"in I&&I.like!==void 0){let W=`${C}_or_${g}_like`,q=new T(W,I.like);L.push(new y(B,"like",q))}if("ilike"in I&&I.ilike!==void 0){let W=`${C}_or_${g}_ilike`,q=new T(W,I.ilike);L.push(new y(B,"ilike",q))}if("in"in I&&I.in!==void 0){let q=I.in.map((gr,Sr)=>new T(`${C}_or_${g}_in_${Sr}`,gr));L.push(new y(B,"in",new Z(new _(q))))}if("any"in I&&I.any!==void 0){let W=`${C}_or_${g}_any`,q=new T(W,I.any);L.push(new y(B,"=",new U(null,"any",q,null)))}if("<"in I&&I["<"]!==void 0){let W=`${C}_or_${g}_lt`,q=new T(W,I["<"]);L.push(new y(B,"<",q))}if(">"in I&&I[">"]!==void 0){let W=`${C}_or_${g}_gt`,q=new T(W,I[">"]);L.push(new y(B,">",q))}if("!="in I&&I["!="]!==void 0){let W=`${C}_or_${g}_neq`,q=new T(W,I["!="]);L.push(new y(B,"!=",q))}if("<>"in I&&I["<>"]!==void 0){let W=`${C}_or_${g}_ne`,q=new T(W,I["<>"]);L.push(new y(B,"<>",q))}if("<="in I&&I["<="]!==void 0){let W=`${C}_or_${g}_le`,q=new T(W,I["<="]);L.push(new y(B,"<=",q))}if(">="in I&&I[">="]!==void 0){let W=`${C}_or_${g}_ge`,q=new T(W,I[">="]);L.push(new y(B,">=",q))}if(L.length>0){let W=L[0];for(let q=1;q<L.length;q++)W=new y(W,"and",L[q]);L.length>1?Q.push(new Z(W)):Q.push(W)}}if(Q.length>0){let g=Q[0];for(let I=1;I<Q.length;I++)g=new y(g,"or",Q[I]);d.appendWhere(new Z(g))}}function h(d,C,F){Object.keys(d).forEach(S=>{if(!C.includes(S))throw new Error(`Unsupported operator '${S}' for state key '${F}'`)})}function w(d,C,F,S){let O=new T(F,S);d.appendWhere(new y(C,"=",O))}function b(d,C,F,S){let O=[];if("="in S){let N=new T(F,S["="]);O.push(new y(C,"=",N))}if("min"in S){let N=new T(F+"_min",S.min);O.push(new y(C,">=",N))}if("max"in S){let N=new T(F+"_max",S.max);O.push(new y(C,"<=",N))}if("like"in S){let N=new T(F+"_like",S.like);O.push(new y(C,"like",N))}if("ilike"in S){let N=new T(F+"_ilike",S.ilike);O.push(new y(C,"ilike",N))}if("in"in S){let Q=S.in.map((g,I)=>new T(`${F}_in_${I}`,g));O.push(new y(C,"in",new Z(new _(Q))))}if("any"in S){let N=new T(F+"_any",S.any);O.push(new y(C,"=",new U(null,"any",N,null)))}if("<"in S){let N=new T(F+"_lt",S["<"]);O.push(new y(C,"<",N))}if(">"in S){let N=new T(F+"_gt",S[">"]);O.push(new y(C,">",N))}if("!="in S){let N=new T(F+"_neq",S["!="]);O.push(new y(C,"!=",N))}if("<>"in S){let N=new T(F+"_ne",S["<>"]);O.push(new y(C,"<>",N))}if("<="in S){let N=new T(F+"_le",S["<="]);O.push(new y(C,"<=",N))}if(">="in S){let N=new T(F+"_ge",S[">="]);O.push(new y(C,">=",N))}if(O.length===1)d.appendWhere(O[0]);else if(O.length>1){let N=O[0];for(let Q=1;Q<O.length;Q++)N=new y(N,"and",O[Q]);d.appendWhere(new Z(N))}}return e}isOrCondition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"or"in e}isAndCondition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"and"in e}isExplicitColumnMapping(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"column"in e&&!("or"in e)}isValidatableObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}hasColumnMapping(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"column"in e}isSimpleValue(e){return e===null||typeof e!="object"||Array.isArray(e)||e instanceof Date}processStateParameter(e,t,n,r,i,s,a,l,u,c,m,h){if(this.isOrCondition(t)){let w=t.or;if(w&&w.length>0){let b=this.findTargetQueryForLogicalCondition(r,n,e,w),d=this.getAllAvailableColumns(b,i);l(b,e,w,s,d,i);return}}if(this.isAndCondition(t)){let w=t.and;if(w&&w.length>0){let b=this.findTargetQueryForLogicalCondition(r,n,e,w),d=this.getAllAvailableColumns(b,i);u(b,e,w,s,d,i);return}}if(this.isExplicitColumnMapping(t)){let w=t.column;if(w){let b=r.find(n,w);if(b.length===0)throw new Error(`Explicit column '${w}' not found in query`);for(let d of b){let F=this.getAllAvailableColumns(d,i).find(S=>s(S.name)===s(w));if(!F)throw new Error(`Explicit column '${w}' not found in query`);this.isValidatableObject(t)&&h(t,a,e),m(d,F.value,e,t)}return}}this.processRegularColumnCondition(e,t,n,r,i,s,a,c,m,h)}processRegularColumnCondition(e,t,n,r,i,s,a,l,u,c){let m=r.find(n,e);if(m.length===0)throw new Error(`Column '${e}' not found in query`);for(let h of m){let w=this.getAllAvailableColumns(h,i),b=w.find(S=>s(S.name)===s(e));if(!b)throw new Error(`Column '${e}' not found in query`);let d=b.value;this.isValidatableObject(t)&&c(t,a,e);let C=d,F=e;if(this.hasColumnMapping(t)){let S=t.column;if(S){let O=w.find(N=>s(N.name)===s(S));O&&(C=O.value,F=S)}}this.isSimpleValue(t)?l(h,C,F,t):u(h,C,F,t)}}findTargetQueryForLogicalCondition(e,t,n,r){let i=r.map(a=>a.column||n).filter((a,l,u)=>u.indexOf(a)===l);for(let a of i){let l=e.find(t,a);if(l.length>0)return l[0]}let s=r===r.or?"OR":"AND";throw new Error(`None of the ${s} condition columns [${i.join(", ")}] found in query`)}getAllAvailableColumns(e,t){let n=t.collect(e),r=this.collectCTEColumns(e);return[...n,...r]}collectCTEColumns(e){let t=[];if(e.withClause)for(let n of e.withClause.tables)try{let r=this.collectColumnsFromSelectQuery(n.query);t.push(...r)}catch(r){console.warn(`Failed to collect columns from CTE '${n.getSourceAliasName()}':`,r)}return t}collectColumnsFromSelectQuery(e){return e instanceof E?new Ie(this.tableColumnResolver).collect(e):e instanceof K?this.collectColumnsFromSelectQuery(e.left):[]}};var qn=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof E))throw new Error("Complex queries are not supported for ORDER BY removal");return new E({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=A.parse(e)),!(e instanceof E))throw new Error("Complex queries are not supported for sorting");let r=new Ie(this.tableColumnResolver).collect(e);for(let l of Object.keys(t))if(!r.find(c=>c.name===l))throw new Error(`Column or alias '${l}' not found in current query`);let i=[];for(let[l,u]of Object.entries(t)){let c=r.find(d=>d.name===l);if(!c)continue;let m=c.value;this.validateSortCondition(l,u);let h;u.desc?h="desc":h="asc";let w=null;u.nullsFirst?w="first":u.nullsLast&&(w="last");let b=new xe(m,h,w);i.push(b)}let s=[];e.orderByClause?s=[...e.orderByClause.order,...i]:s=i;let a=s.length>0?new ce(s):null;return new E({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=A.parse(e)),!(e instanceof E))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,r=new se(new T("paging_limit",t.pageSize)),i=new De(new T("paging_offset",n));return new E({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:r,offsetClause:i,fetchClause:e.fetchClause,forClause:e.forClause})}static removePagination(e){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof E))throw new Error("Complex queries are not supported for pagination removal");return new E({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 It=class{static extractParameterNames(e){return it.collect(e).map(n=>n.name.value)}static hasParameter(e,t){return this.extractParameterNames(e).includes(t)}static separateFilters(e,t){let n=this.extractParameterNames(e),r={},i={};for(let[s,a]of Object.entries(t))n.includes(s)?r[s]=a:i[s]=a;return{hardcodedParams:r,dynamicFilters:i}}};var _n=class{constructor(e={}){this.options={requireAllParameters:!0,...e}}bind(e,t){let n=e,r=It.extractParameterNames(n);if(this.options.requireAllParameters){let i=r.filter(s=>!(s in t)||t[s]===void 0);if(i.length>0)throw new Error(`Missing values for required parameters: ${i.join(", ")}`)}for(let[i,s]of Object.entries(t))if(r.includes(i))try{ze.set(n,i,s)}catch(a){throw new Error(`Failed to bind parameter '${i}': ${a instanceof Error?a.message:"Unknown error"}`)}return n}bindToSimpleQuery(e,t){return this.bind(e,t)}};var Cr=class{constructor(e){this.tableColumnResolver=e}buildQuery(e,t={}){let n;try{n=A.parse(e)}catch(i){throw new Error(`Failed to parse SQL: ${i instanceof Error?i.message:"Unknown error"}`)}let r=n;if(t.filter&&Object.keys(t.filter).length>0){let{hardcodedParams:i,dynamicFilters:s}=It.separateFilters(r,t.filter);if(Object.keys(i).length>0&&(r=new _n({requireAllParameters:!1}).bind(r,i)),Object.keys(s).length>0){let a=new Jn(this.tableColumnResolver),l=Ne.buildSimpleQuery(r);r=a.inject(l,s)}}if(t.sort&&Object.keys(t.sort).length>0){let i=new qn(this.tableColumnResolver),s=Ne.buildSimpleQuery(r);r=i.inject(s,t.sort)}if(t.paging){let{page:i=1,pageSize:s}=t.paging;if(s!==void 0){let a=new Kn,l={page:i,pageSize:s},u=Ne.buildSimpleQuery(r);r=a.inject(u,l)}}if(t.serialize&&typeof t.serialize=="object"){let i=new Vn,s=Ne.buildSimpleQuery(r);r=i.buildJsonQuery(s,t.serialize)}return r}buildFilteredQuery(e,t){return this.buildQuery(e,{filter:t})}buildSortedQuery(e,t){return this.buildQuery(e,{sort:t})}buildPaginatedQuery(e,t){return this.buildQuery(e,{paging:t})}buildSerializedQuery(e,t){return this.buildQuery(e,{serialize:t})}validateSql(e){try{return A.parse(e),!0}catch(t){throw new Error(`Invalid SQL: ${t instanceof Error?t.message:"Unknown error"}`)}}};var yr=class{static validate(e,t){let n=this.extractStructureFromJsonMapping(e);return this.compareStructures(n,t)}static validateStrict(e,t){let n=this.validate(e,t);if(!n.isValid){let r=["JsonMapping validation failed:",...n.errors].join(`
|
|
59
|
+
`),n}getOrCreateTable(e){let t=`table_${e}`,n=this.nodes.get(t);return n||(n=It.createTable(e),this.addNode(n)),n}getOrCreateCTE(e){let t=`cte_${e}`,n=this.nodes.get(t);return n||(n=It.createCTE(e),this.addNode(n)),n}getOrCreateSubquery(e){let t=`subquery_${e}`,n=this.nodes.get(t);return n||(n=It.createSubquery(e),this.addNode(n)),n}createProcessNode(e,t){let n=new jn(t,e);return this.addNode(n),n}createJoinNode(e,t){let n=Vt.createJoin(e,t);return this.addNode(n),n}createSetOperationNode(e,t){let n=Vt.createSetOperation(e,t);return this.addNode(n),n}createOutputNode(e="main"){let t=new Jn(e);return this.addNode(t),t}};var Mt=class{constructor(e){this.graph=e}processSource(e,t,n){if(e.datasource instanceof B)return this.processTableSource(e.datasource,t);if(e.datasource instanceof _)return this.processSubquerySource(e,t,n);throw new Error("Unsupported source type")}processTableSource(e,t){let n=e.getSourceName();return t.has(n)?this.graph.getOrCreateCTE(n).id:this.graph.getOrCreateTable(n).id}processSubquerySource(e,t,n){let r=e.aliasExpression?.table.name||"subquery",i=this.graph.getOrCreateSubquery(r),s=n(e.datasource.query,`subquery_${r}_internal`,t);return s&&!this.graph.hasConnection(s,i.id)&&this.graph.addConnection(s,i.id),i.id}extractTableNodeIds(e,t){let n=[],r=e.source;if(r.datasource instanceof B){let i=r.datasource.getSourceName();if(t.has(i)){let s=this.graph.getOrCreateCTE(i);n.push(s.id)}else{let s=this.graph.getOrCreateTable(i);n.push(s.id)}}if(e.joins&&e.joins.length>0)for(let i of e.joins){let s=i.source;if(s.datasource instanceof B){let a=s.datasource.getSourceName();if(t.has(a)){let l=this.graph.getOrCreateCTE(a);n.push(l.id)}else{let l=this.graph.getOrCreateTable(a);n.push(l.id)}}}return n}};var Wt=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t;this.joinIdCounter=0}resetJoinCounter(){this.joinIdCounter=0}getNextJoinId(){return String(++this.joinIdCounter)}processFromClause(e,t,n){let r=this.dataSourceHandler.processSource(e.source,t,n);return e.joins&&e.joins.length>0?this.processJoins(e.joins,r,t,n):r}processJoins(e,t,n,r){let i=t;for(let s of e){let a=this.dataSourceHandler.processSource(s.source,n,r),l=this.getNextJoinId(),u=this.graph.createJoinNode(l,s.joinType.value),{leftLabel:c,rightLabel:m}=this.getJoinNullabilityLabels(s.joinType.value);i&&!this.graph.hasConnection(i,u.id)&&this.graph.addConnection(i,u.id,c),a&&!this.graph.hasConnection(a,u.id)&&this.graph.addConnection(a,u.id,m),i=u.id}return i}getJoinNullabilityLabels(e){switch(e.toLowerCase()){case"left join":return{leftLabel:"NOT NULL",rightLabel:"NULLABLE"};case"right join":return{leftLabel:"NULLABLE",rightLabel:"NOT NULL"};case"inner join":case"join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};case"full join":case"full outer join":return{leftLabel:"NULLABLE",rightLabel:"NULLABLE"};case"cross join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};default:return{leftLabel:"",rightLabel:""}}}};var Dt=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t}processQueryClauses(e,t,n,r,i){return n}};var jt=class{constructor(e){this.graph=e}processCTEs(e,t,n){for(let r=0;r<e.tables.length;r++){let s=e.tables[r].getSourceAliasName(),a=this.graph.getOrCreateCTE(s);t.add(s),e.recursive&&r===0&&a.addAnnotation("recursive")}for(let r=0;r<e.tables.length;r++){let i=e.tables[r],s=i.getSourceAliasName(),a=this.graph.getOrCreateCTE(s),l=n(i.query,`cte_${s}`,t);if(l&&!this.graph.hasConnection(l,a.id)){let c=e.recursive&&r===0?"RECURSIVE":void 0;this.graph.addConnection(l,a.id,c)}}}detectRecursiveReference(e,t){return e.toString().toLowerCase().includes(t.toLowerCase())}};var wr=class o{constructor(){this.graph=new $t,this.dataSourceHandler=new Mt(this.graph),this.joinHandler=new Wt(this.graph,this.dataSourceHandler),this.processHandler=new Dt(this.graph,this.dataSourceHandler),this.cteHandler=new jt(this.graph)}generateMermaidFlow(e,t){this.graph=new $t,this.dataSourceHandler=new Mt(this.graph),this.joinHandler=new Wt(this.graph,this.dataSourceHandler),this.processHandler=new Dt(this.graph,this.dataSourceHandler),this.cteHandler=new jt(this.graph),this.joinHandler.resetJoinCounter();let n=typeof e=="string"?Q.parse(e):e,r=new Set;return this.processQuery(n,"main",r),this.graph.generateMermaid(t?.direction||"TD",t?.title)}static generate(e){return new o().generateMermaidFlow(e)}processQuery(e,t,n){if(e instanceof g)return this.processSimpleQuery(e,t,n);if(e instanceof W)return this.processBinaryQuery(e,t,n);throw new Error("Unsupported query type")}processSimpleQuery(e,t,n){e.withClause&&this.cteHandler.processCTEs(e.withClause,n,this.processQuery.bind(this));let r="";return e.fromClause&&(e.fromClause.joins&&e.fromClause.joins.length>0?r=this.joinHandler.processFromClause(e.fromClause,n,this.processQuery.bind(this)):r=this.dataSourceHandler.processSource(e.fromClause.source,n,this.processQuery.bind(this))),r&&(r=this.processHandler.processQueryClauses(e,t,r,n,this.processQuery.bind(this))),this.handleOutputNode(r,t)}processBinaryQuery(e,t,n){let r=this.flattenBinaryChain(e,e.operator.value);return r.length>2?this.processMultiPartOperation(r,e.operator.value,t,n):this.processSimpleBinaryOperation(e,t,n)}processSimpleBinaryOperation(e,t,n){let r=this.processQuery(e.left,`${t}_left`,n),i=this.processQuery(e.right,`${t}_right`,n),s=t==="main"?"main":t.replace(/^cte_/,""),a=this.graph.createSetOperationNode(s,e.operator.value);return r&&!this.graph.hasConnection(r,a.id)&&this.graph.addConnection(r,a.id),i&&!this.graph.hasConnection(i,a.id)&&this.graph.addConnection(i,a.id),a.id}processMultiPartOperation(e,t,n,r){let i=[],s=n==="main"?"main":n.replace(/^cte_/,""),a=this.graph.createSetOperationNode(s,t);for(let l=0;l<e.length;l++){let u=`${n}_part${l+1}`,c=this.processQuery(e[l],u,r);i.push(c)}for(let l of i)l&&!this.graph.hasConnection(l,a.id)&&this.graph.addConnection(l,a.id);return a.id}handleOutputNode(e,t){if(t==="main"){let n=this.graph.createOutputNode(t);return e&&this.graph.addConnection(e,n.id),n.id}return e}flattenBinaryChain(e,t){let n=[],r=i=>{i instanceof W&&i.operator.value===t?(r(i.left),r(i.right)):n.push(i)};return r(e),n}};var Kn=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=Q.parse(e));let n=new bt(this.tableColumnResolver,this.options),r=new Oe(this.tableColumnResolver),i=d=>this.options.ignoreCaseAndUnderscore?d.toLowerCase().replace(/_/g,""):d,s=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"],a=Object.values(t);if(a.length>0&&a.every(d=>d===void 0)&&!this.options.allowAllUndefined)throw new Error("All parameters are undefined. This would result in fetching all records. Use allowAllUndefined: true option to explicitly allow this behavior.");for(let[d,y]of Object.entries(t))y!==void 0&&this.processStateParameter(d,y,e,n,r,i,s,m,c,w,b,h);function c(d,y,L,E,O,N){for(let A=0;A<L.length;A++){let S=L[A],I=S.column||y,Pt=O.find(R=>E(R.name)===E(I));if(!Pt)throw new Error(`Column '${I}' not found in query for AND condition`);let ge=Pt.value;if("="in S&&S["="]!==void 0){let R=`${y}_and_${A}_eq`,F=new T(R,S["="]);d.appendWhere(new C(ge,"=",F))}if("min"in S&&S.min!==void 0){let R=`${y}_and_${A}_min`,F=new T(R,S.min);d.appendWhere(new C(ge,">=",F))}if("max"in S&&S.max!==void 0){let R=`${y}_and_${A}_max`,F=new T(R,S.max);d.appendWhere(new C(ge,"<=",F))}if("like"in S&&S.like!==void 0){let R=`${y}_and_${A}_like`,F=new T(R,S.like);d.appendWhere(new C(ge,"like",F))}if("ilike"in S&&S.ilike!==void 0){let R=`${y}_and_${A}_ilike`,F=new T(R,S.ilike);d.appendWhere(new C(ge,"ilike",F))}if("in"in S&&S.in!==void 0){let F=S.in.map((U,z)=>new T(`${y}_and_${A}_in_${z}`,U));d.appendWhere(new C(ge,"in",new H(new K(F))))}if("any"in S&&S.any!==void 0){let R=`${y}_and_${A}_any`,F=new T(R,S.any);d.appendWhere(new C(ge,"=",new j(null,"any",F,null)))}if("<"in S&&S["<"]!==void 0){let R=`${y}_and_${A}_lt`,F=new T(R,S["<"]);d.appendWhere(new C(ge,"<",F))}if(">"in S&&S[">"]!==void 0){let R=`${y}_and_${A}_gt`,F=new T(R,S[">"]);d.appendWhere(new C(ge,">",F))}if("!="in S&&S["!="]!==void 0){let R=`${y}_and_${A}_neq`,F=new T(R,S["!="]);d.appendWhere(new C(ge,"!=",F))}if("<>"in S&&S["<>"]!==void 0){let R=`${y}_and_${A}_ne`,F=new T(R,S["<>"]);d.appendWhere(new C(ge,"<>",F))}if("<="in S&&S["<="]!==void 0){let R=`${y}_and_${A}_le`,F=new T(R,S["<="]);d.appendWhere(new C(ge,"<=",F))}if(">="in S&&S[">="]!==void 0){let R=`${y}_and_${A}_ge`,F=new T(R,S[">="]);d.appendWhere(new C(ge,">=",F))}}}function m(d,y,L,E,O,N){let A=[];for(let S=0;S<L.length;S++){let I=L[S],Pt=I.column||y,ge=O.find(U=>E(U.name)===E(Pt));if(!ge)throw new Error(`Column '${Pt}' not found in query for OR condition`);let R=ge.value,F=[];if("="in I&&I["="]!==void 0){let U=`${y}_or_${S}_eq`,z=new T(U,I["="]);F.push(new C(R,"=",z))}if("min"in I&&I.min!==void 0){let U=`${y}_or_${S}_min`,z=new T(U,I.min);F.push(new C(R,">=",z))}if("max"in I&&I.max!==void 0){let U=`${y}_or_${S}_max`,z=new T(U,I.max);F.push(new C(R,"<=",z))}if("like"in I&&I.like!==void 0){let U=`${y}_or_${S}_like`,z=new T(U,I.like);F.push(new C(R,"like",z))}if("ilike"in I&&I.ilike!==void 0){let U=`${y}_or_${S}_ilike`,z=new T(U,I.ilike);F.push(new C(R,"ilike",z))}if("in"in I&&I.in!==void 0){let z=I.in.map((Er,br)=>new T(`${y}_or_${S}_in_${br}`,Er));F.push(new C(R,"in",new H(new K(z))))}if("any"in I&&I.any!==void 0){let U=`${y}_or_${S}_any`,z=new T(U,I.any);F.push(new C(R,"=",new j(null,"any",z,null)))}if("<"in I&&I["<"]!==void 0){let U=`${y}_or_${S}_lt`,z=new T(U,I["<"]);F.push(new C(R,"<",z))}if(">"in I&&I[">"]!==void 0){let U=`${y}_or_${S}_gt`,z=new T(U,I[">"]);F.push(new C(R,">",z))}if("!="in I&&I["!="]!==void 0){let U=`${y}_or_${S}_neq`,z=new T(U,I["!="]);F.push(new C(R,"!=",z))}if("<>"in I&&I["<>"]!==void 0){let U=`${y}_or_${S}_ne`,z=new T(U,I["<>"]);F.push(new C(R,"<>",z))}if("<="in I&&I["<="]!==void 0){let U=`${y}_or_${S}_le`,z=new T(U,I["<="]);F.push(new C(R,"<=",z))}if(">="in I&&I[">="]!==void 0){let U=`${y}_or_${S}_ge`,z=new T(U,I[">="]);F.push(new C(R,">=",z))}if(F.length>0){let U=F[0];for(let z=1;z<F.length;z++)U=new C(U,"and",F[z]);F.length>1?A.push(new H(U)):A.push(U)}}if(A.length>0){let S=A[0];for(let I=1;I<A.length;I++)S=new C(S,"or",A[I]);d.appendWhere(new H(S))}}function h(d,y,L){Object.keys(d).forEach(E=>{if(!y.includes(E))throw new Error(`Unsupported operator '${E}' for state key '${L}'`)})}function w(d,y,L,E){let O=new T(L,E);d.appendWhere(new C(y,"=",O))}function b(d,y,L,E){let O=[];if("="in E){let N=new T(L,E["="]);O.push(new C(y,"=",N))}if("min"in E){let N=new T(L+"_min",E.min);O.push(new C(y,">=",N))}if("max"in E){let N=new T(L+"_max",E.max);O.push(new C(y,"<=",N))}if("like"in E){let N=new T(L+"_like",E.like);O.push(new C(y,"like",N))}if("ilike"in E){let N=new T(L+"_ilike",E.ilike);O.push(new C(y,"ilike",N))}if("in"in E){let A=E.in.map((S,I)=>new T(`${L}_in_${I}`,S));O.push(new C(y,"in",new H(new K(A))))}if("any"in E){let N=new T(L+"_any",E.any);O.push(new C(y,"=",new j(null,"any",N,null)))}if("<"in E){let N=new T(L+"_lt",E["<"]);O.push(new C(y,"<",N))}if(">"in E){let N=new T(L+"_gt",E[">"]);O.push(new C(y,">",N))}if("!="in E){let N=new T(L+"_neq",E["!="]);O.push(new C(y,"!=",N))}if("<>"in E){let N=new T(L+"_ne",E["<>"]);O.push(new C(y,"<>",N))}if("<="in E){let N=new T(L+"_le",E["<="]);O.push(new C(y,"<=",N))}if(">="in E){let N=new T(L+"_ge",E[">="]);O.push(new C(y,">=",N))}if(O.length===1)d.appendWhere(O[0]);else if(O.length>1){let N=O[0];for(let A=1;A<O.length;A++)N=new C(N,"and",O[A]);d.appendWhere(new H(N))}}return e}isOrCondition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"or"in e}isAndCondition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"and"in e}isExplicitColumnMapping(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"column"in e&&!("or"in e)}isValidatableObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}hasColumnMapping(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"column"in e}isSimpleValue(e){return e===null||typeof e!="object"||Array.isArray(e)||e instanceof Date}processStateParameter(e,t,n,r,i,s,a,l,u,c,m,h){if(this.isOrCondition(t)){let w=t.or;if(w&&w.length>0){let b=this.findTargetQueryForLogicalCondition(r,n,e,w),d=this.getAllAvailableColumns(b,i);l(b,e,w,s,d,i);return}}if(this.isAndCondition(t)){let w=t.and;if(w&&w.length>0){let b=this.findTargetQueryForLogicalCondition(r,n,e,w),d=this.getAllAvailableColumns(b,i);u(b,e,w,s,d,i);return}}if(this.isExplicitColumnMapping(t)){let w=t.column;if(w){let b=r.find(n,w);if(b.length===0)throw new Error(`Explicit column '${w}' not found in query`);for(let d of b){let L=this.getAllAvailableColumns(d,i).find(E=>s(E.name)===s(w));if(!L)throw new Error(`Explicit column '${w}' not found in query`);this.isValidatableObject(t)&&h(t,a,e),m(d,L.value,e,t)}return}}this.processRegularColumnCondition(e,t,n,r,i,s,a,c,m,h)}processRegularColumnCondition(e,t,n,r,i,s,a,l,u,c){let m=r.find(n,e);if(m.length===0)throw new Error(`Column '${e}' not found in query`);for(let h of m){let w=this.getAllAvailableColumns(h,i),b=w.find(E=>s(E.name)===s(e));if(!b)throw new Error(`Column '${e}' not found in query`);let d=b.value;this.isValidatableObject(t)&&c(t,a,e);let y=d,L=e;if(this.hasColumnMapping(t)){let E=t.column;if(E){let O=w.find(N=>s(N.name)===s(E));O&&(y=O.value,L=E)}}this.isSimpleValue(t)?l(h,y,L,t):u(h,y,L,t)}}findTargetQueryForLogicalCondition(e,t,n,r){let i=r.map(a=>a.column||n).filter((a,l,u)=>u.indexOf(a)===l);for(let a of i){let l=e.find(t,a);if(l.length>0)return l[0]}let s=r===r.or?"OR":"AND";throw new Error(`None of the ${s} condition columns [${i.join(", ")}] found in query`)}getAllAvailableColumns(e,t){let n=t.collect(e),r=this.collectCTEColumns(e);return[...n,...r]}collectCTEColumns(e){let t=[];if(e.withClause)for(let n of e.withClause.tables)try{let r=this.collectColumnsFromSelectQuery(n.query);t.push(...r)}catch(r){console.warn(`Failed to collect columns from CTE '${n.getSourceAliasName()}':`,r)}return t}collectColumnsFromSelectQuery(e){return e instanceof g?new Oe(this.tableColumnResolver).collect(e):e instanceof W?this.collectColumnsFromSelectQuery(e.left):[]}};var _n=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=Q.parse(e)),!(e instanceof g))throw new Error("Complex queries are not supported for ORDER BY removal");return new g({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=Q.parse(e)),!(e instanceof g))throw new Error("Complex queries are not supported for sorting");let r=new Oe(this.tableColumnResolver).collect(e);for(let l of Object.keys(t))if(!r.find(c=>c.name===l))throw new Error(`Column or alias '${l}' not found in current query`);let i=[];for(let[l,u]of Object.entries(t)){let c=r.find(d=>d.name===l);if(!c)continue;let m=c.value;this.validateSortCondition(l,u);let h;u.desc?h="desc":h="asc";let w=null;u.nullsFirst?w="first":u.nullsLast&&(w="last");let b=new Ie(m,h,w);i.push(b)}let s=[];e.orderByClause?s=[...e.orderByClause.order,...i]:s=i;let a=s.length>0?new le(s):null;return new g({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 zn=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=Q.parse(e)),!(e instanceof g))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,r=new oe(new T("paging_limit",t.pageSize)),i=new Le(new T("paging_offset",n));return new g({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:r,offsetClause:i,fetchClause:e.fetchClause,forClause:e.forClause})}static removePagination(e){if(typeof e=="string"&&(e=Q.parse(e)),!(e instanceof g))throw new Error("Complex queries are not supported for pagination removal");return new g({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 Nt=class{static extractParameterNames(e){return ot.collect(e).map(n=>n.name.value)}static hasParameter(e,t){return this.extractParameterNames(e).includes(t)}static separateFilters(e,t){let n=this.extractParameterNames(e),r={},i={};for(let[s,a]of Object.entries(t))n.includes(s)?r[s]=a:i[s]=a;return{hardcodedParams:r,dynamicFilters:i}}};var Gn=class{constructor(e={}){this.options={requireAllParameters:!0,...e}}bind(e,t){let n=e,r=Nt.extractParameterNames(n);if(this.options.requireAllParameters){let i=r.filter(s=>!(s in t)||t[s]===void 0);if(i.length>0)throw new Error(`Missing values for required parameters: ${i.join(", ")}`)}for(let[i,s]of Object.entries(t))if(r.includes(i))try{He.set(n,i,s)}catch(a){throw new Error(`Failed to bind parameter '${i}': ${a instanceof Error?a.message:"Unknown error"}`)}return n}bindToSimpleQuery(e,t){return this.bind(e,t)}};var gr=class{constructor(e){this.tableColumnResolver=e}buildQuery(e,t={}){let n;try{n=Q.parse(e)}catch(i){throw new Error(`Failed to parse SQL: ${i instanceof Error?i.message:"Unknown error"}`)}let r=n;if(t.filter&&Object.keys(t.filter).length>0){let{hardcodedParams:i,dynamicFilters:s}=Nt.separateFilters(r,t.filter);if(Object.keys(i).length>0&&(r=new Gn({requireAllParameters:!1}).bind(r,i)),Object.keys(s).length>0){let a=new Kn(this.tableColumnResolver),l=Fe.buildSimpleQuery(r);r=a.inject(l,s)}}if(t.sort&&Object.keys(t.sort).length>0){let i=new _n(this.tableColumnResolver),s=Fe.buildSimpleQuery(r);r=i.inject(s,t.sort)}if(t.paging){let{page:i=1,pageSize:s}=t.paging;if(s!==void 0){let a=new zn,l={page:i,pageSize:s},u=Fe.buildSimpleQuery(r);r=a.inject(u,l)}}if(t.serialize&&typeof t.serialize=="object"){let i=new Mn,s=Fe.buildSimpleQuery(r);r=i.buildJsonQuery(s,t.serialize)}return r}buildFilteredQuery(e,t){return this.buildQuery(e,{filter:t})}buildSortedQuery(e,t){return this.buildQuery(e,{sort:t})}buildPaginatedQuery(e,t){return this.buildQuery(e,{paging:t})}buildSerializedQuery(e,t){return this.buildQuery(e,{serialize:t})}validateSql(e){try{return Q.parse(e),!0}catch(t){throw new Error(`Invalid SQL: ${t instanceof Error?t.message:"Unknown error"}`)}}};var Sr=class{static validate(e,t){let n=this.extractStructureFromJsonMapping(e);return this.compareStructures(n,t)}static validateStrict(e,t){let n=this.validate(e,t);if(!n.isValid){let r=["JsonMapping validation failed:",...n.errors].join(`
|
|
60
60
|
`);throw new Error(r)}}static extractStructureFromJsonMapping(e){let t={};return e.rootEntity&&e.rootEntity.columns&&Object.keys(e.rootEntity.columns).forEach(n=>{t[n]="primitive"}),e.nestedEntities&&e.nestedEntities.filter(n=>n.parentId===e.rootEntity.id).forEach(n=>{n.propertyName&&n.columns&&(n.relationshipType==="object"?t[n.propertyName]=this.extractNestedEntityStructure(n,e):n.relationshipType==="array"&&(t[n.propertyName]=[this.extractNestedEntityStructure(n,e)]))}),t}static extractNestedEntityStructure(e,t){let n={};return e.columns&&Object.keys(e.columns).forEach(r=>{n[r]="primitive"}),t.nestedEntities&&t.nestedEntities.filter(r=>r.parentId===e.id).forEach(r=>{r.propertyName&&r.columns&&(r.relationshipType==="object"?n[r.propertyName]=this.extractNestedEntityStructure(r,t):r.relationshipType==="array"&&(n[r.propertyName]=[this.extractNestedEntityStructure(r,t)]))}),n}static compareStructures(e,t,n=""){let r=[],i=[],s=[];if(e==="primitive"&&t==="primitive")return{isValid:!0,errors:[],missingProperties:[],extraProperties:[]};if(Array.isArray(t)&&Array.isArray(e)){if(t.length>0&&e.length>0){let u=this.compareStructures(e[0],t[0],`${n}[]`);r.push(...u.errors),i.push(...u.missingProperties),s.push(...u.extraProperties)}return{isValid:r.length===0,errors:r,missingProperties:i,extraProperties:s}}if(typeof e!="object"||typeof t!="object"||Array.isArray(e)||Array.isArray(t)||e===null||t===null)return{isValid:!0,errors:[],missingProperties:[],extraProperties:[]};let a=e,l=t;return Object.keys(l).forEach(u=>{let c=n?`${n}.${u}`:u;if(!(u in a)){i.push(c),r.push(`Missing property: ${c}`);return}let m=a[u],h=l[u],w=this.compareStructures(m,h,c);r.push(...w.errors),i.push(...w.missingProperties),s.push(...w.extraProperties)}),Object.keys(a).forEach(u=>{let c=n?`${n}.${u}`:u;u in l||s.push(c)}),{isValid:r.length===0,errors:r,missingProperties:i,extraProperties:s}}static validateAgainstSample(e,t){let n=this.extractStructureFromSample(t);return this.validate(e,n)}static validateAgainstSampleStrict(e,t){let n=this.validateAgainstSample(e,t);if(!n.isValid){let r=["JsonMapping validation against sample object failed:",...n.errors].join(`
|
|
61
|
-
`);throw new Error(r)}}static extractStructureFromSample(e){if(e==null)return"primitive";if(Array.isArray(e))return e.length===0?[]:[this.extractStructureFromSample(e[0])];if(typeof e=="object"){let t={};return Object.keys(e).forEach(n=>{t[n]=this.extractStructureFromSample(e[n])}),t}return"primitive"}};var
|
|
61
|
+
`);throw new Error(r)}}static extractStructureFromSample(e){if(e==null)return"primitive";if(Array.isArray(e))return e.length===0?[]:[this.extractStructureFromSample(e[0])];if(typeof e=="object"){let t={};return Object.keys(e).forEach(n=>{t[n]=this.extractStructureFromSample(e[n])}),t}return"primitive"}};var Jt=class{constructor(e){this.schemas=e,this.validateSchemas()}validateSchemas(){let e=Object.keys(this.schemas),t=[];if(Object.entries(this.schemas).forEach(([n,r])=>{Object.entries(r.columns).filter(([s,a])=>a.isPrimaryKey).map(([s,a])=>s).length===0&&t.push(`Table '${n}' has no primary key defined`),r.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(([i,s])=>{n[i]=s.jsonAlias||s.name});let r=[];return t.relationships?.forEach(i=>{let s=this.schemas[i.table];if(!s)throw new Error(`Related table '${i.table}' not found in schema registry`);let a={};Object.entries(s.columns).forEach(([u,c])=>{a[u]=c.jsonAlias||c.name});let l=i.type;r.push({id:i.propertyName,name:s.displayName||i.table,parentId:e,propertyName:i.propertyName,relationshipType:l,columns:a})}),{rootName:e,rootEntity:{id:e,name:t.displayName||e,columns:n},nestedEntities:r,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(([r,i])=>i.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(([r,i])=>{i.foreignKey&&n.push({column:r,referencedTable:i.foreignKey.table,referencedColumn:i.foreignKey.column})}),n}};function ay(o){return new Jt(o)}function ly(o){return new Jt(o).createTableColumnResolver()}function uy(o,e){return new Jt(o).createJsonMapping(e)}var vr=class{static{this.SQL_COMMANDS=new Set(["select","from","where","and","or","order","by","group","having","limit","offset","as","on","inner","left","right","join","union","insert","update","delete","into","values","set"])}static findLexemeAtPosition(e,t){if(t<0||t>=e.length)return null;let n=this.getAllLexemesWithPosition(e);for(let r of n)if(r.position&&t>=r.position.startPosition&&t<r.position.endPosition)return r;return null}static getAllLexemesWithPosition(e){if(!e?.trim())return[];try{let t=[],n=0;for(;n<e.length&&(n=this.skipWhitespace(e,n),!(n>=e.length));){let r=this.parseNextToken(e,n);r?(t.push(r),n=r.position.endPosition):n++}return t}catch{return[]}}static skipWhitespace(e,t){for(;t<e.length&&/\s/.test(e[t]);)t++;return t}static parseNextToken(e,t){let n=e[t];return n==="'"||n==='"'?this.parseStringLiteral(e,t):/[=<>!+\-*/%().*]/.test(n)?this.parseOperator(e,t):n===","?this.createLexeme(16,",",t,t+1):/[a-zA-Z0-9_]/.test(n)?this.parseWordToken(e,t):null}static parseStringLiteral(e,t){let n=e[t],r=t+1,i=n;for(;r<e.length&&e[r]!==n;)i+=e[r++];return r<e.length&&(i+=e[r++]),this.createLexeme(1,i,t,r)}static parseOperator(e,t){let n=e[t],r=t+1;r<e.length&&/[=<>!]/.test(e[r])&&/[=<>!]/.test(n)&&(n+=e[r++]);let i=this.getOperatorTokenType(n);return this.createLexeme(i,n,t,r)}static parseWordToken(e,t){let n=t,r="";for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)r+=e[n++];let i=this.getWordTokenType(r,e,n),s=this.shouldLowercase(i)?r.toLowerCase():r;return this.createLexeme(i,s,t,n)}static getOperatorTokenType(e){switch(e){case"(":return 4;case")":return 8;case"*":return 64;default:return 2}}static getWordTokenType(e,t,n){let r=e.toLowerCase();if(this.SQL_COMMANDS.has(r))return 128;let i=this.skipWhitespace(t,n);return i<t.length&&t[i]==="("?2048:64}static shouldLowercase(e){return!!(e&128)||!!(e&2)||!!(e&2048)}static createLexeme(e,t,n,r){return{type:e,value:t,comments:null,position:{startPosition:n,endPosition:r}}}};export{fe as ArrayExpression,et as ArrayIndexExpression,Ce as ArrayQueryExpression,Ze as ArraySliceExpression,ye as BetweenExpression,C as BinaryExpression,W as BinarySelectQuery,ee as CTECollector,Bn as CTEComposer,lt as CTEDependencyAnalyzer,gt as CTEDisabler,Ge as CTENormalizer,At as CTENotFoundError,hr as CTEQueryDecomposer,fr as CTERenamer,ie as CaseExpression,xe as CaseKeyValuePair,ae as CastExpression,v as ColumnReference,Rn as ColumnReferenceCollector,Fn as CommentEditor,Lt as DuplicateCTEError,mr as DuplicateDetectionMode,gr as DynamicQueryBuilder,at as Formatter,j as FunctionCall,x as IdentifierString,Se as InlineQuery,Ye as InsertQuery,dr as InsertQueryParser,Et as InvalidCTENameError,Rt as JsonMappingConverter,Sr as JsonSchemaValidator,vr as LexemeCursor,G as LiteralValue,T as ParameterExpression,H as ParenExpression,Mn as PostgresJsonQueryBuilder,Ve as QualifiedName,Fe as QueryBuilder,wr as QueryFlowDiagramGenerator,V as RawString,Ln as SchemaCollector,Jt as SchemaManager,Q as SelectQueryParser,Re as SelectValueCollector,Oe as SelectableColumnCollector,g as SimpleSelectQuery,je as SqlFormatter,zn as SqlPaginationInjector,Kn as SqlParamInjector,An as SqlSchemaValidator,_n as SqlSortInjector,We as StringSpecifierExpression,be as SwitchCaseArgument,Qn as TableSchema,it as TableSourceCollector,M as TokenType,ke as TupleExpression,Dn as TypeTransformationPostProcessor,Yf as TypeTransformers,Te as TypeValue,te as UnaryExpression,bt as UpstreamSelectQueryFinder,xu as VALID_PRESETS,K as ValueList,he as ValuesQuery,ar as WindowFrameBound,dt as WindowFrameBoundStatic,ht as WindowFrameBoundaryValue,Ee as WindowFrameExpression,Je as WindowFrameSpec,or as WindowFrameType,Wn as convertColumnsToLegacy,er as convertModelDrivenMapping,$f as convertToLegacyJsonMapping,uy as createJsonMappingFromSchema,ay as createSchemaManager,ly as createTableColumnResolver,yr as extractTypeProtection,_r as isLegacyFormat,qr as isModelDrivenFormat,Kr as isUnifiedFormat,Jr as processJsonMapping,Cr as toLegacyMapping,Hf as transformDatabaseResult,Ur as unifyJsonMapping,Dr as validateModelDrivenMapping};
|
|
62
62
|
//# sourceMappingURL=index.min.js.map
|