rawsql-ts 0.11.2-beta → 0.11.4-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index.min.js +14 -14
- package/dist/esm/index.min.js.map +4 -4
- package/dist/esm/src/index.js +2 -0
- package/dist/esm/src/index.js.map +1 -1
- package/dist/esm/src/models/BinarySelectQuery.js +9 -0
- package/dist/esm/src/models/BinarySelectQuery.js.map +1 -1
- package/dist/esm/src/models/CTEError.js +31 -0
- package/dist/esm/src/models/CTEError.js.map +1 -0
- package/dist/esm/src/models/Clause.js +2 -1
- package/dist/esm/src/models/Clause.js.map +1 -1
- package/dist/esm/src/models/HintClause.js +37 -0
- package/dist/esm/src/models/HintClause.js.map +1 -0
- package/dist/esm/src/models/SelectQuery.js +1 -0
- package/dist/esm/src/models/SelectQuery.js.map +1 -1
- package/dist/esm/src/models/SimpleSelectQuery.js +229 -0
- package/dist/esm/src/models/SimpleSelectQuery.js.map +1 -1
- package/dist/esm/src/models/ValuesQuery.js +1 -1
- package/dist/esm/src/models/ValuesQuery.js.map +1 -1
- package/dist/esm/src/parsers/FromClauseParser.js +7 -0
- package/dist/esm/src/parsers/FromClauseParser.js.map +1 -1
- package/dist/esm/src/parsers/SelectClauseParser.js +13 -1
- package/dist/esm/src/parsers/SelectClauseParser.js.map +1 -1
- package/dist/esm/src/parsers/SelectQueryParser.js +10 -0
- package/dist/esm/src/parsers/SelectQueryParser.js.map +1 -1
- package/dist/esm/src/parsers/SqlPrintTokenParser.js +39 -4
- package/dist/esm/src/parsers/SqlPrintTokenParser.js.map +1 -1
- package/dist/esm/src/parsers/WhereClauseParser.js +5 -0
- package/dist/esm/src/parsers/WhereClauseParser.js.map +1 -1
- package/dist/esm/src/transformers/DynamicQueryBuilder.js +16 -5
- package/dist/esm/src/transformers/DynamicQueryBuilder.js.map +1 -1
- package/dist/esm/src/transformers/QueryBuilder.js +2 -0
- package/dist/esm/src/transformers/QueryBuilder.js.map +1 -1
- package/dist/esm/src/transformers/SqlFormatter.js.map +1 -1
- package/dist/esm/src/transformers/SqlParameterBinder.js +63 -0
- package/dist/esm/src/transformers/SqlParameterBinder.js.map +1 -0
- package/dist/esm/src/transformers/SqlPrinter.js +12 -2
- package/dist/esm/src/transformers/SqlPrinter.js.map +1 -1
- package/dist/esm/src/utils/CommentUtils.js +65 -0
- package/dist/esm/src/utils/CommentUtils.js.map +1 -0
- package/dist/esm/src/utils/ParameterDetector.js +49 -0
- package/dist/esm/src/utils/ParameterDetector.js.map +1 -0
- package/dist/esm/tsconfig.browser.tsbuildinfo +1 -1
- package/dist/esm/types/src/index.d.ts +3 -0
- package/dist/esm/types/src/models/BinarySelectQuery.d.ts +7 -0
- package/dist/esm/types/src/models/CTEError.d.ts +21 -0
- package/dist/esm/types/src/models/Clause.d.ts +3 -1
- package/dist/esm/types/src/models/HintClause.d.ts +24 -0
- package/dist/esm/types/src/models/SelectQuery.d.ts +12 -0
- package/dist/esm/types/src/models/SimpleSelectQuery.d.ts +166 -2
- package/dist/esm/types/src/models/ValuesQuery.d.ts +1 -1
- package/dist/esm/types/src/parsers/SqlPrintTokenParser.d.ts +5 -0
- package/dist/esm/types/src/transformers/SqlFormatter.d.ts +2 -0
- package/dist/esm/types/src/transformers/SqlParameterBinder.d.ts +36 -0
- package/dist/esm/types/src/transformers/SqlPrinter.d.ts +6 -0
- package/dist/esm/types/src/utils/CommentUtils.d.ts +21 -0
- package/dist/esm/types/src/utils/ParameterDetector.d.ts +32 -0
- package/dist/index.min.js +14 -14
- package/dist/index.min.js.map +4 -4
- package/dist/src/index.d.ts +3 -0
- package/dist/src/index.js +4 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/models/BinarySelectQuery.d.ts +7 -0
- package/dist/src/models/BinarySelectQuery.js +9 -0
- package/dist/src/models/BinarySelectQuery.js.map +1 -1
- package/dist/src/models/CTEError.d.ts +21 -0
- package/dist/src/models/CTEError.js +37 -0
- package/dist/src/models/CTEError.js.map +1 -0
- package/dist/src/models/Clause.d.ts +3 -1
- package/dist/src/models/Clause.js +2 -1
- package/dist/src/models/Clause.js.map +1 -1
- package/dist/src/models/HintClause.d.ts +24 -0
- package/dist/src/models/HintClause.js +41 -0
- package/dist/src/models/HintClause.js.map +1 -0
- package/dist/src/models/SelectQuery.d.ts +12 -0
- package/dist/src/models/SelectQuery.js +5 -1
- package/dist/src/models/SelectQuery.js.map +1 -1
- package/dist/src/models/SimpleSelectQuery.d.ts +166 -2
- package/dist/src/models/SimpleSelectQuery.js +229 -0
- package/dist/src/models/SimpleSelectQuery.js.map +1 -1
- package/dist/src/models/ValuesQuery.d.ts +1 -1
- package/dist/src/models/ValuesQuery.js +1 -1
- package/dist/src/models/ValuesQuery.js.map +1 -1
- package/dist/src/parsers/FromClauseParser.js +7 -0
- package/dist/src/parsers/FromClauseParser.js.map +1 -1
- package/dist/src/parsers/SelectClauseParser.js +13 -1
- package/dist/src/parsers/SelectClauseParser.js.map +1 -1
- package/dist/src/parsers/SelectQueryParser.js +10 -0
- package/dist/src/parsers/SelectQueryParser.js.map +1 -1
- package/dist/src/parsers/SqlPrintTokenParser.d.ts +5 -0
- package/dist/src/parsers/SqlPrintTokenParser.js +39 -4
- package/dist/src/parsers/SqlPrintTokenParser.js.map +1 -1
- package/dist/src/parsers/WhereClauseParser.js +5 -0
- package/dist/src/parsers/WhereClauseParser.js.map +1 -1
- package/dist/src/transformers/DynamicQueryBuilder.js +16 -5
- package/dist/src/transformers/DynamicQueryBuilder.js.map +1 -1
- package/dist/src/transformers/QueryBuilder.js +2 -0
- package/dist/src/transformers/QueryBuilder.js.map +1 -1
- package/dist/src/transformers/SqlFormatter.d.ts +2 -0
- package/dist/src/transformers/SqlFormatter.js.map +1 -1
- package/dist/src/transformers/SqlParameterBinder.d.ts +36 -0
- package/dist/src/transformers/SqlParameterBinder.js +70 -0
- package/dist/src/transformers/SqlParameterBinder.js.map +1 -0
- package/dist/src/transformers/SqlPrinter.d.ts +6 -0
- package/dist/src/transformers/SqlPrinter.js +12 -2
- package/dist/src/transformers/SqlPrinter.js.map +1 -1
- package/dist/src/utils/CommentUtils.d.ts +21 -0
- package/dist/src/utils/CommentUtils.js +69 -0
- package/dist/src/utils/CommentUtils.js.map +1 -0
- package/dist/src/utils/ParameterDetector.d.ts +32 -0
- package/dist/src/utils/ParameterDetector.js +53 -0
- package/dist/src/utils/ParameterDetector.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
package/dist/esm/index.min.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
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 qe=class extends f{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var Oe=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}},E=class extends f{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof b?this.qualifiedName.name:new b(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(e,t){super();let n=typeof t=="string"?new b(t):t;this.qualifiedName=new Ae(Bn(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},D=class extends f{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,r){super(),this.qualifiedName=new Ae(e,t),this.argument=n,this.over=r}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},An=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(An||{}),Qn=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(Qn||{}),nt=class extends f{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},rt=class extends f{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},Me=class extends f{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Le=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 B(e),this.expression=t}},y=class extends f{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new B(t),this.right=n}},G=class extends f{static{this.kind=Symbol("LiteralExpression")}constructor(e){super(),this.value=e}},T=class extends f{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new B(e),this.value=t,this.index=null}},Ce=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}},B=class extends f{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},b=class extends f{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},Y=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}},ve=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}},ge=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}},Je=class extends f{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new B(e),this.value=new G(t)}},Ee=class extends f{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new Ae(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof B?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}},xe=class extends f{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}};function Bn(s){if(s==null)return null;if(typeof s=="string")return s.trim()===""?null:[new b(s)];if(Array.isArray(s)){if(s.length===0)return null;if(typeof s[0]=="string"){let e=s.filter(t=>t.trim()!=="");return e.length===0?null:e.map(t=>new b(t))}else{let e=s.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var Ae=class extends f{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=Bn(e),typeof t=="string"?this.name=new B(t):this.name=t}toString(){let e=this.name instanceof B?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 b(t):null}},U=class extends f{static{this.kind=Symbol("SelectClause")}constructor(e,t=null){super(),this.items=e,this.distinct=t}},it=class extends f{static{this.kind=Symbol("Distinct")}constructor(){super()}},st=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}},$e=class extends f{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},ye=class extends f{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new b(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}},be=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}},M=class extends f{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof b?this.qualifiedName.name:new b(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(e,t){super();let n=typeof t=="string"?new b(t):t;this.qualifiedName=new Ae(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof B?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof B?this.qualifiedName.name.value:this.qualifiedName.name.name}},De=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 Ae(n.namespaces,n.name)}else this.qualifiedName=new Ae(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},We=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}},V=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 M?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 B(e),this.source=t,this.condition=n,this.lateral=r}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof M?this.source.table.name:null}},$=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 M?this.source.datasource.table.name:null}getSources(){let e=[this.source];if(this.joins)for(let t of this.joins)e.push(t.source);return e}},Z=class extends f{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new H(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},ee=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 Re=class extends f{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},Ue=class extends f{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},Ze=class extends f{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var Qe=class extends f{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},H=class extends f{static{this.kind=Symbol("SourceAliasExpression")}constructor(e,t){super(),this.table=new b(e),this.columns=t!==null?t.map(n=>new b(n)):null}},bt=class extends f{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new b(t):t)}},_e=class extends f{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof Ge?t:new Ge(t.column,t.value))}},Ge=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 b(n.column):n.column;this.qualifiedName=new Ae(n.namespaces,r)}else{let n=typeof e=="string"?new b(e):e;this.qualifiedName=new Ae(null,n)}this.value=t}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof b?this.qualifiedName.name:new b(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},ot=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 M?this.source.datasource.table.name:null}},He=class extends f{constructor(e,t){super(),this.source=e,this.columns=t.map(n=>new b(n))}};var R=(m=>(m[m.None=0]="None",m[m.Literal=1]="Literal",m[m.Operator=2]="Operator",m[m.OpenParen=4]="OpenParen",m[m.CloseParen=8]="CloseParen",m[m.Comma=16]="Comma",m[m.Dot=32]="Dot",m[m.Identifier=64]="Identifier",m[m.Command=128]="Command",m[m.Parameter=256]="Parameter",m[m.OpenBracket=512]="OpenBracket",m[m.CloseBracket=1024]="CloseBracket",m[m.Function=2048]="Function",m[m.StringSpecifier=4096]="StringSpecifier",m[m.Type=8192]="Type",m))(R||{});var te=class{static isWhitespace(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===32||t===9||t===10||t===13}static isDigit(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57}static isHexChar(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=97&&t<=102||t>=65&&t<=70}static isOperatorSymbol(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===43||t===45||t===42||t===47||t===37||t===126||t===64||t===35||t===94||t===38||t===58||t===33||t===60||t===62||t===61||t===124}static isDelimiter(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===46||t===44||t===40||t===41||t===91||t===93||t===123||t===125||t===59||t===32||t===9||t===10||t===13?!0:t===43||t===45||t===42||t===47||t===37||t===126||t===64||t===35||t===94||t===38||t===58||t===33||t===60||t===62||t===61||t===124}static isNamedParameterPrefix(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===64||t===58||t===36}};var oe=class s{static getDebugPositionInfo(e,t){let n=Math.max(0,t-5),r=Math.min(e.length,t+5),i=e.slice(n,r),o=" ".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 _e=class extends f{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var Qe=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}},E=class extends f{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof b?this.qualifiedName.name:new b(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(e,t){super();let n=typeof t=="string"?new b(t):t;this.qualifiedName=new Ae(Jn(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){super(),this.qualifiedName=new Ae(e,t),this.argument=n,this.over=r}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},jn=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(jn||{}),Wn=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(Wn||{}),it=class extends f{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},st=class extends f{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},Me=class extends f{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Le=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 B(e),this.expression=t}},C=class extends f{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new B(t),this.right=n}},H=class extends f{static{this.kind=Symbol("LiteralExpression")}constructor(e){super(),this.value=e}},T=class extends f{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new B(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}},B=class extends f{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},b=class extends f{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},Y=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}},ve=class extends f{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},ge=class extends f{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},Se=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}},Je=class extends f{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new B(e),this.value=new H(t)}},Ee=class extends f{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new Ae(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof B?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}},xe=class extends f{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}};function Jn(s){if(s==null)return null;if(typeof s=="string")return s.trim()===""?null:[new b(s)];if(Array.isArray(s)){if(s.length===0)return null;if(typeof s[0]=="string"){let e=s.filter(t=>t.trim()!=="");return e.length===0?null:e.map(t=>new b(t))}else{let e=s.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var Ae=class extends f{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=Jn(e),typeof t=="string"?this.name=new B(t):this.name=t}toString(){let e=this.name instanceof B?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 b(t):null}},D=class extends f{static{this.kind=Symbol("SelectClause")}constructor(e,t=null,n=[]){super(),this.items=e,this.distinct=t,this.hints=n}},ot=class extends f{static{this.kind=Symbol("Distinct")}constructor(){super()}},at=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}},$e=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 b(e),this.expression=t}},He=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}},be=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}},M=class extends f{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof b?this.qualifiedName.name:new b(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(e,t){super();let n=typeof t=="string"?new b(t):t;this.qualifiedName=new Ae(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof B?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof B?this.qualifiedName.name.value:this.qualifiedName.name.name}},Ue=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 Ae(n.namespaces,n.name)}else this.qualifiedName=new Ae(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},je=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}},R=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 M?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 B(e),this.source=t,this.condition=n,this.lateral=r}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof M?this.source.table.name:null}},$=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 M?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 G(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},ee=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 Ve=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}},tt=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}},G=class extends f{static{this.kind=Symbol("SourceAliasExpression")}constructor(e,t){super(),this.table=new b(e),this.columns=t!==null?t.map(n=>new b(n)):null}},Ft=class extends f{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new b(t):t)}},ze=class extends f{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof Ge?t:new Ge(t.column,t.value))}},Ge=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 b(n.column):n.column;this.qualifiedName=new Ae(n.namespaces,r)}else{let n=typeof e=="string"?new b(e):e;this.qualifiedName=new Ae(null,n)}this.value=t}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof b?this.qualifiedName.name:new b(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},lt=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 M?this.source.datasource.table.name:null}},Ye=class extends f{constructor(e,t){super(),this.source=e,this.columns=t.map(n=>new b(n))}};var V=(m=>(m[m.None=0]="None",m[m.Literal=1]="Literal",m[m.Operator=2]="Operator",m[m.OpenParen=4]="OpenParen",m[m.CloseParen=8]="CloseParen",m[m.Comma=16]="Comma",m[m.Dot=32]="Dot",m[m.Identifier=64]="Identifier",m[m.Command=128]="Command",m[m.Parameter=256]="Parameter",m[m.OpenBracket=512]="OpenBracket",m[m.CloseBracket=1024]="CloseBracket",m[m.Function=2048]="Function",m[m.StringSpecifier=4096]="StringSpecifier",m[m.Type=8192]="Type",m))(V||{});var te=class{static isWhitespace(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===32||t===9||t===10||t===13}static isDigit(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57}static isHexChar(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=97&&t<=102||t>=65&&t<=70}static isOperatorSymbol(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===43||t===45||t===42||t===47||t===37||t===126||t===64||t===35||t===94||t===38||t===58||t===33||t===60||t===62||t===61||t===124}static isDelimiter(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===46||t===44||t===40||t===41||t===91||t===93||t===123||t===125||t===59||t===32||t===9||t===10||t===13?!0:t===43||t===45||t===42||t===47||t===37||t===126||t===64||t===35||t===94||t===38||t===58||t===33||t===60||t===62||t===61||t===124}static isNamedParameterPrefix(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===64||t===58||t===36}};var oe=class s{static getDebugPositionInfo(e,t){let n=Math.max(0,t-5),r=Math.min(e.length,t+5),i=e.slice(n,r),o=" ".repeat(t-n)+"^";return`${i}
|
|
2
2
|
${o}`}static skipWhiteSpace(e,t){let n=e.length;for(;t+4<=n&&e.slice(t,t+4)===" ";)t+=4;for(;t<n;){let 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=s.skipWhiteSpace(e,t),t!==i)continue;let o=e.charCodeAt(t);if(o===45){let a=s.readLineComment(e,t);if(a.newPosition!==t){t=a.newPosition,a.comment&&n.push(a.comment.trim());continue}}else if(o===47){let a=s.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
|
-
${s.getDebugPositionInfo(e,t)}`);return n}static tryReadRegularIdentifier(e,t){let n=t;for(;t<e.length&&!te.isDelimiter(e[t]);)t++;if(n===t)return null;for(;t+1<e.length&&e[t]==="["&&e[t+1]==="]";)t+=2;return{identifier:e.slice(n,t),newPosition:t}}};var
|
|
4
|
+
${s.getDebugPositionInfo(e,t)}`);return n}static tryReadRegularIdentifier(e,t){let n=t;for(;t<e.length&&!te.isDelimiter(e[t]);)t++;if(n===t)return null;for(;t+1<e.length&&e[t]==="["&&e[t+1]==="]";)t+=2;return{identifier:e.slice(n,t),newPosition:t}}};var Z=class{constructor(e,t=0){this.input=e,this.position=t}getPosition(){return this.position}setPosition(e){this.position=e}isEndOfInput(e=0){return this.position+e>=this.input.length}canRead(e=0){return!this.isEndOfInput(e)}read(e){if(this.isEndOfInput())throw new Error(`Unexpected character. expect: ${e}, actual: EndOfInput, position: ${this.position}`);let t=this.input[this.position];if(t!==e)throw new Error(`Unexpected character. expect: ${e}, actual: ${t}, position: ${this.position}`);return this.position++,t}createLexeme(e,t,n=null){return e===128||e===2||e===2048?{type:e,value:t.toLowerCase(),comments:n}:{type:e,value:t,comments:n}}getDebugPositionInfo(e){return oe.getDebugPositionInfo(this.input,e)}};var Ot=class extends Z{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="*")return this.position++,this.createLexeme(64,t);let n=oe.readRegularIdentifier(this.input,this.position);return this.position=n.newPosition,this.createLexeme(64,n.identifier)}};var Ne=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=oe.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=oe.readWhiteSpaceAndComment(e,n.newPosition).position,this.isEndOfInput(e,t))return r===2?{keyword:i,newPosition:t}:null;for(;this.canParse(e,t);){let o=r,a=oe.tryReadRegularIdentifier(e,t);if(a!==null){if(r=this.trie.pushLexeme(a.identifier.toLowerCase()),r===0){if(o===2)break;return null}if(i+=" "+a.identifier,t=oe.readWhiteSpaceAndComment(e,a.newPosition).position,r===3)break}else{if(o===2)break;return null}}return{keyword:i,newPosition:t}}};var Fe=class{constructor(e){this.root=new Map;this.hasEndProperty=!1;this.hasMoreProperties=!1;for(let t of e)this.addKeyword(t);this.currentNode=this.root}addKeyword(e){let t=this.root;for(let n of e)t.has(n)||t.set(n,new Map),t=t.get(n);t.set("__end__",!0)}reset(){this.currentNode=this.root,this.hasEndProperty=!1,this.hasMoreProperties=!1}pushLexeme(e){return this.currentNode.has(e)?(this.currentNode=this.currentNode.get(e),this.hasEndProperty=this.currentNode.has("__end__"),this.hasMoreProperties=this.currentNode.size>(this.hasEndProperty?1:0),this.hasEndProperty&&!this.hasMoreProperties?3:this.hasEndProperty&&this.hasMoreProperties?2:1):0}};var tr=[["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"]],nr=new Fe(tr),Fn=new Ne(nr),Qt=class extends Z{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position],n=this.tryReadKeyword();if(n)return n;if(t==="."&&this.canRead(1)&&te.isDigit(this.input[this.position+1]))return this.createLexeme(1,this.readDigit());if(t==="'"){let r=this.readSingleQuotedString(!1);return this.createLexeme(1,r)}if(te.isDigit(t))return this.createLexeme(1,this.readDigit());if((t==="+"||t==="-")&&this.determineSignOrOperator(e)==="sign"){let r=t;this.position++;let i=this.position;for(;this.canRead()&&te.isWhitespace(this.input[this.position]);)this.position++;if(this.canRead()&&(te.isDigit(this.input[this.position])||this.input[this.position]==="."&&this.canRead(1)&&te.isDigit(this.input[this.position+1])))return this.createLexeme(1,r==="-"?r+this.readDigit():this.readDigit());this.position=i-1}return null}tryReadKeyword(){let e=Fn.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 o=this.input[this.position];if(te.isDigit(o)||i&&te.isHexChar(o))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(!te.isDigit(r))break;this.position++}if(e===this.position)throw new Error(`Unexpected character. position: ${e}
|
|
5
5
|
${this.getDebugPositionInfo(e)}`);return this.input[e]==="."?"0"+this.input.slice(e,this.position):this.input.slice(e,this.position)}readSingleQuotedString(e){let t=this.position,n=!1;for(this.read("'");this.canRead();){let 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}
|
|
6
|
-
${this.getDebugPositionInfo(t)}`);return e?this.input.slice(t,this.position):this.input.slice(t+1,this.position-1)}};var
|
|
7
|
-
${this.getDebugPositionInfo(t)}`);return this.position++,this.input.slice(t+1,this.position-1)}};var N=class{constructor(e){this.input=e,this.position=0,this.readerManager=new
|
|
8
|
-
${this.getDebugPositionInfo(this.position)}`);this.position=this.readerManager.getMaxPosition();let l=this.readComment();this.position=l.position,a.type&16||a.type&2?l.lines.length>0&&i.push(...l.lines):((i.length>0||l.lines.length>0)&&this.addCommentsToToken(a,i,l.lines),i=[]),t[n++]=a,o=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 s{static parseFromLexeme(e,t){let{identifiers:n,newIndex:r}=s.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:i,name:o}=s.extractNamespacesAndName(n),a=0;return r>t&&(a=e[r-1].type),{namespaces:i,name:new b(o),newIndex:r,lastTokenType:a}}static parse(e){let n=new N(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 Vt=class{static parseFromLexeme(e,t){let{namespaces:n,name:r,newIndex:i}=ke.parseFromLexeme(e,t);return{value:new E(n,r),newIndex:i}}};var Ct=class{static parseFromLexeme(e,t){let n=t,r=e[n].value,i,o=xn.parse(r.toLowerCase(),0);if(o){let l=new B(o.keyword);return n++,{value:l,newIndex:n}}return/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(r)?i=Number(r):r.startsWith("'")&&r.endsWith("'")?i=r.slice(1,-1):i=r,n++,{value:new G(i),newIndex:n}}};var Rt=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=W.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 Oe(r.value),newIndex:n}}else{let r=k.parseArgument(4,8,e,t);return n=r.newIndex,{value:new Y(r.value),newIndex:n}}}};var Mt=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 E(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 $t=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 Wt=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 Je(r,i),newIndex:n}}};var jt=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],o=this.parseSwitchCaseArgument(e,n,i);return n=o.newIndex,{value:new le(null,o.value),newIndex:n}}static parseSwitchCaseArgument(e,t,n){let r=t,i=[...n],o=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);o=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 Ce(i,o),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 at=class{static parse(e){let n=new N(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 o=this.parseItem(e,n);r.push(o.value),n=o.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 o=n>=e.length?null:e[n].value==="asc"?(n++,"asc"):e[n].value==="desc"?(n++,"desc"):null,a=n>=e.length?null:e[n].value==="nulls first"?(n++,"first"):e[n].value==="nulls last"?(n++,"last"):null;return o===null&&a===null?{value:i,newIndex:n}:{value:new be(i,o,a),newIndex:n}}};var Jt=class{static parse(e){let n=new N(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 o=k.parseFromLexeme(e,n);r.push(o.value),n=o.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 $e(r[0]),newIndex:n}:{value:new $e(new _(r)),newIndex:n}}};var lt=class{static parse(e){let n=new N(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,o=null;if(n<e.length&&e[n].value==="partition by"){let a=Jt.parseFromLexeme(e,n);r=a.value,n=a.newIndex}if(n<e.length&&e[n].value==="order by"){let a=at.parseFromLexeme(e,n);i=a.value,n=a.newIndex}if(n<e.length&&this.isFrameTypeKeyword(e[n].value)){let a=this.parseFrameSpec(e,n);o=a.value,n=a.newIndex}if(n>=e.length||e[n].type!==8)throw new Error(`Syntax error at position ${n}: Missing closing parenthesis ')' for window frame. Each opening parenthesis must have a matching closing parenthesis.`);return n++,{value:new Le(r,i,o),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 o=this.parseFrameBoundary(e,n),a=o.value;if(n=o.newIndex,n>=e.length||e[n].value!=="and")throw new Error(`Syntax error at position ${n}: Expected 'AND' keyword in BETWEEN clause.`);n++;let l=this.parseFrameBoundary(e,n),u=l.value;return n=l.newIndex,{value:new Me(i,a,u),newIndex:n}}else{let o=this.parseFrameBoundary(e,n),a=o.value;return n=o.newIndex,{value:new Me(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 nt(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,o;if(i==="preceding")o=!1;else if(i==="following")o=!0;else throw new Error(`Syntax error at position ${n}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`);return n++,{value:new rt(r.value,o),newIndex:n}}else throw new Error(`Syntax error at position ${n}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`)}throw new Error(`Syntax error at position ${n}: Expected a valid frame boundary component.`)}};var wt=class{static parse(e){let n=new N(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 b(r),newIndex:n}}if(e[n].type&4)return lt.parseFromLexeme(e,n);throw new Error(`Syntax error at position ${n}: Expected a window name or opening parenthesis '(' after OVER keyword, but found "${e[n].value}".`)}};var Be=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 ve(r.value),newIndex:n}}else if(n+1<e.length&&e[n+1].type&4){n++,n++;let r=W.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 o=t;if(o<e.length&&e[o].type&2){let a=e[o].value.toLowerCase();if(!r&&a==="and"||!i&&a==="or")return null;if(o++,a==="between")return this.parseBetweenExpression(e,o,n,!1);if(a==="not between")return this.parseBetweenExpression(e,o,n,!0);if(a==="::"){let c=this.parseTypeValue(e,o);return o=c.newIndex,{value:new ue(n,c.value),newIndex:o}}let l=k.parseFromLexeme(e,o);return o=l.newIndex,{value:new y(n,a,l.value),newIndex:o}}return null}static parseBetweenExpression(e,t,n,r){let i=t,o=k.parseFromLexeme(e,i,!1);if(i=o.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 ge(n,o.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,o=r.name;if(n=r.newIndex,n<e.length&&e[n].type&4){let a=k.parseArgument(4,8,e,n);if(n=a.newIndex,n<e.length&&e[n].value==="over"){let l=wt.parseFromLexeme(e,n);return n=l.newIndex,{value:new D(i,o.name,a.value,l.value),newIndex:n}}else return{value:new D(i,o.name,a.value,null),newIndex:n}}else throw new Error(`Expected opening parenthesis after function name '${o.name}' at index ${n}`)}static parseKeywordFunction(e,t,n){let r=t,i=ke.parseFromLexeme(e,r),o=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:d}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(d)throw new Error(`Keyword '${c}' is required at index ${r}`);if(r<e.length&&e[r].type&8)if(r++,r<e.length&&e[r].value==="over"){r++;let c=wt.parseFromLexeme(e,r);return r=c.newIndex,{value:new D(o,a.name,u,c.value),newIndex:r}}else return{value:new D(o,a.name,u,null),newIndex:r};else throw new Error(`Missing closing parenthesis for function '${a.name}' at index ${r}`)}else throw new Error(`Missing opening parenthesis for function '${a.name}' at index ${r}`)}static parseTypeValue(e,t){let n=t,{namespaces:r,name:i,newIndex:o}=ke.parseFromLexeme(e,n);if(n=o,n<e.length&&e[n].type&4){let a=k.parseArgument(4,8,e,n);return n=a.newIndex,{value:new Ee(r,new B(i.name),a.value),newIndex:n}}else return{value:new Ee(r,new B(i.name)),newIndex:n}}};var Dt=class s 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),o=Math.min(t.length,n+3),a=t.slice(i,o).map((u,c)=>{let d=c+i===n?">":" ",h=R[u.type]||u.type;return`${d} ${c+i}:${u.value} [${h}]`}).join(`
|
|
9
|
-
`),
|
|
6
|
+
${this.getDebugPositionInfo(t)}`);return e?this.input.slice(t,this.position):this.input.slice(t+1,this.position-1)}};var Lt=class extends Z{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(te.isNamedParameterPrefix(t)){if(this.canRead(1)&&te.isOperatorSymbol(this.input[this.position+1]))return null;this.position++;let n=this.position;for(;this.canRead()&&!te.isDelimiter(this.input[this.position]);)this.position++;let r=this.input.slice(n,this.position);return this.createLexeme(256,t+r)}return t==="?"?(this.position++,this.createLexeme(256,t)):null}};var At=class s extends Z{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 s.SPECIAL_SYMBOL_TOKENS?(this.position++,this.createLexeme(s.SPECIAL_SYMBOL_TOKENS[t],t)):null}};var Bt=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 rr=new Fe([["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"],["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 Fe([["date"],["time"],["timestamp"],["timestamptz"],["timetz"],["interval"],["boolean"],["integer"],["bigint"],["smallint"],["numeric"],["decimal"],["real"],["double","precision"],["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),sr=new Ne(rr),or=new Ne(ir);var Rt=class extends Z{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(te.isOperatorSymbol(t)){let r=this.position;for(;this.canRead()&&te.isOperatorSymbol(this.input[this.position]);){if(this.canRead(1)){let o=this.input[this.position];if(o==="-"&&this.input[this.position+1]==="-")break;if(o==="/"&&this.input[this.position+1]==="*")break}this.position++}let i=this.input.slice(r,this.position);return this.createLexeme(2,i)}let n=or.parse(this.input,this.position);return n!==null?(this.position=n.newPosition,this.createLexeme(8258,n.keyword)):(n=sr.parse(this.input,this.position),n!==null?(this.position=n.newPosition,this.createLexeme(2,n.keyword)):null)}};var ar=new Fe([["join"],["inner","join"],["cross","join"],["left","join"],["left","outer","join"],["right","join"],["right","outer","join"],["full","join"],["full","outer","join"],["natural","join"],["natural","inner","join"],["natural","left","join"],["natural","left","outer","join"],["natural","right","join"],["natural","right","outer","join"],["natural","full","join"],["natural","full","outer","join"]]),lr=new Fe([["with"],["recursive"],["materialized"],["not","materialized"],["select"],["from"],["distinct"],["distinct","on"],["where"],["group","by"],["having"],["order","by"],["limit"],["offset"],["fetch"],["first"],["next"],["row"],["row","only"],["rows","only"],["percent"],["percent","with","ties"],["for"],["update"],["share"],["key","share"],["no","key","update"],["union"],["union","all"],["intersect"],["intersect","all"],["except"],["except","all"],["beteen"],["window"],["over"],["partition","by"],["range"],["rows"],["groups"],["current","row"],["unbounded","preceding"],["unbounded","following"],["preceding"],["following"],["on"],["using"],["lateral"],["case"],["case","when"],["when"],["then"],["else"],["end"],["insert","into"],["update"],["delete","from"],["merge","into"],["matched"],["not","matched"],["update","set"],["do","nothing"],["values"],["set"],["returning"],["create","table"],["create","temporary","table"],["tablesample"],["as"],["asc"],["desc"],["nulls","first"],["nulls","last"]]),ur=new Ne(lr),On=new Ne(ar),Vt=class extends Z{tryRead(e){if(this.isEndOfInput())return null;let t=On.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(128,t.keyword);let n=ur.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 cr=new Set(["e'","E'","x'","X'","b'","B'"]),pr=new Set(["u&'","U&'"]),Mt=class extends Z{tryRead(e){let t=this.position;return this.canRead(1)&&cr.has(this.input.slice(t,t+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(t,this.position))):this.canRead(2)&&pr.has(this.input.slice(t,t+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(t,this.position))):null}};var mr=new Fe([["grouping","sets"],["array"]]),dr=new Ne(mr),$t=class extends Z{tryRead(e){if(this.isEndOfInput())return null;let t=dr.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 hr=new Fe([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),fr=new Ne(hr),jt=class extends Z{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(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 Wt=class extends Z{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="`"){let n=this.readEscapedIdentifier("`");return this.createLexeme(64,n)}if(t==='"'){let n=this.readEscapedIdentifier('"');return this.createLexeme(64,n)}if(t==="["&&(e===null||e.value!=="array")){let n=this.readEscapedIdentifier("]");return this.createLexeme(64,n)}return null}readEscapedIdentifier(e){let t=this.position;for(this.position++;this.canRead()&&this.input[this.position]!==e;)this.position++;if(t===this.position)throw new Error(`Closing delimiter is not found. position: ${t}, delimiter: ${e}
|
|
7
|
+
${this.getDebugPositionInfo(t)}`);return this.position++,this.input.slice(t+1,this.position-1)}};var N=class{constructor(e){this.input=e,this.position=0,this.readerManager=new Bt(e).register(new Wt(e)).register(new Lt(e)).register(new Mt(e)).register(new Qt(e)).register(new At(e)).register(new Vt(e)).register(new Rt(e)).register(new jt(e)).register(new $t(e)).register(new Ot(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 o=null;for(;this.canRead()&&this.input[this.position]!==";";){let a=this.readerManager.tryRead(this.position,o);if(a===null)throw new Error(`Unexpected character. actual: ${this.input[this.position]}, position: ${this.position}
|
|
8
|
+
${this.getDebugPositionInfo(this.position)}`);this.position=this.readerManager.getMaxPosition();let u=this.readComment();this.position=u.position,a.type&16||a.type&2?u.lines.length>0&&i.push(...u.lines):((i.length>0||u.lines.length>0)&&this.addCommentsToToken(a,i,u.lines),i=[]),t[n++]=a,o=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 s{static parseFromLexeme(e,t){let{identifiers:n,newIndex:r}=s.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:i,name:o}=s.extractNamespacesAndName(n),a=0;return r>t&&(a=e[r-1].type),{namespaces:i,name:new b(o),newIndex:r,lastTokenType:a}}static parse(e){let n=new N(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 Jt=class{static parseFromLexeme(e,t){let{namespaces:n,name:r,newIndex:i}=ke.parseFromLexeme(e,t);return{value:new E(n,r),newIndex:i}}};var St=class{static parseFromLexeme(e,t){let n=t,r=e[n].value,i,o=Fn.parse(r.toLowerCase(),0);if(o){let u=new B(o.keyword);return n++,{value:u,newIndex:n}}return/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(r)?i=Number(r):r.startsWith("'")&&r.endsWith("'")?i=r.slice(1,-1):i=r,n++,{value:new H(i),newIndex:n}}};var Ut=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=j.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 Qe(r.value),newIndex:n}}else{let r=k.parseArgument(4,8,e,t);return n=r.newIndex,{value:new Y(r.value),newIndex:n}}}};var Dt=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 E(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 Kt=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 qt=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 Je(r,i),newIndex:n}}};var _t=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],o=this.parseSwitchCaseArgument(e,n,i);return n=o.newIndex,{value:new le(null,o.value),newIndex:n}}static parseSwitchCaseArgument(e,t,n){let r=t,i=[...n],o=null;for(;r<e.length&&this.isCommandWithValue(e[r],"when");){r++;let u=this.parseCaseConditionValuePair(e,r);r=u.newIndex,i.push(u.value)}if(r<e.length&&this.isCommandWithValue(e[r],"else")){r++;let u=k.parseFromLexeme(e,r);o=u.value,r=u.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,o),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 ut=class{static parse(e){let n=new N(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 o=this.parseItem(e,n);r.push(o.value),n=o.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 o=n>=e.length?null:e[n].value==="asc"?(n++,"asc"):e[n].value==="desc"?(n++,"desc"):null,a=n>=e.length?null:e[n].value==="nulls first"?(n++,"first"):e[n].value==="nulls last"?(n++,"last"):null;return o===null&&a===null?{value:i,newIndex:n}:{value:new be(i,o,a),newIndex:n}}};var zt=class{static parse(e){let n=new N(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 o=k.parseFromLexeme(e,n);r.push(o.value),n=o.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 $e(r[0]),newIndex:n}:{value:new $e(new _(r)),newIndex:n}}};var ct=class{static parse(e){let n=new N(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,o=null;if(n<e.length&&e[n].value==="partition by"){let a=zt.parseFromLexeme(e,n);r=a.value,n=a.newIndex}if(n<e.length&&e[n].value==="order by"){let a=ut.parseFromLexeme(e,n);i=a.value,n=a.newIndex}if(n<e.length&&this.isFrameTypeKeyword(e[n].value)){let a=this.parseFrameSpec(e,n);o=a.value,n=a.newIndex}if(n>=e.length||e[n].type!==8)throw new Error(`Syntax error at position ${n}: Missing closing parenthesis ')' for window frame. Each opening parenthesis must have a matching closing parenthesis.`);return n++,{value:new Le(r,i,o),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 o=this.parseFrameBoundary(e,n),a=o.value;if(n=o.newIndex,n>=e.length||e[n].value!=="and")throw new Error(`Syntax error at position ${n}: Expected 'AND' keyword in BETWEEN clause.`);n++;let u=this.parseFrameBoundary(e,n),l=u.value;return n=u.newIndex,{value:new Me(i,a,l),newIndex:n}}else{let o=this.parseFrameBoundary(e,n),a=o.value;return n=o.newIndex,{value:new Me(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 it(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,o;if(i==="preceding")o=!1;else if(i==="following")o=!0;else throw new Error(`Syntax error at position ${n}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`);return n++,{value:new st(r.value,o),newIndex:n}}else throw new Error(`Syntax error at position ${n}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`)}throw new Error(`Syntax error at position ${n}: Expected a valid frame boundary component.`)}};var Et=class{static parse(e){let n=new N(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 b(r),newIndex:n}}if(e[n].type&4)return ct.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 Re=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 ve(r.value),newIndex:n}}else if(n+1<e.length&&e[n+1].type&4){n++,n++;let r=j.parseFromLexeme(e,n);return n=r.newIndex,n++,{value:new ge(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 o=t;if(o<e.length&&e[o].type&2){let a=e[o].value.toLowerCase();if(!r&&a==="and"||!i&&a==="or")return null;if(o++,a==="between")return this.parseBetweenExpression(e,o,n,!1);if(a==="not between")return this.parseBetweenExpression(e,o,n,!0);if(a==="::"){let c=this.parseTypeValue(e,o);return o=c.newIndex,{value:new ue(n,c.value),newIndex:o}}let u=k.parseFromLexeme(e,o);return o=u.newIndex,{value:new C(n,a,u.value),newIndex:o}}return null}static parseBetweenExpression(e,t,n,r){let i=t,o=k.parseFromLexeme(e,i,!1);if(i=o.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 Se(n,o.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,o=r.name;if(n=r.newIndex,n<e.length&&e[n].type&4){let a=k.parseArgument(4,8,e,n);if(n=a.newIndex,n<e.length&&e[n].value==="over"){let u=Et.parseFromLexeme(e,n);return n=u.newIndex,{value:new U(i,o.name,a.value,u.value),newIndex:n}}else return{value:new U(i,o.name,a.value,null),newIndex:n}}else throw new Error(`Expected opening parenthesis after function name '${o.name}' at index ${n}`)}static parseKeywordFunction(e,t,n){let r=t,i=ke.parseFromLexeme(e,r),o=i.namespaces,a=i.name;if(r=i.newIndex,r<e.length&&e[r].type&4){r++;let u=k.parseFromLexeme(e,r),l=u.value;if(r=u.newIndex,r<e.length&&e[r].type&16)return this.parseFunctionCall(e,t);for(let{key:c,required:d}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);l=new C(l,c,h.value),r=h.newIndex}else{let h=k.parseFromLexeme(e,r);l=new C(l,c,h.value),r=h.newIndex}else if(d)throw new Error(`Keyword '${c}' is required at index ${r}`);if(r<e.length&&e[r].type&8)if(r++,r<e.length&&e[r].value==="over"){r++;let c=Et.parseFromLexeme(e,r);return r=c.newIndex,{value:new U(o,a.name,l,c.value),newIndex:r}}else return{value:new U(o,a.name,l,null),newIndex:r};else throw new Error(`Missing closing parenthesis for function '${a.name}' at index ${r}`)}else throw new Error(`Missing opening parenthesis for function '${a.name}' at index ${r}`)}static parseTypeValue(e,t){let n=t,{namespaces:r,name:i,newIndex:o}=ke.parseFromLexeme(e,n);if(n=o,n<e.length&&e[n].type&4){let a=k.parseArgument(4,8,e,n);return n=a.newIndex,{value:new Ee(r,new B(i.name),a.value),newIndex:n}}else return{value:new Ee(r,new B(i.name)),newIndex:n}}};var Ht=class s 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),o=Math.min(t.length,n+3),a=t.slice(i,o).map((l,c)=>{let d=c+i===n?">":" ",h=V[l.type]||l.type;return`${d} ${c+i}:${l.value} [${h}]`}).join(`
|
|
9
|
+
`),u=`${r} Unparsed lexeme remains at index ${n}: ${t[n].value}
|
|
10
10
|
Context:
|
|
11
|
-
${a}`;return new s(l,n,a)}};var vt=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,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"].includes(t)}};var k=class{static parse(e){let n=new N(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw Dt.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 o=t,a=e[o].comments,l=this.parseItem(e,o);l.value.comments=a,o=l.newIndex;let u=l.value;for(;o<e.length&&e[o].type&2;){let d=e[o].value;if(!r&&d.toLowerCase()==="and"||!i&&d.toLowerCase()==="or")break;let h=vt.getPrecedence(d);if(h<n)break;if(o++,vt.isBetweenOperator(d)){let m=Be.parseBetweenExpression(e,o,u,d.toLowerCase().includes("not"));u=m.value,o=m.newIndex;continue}if(d==="::"){let m=Be.parseTypeValue(e,o);u=new ue(u,m.value),o=m.newIndex;continue}let C=h+1,g=this.parseExpressionWithPrecedence(e,o,C,r,i);o=g.newIndex,u=new y(u,d,g.value)}return{value:u,newIndex:o}}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=Be.parseTypeValue(e,n);return{value:a.value,newIndex:a.newIndex}}else return Be.parseFromLexeme(e,n);let i=Vt.parseFromLexeme(e,n);if(i.newIndex>=e.length)return i;if(e[i.newIndex].type&1){let a=Ct.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:o,newIndex:a}=ke.parseFromLexeme(e,n);if(e[a-1].type&2048)return Be.parseFromLexeme(e,n);if(e[a-1].type&8192)if(a<e.length&&e[a].type&4)if(this.isTypeConstructor(e,a,o.name)){let u=Be.parseTypeValue(e,n);return{value:u.value,newIndex:u.newIndex}}else return Be.parseFromLexeme(e,n);else return{value:new Ee(i,o),newIndex:a};return{value:new E(i,o),newIndex:a}}else{if(r.type&1)return Ct.parseFromLexeme(e,n);if(r.type&4)return Rt.parseFromLexeme(e,n);if(r.type&2048)return Be.parseFromLexeme(e,n);if(r.type&2)return Mt.parseFromLexeme(e,n);if(r.type&256)return $t.parseFromLexeme(e,n);if(r.type&4096)return Wt.parseFromLexeme(e,n);if(r.type&128)return jt.parseFromLexeme(e,n);if(r.type&512){let{namespaces:i,name:o,newIndex:a}=ke.parseFromLexeme(e,n);return{value:new E(i,o),newIndex:a}}else if(r.type&8192){let{namespaces:i,name:o,newIndex:a}=ke.parseFromLexeme(e,n);if(a<e.length&&e[a].type&4)if(this.isTypeConstructor(e,a,o.name)){let l=Be.parseTypeValue(e,n);return{value:l.value,newIndex:l.newIndex}}else return Be.parseFromLexeme(e,n);else return{value:new Ee(i,o),newIndex:a}}}throw new Error(`[ValueParser] Invalid lexeme. index: ${n}, type: ${e[n].type}, value: ${e[n].value}`)}static parseArgument(e,t,n,r){let i=r,o=[];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 E(null,"*");if(i++,i<n.length&&n[i].type===t)return i++,{value:l,newIndex:i};throw new Error(`Expected closing parenthesis at index ${i}`)}let a=this.parseFromLexeme(n,i);for(i=a.newIndex,o.push(a.value);i<n.length&&n[i].type&16;){i++;let l=this.parseFromLexeme(n,i);i=l.newIndex,o.push(l.value)}if(i<n.length&&n[i].type===t)return i++,o.length===1?{value:o[0],newIndex:i}:{value:new _(o),newIndex:i};throw new Error(`Missing closing parenthesis at index ${i}`)}throw new Error(`Expected opening parenthesis at index ${r}`)}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 o=t+1;if(o<e.length){let a=e[o];return!(a.type&1&&typeof a.value=="string"&&isNaN(Number(a.value)))}}return!1}};var ne=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(x.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(q.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ae.kind,e=>this.visitValuesQuery(e)),this.handlers.set(ee.kind,e=>this.visitWithClause(e)),this.handlers.set(Z.kind,e=>this.visitCommonTable(e)),this.handlers.set(J.kind,e=>this.visitSelectItem(e)),this.handlers.set(b.kind,e=>this.visitIdentifierString(e)),this.handlers.set(B.kind,e=>this.visitRawString(e)),this.handlers.set(E.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(V.kind,e=>this.visitSourceExpression(e)),this.handlers.set(M.kind,e=>this.visitTableSource(e)),this.handlers.set(De.kind,e=>this.visitFunctionSource(e)),this.handlers.set(We.kind,e=>this.visitParenSource(e)),this.handlers.set(z.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Oe.kind,e=>this.visitInlineQuery(e)),this.handlers.set($.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(Y.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(Ce.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ge.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(D.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ve.kind,e=>this.visitArrayExpression(e)),this.handlers.set(Se.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(xe.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ue.kind,e=>this.visitCastExpression(e)),this.handlers.set(Le.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Me.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(Je.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(U.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(ye.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(se.kind,e=>this.visitLimitClause(e)),this.handlers.set(Qe.kind,e=>this.visitForClause(e)),this.handlers.set(be.kind,e=>this.visitOrderByItem(e)),this.handlers.set($e.kind,e=>this.visitPartitionByClause(e))}getCommonTables(){return this.commonTables}reset(){this.commonTables=[],this.visitedNodes.clear()}collect(e){return this.visit(e),this.getCommonTables()}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}let n=e.getKind()?.toString()||"unknown",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 ut=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(x.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(q.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(b.kind,e=>this.visitIdentifierString(e)),this.handlers.set(B.kind,e=>this.visitRawString(e)),this.handlers.set(E.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(V.kind,e=>this.visitSourceExpression(e)),this.handlers.set(M.kind,e=>this.visitTableSource(e)),this.handlers.set(We.kind,e=>this.visitParenSource(e)),this.handlers.set(z.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Oe.kind,e=>this.visitInlineQuery(e)),this.handlers.set($.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(Y.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(Ce.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(ge.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(D.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ve.kind,e=>this.visitArrayExpression(e)),this.handlers.set(Se.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(xe.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ue.kind,e=>this.visitCastExpression(e)),this.handlers.set(Le.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Me.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Ee.kind,e=>this.visitTypeValue(e)),this.handlers.set(U.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(ye.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(se.kind,e=>this.visitLimitClause(e)),this.handlers.set(Qe.kind,e=>this.visitForClause(e)),this.handlers.set(be.kind,e=>this.visitOrderByItem(e))}reset(){this.visitedNodes.clear()}execute(e){return this.reset(),this.visit(e)}visit(e){if(!this.isRootVisit)return this.visitNode(e);this.reset(),this.isRootVisit=!1;try{return this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return e;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t)return t(e);let n=e.getKind()?.toString()||"unknown",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 U(t,e.distinct)}visitFromClause(e){let t=this.visit(e.source),n=e.joins?e.joins.map(r=>this.visit(r)):null;return new $(t,n)}visitSubQuerySource(e){let t=this.visit(e.query);return new z(t)}visitInlineQuery(e){let t=this.visit(e.selectQuery);return new Oe(t)}visitJoinClause(e){let t=this.visit(e.source),n=e.condition?this.visit(e.condition):null;return new he(e.joinType.value,t,n,e.lateral)}visitJoinOnClause(e){let t=this.visit(e.condition);return new 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 ye(e.name.name,t)}visitLimitClause(e){let t=this.visit(e.value);return new se(t)}visitForClause(e){return new Qe(e.lockMode)}visitParenExpression(e){let t=this.visit(e.expression);return new Y(t)}visitBinaryExpression(e){let t=this.visit(e.left),n=this.visit(e.right);return new 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 Ce(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 ge(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 D(e.namespaces,e.name,t,n)}visitArrayExpression(e){let t=this.visit(e.expression);return new ve(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 xe(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 V(t,n)}visitTableSource(e){return e}visitParenSource(e){let t=this.visit(e.source);return new We(t)}visitParameterExpression(e){return e}visitWindowFrameExpression(e){let t=e.partition?this.visit(e.partition):null,n=e.order?this.visit(e.order):null,r=e.frameSpec?this.visit(e.frameSpec):null;return new Le(t,n,r)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new be(t,e.sortDirection,e.nullsPosition)}};var Ut=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(x.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(q.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ae.kind,t=>this.visitValuesQuery(t)),this.handlers.set(ee.kind,t=>this.visitWithClause(t)),this.handlers.set(Z.kind,t=>this.visitCommonTable(t)),this.handlers.set($.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(V.kind,t=>this.visitSourceExpression(t)),this.handlers.set(M.kind,t=>this.visitTableSource(t)),this.handlers.set(De.kind,t=>this.visitFunctionSource(t)),this.handlers.set(We.kind,t=>this.visitParenSource(t)),this.handlers.set(z.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(Oe.kind,t=>this.visitInlineQuery(t)),e||(this.handlers.set(ie.kind,t=>this.visitWhereClause(t)),this.handlers.set(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(ye.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(se.kind,t=>this.visitLimitClause(t)),this.handlers.set(Re.kind,t=>this.visitOffsetClause(t)),this.handlers.set(Ue.kind,t=>this.visitFetchClause(t)),this.handlers.set(Qe.kind,t=>this.visitForClause(t)),this.handlers.set(be.kind,t=>this.visitOrderByItem(t)),this.handlers.set(U.kind,t=>this.visitSelectClause(t)),this.handlers.set(J.kind,t=>this.visitSelectItem(t)),this.handlers.set(Y.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(Ce.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(ge.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(D.kind,t=>this.visitFunctionCall(t)),this.handlers.set(ve.kind,t=>this.visitArrayExpression(t)),this.handlers.set(Se.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(xe.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(Je.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 B?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof B?e.qualifiedName.name.value:e.qualifiedName.name.name}collect(e){return this.visit(e),this.getTableSources()}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.selectableOnly||this.collectCTEs(e),this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}collectCTEs(e){let t=new ne;t.visit(e);let n=t.getCommonTables();for(let 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 p=class{constructor(e,t="",n=""){this.innerTokens=[];this.type=e,this.text=t,this.containerType=n}};var ct=class{static collect(e){let t=[];function n(r){if(!(!r||typeof r!="object")){r.constructor&&r.constructor.kind===T.kind&&t.push(r);for(let i of Object.keys(r)){let o=r[i];Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&o.constructor&&o.constructor.kind&&n(o)}}}return n(e),t}};var Kt=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var qt=class{constructor(e){this.prefix=e?.prefix??":",this.suffix=e?.suffix??"",this.style=e?.style??"named"}decorate(e,t){let n="";return this.style==="anonymous"?n=this.prefix:this.style==="indexed"?n=this.prefix+t:this.style==="named"&&(n=this.prefix+e+this.suffix),e=n,e}};var pt=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 _e?e.setClause:new _e(e.setClause),this.whereClause=e.whereClause??null,this.fromClause=e.fromClause??null,this.returningClause=e.returning??null}};var Fe=class s{constructor(e=null,t=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=e??null,this.commonTableCollector=new ne,this.commonTables=[],this.initialCommonTables=t,this.handlers=new Map,this.handlers.set(x.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(U.kind,n=>this.visitSelectClause(n)),this.handlers.set(V.kind,n=>this.visitSourceExpression(n)),this.handlers.set($.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 E&&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 E&&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 o=i.getSourceAliasName();o&&n.includes(o)&&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 s(this.tableColumnResolver,r).collect(n.query).forEach(a=>{this.addSelectValueAsUnique(a.name,new E(e?[e]:null,a.name))})}else new s(this.tableColumnResolver,this.commonTables).collect(t).forEach(o=>{this.addSelectValueAsUnique(o.name,new E(e?[e]:null,o.name))})}visitSelectClause(e){for(let t of e.items)this.processSelectItem(t)}processSelectItem(e){if(e.identifier)this.addSelectValueAsUnique(e.identifier.name,e.value);else if(e.value instanceof E){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 E(t?[t]:null,n.name))});return}else if(e.datasource instanceof M){if(this.tableColumnResolver){let t=e.datasource.getSourceName();this.tableColumnResolver(t).forEach(n=>{this.addSelectValueAsUnique(n,new E([t],n))})}return}else if(e.datasource instanceof z){let t=e.getAliasName();new s(this.tableColumnResolver,this.commonTables).collect(e.datasource.query).forEach(i=>{this.addSelectValueAsUnique(i.name,new E(t?[t]:null,i.name))});return}else if(e.datasource instanceof We)return this.visit(e.datasource.source)}visitFromClause(e){e&&this.processFromClause(e,!0)}addSelectValueAsUnique(e,t){this.selectValues.some(n=>n.name===e)||this.selectValues.push({name:e,value:t})}};var mt=class extends f{static{this.kind=Symbol("CreateTableQuery")}constructor(e){super(),this.tableName=new b(e.tableName),this.isTemporary=e.isTemporary??!1,this.asSelectQuery=e.asSelectQuery}getSelectQuery(){let e;return this.asSelectQuery?e=new Fe().collect(this.asSelectQuery).map(r=>new J(r.value,r.name)):e=[new J(new B("*"))],new x({selectClause:new U(e),fromClause:new $(new V(new M(null,this.tableName.name),null),null)})}getCountQuery(){return new x({selectClause:new U([new J(new D(null,"count",new E(null,"*"),null))]),fromClause:new $(new V(new M(null,this.tableName.name),null),null)})}};var Mn={mysql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},postgres:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed"},postgresWithNamedParams:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"},sqlserver:{identifierEscape:{start:"[",end:"]"},parameterSymbol:"@",parameterStyle:"named"},sqlite:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"},oracle:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"},clickhouse:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},firebird:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},db2:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},snowflake:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},cloudspanner:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"@",parameterStyle:"named"},duckdb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},cockroachdb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed"},athena:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},bigquery:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"@",parameterStyle:"named"},hive:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},mariadb:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},redshift:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed"},flinksql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},mongodb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"}},_t=class s{constructor(e){this.handlers=new Map;this.index=1;e?.preset&&(e={...e.preset,...e}),this.parameterDecorator=new qt({prefix:typeof e?.parameterSymbol=="string"?e.parameterSymbol:e?.parameterSymbol?.start??":",suffix:typeof e?.parameterSymbol=="object"?e.parameterSymbol.end:"",style:e?.parameterStyle??"named"}),this.identifierDecorator=new Kt({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.handlers.set(_.kind,t=>this.visitValueList(t)),this.handlers.set(E.kind,t=>this.visitColumnReference(t)),this.handlers.set(Ae.kind,t=>this.visitQualifiedName(t)),this.handlers.set(D.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(Ce.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(we.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(B.kind,t=>this.visitRawString(t)),this.handlers.set(b.kind,t=>this.visitIdentifierString(t)),this.handlers.set(Y.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(ve.kind,t=>this.visitArrayExpression(t)),this.handlers.set(Se.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(ge.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(Je.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(Ee.kind,t=>this.visitTypeValue(t)),this.handlers.set(xe.kind,t=>this.visitTupleExpression(t)),this.handlers.set(Oe.kind,t=>this.visitInlineQuery(t)),this.handlers.set(Le.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(Me.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(nt.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(rt.kind,t=>this.visitWindowFrameBoundaryValue(t)),this.handlers.set($e.kind,t=>this.visitPartitionByClause(t)),this.handlers.set(ce.kind,t=>this.visitOrderByClause(t)),this.handlers.set(be.kind,t=>this.visitOrderByItem(t)),this.handlers.set(J.kind,t=>this.visitSelectItem(t)),this.handlers.set(U.kind,t=>this.visitSelectClause(t)),this.handlers.set(it.kind,t=>this.visitDistinct(t)),this.handlers.set(st.kind,t=>this.visitDistinctOn(t)),this.handlers.set(M.kind,t=>this.visitTableSource(t)),this.handlers.set(De.kind,t=>this.visitFunctionSource(t)),this.handlers.set(V.kind,t=>this.visitSourceExpression(t)),this.handlers.set(H.kind,t=>this.visitSourceAliasExpression(t)),this.handlers.set($.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(ye.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(se.kind,t=>this.visitLimitClause(t)),this.handlers.set(Re.kind,t=>this.visitOffsetClause(t)),this.handlers.set(Ue.kind,t=>this.visitFetchClause(t)),this.handlers.set(Ze.kind,t=>this.visitFetchExpression(t)),this.handlers.set(Qe.kind,t=>this.visitForClause(t)),this.handlers.set(ee.kind,t=>this.visitWithClause(t)),this.handlers.set(Z.kind,t=>this.visitCommonTable(t)),this.handlers.set(x.kind,t=>this.visitSimpleQuery(t)),this.handlers.set(z.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(q.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ae.kind,t=>this.visitValuesQuery(t)),this.handlers.set(xe.kind,t=>this.visitTupleExpression(t)),this.handlers.set(qe.kind,t=>this.visitInsertQuery(t)),this.handlers.set(He.kind,t=>this.visitInsertClause(t)),this.handlers.set(pt.kind,t=>this.visitUpdateQuery(t)),this.handlers.set(ot.kind,t=>this.visitUpdateClause(t)),this.handlers.set(_e.kind,t=>this.visitSetClause(t)),this.handlers.set(Ge.kind,t=>this.visitSetClauseItem(t)),this.handlers.set(bt.kind,t=>this.visitReturningClause(t)),this.handlers.set(mt.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(s.SPACE_TOKEN),t.innerTokens.push(new p(1,e.operator.value,"BinarySelectQueryOperator")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}static commaSpaceTokens(){return[s.COMMA_TOKEN,s.SPACE_TOKEN]}static argumentCommaSpaceTokens(){return[s.ARGUMENT_SPLIT_COMMA_TOKEN,s.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(s.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(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOrderByClause(e){let t=new p(1,"order by","OrderByClause");t.innerTokens.push(s.SPACE_TOKEN);for(let n=0;n<e.order.length;n++)n>0&&t.innerTokens.push(...s.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(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"desc"))),e.nullsPosition&&(e.nullsPosition==="first"?(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"nulls first"))):e.nullsPosition==="last"&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"nulls last")))),t}parse(e){this.index=1;let t=this.visit(e),n=ct.collect(e).sort((i,o)=>(i.index??0)-(o.index??0)),r=this.parameterDecorator.style;if(r==="named"){let i={};for(let o of n){let a=o.name.value;if(i.hasOwnProperty(a)){if(i[a]!==o.value)throw new Error(`Duplicate parameter name '${a}' with different values detected during query composition.`);continue}i[a]=o.value}return{token:t,params:i}}else if(r==="indexed"){let i=n.map(o=>o.value);return{token:t,params:i}}else if(r==="anonymous"){let i=n.map(o=>o.value);return{token:t,params:i}}return{token:t,params:[]}}visit(e){let t=this.handlers.get(e.getKind());if(t)return t(e);throw new Error(`[SqlPrintTokenParser] No handler for kind: ${e.getKind().toString()}`)}visitValueList(e){let t=new p(0,"","ValueList");for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...s.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(s.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(s.PAREN_CLOSE_TOKEN),e.over&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"over")),e.over instanceof b?(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.over.accept(this))):(t.innerTokens.push(s.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.over)),t.innerTokens.push(s.PAREN_CLOSE_TOKEN))),t}visitUnaryExpression(e){let t=new p(0,"","UnaryExpression");return t.innerTokens.push(this.visit(e.operator)),t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(new p(5,e.operator.value)),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}visitLiteralValue(e){let t;return typeof e.value=="string"?t=`'${e.value.replace(/'/g,"''")}'`:e.value===null?t="null":t=e.value.toString(),new p(2,t,"LiteralValue")}visitParameterExpression(e){e.index=this.index;let t=this.parameterDecorator.decorate(e.name.value,e.index),n=new p(7,t);return this.index++,n}visitSwitchCaseArgument(e){let t=new p(0,"","SwitchCaseArgument");for(let n of e.cases)t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(n.accept(this));return e.elseValue&&(t.innerTokens.push(s.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(s.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(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.key)),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"then")),t.innerTokens.push(s.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(s.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition))),t.innerTokens.push(this.visit(e.switchCase)),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"end")),t}visitArrayExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(new p(1,"array")),t.innerTokens.push(new p(4,"[")),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(new p(4,"]")),t}visitArrayQueryExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(new p(1,"array")),t.innerTokens.push(new p(4,"(")),t.innerTokens.push(this.visit(e.query)),t.innerTokens.push(new p(4,")")),t}visitBetweenExpression(e){let t=new p(0,"","BetweenExpression");return t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(s.SPACE_TOKEN),e.negated&&(t.innerTokens.push(new p(1,"not")),t.innerTokens.push(s.SPACE_TOKEN)),t.innerTokens.push(new p(1,"between")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.lower)),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"and")),t.innerTokens.push(s.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(s.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(s.PAREN_CLOSE_TOKEN)),t}visitTupleExpression(e){let t=new p(0,"","TupleExpression");t.innerTokens.push(s.PAREN_OPEN_TOKEN);for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...s.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.order))),e.frameSpec&&(n?n=!1:t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this))):(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"between")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this)),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"and")),t.innerTokens.push(s.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(s.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 E){let n=e.value.column.name;if(e.identifier.name===n)return t}return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.identifier)),t}visitSelectClause(e){let t=new p(1,"select","SelectClause");t.innerTokens.push(s.SPACE_TOKEN),e.distinct&&(t.keywordTokens=[],t.keywordTokens.push(s.SPACE_TOKEN),t.keywordTokens.push(e.distinct.accept(this)));for(let n=0;n<e.items.length;n++)n>0&&t.innerTokens.push(...s.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[n]));return t}visitDistinct(e){return new p(1,"distinct")}visitDistinctOn(e){let t=new p(0,"","DistinctOn");return t.innerTokens.push(new p(1,"distinct on")),t.innerTokens.push(s.PAREN_OPEN_TOKEN),t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(s.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 M){let n=e.datasource.table.name;return e.aliasExpression.table.name===n||(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this))),t}else return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this)),t}visitFromClause(e){let t=new p(1,"from","FromClause");if(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.joins)for(let n=0;n<e.joins.length;n++)t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"lateral"))),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.condition&&(t.innerTokens.push(s.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(s.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(s.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.condition)),t.innerTokens.push(s.PAREN_CLOSE_TOKEN),t}visitFunctionSource(e){let t=new p(0,"","FunctionSource");return t.innerTokens.push(e.qualifiedName.accept(this)),t.innerTokens.push(s.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(s.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(s.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...s.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));t.innerTokens.push(s.PAREN_CLOSE_TOKEN)}return t}visitWhereClause(e){let t=new p(1,"where","WhereClause");return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitGroupByClause(e){let t=new p(1,"group by","GroupByClause");t.innerTokens.push(s.SPACE_TOKEN);for(let n=0;n<e.grouping.length;n++)n>0&&t.innerTokens.push(...s.commaSpaceTokens()),t.innerTokens.push(this.visit(e.grouping[n]));return t}visitHavingClause(e){let t=new p(1,"having","HavingClause");return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitWindowClause(e){let t=new p(1,"window","WindowClause");t.innerTokens.push(s.SPACE_TOKEN);for(let n=0;n<e.windows.length;n++)n>0&&t.innerTokens.push(...s.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(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(s.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(s.PAREN_CLOSE_TOKEN),t}visitLimitClause(e){let t=new p(1,"limit","LimitClause");return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOffsetClause(e){let t=new p(1,"offset","OffsetClause");return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitFetchClause(e){let t=new p(1,"fetch","FetchClause");return t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(e.count.accept(this)),e.unit&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,e.unit))),t}visitForClause(e){let t=new p(1,"for","ForClause");return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,e.lockMode)),t}visitWithClause(e){let t=new p(1,"with","WithClause");t.innerTokens.push(s.SPACE_TOKEN),e.recursive&&(t.innerTokens.push(new p(1,"recursive")),t.innerTokens.push(s.SPACE_TOKEN));for(let n=0;n<e.tables.length;n++)n>0&&t.innerTokens.push(...s.commaSpaceTokens()),t.innerTokens.push(e.tables[n].accept(this));return t.innerTokens.push(s.SPACE_TOKEN),t}visitCommonTable(e){let t=new p(0,"","CommonTable");t.innerTokens.push(e.aliasExpression.accept(this)),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(s.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(s.SPACE_TOKEN)),t.innerTokens.push(s.PAREN_OPEN_TOKEN);let n=new p(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this)),e.whereClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.groupByClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.groupByClause.accept(this))),e.havingClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.havingClause.accept(this))),e.orderByClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.orderByClause.accept(this))),e.windowClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.windowClause.accept(this))),e.limitClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.limitClause.accept(this))),e.offsetClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.offsetClause.accept(this))),e.fetchClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.fetchClause.accept(this))),e.forClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.forClause.accept(this)))),t}visitSubQuerySource(e){let t=new p(0,"");t.innerTokens.push(s.PAREN_OPEN_TOKEN);let n=new p(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(s.PAREN_CLOSE_TOKEN),t}visitValuesQuery(e){let t=new p(1,"values","ValuesQuery");t.innerTokens.push(s.SPACE_TOKEN);let n=new p(0,"","Values");for(let r=0;r<e.tuples.length;r++)r>0&&n.innerTokens.push(...s.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(s.PAREN_OPEN_TOKEN);let n=new p(0,"","InlineQuery");return n.innerTokens.push(e.selectQuery.accept(this)),t.innerTokens.push(n),t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.selectQuery))),t}visitInsertClause(e){let t=new p(0,"");if(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"insert into")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),e.columns.length>0){t.innerTokens.push(s.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...s.commaSpaceTokens()),t.innerTokens.push(e.columns[n].accept(this));t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(e.setClause.accept(this)),e.fromClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this))),e.whereClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.returningClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.returningClause.accept(this))),t}visitUpdateClause(e){let t=new p(1,"update","UpdateClause");return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t}visitSetClause(e){let t=new p(1,"set","SelectClause");t.innerTokens.push(s.SPACE_TOKEN);for(let n=0;n<e.items.length;n++)n>0&&t.innerTokens.push(...s.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(s.SPACE_TOKEN),t.innerTokens.push(new p(5,"=")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.value.accept(this)),t}visitReturningClause(e){let t=new p(1,"returning","ReturningClause");t.innerTokens.push(s.SPACE_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...s.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(s.SPACE_TOKEN),t.innerTokens.push(e.tableName.accept(this)),e.asSelectQuery&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.asSelectQuery.accept(this))),t}};var St=class{constructor(e=" ",t=0,n=`\r
|
|
12
|
-
`){this.indentChar=e,this.indentSize=t,this.newline=n,this.lines=[],this.appendNewline(0)}print(){let e="";for(let t of this.lines)t.text!==""&&(e+=this.indent(t.level)+t.text);return e.trimEnd()}indent(e){return this.indentChar.repeat(this.indentSize*e)}appendNewline(e){if(this.lines.length>0){let t=this.lines[this.lines.length-1];t.text!==""&&(t.text=t.text.trimEnd()+this.newline)}this.lines.push(new Tn(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.")}},Tn=class{constructor(e,t){this.level=e,this.text=t}};var zt=class{constructor(e){this.indentChar=e?.indentChar??"",this.indentSize=e?.indentSize??0,this.newline=e?.newline??" ",this.commaBreak=e?.commaBreak??"none",this.andBreak=e?.andBreak??"none",this.keywordCase=e?.keywordCase??"none",this.linePrinter=new St(this.indentChar,this.indentSize,this.newline),this.indentIncrementContainers=new Set(e?.indentIncrementContainerTypes??["SelectClause","FromClause","WhereClause","GroupByClause","HavingClause","WindowFrameExpression","PartitionByClause","OrderByClause","WindowClause","LimitClause","OffsetClause","SubQuerySource","BinarySelectQueryOperator","Values","WithClause","SwitchCaseArgument","CaseKeyValuePair","CaseThenValue","ElseClause","CaseElseValue"])}print(e,t=0){return this.linePrinter=new St(this.indentChar,this.indentSize,this.newline),this.linePrinter.lines.length>0&&t!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=t),this.appendToken(e,t),this.linePrinter.print()}appendToken(e,t){if((!e.innerTokens||e.innerTokens.length===0)&&e.text==="")return;let n=this.linePrinter.getCurrentLine();if(e.type===1){let i=e.text;this.keywordCase==="upper"?i=i.toUpperCase():this.keywordCase==="lower"&&(i=i.toLowerCase()),this.linePrinter.appendText(i)}else if(e.type===3){let i=e.text;this.commaBreak==="before"?(this.linePrinter.appendNewline(t),this.linePrinter.appendText(i)):this.commaBreak==="after"?(this.linePrinter.appendText(i),this.linePrinter.appendNewline(t)):this.linePrinter.appendText(i)}else if(e.type===5&&e.text.toLowerCase()==="and"){let i=e.text;this.keywordCase==="upper"?i=i.toUpperCase():this.keywordCase==="lower"&&(i=i.toLowerCase()),this.andBreak==="before"?(this.linePrinter.appendNewline(t),this.linePrinter.appendText(i)):this.andBreak==="after"?(this.linePrinter.appendText(i),this.linePrinter.appendNewline(t)):this.linePrinter.appendText(i)}else if(e.containerType==="JoinClause"){let i=e.text;this.keywordCase==="upper"?i=i.toUpperCase():this.keywordCase==="lower"&&(i=i.toLowerCase()),this.linePrinter.appendNewline(t),this.linePrinter.appendText(i)}else this.linePrinter.appendText(e.text);if(e.keywordTokens&&e.keywordTokens.length>0)for(let i=0;i<e.keywordTokens.length;i++){let o=e.keywordTokens[i];this.appendToken(o,t)}let r=t;this.newline!==" "&&n.text!==""&&this.indentIncrementContainers.has(e.containerType)&&(r++,this.linePrinter.appendNewline(r));for(let i=0;i<e.innerTokens.length;i++){let o=e.innerTokens[i];this.appendToken(o,r)}r!==t&&this.linePrinter.appendNewline(t)}};var Dl=["mysql","postgres","sqlserver","sqlite"],dt=class{constructor(e={}){let t=e.preset?Mn[e.preset]:void 0;if(e.preset&&!t)throw new Error(`Invalid preset: ${e.preset}`);let n={...t,identifierEscape:e.identifierEscape??t?.identifierEscape,parameterSymbol:e.parameterSymbol??t?.parameterSymbol,parameterStyle:e.parameterStyle??t?.parameterStyle};this.parser=new _t(n),this.printer=new zt(e)}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var Ye=class{constructor(){this.sqlFormatter=new dt({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(e,t=null){return t&&(this.sqlFormatter=new dt(t)),this.sqlFormatter.format(e).formattedSql}formatWithParameters(e,t=null){t&&(this.sqlFormatter=new dt(t));let n=this.sqlFormatter.format(e);return{sql:n.formattedSql,params:n.params}}visit(e){return this.format(e)}};var Gt=class{constructor(){this.sourceCollector=new Ut(!0),this.cteCollector=new ne,this.formatter=new Ye}build(e){if(e.length===0)return new ee(!1,e);let t=this.resolveDuplicateNames(e),{tableMap:n,recursiveCTEs:r,dependencies:i}=this.buildDependencyGraph(t),o=this.sortCommonTables(t,n,r,i);return new ee(r.size>0,o)}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 o=i.map(l=>this.formatter.format(l.query));if(new Set(o).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 o of e)t.set(o.aliasExpression.table.name,o);let n=new Set,r=new Map,i=new Map;for(let o of e){let a=o.aliasExpression.table.name,l=this.sourceCollector.collect(o.query);for(let c of l)if(c.table.name===a){n.add(a);break}r.has(a)||r.set(a,new Set);let u=this.cteCollector.collect(o.query);for(let c of u){let d=c.aliasExpression.table.name;t.has(d)&&(r.get(a).add(d),i.has(d)||i.set(d,new Set),i.get(d).add(a))}}return{tableMap:t,recursiveCTEs:n,dependencies:r}}sortCommonTables(e,t,n,r){let i=[],o=[],a=new Set,l=new Set,u=c=>{if(a.has(c))return;if(l.has(c))throw new Error(`Circular reference detected in CTE: ${c}`);l.add(c);let d=r.get(c)||new Set;for(let h of d)u(h);l.delete(c),a.add(c),n.has(c)?i.push(t.get(c)):o.push(t.get(c))};for(let c of e){let d=c.aliasExpression.table.name;a.has(d)||u(d)}return[...i,...o]}};var Ht=class{constructor(){this.nameConflictResolver=new Gt,this.cteCollector=new ne}inject(e,t){if(t.length===0)return e;t.push(...this.cteCollector.collect(e));let n=this.nameConflictResolver.build(t);if(e instanceof x)return this.injectIntoSimpleQuery(e,n);if(e instanceof q)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 x)return this.injectIntoSimpleQuery(e.left,t),e;if(e.left instanceof q)return this.injectIntoBinaryQuery(e.left,t),e;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var Ke=class{constructor(){}static normalize(e){let n=new ne().collect(e);return n.length===0?e:(new ut().execute(e),new Ht().inject(e,n))}};var $n=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))($n||{}),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 ne,this.commonTables=[],this.duplicateDetection=n,this.options=r||{},this.handlers=new Map,this.handlers.set(x.kind,i=>this.visitSimpleSelectQuery(i)),this.handlers.set(U.kind,i=>this.visitSelectClause(i)),this.handlers.set($.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(ye.kind,i=>this.visitWindowFrameClause(i)),this.handlers.set(se.kind,i=>this.visitLimitClause(i)),this.handlers.set(Re.kind,i=>this.offsetClause(i)),this.handlers.set(Ue.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(E.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(D.kind,i=>this.visitFunctionCall(i)),this.handlers.set(Y.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(ge.kind,i=>this.visitBetweenExpression(i)),this.handlers.set(ve.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(ye.kind,i=>this.visitWindowFrameClause(i)),this.handlers.set(Le.kind,i=>this.visitWindowFrameExpression(i)),this.handlers.set($e.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 o="";return i.value&&typeof i.value.getNamespace=="function"&&(o=i.value.getNamespace()||""),(o?o+"."+i.name:i.name)===r})||this.selectValues.push({name:e,value:t})}}visit(e){if(!this.isRootVisit){this.visitNode(e);return}if(!(e instanceof x))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 Fe(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 et=class s{static parse(e){let n=new N(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?s.parseFunctionSource(e,r):s.parseTableSource(r)}static parseTableSource(e){let{namespaces:t,name:n,newIndex:r}=e;return{value:new M(t,n.name),newIndex:r}}static parseFunctionSource(e,t){let n=t.newIndex,{namespaces:r,name:i}=t,o=k.parseArgument(4,8,e,n);n=o.newIndex;let a=i.name;return{value:new De({namespaces:r,name:a},o.value),newIndex:n}}static parseParenSource(e,t){let n=t;if(n++,n>=e.length)throw new Error(`Syntax error: Unexpected end of input at position ${n}. Expected a subquery or nested expression after opening parenthesis.`);let 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}=W.parseFromLexeme(e,n);return n=i,{value:new z(r),newIndex:n}}};var ht=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 ne().collect(e),o=new Map;for(let a of i)o.set(a.getSourceAliasName(),a);return this.findUpstream(e,n,o)}handleTableSource(e,t,n){let r=n.get(e.table.name);if(r){let i=new Map(n);i.delete(e.table.name);let o=this.findUpstream(r.query,t,i);return o.length===0?null:o}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=[],o=!0,a=0;for(let l of r){let u=l.datasource,c=null;if(u instanceof M)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;o=!1;break}if(c===null){o=!1;break}i.push(c)}return o&&i.length===a?i.flat():null}findUpstream(e,t,n){if(e instanceof x){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),o=this.collectCTEColumns(e,n),a=[...i,...o],l=c=>this.options.ignoreCaseAndUnderscore?c.toLowerCase().replace(/_/g,""):c;return t.every(c=>a.some(d=>l(d)===l(c)))?[e]:[]}else if(e instanceof q){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 x)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 q)return this.collectColumnsFromSelectQuery(e.left);return[]}};var tt=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 H(r,i),newIndex:n}}return{value:new H(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 N(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=et.parseTableSourceFromLexemes(e,t);return{value:new V(n.value,null),newIndex:n.newIndex}}static parseFromLexeme(e,t){let n=t,r=et.parseFromLexeme(e,n);if(n=r.newIndex,n<e.length){if(e[n].value==="as"){n++;let o=tt.parseFromLexeme(e,n);return n=o.newIndex,{value:new V(r.value,o.value),newIndex:n}}if(n<e.length&&this.isTokenTypeAliasCandidate(e[n].type)){let o=tt.parseFromLexeme(e,n);return n=o.newIndex,{value:new V(r.value,o.value),newIndex:n}}}return{value:new V(r.value,null),newIndex:n}}static isTokenTypeAliasCandidate(e){return(e&64)!==0||(e&2048)!==0}};var Ve=class s{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?s.buildSimpleQuery(i):i,r=new q(n(e[0]),t,n(e[1]));Ke.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 x)return e;if(e instanceof q)return s.buildSimpleBinaryQuery(e);if(e instanceof ae)return s.buildSimpleValuesQuery(e);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(e){let t=new z(e),n=new V(t,new H("bq",null)),r=new $(n,null),i=s.createSelectAllClause(),o=new x({selectClause:i,fromClause:r});return Ke.normalize(o)}static buildSimpleValuesQuery(e){let t=e.tuples.length>0?e.tuples[0].values.length:0;if(e.tuples.length===0)throw new Error("Empty VALUES clause cannot be converted to a SimpleSelectQuery");if(!e.columnAliases)throw new Error("Column aliases are required to convert a VALUES clause to SimpleSelectQuery. Please specify column aliases.");if(e.columnAliases.length!==t)throw new Error(`The number of column aliases (${e.columnAliases.length}) does not match the number of columns in the first tuple (${t}).`);let n=new z(e),r=new V(n,new H("vq",e.columnAliases)),i=new $(r,null),o=e.columnAliases.map(l=>new J(new E("vq",l),l)),a=new U(o,null);return new x({selectClause:a,fromClause:i})}static createSelectAllClause(){let e=new E(null,"*"),t=new J(e,"*");return new U([t],null)}static buildCreateTableQuery(e,t,n=!1){return new mt({tableName:t,isTemporary:n,asSelectQuery:e})}static buildInsertQuery(e,t){let n,r=e.selectClause.items.length;if(n=new Fe().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.
|
|
11
|
+
${a}`;return new s(u,n,a)}};var xt=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,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"].includes(t)}};var k=class{static parse(e){let n=new N(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw Ht.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 o=t,a=e[o].comments,u=this.parseItem(e,o);u.value.comments=a,o=u.newIndex;let l=u.value;for(;o<e.length&&e[o].type&2;){let d=e[o].value;if(!r&&d.toLowerCase()==="and"||!i&&d.toLowerCase()==="or")break;let h=xt.getPrecedence(d);if(h<n)break;if(o++,xt.isBetweenOperator(d)){let m=Re.parseBetweenExpression(e,o,l,d.toLowerCase().includes("not"));l=m.value,o=m.newIndex;continue}if(d==="::"){let m=Re.parseTypeValue(e,o);l=new ue(l,m.value),o=m.newIndex;continue}let y=h+1,S=this.parseExpressionWithPrecedence(e,o,y,r,i);o=S.newIndex,l=new C(l,d,S.value)}return{value:l,newIndex:o}}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=Re.parseTypeValue(e,n);return{value:a.value,newIndex:a.newIndex}}else return Re.parseFromLexeme(e,n);let i=Jt.parseFromLexeme(e,n);if(i.newIndex>=e.length)return i;if(e[i.newIndex].type&1){let a=St.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:o,newIndex:a}=ke.parseFromLexeme(e,n);if(e[a-1].type&2048)return Re.parseFromLexeme(e,n);if(e[a-1].type&8192)if(a<e.length&&e[a].type&4)if(this.isTypeConstructor(e,a,o.name)){let l=Re.parseTypeValue(e,n);return{value:l.value,newIndex:l.newIndex}}else return Re.parseFromLexeme(e,n);else return{value:new Ee(i,o),newIndex:a};return{value:new E(i,o),newIndex:a}}else{if(r.type&1)return St.parseFromLexeme(e,n);if(r.type&4)return Ut.parseFromLexeme(e,n);if(r.type&2048)return Re.parseFromLexeme(e,n);if(r.type&2)return Dt.parseFromLexeme(e,n);if(r.type&256)return Kt.parseFromLexeme(e,n);if(r.type&4096)return qt.parseFromLexeme(e,n);if(r.type&128)return _t.parseFromLexeme(e,n);if(r.type&512){let{namespaces:i,name:o,newIndex:a}=ke.parseFromLexeme(e,n);return{value:new E(i,o),newIndex:a}}else if(r.type&8192){let{namespaces:i,name:o,newIndex:a}=ke.parseFromLexeme(e,n);if(a<e.length&&e[a].type&4)if(this.isTypeConstructor(e,a,o.name)){let u=Re.parseTypeValue(e,n);return{value:u.value,newIndex:u.newIndex}}else return Re.parseFromLexeme(e,n);else return{value:new Ee(i,o),newIndex:a}}}throw new Error(`[ValueParser] Invalid lexeme. index: ${n}, type: ${e[n].type}, value: ${e[n].value}`)}static parseArgument(e,t,n,r){let i=r,o=[];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 u=new E(null,"*");if(i++,i<n.length&&n[i].type===t)return i++,{value:u,newIndex:i};throw new Error(`Expected closing parenthesis at index ${i}`)}let a=this.parseFromLexeme(n,i);for(i=a.newIndex,o.push(a.value);i<n.length&&n[i].type&16;){i++;let u=this.parseFromLexeme(n,i);i=u.newIndex,o.push(u.value)}if(i<n.length&&n[i].type===t)return i++,o.length===1?{value:o[0],newIndex:i}:{value:new _(o),newIndex:i};throw new Error(`Missing closing parenthesis at index ${i}`)}throw new Error(`Expected opening parenthesis at index ${r}`)}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 o=t+1;if(o<e.length){let a=e[o];return!(a.type&1&&typeof a.value=="string"&&isNaN(Number(a.value)))}}return!1}};var ne=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(x.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(q.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ae.kind,e=>this.visitValuesQuery(e)),this.handlers.set(ee.kind,e=>this.visitWithClause(e)),this.handlers.set(X.kind,e=>this.visitCommonTable(e)),this.handlers.set(J.kind,e=>this.visitSelectItem(e)),this.handlers.set(b.kind,e=>this.visitIdentifierString(e)),this.handlers.set(B.kind,e=>this.visitRawString(e)),this.handlers.set(E.kind,e=>this.visitColumnReference(e)),this.handlers.set(T.kind,e=>this.visitParameterExpression(e)),this.handlers.set(H.kind,e=>this.visitLiteralValue(e)),this.handlers.set(R.kind,e=>this.visitSourceExpression(e)),this.handlers.set(M.kind,e=>this.visitTableSource(e)),this.handlers.set(Ue.kind,e=>this.visitFunctionSource(e)),this.handlers.set(je.kind,e=>this.visitParenSource(e)),this.handlers.set(z.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Qe.kind,e=>this.visitInlineQuery(e)),this.handlers.set($.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(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(C.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(re.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(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(Se.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(U.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ve.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ge.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(xe.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ue.kind,e=>this.visitCastExpression(e)),this.handlers.set(Le.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Me.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(Je.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(D.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(be.kind,e=>this.visitOrderByItem(e)),this.handlers.set($e.kind,e=>this.visitPartitionByClause(e))}getCommonTables(){return this.commonTables}reset(){this.commonTables=[],this.visitedNodes.clear()}collect(e){return this.visit(e),this.getCommonTables()}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}let n=e.getKind()?.toString()||"unknown",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 pt=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(x.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(q.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(b.kind,e=>this.visitIdentifierString(e)),this.handlers.set(B.kind,e=>this.visitRawString(e)),this.handlers.set(E.kind,e=>this.visitColumnReference(e)),this.handlers.set(T.kind,e=>this.visitParameterExpression(e)),this.handlers.set(H.kind,e=>this.visitLiteralValue(e)),this.handlers.set(R.kind,e=>this.visitSourceExpression(e)),this.handlers.set(M.kind,e=>this.visitTableSource(e)),this.handlers.set(je.kind,e=>this.visitParenSource(e)),this.handlers.set(z.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Qe.kind,e=>this.visitInlineQuery(e)),this.handlers.set($.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(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(C.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(re.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(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(Se.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(U.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ve.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ge.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(xe.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ue.kind,e=>this.visitCastExpression(e)),this.handlers.set(Le.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Me.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Ee.kind,e=>this.visitTypeValue(e)),this.handlers.set(D.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(be.kind,e=>this.visitOrderByItem(e))}reset(){this.visitedNodes.clear()}execute(e){return this.reset(),this.visit(e)}visit(e){if(!this.isRootVisit)return this.visitNode(e);this.reset(),this.isRootVisit=!1;try{return this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return e;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t)return t(e);let n=e.getKind()?.toString()||"unknown",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 He(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 D(t,e.distinct)}visitFromClause(e){let t=this.visit(e.source),n=e.joins?e.joins.map(r=>this.visit(r)):null;return new $(t,n)}visitSubQuerySource(e){let t=this.visit(e.query);return new z(t)}visitInlineQuery(e){let t=this.visit(e.selectQuery);return new Qe(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 Y(t)}visitBinaryExpression(e){let t=this.visit(e.left),n=this.visit(e.right);return new C(t,e.operator.value,n)}visitUnaryExpression(e){let t=this.visit(e.expression);return new re(e.operator.value,t)}visitCaseExpression(e){let t=e.condition?this.visit(e.condition):null,n=this.visit(e.switchCase);return new 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 Se(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 ve(t)}visitArrayQueryExpression(e){let t=this.visit(e.query);return new ge(t)}visitTupleExpression(e){let t=e.values.map(n=>this.visit(n));return new xe(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 R(t,n)}visitTableSource(e){return e}visitParenSource(e){let t=this.visit(e.source);return new je(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 Le(t,n,r)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new be(t,e.sortDirection,e.nullsPosition)}};var Gt=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(x.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(q.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ae.kind,t=>this.visitValuesQuery(t)),this.handlers.set(ee.kind,t=>this.visitWithClause(t)),this.handlers.set(X.kind,t=>this.visitCommonTable(t)),this.handlers.set($.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(R.kind,t=>this.visitSourceExpression(t)),this.handlers.set(M.kind,t=>this.visitTableSource(t)),this.handlers.set(Ue.kind,t=>this.visitFunctionSource(t)),this.handlers.set(je.kind,t=>this.visitParenSource(t)),this.handlers.set(z.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(Qe.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(Ve.kind,t=>this.visitOffsetClause(t)),this.handlers.set(De.kind,t=>this.visitFetchClause(t)),this.handlers.set(Be.kind,t=>this.visitForClause(t)),this.handlers.set(be.kind,t=>this.visitOrderByItem(t)),this.handlers.set(D.kind,t=>this.visitSelectClause(t)),this.handlers.set(J.kind,t=>this.visitSelectItem(t)),this.handlers.set(Y.kind,t=>this.visitParenExpression(t)),this.handlers.set(C.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(re.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(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(Se.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(U.kind,t=>this.visitFunctionCall(t)),this.handlers.set(ve.kind,t=>this.visitArrayExpression(t)),this.handlers.set(ge.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(xe.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(Je.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 B?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof B?e.qualifiedName.name.value:e.qualifiedName.name.name}collect(e){return this.visit(e),this.getTableSources()}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.selectableOnly||this.collectCTEs(e),this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}collectCTEs(e){let t=new ne;t.visit(e);let n=t.getCommonTables();for(let 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 Xe=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 Ze=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 o=r[i];Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&o.constructor&&o.constructor.kind&&n(o)}}}return n(e),t}};var Yt=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var Xt=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 mt=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 ze?e.setClause:new ze(e.setClause),this.whereClause=e.whereClause??null,this.fromClause=e.fromClause??null,this.returningClause=e.returning??null}};var Oe=class s{constructor(e=null,t=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=e??null,this.commonTableCollector=new ne,this.commonTables=[],this.initialCommonTables=t,this.handlers=new Map,this.handlers.set(x.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(D.kind,n=>this.visitSelectClause(n)),this.handlers.set(R.kind,n=>this.visitSourceExpression(n)),this.handlers.set($.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 E&&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 E&&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 o=i.getSourceAliasName();o&&n.includes(o)&&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 s(this.tableColumnResolver,r).collect(n.query).forEach(a=>{this.addSelectValueAsUnique(a.name,new E(e?[e]:null,a.name))})}else new s(this.tableColumnResolver,this.commonTables).collect(t).forEach(o=>{this.addSelectValueAsUnique(o.name,new E(e?[e]:null,o.name))})}visitSelectClause(e){for(let t of e.items)this.processSelectItem(t)}processSelectItem(e){if(e.identifier)this.addSelectValueAsUnique(e.identifier.name,e.value);else if(e.value instanceof E){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 E(t?[t]:null,n.name))});return}else if(e.datasource instanceof M){if(this.tableColumnResolver){let t=e.datasource.getSourceName();this.tableColumnResolver(t).forEach(n=>{this.addSelectValueAsUnique(n,new E([t],n))})}return}else if(e.datasource instanceof z){let t=e.getAliasName();new s(this.tableColumnResolver,this.commonTables).collect(e.datasource.query).forEach(i=>{this.addSelectValueAsUnique(i.name,new E(t?[t]:null,i.name))});return}else if(e.datasource instanceof je)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 dt=class extends f{static{this.kind=Symbol("CreateTableQuery")}constructor(e){super(),this.tableName=new b(e.tableName),this.isTemporary=e.isTemporary??!1,this.asSelectQuery=e.asSelectQuery}getSelectQuery(){let e;return this.asSelectQuery?e=new Oe().collect(this.asSelectQuery).map(r=>new J(r.value,r.name)):e=[new J(new B("*"))],new x({selectClause:new D(e),fromClause:new $(new R(new M(null,this.tableName.name),null),null)})}getCountQuery(){return new x({selectClause:new D([new J(new U(null,"count",new E(null,"*"),null))]),fromClause:new $(new R(new M(null,this.tableName.name),null),null)})}};var Kn={mysql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},postgres:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed"},postgresWithNamedParams:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"},sqlserver:{identifierEscape:{start:"[",end:"]"},parameterSymbol:"@",parameterStyle:"named"},sqlite:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"},oracle:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"},clickhouse:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},firebird:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},db2:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},snowflake:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},cloudspanner:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"@",parameterStyle:"named"},duckdb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},cockroachdb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed"},athena:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},bigquery:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"@",parameterStyle:"named"},hive:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},mariadb:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},redshift:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed"},flinksql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},mongodb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"}},Zt=class s{constructor(e){this.handlers=new Map;this.index=1;e?.preset&&(e={...e.preset,...e}),this.parameterDecorator=new Xt({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 Yt({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.handlers.set(_.kind,t=>this.visitValueList(t)),this.handlers.set(E.kind,t=>this.visitColumnReference(t)),this.handlers.set(Ae.kind,t=>this.visitQualifiedName(t)),this.handlers.set(U.kind,t=>this.visitFunctionCall(t)),this.handlers.set(re.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(C.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(H.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(B.kind,t=>this.visitRawString(t)),this.handlers.set(b.kind,t=>this.visitIdentifierString(t)),this.handlers.set(Y.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(ve.kind,t=>this.visitArrayExpression(t)),this.handlers.set(ge.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(Se.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(Je.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(Ee.kind,t=>this.visitTypeValue(t)),this.handlers.set(xe.kind,t=>this.visitTupleExpression(t)),this.handlers.set(Qe.kind,t=>this.visitInlineQuery(t)),this.handlers.set(Le.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(Me.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(it.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(st.kind,t=>this.visitWindowFrameBoundaryValue(t)),this.handlers.set($e.kind,t=>this.visitPartitionByClause(t)),this.handlers.set(ce.kind,t=>this.visitOrderByClause(t)),this.handlers.set(be.kind,t=>this.visitOrderByItem(t)),this.handlers.set(J.kind,t=>this.visitSelectItem(t)),this.handlers.set(D.kind,t=>this.visitSelectClause(t)),this.handlers.set(ot.kind,t=>this.visitDistinct(t)),this.handlers.set(at.kind,t=>this.visitDistinctOn(t)),this.handlers.set(Xe.kind,t=>this.visitHintClause(t)),this.handlers.set(M.kind,t=>this.visitTableSource(t)),this.handlers.set(Ue.kind,t=>this.visitFunctionSource(t)),this.handlers.set(R.kind,t=>this.visitSourceExpression(t)),this.handlers.set(G.kind,t=>this.visitSourceAliasExpression(t)),this.handlers.set($.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(He.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(Ve.kind,t=>this.visitOffsetClause(t)),this.handlers.set(De.kind,t=>this.visitFetchClause(t)),this.handlers.set(tt.kind,t=>this.visitFetchExpression(t)),this.handlers.set(Be.kind,t=>this.visitForClause(t)),this.handlers.set(ee.kind,t=>this.visitWithClause(t)),this.handlers.set(X.kind,t=>this.visitCommonTable(t)),this.handlers.set(x.kind,t=>this.visitSimpleQuery(t)),this.handlers.set(z.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(q.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ae.kind,t=>this.visitValuesQuery(t)),this.handlers.set(xe.kind,t=>this.visitTupleExpression(t)),this.handlers.set(_e.kind,t=>this.visitInsertQuery(t)),this.handlers.set(Ye.kind,t=>this.visitInsertClause(t)),this.handlers.set(mt.kind,t=>this.visitUpdateQuery(t)),this.handlers.set(lt.kind,t=>this.visitUpdateClause(t)),this.handlers.set(ze.kind,t=>this.visitSetClause(t)),this.handlers.set(Ge.kind,t=>this.visitSetClauseItem(t)),this.handlers.set(Ft.kind,t=>this.visitReturningClause(t)),this.handlers.set(dt.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(s.SPACE_TOKEN),t.innerTokens.push(new p(1,e.operator.value,"BinarySelectQueryOperator")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}static commaSpaceTokens(){return[s.COMMA_TOKEN,s.SPACE_TOKEN]}static argumentCommaSpaceTokens(){return[s.ARGUMENT_SPLIT_COMMA_TOKEN,s.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(s.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(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOrderByClause(e){let t=new p(1,"order by","OrderByClause");t.innerTokens.push(s.SPACE_TOKEN);for(let n=0;n<e.order.length;n++)n>0&&t.innerTokens.push(...s.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(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"desc"))),e.nullsPosition&&(e.nullsPosition==="first"?(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"nulls first"))):e.nullsPosition==="last"&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"nulls last")))),t}parse(e){this.index=1;let t=this.visit(e),n=Ze.collect(e).sort((i,o)=>(i.index??0)-(o.index??0)),r=this.parameterDecorator.style;if(r==="named"){let i={};for(let o of n){let a=o.name.value;if(i.hasOwnProperty(a)){if(i[a]!==o.value)throw new Error(`Duplicate parameter name '${a}' with different values detected during query composition.`);continue}i[a]=o.value}return{token:t,params:i}}else if(r==="indexed"){let i=n.map(o=>o.value);return{token:t,params:i}}else if(r==="anonymous"){let i=n.map(o=>o.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=[];for(let r of t)r.trim()&&n.push(new p(6,`/* ${r} */`));n.length>0&&e.innerTokens.unshift(...n)}visitValueList(e){let t=new p(0,"","ValueList");for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...s.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(s.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(s.PAREN_CLOSE_TOKEN),e.over&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"over")),e.over instanceof b?(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.over.accept(this))):(t.innerTokens.push(s.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.over)),t.innerTokens.push(s.PAREN_CLOSE_TOKEN))),t}visitUnaryExpression(e){let t=new p(0,"","UnaryExpression");return t.innerTokens.push(this.visit(e.operator)),t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(new p(5,e.operator.value)),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}visitLiteralValue(e){let t;return typeof e.value=="string"?t=`'${e.value.replace(/'/g,"''")}'`:e.value===null?t="null":t=e.value.toString(),new p(2,t,"LiteralValue")}visitParameterExpression(e){e.index=this.index;let t=this.parameterDecorator.decorate(e.name.value,e.index),n=new p(7,t);return this.index++,n}visitSwitchCaseArgument(e){let t=new p(0,"","SwitchCaseArgument");for(let n of e.cases)t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(n.accept(this));return e.elseValue&&(t.innerTokens.push(s.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(s.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(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.key)),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"then")),t.innerTokens.push(s.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(s.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition))),t.innerTokens.push(this.visit(e.switchCase)),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"end")),t}visitArrayExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(new p(1,"array")),t.innerTokens.push(new p(4,"[")),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(new p(4,"]")),t}visitArrayQueryExpression(e){let t=new p(0,"","ArrayExpression");return t.innerTokens.push(new p(1,"array")),t.innerTokens.push(new p(4,"(")),t.innerTokens.push(this.visit(e.query)),t.innerTokens.push(new p(4,")")),t}visitBetweenExpression(e){let t=new p(0,"","BetweenExpression");return t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(s.SPACE_TOKEN),e.negated&&(t.innerTokens.push(new p(1,"not")),t.innerTokens.push(s.SPACE_TOKEN)),t.innerTokens.push(new p(1,"between")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.lower)),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"and")),t.innerTokens.push(s.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(s.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(s.PAREN_CLOSE_TOKEN)),t}visitTupleExpression(e){let t=new p(0,"","TupleExpression");t.innerTokens.push(s.PAREN_OPEN_TOKEN);for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...s.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.order))),e.frameSpec&&(n?n=!1:t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this))):(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"between")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this)),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"and")),t.innerTokens.push(s.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(s.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 E){let n=e.value.column.name;if(e.identifier.name===n)return t}return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.identifier)),t}visitSelectClause(e){let t=new p(1,"select","SelectClause");t.innerTokens.push(s.SPACE_TOKEN);for(let n of e.hints)t.innerTokens.push(this.visit(n)),t.innerTokens.push(s.SPACE_TOKEN);e.distinct&&(t.innerTokens.push(e.distinct.accept(this)),t.innerTokens.push(s.SPACE_TOKEN));for(let n=0;n<e.items.length;n++)n>0&&t.innerTokens.push(...s.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[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(s.PAREN_OPEN_TOKEN),t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(s.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 M){let n=e.datasource.table.name;return e.aliasExpression.table.name===n||(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this))),t}else return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this)),t}visitFromClause(e){let t=new p(1,"from","FromClause");if(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.joins)for(let n=0;n<e.joins.length;n++)t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"lateral"))),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.condition&&(t.innerTokens.push(s.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(s.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(s.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.condition)),t.innerTokens.push(s.PAREN_CLOSE_TOKEN),t}visitFunctionSource(e){let t=new p(0,"","FunctionSource");return t.innerTokens.push(e.qualifiedName.accept(this)),t.innerTokens.push(s.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(s.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(s.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...s.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));t.innerTokens.push(s.PAREN_CLOSE_TOKEN)}return t}visitWhereClause(e){let t=new p(1,"where","WhereClause");return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitGroupByClause(e){let t=new p(1,"group by","GroupByClause");t.innerTokens.push(s.SPACE_TOKEN);for(let n=0;n<e.grouping.length;n++)n>0&&t.innerTokens.push(...s.commaSpaceTokens()),t.innerTokens.push(this.visit(e.grouping[n]));return t}visitHavingClause(e){let t=new p(1,"having","HavingClause");return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitWindowClause(e){let t=new p(1,"window","WindowClause");t.innerTokens.push(s.SPACE_TOKEN);for(let n=0;n<e.windows.length;n++)n>0&&t.innerTokens.push(...s.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(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(s.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(s.PAREN_CLOSE_TOKEN),t}visitLimitClause(e){let t=new p(1,"limit","LimitClause");return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOffsetClause(e){let t=new p(1,"offset","OffsetClause");return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitFetchClause(e){let t=new p(1,"fetch","FetchClause");return t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(e.count.accept(this)),e.unit&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,e.unit))),t}visitForClause(e){let t=new p(1,"for","ForClause");return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,e.lockMode)),t}visitWithClause(e){let t=new p(1,"with","WithClause");t.innerTokens.push(s.SPACE_TOKEN),e.recursive&&(t.innerTokens.push(new p(1,"recursive")),t.innerTokens.push(s.SPACE_TOKEN));for(let n=0;n<e.tables.length;n++)n>0&&t.innerTokens.push(...s.commaSpaceTokens()),t.innerTokens.push(e.tables[n].accept(this));return t.innerTokens.push(s.SPACE_TOKEN),t}visitCommonTable(e){let t=new p(0,"","CommonTable");t.innerTokens.push(e.aliasExpression.accept(this)),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(s.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(s.SPACE_TOKEN)),t.innerTokens.push(s.PAREN_OPEN_TOKEN);let n=new p(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this)),e.whereClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.groupByClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.groupByClause.accept(this))),e.havingClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.havingClause.accept(this))),e.orderByClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.orderByClause.accept(this))),e.windowClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.windowClause.accept(this))),e.limitClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.limitClause.accept(this))),e.offsetClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.offsetClause.accept(this))),e.fetchClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.fetchClause.accept(this))),e.forClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.forClause.accept(this)))),t}visitSubQuerySource(e){let t=new p(0,"");t.innerTokens.push(s.PAREN_OPEN_TOKEN);let n=new p(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(s.PAREN_CLOSE_TOKEN),t}visitValuesQuery(e){let t=new p(1,"values","ValuesQuery");t.innerTokens.push(s.SPACE_TOKEN);let n=new p(0,"","Values");for(let r=0;r<e.tuples.length;r++)r>0&&n.innerTokens.push(...s.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(s.PAREN_OPEN_TOKEN);let n=new p(0,"","InlineQuery");return n.innerTokens.push(e.selectQuery.accept(this)),t.innerTokens.push(n),t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(this.visit(e.selectQuery))),t}visitInsertClause(e){let t=new p(0,"");if(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"insert into")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),e.columns.length>0){t.innerTokens.push(s.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...s.commaSpaceTokens()),t.innerTokens.push(e.columns[n].accept(this));t.innerTokens.push(s.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(s.SPACE_TOKEN),t.innerTokens.push(e.setClause.accept(this)),e.fromClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this))),e.whereClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.returningClause&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.returningClause.accept(this))),t}visitUpdateClause(e){let t=new p(1,"update","UpdateClause");return t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t}visitSetClause(e){let t=new p(1,"set","SelectClause");t.innerTokens.push(s.SPACE_TOKEN);for(let n=0;n<e.items.length;n++)n>0&&t.innerTokens.push(...s.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(s.SPACE_TOKEN),t.innerTokens.push(new p(5,"=")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.value.accept(this)),t}visitReturningClause(e){let t=new p(1,"returning","ReturningClause");t.innerTokens.push(s.SPACE_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...s.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(s.SPACE_TOKEN),t.innerTokens.push(e.tableName.accept(this)),e.asSelectQuery&&(t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(new p(1,"as")),t.innerTokens.push(s.SPACE_TOKEN),t.innerTokens.push(e.asSelectQuery.accept(this))),t}};var bt=class{constructor(e=" ",t=0,n=`\r
|
|
12
|
+
`){this.indentChar=e,this.indentSize=t,this.newline=n,this.lines=[],this.appendNewline(0)}print(){let e="";for(let t of this.lines)t.text!==""&&(e+=this.indent(t.level)+t.text);return e.trimEnd()}indent(e){return this.indentChar.repeat(this.indentSize*e)}appendNewline(e){if(this.lines.length>0){let t=this.lines[this.lines.length-1];t.text!==""&&(t.text=t.text.trimEnd()+this.newline)}this.lines.push(new Qn(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.")}},Qn=class{constructor(e,t){this.level=e,this.text=t}};var en=class{constructor(e){this.indentChar=e?.indentChar??"",this.indentSize=e?.indentSize??0,this.newline=e?.newline??" ",this.commaBreak=e?.commaBreak??"none",this.andBreak=e?.andBreak??"none",this.keywordCase=e?.keywordCase??"none",this.exportComment=e?.exportComment??!1,this.strictCommentPlacement=e?.strictCommentPlacement??!1,this.linePrinter=new bt(this.indentChar,this.indentSize,this.newline),this.indentIncrementContainers=new Set(e?.indentIncrementContainerTypes??["SelectClause","FromClause","WhereClause","GroupByClause","HavingClause","WindowFrameExpression","PartitionByClause","OrderByClause","WindowClause","LimitClause","OffsetClause","SubQuerySource","BinarySelectQueryOperator","Values","WithClause","SwitchCaseArgument","CaseKeyValuePair","CaseThenValue","ElseClause","CaseElseValue"])}print(e,t=0){return this.linePrinter=new bt(this.indentChar,this.indentSize,this.newline),this.linePrinter.lines.length>0&&t!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=t),this.appendToken(e,t),this.linePrinter.print()}appendToken(e,t){if((!e.innerTokens||e.innerTokens.length===0)&&e.text==="")return;let n=this.linePrinter.getCurrentLine();if(e.type===1){let i=e.text;this.keywordCase==="upper"?i=i.toUpperCase():this.keywordCase==="lower"&&(i=i.toLowerCase()),this.linePrinter.appendText(i)}else if(e.type===3){let i=e.text;this.commaBreak==="before"?(this.linePrinter.appendNewline(t),this.linePrinter.appendText(i)):this.commaBreak==="after"?(this.linePrinter.appendText(i),this.linePrinter.appendNewline(t)):this.linePrinter.appendText(i)}else if(e.type===5&&e.text.toLowerCase()==="and"){let i=e.text;this.keywordCase==="upper"?i=i.toUpperCase():this.keywordCase==="lower"&&(i=i.toLowerCase()),this.andBreak==="before"?(this.linePrinter.appendNewline(t),this.linePrinter.appendText(i)):this.andBreak==="after"?(this.linePrinter.appendText(i),this.linePrinter.appendNewline(t)):this.linePrinter.appendText(i)}else if(e.containerType==="JoinClause"){let i=e.text;this.keywordCase==="upper"?i=i.toUpperCase():this.keywordCase==="lower"&&(i=i.toLowerCase()),this.linePrinter.appendNewline(t),this.linePrinter.appendText(i)}else e.type===6?this.exportComment&&(this.linePrinter.appendText(e.text),this.linePrinter.appendText(" ")):this.linePrinter.appendText(e.text);if(e.keywordTokens&&e.keywordTokens.length>0)for(let i=0;i<e.keywordTokens.length;i++){let o=e.keywordTokens[i];this.appendToken(o,t)}let r=t;this.newline!==" "&&n.text!==""&&this.indentIncrementContainers.has(e.containerType)&&(r++,this.linePrinter.appendNewline(r));for(let i=0;i<e.innerTokens.length;i++){let o=e.innerTokens[i];this.appendToken(o,r)}r!==t&&this.linePrinter.appendNewline(t)}};var eu=["mysql","postgres","sqlserver","sqlite"],ht=class{constructor(e={}){let t=e.preset?Kn[e.preset]:void 0;if(e.preset&&!t)throw new Error(`Invalid preset: ${e.preset}`);let n={...t,identifierEscape:e.identifierEscape??t?.identifierEscape,parameterSymbol:e.parameterSymbol??t?.parameterSymbol,parameterStyle:e.parameterStyle??t?.parameterStyle};this.parser=new Zt(n),this.printer=new en(e)}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var et=class{constructor(){this.sqlFormatter=new ht({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(e,t=null){return t&&(this.sqlFormatter=new ht(t)),this.sqlFormatter.format(e).formattedSql}formatWithParameters(e,t=null){t&&(this.sqlFormatter=new ht(t));let n=this.sqlFormatter.format(e);return{sql:n.formattedSql,params:n.params}}visit(e){return this.format(e)}};var tn=class{constructor(){this.sourceCollector=new Gt(!0),this.cteCollector=new ne,this.formatter=new et}build(e){if(e.length===0)return new ee(!1,e);let t=this.resolveDuplicateNames(e),{tableMap:n,recursiveCTEs:r,dependencies:i}=this.buildDependencyGraph(t),o=this.sortCommonTables(t,n,r,i);return new ee(r.size>0,o)}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 o=i.map(u=>this.formatter.format(u.query));if(new Set(o).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 o of e)t.set(o.aliasExpression.table.name,o);let n=new Set,r=new Map,i=new Map;for(let o of e){let a=o.aliasExpression.table.name,u=this.sourceCollector.collect(o.query);for(let c of u)if(c.table.name===a){n.add(a);break}r.has(a)||r.set(a,new Set);let l=this.cteCollector.collect(o.query);for(let c of l){let d=c.aliasExpression.table.name;t.has(d)&&(r.get(a).add(d),i.has(d)||i.set(d,new Set),i.get(d).add(a))}}return{tableMap:t,recursiveCTEs:n,dependencies:r}}sortCommonTables(e,t,n,r){let i=[],o=[],a=new Set,u=new Set,l=c=>{if(a.has(c))return;if(u.has(c))throw new Error(`Circular reference detected in CTE: ${c}`);u.add(c);let d=r.get(c)||new Set;for(let h of d)l(h);u.delete(c),a.add(c),n.has(c)?i.push(t.get(c)):o.push(t.get(c))};for(let c of e){let d=c.aliasExpression.table.name;a.has(d)||l(d)}return[...i,...o]}};var nn=class{constructor(){this.nameConflictResolver=new tn,this.cteCollector=new ne}inject(e,t){if(t.length===0)return e;t.push(...this.cteCollector.collect(e));let n=this.nameConflictResolver.build(t);if(e instanceof x)return this.injectIntoSimpleQuery(e,n);if(e instanceof q)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 x)return this.injectIntoSimpleQuery(e.left,t),e;if(e.left instanceof q)return this.injectIntoBinaryQuery(e.left,t),e;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var Ke=class{constructor(){}static normalize(e){let n=new ne().collect(e);return n.length===0?e:(new pt().execute(e),new nn().inject(e,n))}};var qn=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))(qn||{}),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 ne,this.commonTables=[],this.duplicateDetection=n,this.options=r||{},this.handlers=new Map,this.handlers.set(x.kind,i=>this.visitSimpleSelectQuery(i)),this.handlers.set(D.kind,i=>this.visitSelectClause(i)),this.handlers.set($.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(Ve.kind,i=>this.offsetClause(i)),this.handlers.set(De.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(E.kind,i=>this.visitColumnReference(i)),this.handlers.set(C.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(Y.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(Se.kind,i=>this.visitBetweenExpression(i)),this.handlers.set(ve.kind,i=>this.visitArrayExpression(i)),this.handlers.set(ge.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(Le.kind,i=>this.visitWindowFrameExpression(i)),this.handlers.set($e.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 o="";return i.value&&typeof i.value.getNamespace=="function"&&(o=i.value.getNamespace()||""),(o?o+"."+i.name:i.name)===r})||this.selectValues.push({name:e,value:t})}}visit(e){if(!this.isRootVisit){this.visitNode(e);return}if(!(e instanceof x))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 Oe(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 nt=class s{static parse(e){let n=new N(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?s.parseFunctionSource(e,r):s.parseTableSource(r)}static parseTableSource(e){let{namespaces:t,name:n,newIndex:r}=e;return{value:new M(t,n.name),newIndex:r}}static parseFunctionSource(e,t){let n=t.newIndex,{namespaces:r,name:i}=t,o=k.parseArgument(4,8,e,n);n=o.newIndex;let a=i.name;return{value:new Ue({namespaces:r,name:a},o.value),newIndex:n}}static parseParenSource(e,t){let n=t;if(n++,n>=e.length)throw new Error(`Syntax error: Unexpected end of input at position ${n}. Expected a subquery or nested expression after opening parenthesis.`);let 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}=j.parseFromLexeme(e,n);return n=i,{value:new z(r),newIndex:n}}};var Tt=class extends Error{constructor(t){super(`CTE '${t}' already exists in the query`);this.cteName=t;this.name="DuplicateCTEError"}},ft=class extends Error{constructor(t,n){super(`Invalid CTE name '${t}': ${n}`);this.cteName=t;this.name="InvalidCTENameError"}},kt=class extends Error{constructor(t){super(`CTE '${t}' not found in the query`);this.cteName=t;this.name="CTENotFoundError"}};var Ct=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 ne().collect(e),o=new Map;for(let a of i)o.set(a.getSourceAliasName(),a);return this.findUpstream(e,n,o)}handleTableSource(e,t,n){let r=n.get(e.table.name);if(r){let i=new Map(n);i.delete(e.table.name);let o=this.findUpstream(r.query,t,i);return o.length===0?null:o}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=[],o=!0,a=0;for(let u of r){let l=u.datasource,c=null;if(l instanceof M)c=this.handleTableSource(l,t,n),a++;else if(l instanceof z)c=this.handleSubQuerySource(l,t,n),a++;else{if(l instanceof ae)continue;o=!1;break}if(c===null){o=!1;break}i.push(c)}return o&&i.length===a?i.flat():null}findUpstream(e,t,n){if(e instanceof x){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),o=this.collectCTEColumns(e,n),a=[...i,...o],u=c=>this.options.ignoreCaseAndUnderscore?c.toLowerCase().replace(/_/g,""):c;return t.every(c=>a.some(d=>u(d)===u(c)))?[e]:[]}else if(e instanceof q){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 x)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 q)return this.collectColumnsFromSelectQuery(e.left);return[]}};var rt=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 G(r,i),newIndex:n}}return{value:new G(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 We=class{static parse(e){let n=new N(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=nt.parseTableSourceFromLexemes(e,t);return{value:new R(n.value,null),newIndex:n.newIndex}}static parseFromLexeme(e,t){let n=t,r=nt.parseFromLexeme(e,n);if(n=r.newIndex,n<e.length){if(e[n].value==="as"){n++;let o=rt.parseFromLexeme(e,n);return n=o.newIndex,{value:new R(r.value,o.value),newIndex:n}}if(n<e.length&&this.isTokenTypeAliasCandidate(e[n].type)){let o=rt.parseFromLexeme(e,n);return n=o.newIndex,{value:new R(r.value,o.value),newIndex:n}}}return{value:new R(r.value,null),newIndex:n}}static isTokenTypeAliasCandidate(e){return(e&64)!==0||(e&2048)!==0}};var Pe=class s{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?s.buildSimpleQuery(i):i,r=new q(n(e[0]),t,n(e[1]));Ke.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 x)return e;if(e instanceof q)return s.buildSimpleBinaryQuery(e);if(e instanceof ae)return s.buildSimpleValuesQuery(e);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(e){let t=new z(e),n=new R(t,new G("bq",null)),r=new $(n,null),i=s.createSelectAllClause(),o=new x({selectClause:i,fromClause:r});return Ke.normalize(o)}static buildSimpleValuesQuery(e){let t=e.tuples.length>0?e.tuples[0].values.length:0;if(e.tuples.length===0)throw new Error("Empty VALUES clause cannot be converted to a SimpleSelectQuery");if(!e.columnAliases)throw new Error("Column aliases are required to convert a VALUES clause to SimpleSelectQuery. Please specify column aliases.");if(e.columnAliases.length!==t)throw new Error(`The number of column aliases (${e.columnAliases.length}) does not match the number of columns in the first tuple (${t}).`);let n=new z(e),r=new R(n,new G("vq",e.columnAliases)),i=new $(r,null),o=e.columnAliases.map(u=>new J(new E("vq",u),u)),a=new D(o,null);return new x({selectClause:a,fromClause:i})}static createSelectAllClause(){let e=new E(null,"*"),t=new J(e,"*");return new D([t],null)}static buildCreateTableQuery(e,t,n=!1){return new dt({tableName:t,isTemporary:n,asSelectQuery:e})}static buildInsertQuery(e,t){let n,r=e.selectClause.items.length;if(n=new Oe().collect(e).map(u=>u.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.
|
|
13
13
|
Select clause column count: ${r}, Columns with valid names: ${n.length}
|
|
14
|
-
Detected column names: [${n.join(", ")}]`);let a=je.parse(t);return new qe({insertClause:new He(a,n),selectQuery:e})}static buildUpdateQuery(e,t,n,r){let i=new ot(je.parse(n)),o=Array.isArray(r)?r:[r],l=new Fe().collect(e),c=new ne().collect(e);new ut().execute(e);for(let P of o)if(!l.some(L=>L.name===P))throw new Error(`Primary key column '${P}' 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 g=l.filter(P=>!o.includes(P.name)).map(P=>new Ge(P.name,new E(h,P.name))),m=new _e(g),v=new $(e.toSource(t),null),A=null;for(let P of o){let L=new y(new E(h,P),"=",new E(t,P));A=A?new y(A,"and",L):L}let S=new ie(A);return new pt({updateClause:i,setClause:m,fromClause:v,whereClause:S,withClause:c.length>0?new ee(!1,c):void 0})}};var Xe=class{static set(e,t,n){let r=ct.collect(e),i=!1;for(let o of r)o.name.value===t&&(o.value=n,i=!0);if(!i)throw new Error(`Parameter '${t}' not found in query.`)}};var x=class extends f{static{this.kind=Symbol("SelectQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.selectClause=e.selectClause,this.fromClause=e.fromClause??null,this.whereClause=e.whereClause??null,this.groupByClause=e.groupByClause??null,this.havingClause=e.havingClause??null,this.orderByClause=e.orderByClause??null,this.windowClause=e.windowClause??null,this.limitClause=e.limitClause??null,this.offsetClause=e.offsetClause??null,this.fetchClause=e.fetchClause??null,this.forClause=e.forClause??null}toUnion(e){return this.toBinaryQuery("union",e)}toUnionAll(e){return this.toBinaryQuery("union all",e)}toIntersect(e){return this.toBinaryQuery("intersect",e)}toIntersectAll(e){return this.toBinaryQuery("intersect all",e)}toExcept(e){return this.toBinaryQuery("except",e)}toExceptAll(e){return this.toBinaryQuery("except all",e)}toBinaryQuery(e,t){return Ve.buildBinaryQuery([this,t],e)}appendWhereRaw(e){let t=k.parse(e);this.appendWhere(t)}appendWhere(e){this.whereClause?this.whereClause.condition=new y(this.whereClause.condition,"and",e):this.whereClause=new ie(e)}appendHavingRaw(e){let t=k.parse(e);this.appendHaving(t)}appendHaving(e){this.havingClause?this.havingClause.condition=new y(this.havingClause.condition,"and",e):this.havingClause=new me(e)}innerJoinRaw(e,t,n,r=null){this.joinSourceRaw("inner join",e,t,n,r)}leftJoinRaw(e,t,n,r=null){this.joinSourceRaw("left join",e,t,n,r)}rightJoinRaw(e,t,n,r=null){this.joinSourceRaw("right join",e,t,n,r)}innerJoin(e,t,n=null){this.joinSource("inner join",e,t,n)}leftJoin(e,t,n=null){this.joinSource("left join",e,t,n)}rightJoin(e,t,n=null){this.joinSource("right join",e,t,n)}joinSourceRaw(e,t,n,r,i=null){let o=et.parse(t),a=new V(o,new H(n,null));this.joinSource(e,a,r,i)}joinSource(e,t,n,r=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let i=Array.isArray(n)?n:[n],a=new Ie(r).collect(this),l=null,u=0,c=t.getAliasName();if(!c)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let C of a)if(i.some(g=>g==C.name)){let g=new y(C.value,"=",new E([c],C.name));l?l=new y(l,"and",g):l=g,u++}if(!l||u!==i.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${i.join(", ")}`);let d=new de(l),h=new he(e,t,d,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(h):this.fromClause.joins=[h]),Ke.normalize(this)}toSource(e){if(!e||e.trim()==="")throw new Error("Alias is required for toSource(). Please specify a non-empty alias name.");return new V(new z(this),new H(e,null))}appendWith(e){let t=Array.isArray(e)?e:[e];this.withClause?this.withClause.tables.push(...t):this.withClause=new ee(!1,t),Ke.normalize(this)}appendWithRaw(e,t){let n=W.parse(e),r=new Z(n,t,null);this.appendWith(r)}overrideSelectItemExpr(e,t){let n=this.selectClause.items.filter(l=>l.identifier?.name===e);if(n.length===0)throw new Error(`Column ${e} not found in the query`);if(n.length>1)throw new Error(`Duplicate column name ${e} found in the query`);let r=n[0],o=new Ye().visit(r.value),a=t(o);r.value=k.parse(a)}appendWhereExpr(e,t,n){if(n&&n.upstream){let i=new ht().find(this,[e]),o=new Ie,a=new Ye;for(let l of i){let u=o.collect(l).filter(d=>d.name===e).map(d=>d.value);if(u.length!==1)throw new Error(`Expected exactly one expression for column '${e}'`);let c=a.format(u[0]);l.appendWhereRaw(t(c))}}else{let r=new Ie,i=new Ye,o=r.collect(this).filter(l=>l.name===e).map(l=>l.value);if(o.length!==1)throw new Error(`Expected exactly one expression for column '${e}'`);let a=i.format(o[0]);this.appendWhereRaw(t(a))}}setParameter(e,t){return Xe.set(this,e,t),this}};var q=class s extends f{static{this.kind=Symbol("BinarySelectQuery")}constructor(e,t,n){super(),this.left=e,this.operator=new B(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 s(this.left,this.operator.value,this.right),this.operator=new B(e),this.right=t,Ke.normalize(this),this}unionRaw(e){let t=W.parse(e);return this.union(t)}unionAllRaw(e){let t=W.parse(e);return this.unionAll(t)}intersectRaw(e){let t=W.parse(e);return this.intersect(t)}intersectAllRaw(e){let t=W.parse(e);return this.intersectAll(t)}exceptRaw(e){let t=W.parse(e);return this.except(t)}exceptAllRaw(e){let t=W.parse(e);return this.exceptAll(t)}toSource(e="subq"){return new V(new z(this),new H(e,null))}setParameter(e,t){return Xe.set(this,e,t),this}};var ae=class extends f{static{this.kind=Symbol("ValuesQuery")}constructor(e,t=null){super(),this.tuples=e,this.columnAliases=t}toSimpleSelectQuery(){return Ve.buildSimpleQuery(this)}setParameter(e,t){return Xe.set(this,e,t),this}};var Yt=class{static parse(e){let n=new N(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;if(e[n].value!=="select")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword but found "${e[n].value}". SELECT clauses must start with the SELECT keyword.`);if(n++,n<e.length&&e[n].value==="distinct")n++,r=new it;else if(n<e.length&&e[n].value==="distinct on"){n++;let a=k.parseArgument(4,8,e,n);r=new st(a.value),n=a.newIndex}let i=[],o=Xt.parseItem(e,n);for(i.push(o.value),n=o.newIndex;n<e.length&&e[n].type&16;){n++;let a=Xt.parseItem(e,n);i.push(a.value),n=a.newIndex}if(i.length===0)throw new Error(`Syntax error at position ${t}: No select items found. The SELECT clause requires at least one expression to select.`);return{value:new U(i,r),newIndex:n}}},Xt=class{static parse(e){let n=new N(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 o=e[n].value;return n++,{value:new J(i,o),newIndex:n}}else if(i instanceof E&&i.column.name!=="*")return{value:new J(i,i.column.name),newIndex:n};return{value:new J(i),newIndex:n}}};var Zt=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 en=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 tn=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!!bn.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),o=i.value;n=i.newIndex;let a=je.parseFromLexeme(e,n);if(n=a.newIndex,n<e.length){let u=Zt.tryParse(e,n);if(u)return{value:new he(r,a.value,u.value,o),newIndex:u.newIndex};let c=en.tryParse(e,n);if(c)return{value:new he(r,a.value,c.value,o),newIndex:c.newIndex}}return{value:new he(r,a.value,null,o),newIndex:n}}};var nn=class{static parse(e){let n=new N(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;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 r=je.parseFromLexeme(e,n);n=r.newIndex;let i=tn.tryParse(e,n);return n=i?.newIndex||n,i!==null?{value:new $(r.value,i.value),newIndex:n}:{value:new $(r.value,null),newIndex:n}}};var rn=class{static parse(e){let n=new N(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;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 r=k.parseFromLexeme(e,n);return{value:new ie(r.value),newIndex:r.newIndex}}};var sn=class{static parse(e){let n=new N(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 o=this.parseItem(e,n);r.push(o.value),n=o.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 on=class{static parse(e){let n=new N(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 an=class{static parse(e){let n=new N(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 o=lt.parseFromLexeme(e,n);if(n=o.newIndex,r.push(new ye(i,o.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 ln=class{static parse(e){let n=new N(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 un=class{static parse(e){let n=new N(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 Qe(i),newIndex:n}}};var gt=class{static parse(e){let n=new N(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=tt.parseFromLexeme(e,n);if(n=r.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 i=null;if(n<e.length){let l=e[n].value;l==="materialized"?(i=!0,n++):l==="not materialized"&&(i=!1,n++)}if(n<e.length&&e[n].type!==4)throw new Error(`Syntax error at position ${n}: Expected '(' after CTE name but found "${e[n].value}".`);n++;let o=W.parseFromLexeme(e,n);if(n=o.newIndex,n<e.length&&e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected ')' after CTE query but found "${e[n].value}".`);return n++,{value:new Z(o.value,r.value,i),newIndex:n}}};var ft=class{static parse(e){let n=new N(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;if(n<e.length&&e[n].value.toLowerCase()==="with")n++;else throw new Error(`Syntax error at position ${n}: Expected WITH keyword.`);let r=n<e.length&&e[n].value.toLowerCase()==="recursive";r&&n++;let i=[],o=gt.parseFromLexeme(e,n);for(i.push(o.value),n=o.newIndex;n<e.length&&e[n].type&16;){n++;let a=gt.parseFromLexeme(e,n);i.push(a.value),n=a.newIndex}return{value:new ee(r,i),newIndex:n}}};var cn=class{static parse(e){let n=new N(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 xe([]),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 o=k.parseFromLexeme(e,n);r.push(o.value),n=o.newIndex}if(n>=e.length||e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected closing parenthesis but found "${n<e.length?e[n].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);return n++,{value:new xe(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=kn.parseFromLexeme(e,n),i=r.value;return n=r.newIndex,{value:new Ue(i),newIndex:n}}},kn=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 o=null,a=null;if(e[n].value==="row only"||e[n].value==="rows only")return o=new G(1),a="rows only",n++,{value:new Ze(r,o,a),newIndex:n};let l=k.parseFromLexeme(e,n);if(o=l.value,n=l.newIndex,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT <count>'.");if(e[n].value==="rows only"?(a="rows only",n++):e[n].value==="percent"?(a="percent",n++):e[n].value==="percent with ties"&&(a="percent with ties",n++),!a)throw new Error("Syntax error: Expected 'ROWS ONLY', 'PERCENT', or 'PERCENT WITH TIES' after 'FETCH FIRST|NEXT <count>'.");return{value:new Ze(r,o,a),newIndex:n}}};var mn=class{static parse(e){let n=new N(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 Re(r.value),newIndex:n}}};var W=class{static parse(e){let n=new N(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),o=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);o=new q(o,a,u.value),n=u.newIndex}else if(l==="values"){let u=this.parseValuesQuery(e,n);o=new q(o,a,u.value),n=u.newIndex}else throw new Error(`Syntax error at position ${n}: Expected 'SELECT' or 'VALUES' after '${a.toUpperCase()}' but found "${e[n].value}".`)}return{value:o,newIndex:n}}static parseSimpleSelectQuery(e,t){let n=t,r=null;if(n<e.length&&e[n].value==="with"&&(r=ft.parseFromLexeme(e,n),n=r.newIndex),n>=e.length||e[n].value!=="select")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword but found "${n<e.length?e[n].value:"end of input"}". SELECT queries must start with the SELECT keyword.`);let i=Yt.parseFromLexeme(e,n);n=i.newIndex;let o=null;n<e.length&&e[n].value==="from"&&(o=nn.parseFromLexeme(e,n),n=o.newIndex);let a=null;n<e.length&&e[n].value==="where"&&(a=rn.parseFromLexeme(e,n),n=a.newIndex);let l=null;n<e.length&&e[n].value==="group by"&&(l=sn.parseFromLexeme(e,n),n=l.newIndex);let u=null;n<e.length&&e[n].value==="having"&&(u=on.parseFromLexeme(e,n),n=u.newIndex);let c=null;n<e.length&&e[n].value==="window"&&(c=an.parseFromLexeme(e,n),n=c.newIndex);let d=null;n<e.length&&e[n].value==="order by"&&(d=at.parseFromLexeme(e,n),n=d.newIndex);let h=null;n<e.length&&e[n].value==="limit"&&(h=ln.parseFromLexeme(e,n),n=h.newIndex);let C=null;n<e.length&&e[n].value==="offset"&&(C=mn.parseFromLexeme(e,n),n=C.newIndex);let g=null;n<e.length&&e[n].value==="fetch"&&(g=pn.parseFromLexeme(e,n),n=g.newIndex);let m=null;return n<e.length&&e[n].value.toLowerCase()==="for"&&(m=un.parseFromLexeme(e,n),n=m.newIndex),{value:new x({withClause:r?r.value:null,selectClause:i.value,fromClause:o?o.value:null,whereClause:a?a.value:null,groupByClause:l?l.value:null,havingClause:u?u.value:null,orderByClause:d?d.value:null,windowClause:c?c.value:null,limitClause:h?h.value:null,offsetClause:C?C.value:null,fetchClause:g?g.value:null,forClause:m?m.value:null}),newIndex:n}}static parseValuesQuery(e,t){let n=cn.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}};var Wn=class{static parse(e){let n=new N(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=ft.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 o=[];if(e[n]?.type===4){for(n++;n<e.length&&e[n].type===64&&(o.push(e[n].value),n++,e[n]?.type===16);)n++;if(e[n]?.type!==8)throw new Error(`Syntax error at position ${n}: Expected ')' after column list.`);n++}let a=W.parseFromLexeme(e,n);if(r)if(a.value instanceof x)a.value.withClause=r;else throw new Error("WITH clause is not supported in this context.");return n=a.newIndex,{value:new qe({insertClause:new He(i.value,o),selectQuery:a.value}),newIndex:n}}};var dn=class s{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,o=this.collectAndSortObjectEntities(n,t),a=this.groupEntitiesByDepth(o),l=Array.from(a.keys()).sort((u,c)=>c-u);for(let u of l){let c=a.get(u),d=`${s.CTE_OBJECT_PREFIX}${u}`,h=this.buildDepthCte(c,i,d,n,t);r.push(h),i=d}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 o=t.get(i);if(!o)throw new Error(`Entity ${i} not found for depth calculation.`);if(o.isRoot)return 0;if(!o.parentId)return 1;let a=o.parentId,l=0,u=new Set;for(u.add(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 d=!1;if(c.isRoot)d=!0;else{let h=e.nestedEntities.find(C=>C.id===a);if(h)h.relationshipType==="object"&&(d=!0);else throw new Error(`Parent entity ${a} (ancestor of ${i}) has no definition in mapping.nestedEntities and is not root.`)}if(d&&l++,c.isRoot)break;a=c.parentId}return l};return e.nestedEntities.forEach(i=>{if(i.relationshipType==="object"){let o=t.get(i.id);o&&!o.isRoot&&n.push({entity:o,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 o=[new J(new E(null,new b(s.WILDCARD_COLUMN)))];for(let{entity:l}of e){let u=this.buildEntityJsonColumn(l,r,i);o.push(u)}let a=new x({selectClause:new U(o),fromClause:new $(new V(new M(null,new b(t)),null),null)});return new Z(a,new H(n,null),null)}buildEntityJsonColumn(e,t,n){let{jsonObjectArgs:r,nullChecks:i}=this.prepareEntityColumns(e);this.addChildObjectRelationships(e,r,t,n);let o=this.createJsonObject(r),a=this.buildNullCondition(i),l=this.createCaseExpression(a,o),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(o=>o.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 E(null,new b(i))),n.push(new y(new E(null,new b(i)),"is",new G(null)))}),{jsonObjectArgs:t,nullChecks:n}}addChildObjectRelationships(e,t,n,r){n.nestedEntities.filter(o=>o.parentId===e.id&&o.relationshipType==="object").forEach(o=>{let a=r.get(o.id);if(a){t.push(new G(o.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 E(null,new b(l)))}})}createJsonObject(e){let t="jsonb_build_object";return new D(null,new B(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 Ce([new we(e,new G(null))],t))}};var hn=class s{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 o=[...e],a=t,l=this.collectAndSortArrayEntities(r,n);if(l.length===0)return{updatedCtes:o,lastCteAlias:a};let u=this.groupEntitiesByDepth(l),c=Array.from(u.keys()).sort((d,h)=>h-d);for(let d of c){let h=u.get(d),{cte:C,newCteAlias:g}=this.buildDepthCte(h,a,o,d,r,i);o.push(C),a=g}return{updatedCtes:o,lastCteAlias:a}}collectAndSortArrayEntities(e,t){let n=[],r=i=>{let o=t.get(i);return!o||o.isRoot?0:o.parentId?1+r(o.parentId):1};return e.nestedEntities.forEach(i=>{if(i.relationshipType==="array"){let o=t.get(i.id),a=t.get(i.parentId);if(!o||!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:o,parentEntity:a,parentIdColumnSqlName:u,depth:r(i.id)})}}),n.sort((i,o)=>o.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,o){let a=new Set;e.forEach(S=>{Object.values(S.entity.columns).forEach(P=>a.add(P));let F=P=>{i.nestedEntities.filter(L=>L.parentId===P).forEach(L=>{Object.values(L.columns).forEach(w=>{let I=typeof w=="string"?w:w.column;a.add(I)}),F(L.id)})};F(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 Fe(null,n).collect(l),c=[],d=[],h=new Set;e.forEach(S=>{Object.values(S.entity.columns).forEach(F=>h.add(F))});let C=this.collectArrayEntityColumnsByDepth(i,r),g=new Set;o&&e.forEach(S=>{i.nestedEntities.filter(F=>F.parentId===S.entity.id&&F.relationshipType==="object").forEach(F=>{let P=o.find(L=>L.entityId===F.id);P&&g.add(P.generatedColumnName)})}),this.processSelectVariablesForGroupBy(u,a,C,r,d,c,g);for(let S of e){let F=this.buildAggregationDetailsForArrayEntity(S.entity,i.nestedEntities,new Map,o);d.push(new J(F.jsonAgg,S.entity.propertyName))}let m=`${s.CTE_ARRAY_PREFIX}${r}`,v=new x({selectClause:new U(d),fromClause:new $(new V(new M(null,new b(t)),null),null),groupByClause:c.length>0?new pe(c):null});return{cte:new Z(v,new H(m,null),null),newCteAlias:m}}buildAggregationDetailsForArrayEntity(e,t,n,r){let i=s.JSON_FUNCTIONS.BUILD_OBJECT,o=[];Object.entries(e.columns).forEach(([h,C])=>{o.push(new G(h)),o.push(new E(null,new b(C)))}),t.filter(h=>h.parentId===e.id).forEach(h=>{let C=h.originalPropertyName||h.propertyName;if(o.push(new G(C)),h.relationshipType==="object"){if(!r)throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mappings not provided
|
|
14
|
+
Detected column names: [${n.join(", ")}]`);let a=We.parse(t);return new _e({insertClause:new Ye(a,n),selectQuery:e})}static buildUpdateQuery(e,t,n,r){let i=new lt(We.parse(n)),o=Array.isArray(r)?r:[r],u=new Oe().collect(e),c=new ne().collect(e);new pt().execute(e);for(let P of o)if(!u.some(L=>L.name===P))throw new Error(`Primary key column '${P}' 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 S=u.filter(P=>!o.includes(P.name)).map(P=>new Ge(P.name,new E(h,P.name))),m=new ze(S),w=new $(e.toSource(t),null),Q=null;for(let P of o){let L=new C(new E(h,P),"=",new E(t,P));Q=Q?new C(Q,"and",L):L}let g=new ie(Q);return new mt({updateClause:i,setClause:m,fromClause:w,whereClause:g,withClause:c.length>0?new ee(!1,c):void 0})}};var qe=class{static set(e,t,n){let r=Ze.collect(e),i=!1;for(let o of r)o.name.value===t&&(o.value=n,i=!0);if(!i)throw new Error(`Parameter '${t}' not found in query.`)}};var x=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 Pe.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 ie(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 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,o=null){let a=nt.parse(n),u=new R(a,new G(r,null));this.joinSource(t,u,i,o)}joinSource(t,n,r,i=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let o=Array.isArray(r)?r:[r],u=new Ie(i).collect(this),l=null,c=0,d=n.getAliasName();if(!d)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let S of u)if(o.some(m=>m==S.name)){let m=new C(S.value,"=",new E([d],S.name));l?l=new C(l,"and",m):l=m,c++}if(!l||c!==o.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${o.join(", ")}`);let h=new de(l),y=new he(t,n,h,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(y):this.fromClause.joins=[y]),Ke.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 R(new z(this),new G(t,null))}appendWith(t){let n=Array.isArray(t)?t:[t];this.withClause?this.withClause.tables.push(...n):this.withClause=new ee(!1,n),Ke.normalize(this)}appendWithRaw(t,n){let r=j.parse(t),i=new X(r,n,null);this.appendWith(i)}overrideSelectItemExpr(t,n){let r=this.selectClause.items.filter(l=>l.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 et().visit(i.value),u=n(a);i.value=k.parse(u)}appendWhereExpr(t,n,r){if(r&&r.upstream){let o=new Ct().find(this,[t]),a=new Ie,u=new et;for(let l of o){let c=a.collect(l).filter(h=>h.name===t).map(h=>h.value);if(c.length!==1)throw new Error(`Expected exactly one expression for column '${t}'`);let d=u.format(c[0]);l.appendWhereRaw(n(d))}}else{let i=new Ie,o=new et,a=i.collect(this).filter(l=>l.name===t).map(l=>l.value);if(a.length!==1)throw new Error(`Expected exactly one expression for column '${t}'`);let u=o.format(a[0]);this.appendWhereRaw(n(u))}}setParameter(t,n){return qe.set(this,t,n),this}toSimpleQuery(){return this}addCTE(t,n,r){if(!t||t.trim()==="")throw new ft(t,"name cannot be empty or whitespace-only");if(this.hasCTE(t))throw new Tt(t);let i=r?.materialized??null,o=new X(n,t,i);return this.appendWith(o),this.cteNameCache.add(t),this}removeCTE(t){if(!this.hasCTE(t))throw new kt(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 ft(t,"name cannot be empty or whitespace-only");this.hasCTE(t)&&this.removeCTE(t);let i=r?.materialized??null,o=new X(n,t,i);return this.appendWith(o),this.cteNameCache.add(t),this}};var q=class s extends f{static{this.kind=Symbol("BinarySelectQuery")}constructor(e,t,n){super(),this.left=e,this.operator=new B(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 s(this.left,this.operator.value,this.right),this.operator=new B(e),this.right=t,Ke.normalize(this),this}unionRaw(e){let t=j.parse(e);return this.union(t)}unionAllRaw(e){let t=j.parse(e);return this.unionAll(t)}intersectRaw(e){let t=j.parse(e);return this.intersect(t)}intersectAllRaw(e){let t=j.parse(e);return this.intersectAll(t)}exceptRaw(e){let t=j.parse(e);return this.except(t)}exceptAllRaw(e){let t=j.parse(e);return this.exceptAll(t)}toSource(e="subq"){return new R(new z(this),new G(e,null))}setParameter(e,t){return qe.set(this,e,t),this}toSimpleQuery(){return Pe.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 Pe.buildSimpleQuery(this)}setParameter(e,t){return qe.set(this,e,t),this}};var rn=class{static parse(e){let n=new N(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 o=[];for(;n<e.length&&Xe.isHintClause(e[n].value);){let l=Xe.extractHintContent(e[n].value);o.push(new Xe(l)),n++}if(n<e.length&&e[n].value==="distinct")n++,r=new ot;else if(n<e.length&&e[n].value==="distinct on"){n++;let l=k.parseArgument(4,8,e,n);r=new at(l.value),n=l.newIndex}let a=[],u=sn.parseItem(e,n);for(a.push(u.value),n=u.newIndex;n<e.length&&e[n].type&16;){n++;let l=sn.parseItem(e,n);a.push(l.value),n=l.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 l=new D(a,r,o);return l.comments=i,{value:l,newIndex:n}}}},sn=class{static parse(e){let n=new N(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 o=e[n].value;return n++,{value:new J(i,o),newIndex:n}}else if(i instanceof E&&i.column.name!=="*")return{value:new J(i,i.column.name),newIndex:n};return{value:new J(i),newIndex:n}}};var on=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 an=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 ln=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!!On.parse(e,0)}static parseLateral(e,t){let n=t;return n<e.length&&e[n].value==="lateral"?(n++,{value:!0,newIndex:n}):{value:!1,newIndex:n}}static isJoinCommand(e,t){return t>=e.length?!1:!!(e[t].type&16||this.isJoinKeyword(e[t].value)===!0)}static parseJoinClause(e,t){let n=t,r=e[n].value===","?"cross join":e[n].value;n++;let i=this.parseLateral(e,n),o=i.value;n=i.newIndex;let a=We.parseFromLexeme(e,n);if(n=a.newIndex,n<e.length){let l=on.tryParse(e,n);if(l)return{value:new he(r,a.value,l.value,o),newIndex:l.newIndex};let c=an.tryParse(e,n);if(c)return{value:new he(r,a.value,c.value,o),newIndex:c.newIndex}}return{value:new he(r,a.value,null,o),newIndex:n}}};var yt=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 o=e[i];if(o.comments&&o.comments.length>0){let a=o.comments.filter(u=>{let l=u.toLowerCase();return l.includes(n.toLowerCase())||l.includes("\u306E")||l.includes("\u30B3\u30E1\u30F3\u30C8")});a.length>0&&(r.unshift(...a),o.comments=o.comments.filter(u=>!a.includes(u)),o.comments.length===0&&(o.comments=null));break}if(this.isSignificantSqlKeyword(o.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 un=class{static parse(e){let n=new N(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=yt.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=We.parseFromLexeme(e,n);n=i.newIndex;let o=ln.tryParse(e,n);if(n=o?.newIndex||n,o!==null){let a=new $(i.value,o.value);return a.comments=r,{value:a,newIndex:n}}else{let a=new $(i.value,null);return a.comments=r,{value:a,newIndex:n}}}};var cn=class{static parse(e){let n=new N(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=yt.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),o=new ie(i.value);return o.comments=r,{value:o,newIndex:i.newIndex}}};var pn=class{static parse(e){let n=new N(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 o=this.parseItem(e,n);r.push(o.value),n=o.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 mn=class{static parse(e){let n=new N(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 dn=class{static parse(e){let n=new N(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 o=ct.parseFromLexeme(e,n);if(n=o.newIndex,r.push(new Ce(i,o.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 He(r),newIndex:n}}};var hn=class{static parse(e){let n=new N(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 fn=class{static parse(e){let n=new N(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 It=class{static parse(e){let n=new N(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=rt.parseFromLexeme(e,n);if(n=r.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 i=null;if(n<e.length){let u=e[n].value;u==="materialized"?(i=!0,n++):u==="not materialized"&&(i=!1,n++)}if(n<e.length&&e[n].type!==4)throw new Error(`Syntax error at position ${n}: Expected '(' after CTE name but found "${e[n].value}".`);n++;let o=j.parseFromLexeme(e,n);if(n=o.newIndex,n<e.length&&e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected ')' after CTE query but found "${e[n].value}".`);return n++,{value:new X(o.value,r.value,i),newIndex:n}}};var wt=class{static parse(e){let n=new N(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;if(n<e.length&&e[n].value.toLowerCase()==="with")n++;else throw new Error(`Syntax error at position ${n}: Expected WITH keyword.`);let r=n<e.length&&e[n].value.toLowerCase()==="recursive";r&&n++;let i=[],o=It.parseFromLexeme(e,n);for(i.push(o.value),n=o.newIndex;n<e.length&&e[n].type&16;){n++;let a=It.parseFromLexeme(e,n);i.push(a.value),n=a.newIndex}return{value:new ee(r,i),newIndex:n}}};var Cn=class{static parse(e){let n=new N(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 xe([]),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 o=k.parseFromLexeme(e,n);r.push(o.value),n=o.newIndex}if(n>=e.length||e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected closing parenthesis but found "${n<e.length?e[n].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);return n++,{value:new xe(r),newIndex:n}}};var yn=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=Ln.parseFromLexeme(e,n),i=r.value;return n=r.newIndex,{value:new De(i),newIndex:n}}},Ln=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 o=null,a=null;if(e[n].value==="row only"||e[n].value==="rows only")return o=new H(1),a="rows only",n++,{value:new tt(r,o,a),newIndex:n};let u=k.parseFromLexeme(e,n);if(o=u.value,n=u.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 tt(r,o,a),newIndex:n}}};var wn=class{static parse(e){let n=new N(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 Ve(r.value),newIndex:n}}};var j=class{static parse(e){let n=new N(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),o=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 u=e[n].value.toLowerCase();if(this.selectCommandSet.has(u)){let l=this.parseSimpleSelectQuery(e,n);o=new q(o,a,l.value),n=l.newIndex}else if(u==="values"){let l=this.parseValuesQuery(e,n);o=new q(o,a,l.value),n=l.newIndex}else throw new Error(`Syntax error at position ${n}: Expected 'SELECT' or 'VALUES' after '${a.toUpperCase()}' but found "${e[n].value}".`)}return{value:o,newIndex:n}}static parseSimpleSelectQuery(e,t){let n=t,r=null,i=n<e.length?e[n].comments:null;if(n<e.length&&e[n].value==="with"&&(r=wt.parseFromLexeme(e,n),n=r.newIndex),n>=e.length||e[n].value!=="select")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword but found "${n<e.length?e[n].value:"end of input"}". SELECT queries must start with the SELECT keyword.`);let o=rn.parseFromLexeme(e,n);n=o.newIndex,i&&o.value.comments&&JSON.stringify(i)===JSON.stringify(o.value.comments)&&(o.value.comments=null);let a=null;n<e.length&&e[n].value==="from"&&(a=un.parseFromLexeme(e,n),n=a.newIndex);let u=null;n<e.length&&e[n].value==="where"&&(u=cn.parseFromLexeme(e,n),n=u.newIndex);let l=null;n<e.length&&e[n].value==="group by"&&(l=pn.parseFromLexeme(e,n),n=l.newIndex);let c=null;n<e.length&&e[n].value==="having"&&(c=mn.parseFromLexeme(e,n),n=c.newIndex);let d=null;n<e.length&&e[n].value==="window"&&(d=dn.parseFromLexeme(e,n),n=d.newIndex);let h=null;n<e.length&&e[n].value==="order by"&&(h=ut.parseFromLexeme(e,n),n=h.newIndex);let y=null;n<e.length&&e[n].value==="limit"&&(y=hn.parseFromLexeme(e,n),n=y.newIndex);let S=null;n<e.length&&e[n].value==="offset"&&(S=wn.parseFromLexeme(e,n),n=S.newIndex);let m=null;n<e.length&&e[n].value==="fetch"&&(m=yn.parseFromLexeme(e,n),n=m.newIndex);let w=null;n<e.length&&e[n].value.toLowerCase()==="for"&&(w=fn.parseFromLexeme(e,n),n=w.newIndex);let Q=new x({withClause:r?r.value:null,selectClause:o.value,fromClause:a?a.value:null,whereClause:u?u.value:null,groupByClause:l?l.value:null,havingClause:c?c.value:null,orderByClause:h?h.value:null,windowClause:d?d.value:null,limitClause:y?y.value:null,offsetClause:S?S.value:null,fetchClause:m?m.value:null,forClause:w?w.value:null});return Q.comments=i,{value:Q,newIndex:n}}static parseValuesQuery(e,t){let n=Cn.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}};var _n=class{static parse(e){let n=new N(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 u=wt.parseFromLexeme(e,n);r=u.value,n=u.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=We.parseTableSourceFromLexemes(e,n);n=i.newIndex;let o=[];if(e[n]?.type===4){for(n++;n<e.length&&e[n].type===64&&(o.push(e[n].value),n++,e[n]?.type===16);)n++;if(e[n]?.type!==8)throw new Error(`Syntax error at position ${n}: Expected ')' after column list.`);n++}let a=j.parseFromLexeme(e,n);if(r)if(a.value instanceof x)a.value.withClause=r;else throw new Error("WITH clause is not supported in this context.");return n=a.newIndex,{value:new _e({insertClause:new Ye(i.value,o),selectQuery:a.value}),newIndex:n}}};var vn=class s{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,o=this.collectAndSortObjectEntities(n,t),a=this.groupEntitiesByDepth(o),u=Array.from(a.keys()).sort((l,c)=>c-l);for(let l of u){let c=a.get(l),d=`${s.CTE_OBJECT_PREFIX}${l}`,h=this.buildDepthCte(c,i,d,n,t);r.push(h),i=d}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 o=t.get(i);if(!o)throw new Error(`Entity ${i} not found for depth calculation.`);if(o.isRoot)return 0;if(!o.parentId)return 1;let a=o.parentId,u=0,l=new Set;for(l.add(i);a;){if(l.has(a))throw new Error(`Circular dependency detected: ${a} already visited in path for ${i}`);l.add(a);let c=t.get(a);if(!c)throw new Error(`Parent entity ${a} not found during depth calculation for ${i}`);let d=!1;if(c.isRoot)d=!0;else{let h=e.nestedEntities.find(y=>y.id===a);if(h)h.relationshipType==="object"&&(d=!0);else throw new Error(`Parent entity ${a} (ancestor of ${i}) has no definition in mapping.nestedEntities and is not root.`)}if(d&&u++,c.isRoot)break;a=c.parentId}return u};return e.nestedEntities.forEach(i=>{if(i.relationshipType==="object"){let o=t.get(i.id);o&&!o.isRoot&&n.push({entity:o,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 o=[new J(new E(null,new b(s.WILDCARD_COLUMN)))];for(let{entity:u}of e){let l=this.buildEntityJsonColumn(u,r,i);o.push(l)}let a=new x({selectClause:new D(o),fromClause:new $(new R(new M(null,new b(t)),null),null)});return new X(a,new G(n,null),null)}buildEntityJsonColumn(e,t,n){let{jsonObjectArgs:r,nullChecks:i}=this.prepareEntityColumns(e);this.addChildObjectRelationships(e,r,t,n);let o=this.createJsonObject(r),a=this.buildNullCondition(i),u=this.createCaseExpression(a,o),l=this.calculateApproximateDepth(e,t),c=this.generateUniqueJsonColumnName(e.name,e.id,l);return this.entityToJsonColumnMap.set(e.id,c),new J(u,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(o=>o.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 H(r)),t.push(new E(null,new b(i))),n.push(new C(new E(null,new b(i)),"is",new H(null)))}),{jsonObjectArgs:t,nullChecks:n}}addChildObjectRelationships(e,t,n,r){n.nestedEntities.filter(o=>o.parentId===e.id&&o.relationshipType==="object").forEach(o=>{let a=r.get(o.id);if(a){t.push(new H(o.propertyName));let u=this.entityToJsonColumnMap.get(a.id);if(!u)throw new Error(`JSON column name not found for child entity: ${a.id}`);t.push(new E(null,new b(u)))}})}createJsonObject(e){let t="jsonb_build_object";return new U(null,new B(t),new _(e),null)}buildNullCondition(e){return e.reduce((t,n)=>t?new C(t,"and",n):n)}createCaseExpression(e,t){return new le(null,new ye([new we(e,new H(null))],t))}};var gn=class s{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 o=[...e],a=t,u=this.collectAndSortArrayEntities(r,n);if(u.length===0)return{updatedCtes:o,lastCteAlias:a};let l=this.groupEntitiesByDepth(u),c=Array.from(l.keys()).sort((d,h)=>h-d);for(let d of c){let h=l.get(d),{cte:y,newCteAlias:S}=this.buildDepthCte(h,a,o,d,r,i);o.push(y),a=S}return{updatedCtes:o,lastCteAlias:a}}collectAndSortArrayEntities(e,t){let n=[],r=i=>{let o=t.get(i);return!o||o.isRoot?0:o.parentId?1+r(o.parentId):1};return e.nestedEntities.forEach(i=>{if(i.relationshipType==="array"){let o=t.get(i.id),a=t.get(i.parentId);if(!o||!a)throw new Error(`Configuration error: Array entity '${i.id}' or its parent '${i.parentId}' not found.`);let u=Object.values(a.columns);if(u.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 l=u[0];n.push({entity:o,parentEntity:a,parentIdColumnSqlName:l,depth:r(i.id)})}}),n.sort((i,o)=>o.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,o){let a=new Set;e.forEach(g=>{Object.values(g.entity.columns).forEach(P=>a.add(P));let F=P=>{i.nestedEntities.filter(L=>L.parentId===P).forEach(L=>{Object.values(L.columns).forEach(v=>{let I=typeof v=="string"?v:v.column;a.add(I)}),F(L.id)})};F(g.entity.id)});let u=n.find(g=>g.aliasExpression.table.name===t)?.query;if(!u)throw new Error(`CTE not found: ${t}`);let l=new Oe(null,n).collect(u),c=[],d=[],h=new Set;e.forEach(g=>{Object.values(g.entity.columns).forEach(F=>h.add(F))});let y=this.collectArrayEntityColumnsByDepth(i,r),S=new Set;o&&e.forEach(g=>{i.nestedEntities.filter(F=>F.parentId===g.entity.id&&F.relationshipType==="object").forEach(F=>{let P=o.find(L=>L.entityId===F.id);P&&S.add(P.generatedColumnName)})}),this.processSelectVariablesForGroupBy(l,a,y,r,d,c,S);for(let g of e){let F=this.buildAggregationDetailsForArrayEntity(g.entity,i.nestedEntities,new Map,o);d.push(new J(F.jsonAgg,g.entity.propertyName))}let m=`${s.CTE_ARRAY_PREFIX}${r}`,w=new x({selectClause:new D(d),fromClause:new $(new R(new M(null,new b(t)),null),null),groupByClause:c.length>0?new pe(c):null});return{cte:new X(w,new G(m,null),null),newCteAlias:m}}buildAggregationDetailsForArrayEntity(e,t,n,r){let i=s.JSON_FUNCTIONS.BUILD_OBJECT,o=[];Object.entries(e.columns).forEach(([h,y])=>{o.push(new H(h)),o.push(new E(null,new b(y)))}),t.filter(h=>h.parentId===e.id).forEach(h=>{let y=h.originalPropertyName||h.propertyName;if(o.push(new H(y)),h.relationshipType==="object"){if(!r)throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mappings not provided
|
|
15
15
|
|
|
16
16
|
\u{1F50D} Details:
|
|
17
17
|
- Entity ID: ${h.id}
|
|
@@ -27,7 +27,7 @@ Detected column names: [${n.join(", ")}]`);let a=je.parse(t);return new qe({inse
|
|
|
27
27
|
\u{1F527} Check:
|
|
28
28
|
1. Ensure PostgresJsonQueryBuilder.buildJsonWithCteStrategy() passes columnMappings
|
|
29
29
|
2. Verify PostgresObjectEntityCteBuilder.buildObjectEntityCtes() returns columnMappings
|
|
30
|
-
3. Check that Model-driven mapping conversion generates unique entity IDs`);let
|
|
30
|
+
3. Check that Model-driven mapping conversion generates unique entity IDs`);let S=r.find(m=>m.entityId===h.id);if(!S){let m=r.map(w=>`${w.entityId} \u2192 ${w.generatedColumnName}`).join(", ");throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mapping not found
|
|
31
31
|
|
|
32
32
|
\u{1F50D} Details:
|
|
33
33
|
- Looking for Entity ID: ${h.id}
|
|
@@ -45,8 +45,8 @@ Detected column names: [${n.join(", ")}]`);let a=je.parse(t);return new qe({inse
|
|
|
45
45
|
\u{1F527} Check:
|
|
46
46
|
1. Model-driven mapping conversion generates consistent entity IDs
|
|
47
47
|
2. PostgresObjectEntityCteBuilder processes all entities correctly
|
|
48
|
-
3. Entity hierarchy and parentId relationships are correct`)}o.push(new E(null,new b(g.generatedColumnName)))}else h.relationshipType==="array"&&o.push(new E(null,new b(h.propertyName)))});let l=new D(null,new B(i),new _(o),null),u=s.JSON_FUNCTIONS.AGGREGATE,c=Object.values(e.columns)[0];return{jsonAgg:new D(null,new B(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 o=this.calculateEntityDepth(i,e);n.has(o)||n.set(o,new Set),this.addEntityColumnsToDepthSet(i,o,n),this.collectDescendantColumns(i.id,o,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,o,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 E(null,new b(l.name)),l.name)),l.name.endsWith("_json")||o.push(new E(null,new b(l.name))))}})}shouldIncludeColumnInGroupBy(e,t,n){let r=e.endsWith("_json"),i=!0;for(let[o,a]of t.entries())if(o>=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 fn=class{constructor(){this.selectValueCollector=new Fe(null),this.objectEntityCteBuilder=new dn,this.arrayEntityCteBuilder=new hn}validateMapping(e,t){let r=new Fe().collect(e),i=new Set(r.map(u=>u.name));for(let u in t.rootEntity.columns){let c=t.rootEntity.columns[u],d=typeof c=="string"?c:c.column;if(!i.has(d))throw new Error(`Validation Error: Column "${d}" for JSON key "${u}" in root entity "${t.rootEntity.name}" not found in the query's select list.`)}let o=new Set([t.rootEntity.id]),a=new Map;t.nestedEntities.forEach(u=>{o.add(u.id),a.has(u.parentId)||a.set(u.parentId,[]),a.get(u.parentId).push(u.id)});for(let u of t.nestedEntities){if(!o.has(u.parentId))throw new Error(`Validation Error: Parent entity with ID "${u.parentId}" for nested entity "${u.name}" (ID: ${u.id}) not found.`);for(let c in u.columns){let d=u.columns[c],h=typeof d=="string"?d:d.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(C=>C.parentId===u);if(c.filter(C=>C.relationshipType==="array").length>1){let C=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(g=>g.id===u)?.name;throw new Error(`Validation Error: Parent entity "${C}" (ID: ${u}) has multiple direct array children. This is not supported.`)}let h=new Set;for(let C of c){if(h.has(C.propertyName)){let g=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(m=>m.id===u)?.name;throw new Error(`Validation Error: Parent entity "${g}" (ID: ${u}) has duplicate property name "${C.propertyName}" for its children.`)}h.add(C.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 x?e:Ve.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],o=r,a=new Map;a.set(t.rootEntity.id,{...t.rootEntity,isRoot:!0,propertyName:t.rootName}),t.nestedEntities.forEach(d=>a.set(d.id,{...d,isRoot:!1,propertyName:d.propertyName}));let l=this.objectEntityCteBuilder.buildObjectEntityCtes(n,a,t);i=l.ctes,o=l.lastCteAlias;let u=l.columnMappings,c=this.arrayEntityCteBuilder.buildArrayEntityCtes(i,o,a,t,u);return i=c.updatedCtes,o=c.lastCteAlias,this.buildFinalSelectQuery(i,o,a,t,u)}createInitialCte(e){let t="origin_query";return{initialCte:new Z(e,new H(t,null),null),initialCteAlias:t}}buildFinalSelectQuery(e,t,n,r,i){let o=[...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),d=new Z(new x({selectClause:new U([c]),fromClause:new $(new V(new M(null,new b(t)),null),null)}),new H(a,null),null);o.push(d);let h="jsonb_agg",C=new D(null,new B(h),new _([new E(null,new b(r.rootName))]),null);return new x({withClause:new ee(!1,o),selectClause:new U([new J(C,`${r.rootName}_array`)]),fromClause:new $(new V(new M(null,new b(a)),null),null)})}else{let u=this.buildEntityJsonObject(l,null,r.nestedEntities,n,i),c=new J(u,r.rootName),d=new Z(new x({selectClause:new U([c]),fromClause:new $(new V(new M(null,new b(t)),null),null)}),new H(a,null),null);return o.push(d),new x({withClause:new ee(!1,o),selectClause:new U([new J(new E(null,new b(r.rootName)),r.rootName)]),fromClause:new $(new V(new M(null,new b(a)),null),null),limitClause:new se(new G(1))})}}buildEntityJsonObject(e,t,n,r,i){let o="jsonb_build_object",a=[];return Object.entries(e.columns).forEach(([u,c])=>{let d=typeof c=="string"?c:c.column;a.push(new G(u)),a.push(new E(null,new b(d)))}),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 d=i.find(h=>h.entityId===c.id);if(!d)throw new Error(`Column mapping not found for entity: ${c.id}`);a.push(new E(null,new b(d.generatedColumnName)))}else u.relationshipType==="array"&&a.push(new E(null,new b(u.propertyName)))}),new D(null,new B(o),new _(a),null)}};function In(s){let e=[],t=0,n={},r=()=>`entity_${++t}`,i=u=>(n[u]||(n[u]=0),n[u]++,n[u]===1?u:`${u}_${n[u]}`),o=(u,c=null)=>{let d={},h=[];for(let[C,g]of Object.entries(u))if(typeof g=="string")d[C]=g;else if("column"in g&&typeof g.column=="string"&&!("type"in g&&(g.type==="object"||g.type==="array"))){let m=g;typeof m=="object"&&"column"in m&&(d[C]=m.column,m.type==="string"&&e.push(m.column))}else if("from"in g&&typeof g.from=="string"&&!("type"in g&&(g.type==="object"||g.type==="array"))){let m=g;typeof m=="object"&&"from"in m&&(d[C]=m.from,m.type==="string"&&e.push(m.from))}else if("type"in g&&(g.type==="object"||g.type==="array")){let m=g,v=i(C),A=r(),S=o(m.structure,A);h.push({id:A,name:C.charAt(0).toUpperCase()+C.slice(1),parentId:c||"root",propertyName:v,originalPropertyName:C,relationshipType:m.type,columns:S.columns}),h.push(...S.nestedEntities.map(F=>({...F,parentId:F.parentId==="root"?A:F.parentId})))}return{columns:d,nestedEntities:h}},a=o(s.structure),l={rootName:"root",rootEntity:{id:"root",name:"Root",columns:a.columns},nestedEntities:a.nestedEntities};return l.typeInfo=s.typeInfo,{jsonMapping:l,typeProtection:{protectedStringFields:e}}}function pr(s){let e=[];return s.typeInfo?(s.typeInfo.interface||e.push("typeInfo.interface is required"),s.typeInfo.importPath||e.push("typeInfo.importPath is required")):e.push("typeInfo is required"),(!s.structure||typeof s.structure!="object")&&e.push("structure is required and must be an object"),e}function yn(s){let e={};for(let[t,n]of Object.entries(s))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 qd(s){if(!s)throw new Error("Input mapping is required");if(s.rootName&&s.rootEntity&&typeof s.rootEntity.columns=="object"&&!s.typeInfo&&!s.typeProtection&&!s.metadata&&Object.values(s.rootEntity.columns).every(t=>typeof t=="string"))return s;if(s.rootName&&s.rootEntity)return{rootName:s.rootName,rootEntity:{id:s.rootEntity.id||"root",name:s.rootEntity.name||s.rootName,columns:yn(s.rootEntity.columns||{})},nestedEntities:(s.nestedEntities||[]).map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:yn(e.columns||{})})),resultFormat:s.resultFormat,emptyResult:s.emptyResult};throw new Error("Unsupported mapping format")}function jn(s){return{rootName:s.rootName,rootEntity:{id:s.rootEntity.id,name:s.rootEntity.name,columns:yn(s.rootEntity.columns)},nestedEntities:s.nestedEntities.map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:yn(e.columns)})),resultFormat:s.resultFormat,emptyResult:s.emptyResult}}function Jn(s){let e=[],t=[],n=[];if(s.typeProtection)return{protectedStringFields:s.typeProtection.protectedStringFields||[],dateFields:s.typeProtection.dateFields,numberFields:s.typeProtection.numberFields,customTransforms:s.typeProtection.customTransforms};for(let[r,i]of Object.entries(s.rootEntity.columns))if(typeof i=="object"&&i.type){let o=i.column;switch(i.type){case"string":e.push(o);break;case"date":t.push(o);break;case"number":n.push(o);break}}for(let r of s.nestedEntities)for(let[i,o]of Object.entries(r.columns))if(typeof o=="object"&&o.type){let a=o.column;switch(o.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 On(s){return s!=null&&typeof s=="object"}var Pn=class{detect(e){if(!On(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:jn(e),typeProtection:Jn(e),originalInput:e,metadata:{typeInfo:e.typeInfo,version:e.metadata?.version,description:e.metadata?.description}}}},Nn=class{detect(e){if(!On(e))return!1;let t=e;return t&&t.typeInfo&&t.structure&&typeof t.typeInfo.interface=="string"}convert(e){let t=In(e);return{format:"model-driven",mapping:t.jsonMapping,typeProtection:t.typeProtection,originalInput:e,metadata:{typeInfo:e.typeInfo}}}},Fn=class{detect(e){if(!On(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}}},Et=class{constructor(){this.strategies=[new Pn,new Nn,new Fn]}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 Ln(s){return s.typeInfo&&s.structure?"model-driven":s.rootName&&s.rootEntity?"unified":(s.columns||s.relationships,"legacy")}function mr(s){let e={rootName:s.rootName||"root",rootEntity:{id:"root",name:s.rootName||"Root",columns:s.columns||{}},nestedEntities:[]};if(s.relationships&&typeof s.relationships=="object")for(let[t,n]of Object.entries(s.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(s){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"),(s.columns||s.relationships)&&!s.rootName&&!s.rootEntity)return{format:"legacy",jsonMapping:mr(s),originalInput:s,metadata:{}};let t=new Et().convert(s),n=t.format;return t.format==="legacy"&&s.rootName&&s.rootEntity&&(n="unified"),{format:n,jsonMapping:t.mapping,originalInput:s,metadata:{typeInfo:t.metadata?.typeInfo,typeProtection:t.typeProtection}}}function hr(s){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 Et().toLegacyMapping(s)}function fr(s){return Ln(s)==="model-driven"}function yr(s){return Ln(s)==="unified"}function Cr(s){return Ln(s)==="legacy"}var Cn=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 o=this.config.globalTransformations&&this.getGlobalTransformationForValue(r);if(o){t[n]=this.applyTransformation(r,o);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 BigInt(t),!0}catch{return!1}}}:typeof e=="string"&&/^\d{16,}$/.test(e)?{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return BigInt(t),!0}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 BigInt(e),!0}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 BigInt(t),!0}catch{return!1}}}}}}};function ih(s,e){return new Cn(e||Cn.createDefaultConfig()).transformResult(s)}var sh={toDate:s=>{if(s==null)return null;let e=new Date(s);return isNaN(e.getTime())?null:e},toBigInt:s=>{if(s==null)return null;try{return BigInt(s)}catch{return null}},toObject:s=>{if(s==null)return null;try{return JSON.parse(s)}catch{return null}}};var wn=class{constructor(e,t){this.name=e,this.columns=t}},vn=class{constructor(e=null){this.tableColumnResolver=e;this.tableSchemas=[];this.visitedNodes=new Set;this.commonTables=[];this.running=!1;this.handlers=new Map,this.handlers.set(x.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(q.kind,t=>this.visitBinarySelectQuery(t))}collect(e){return this.visit(e),this.tableSchemas}visit(e){if(this.running){this.visitNode(e);return}this.reset(),this.running=!0;try{if(!(e instanceof x||e instanceof q))throw new Error(`Unsupported SQL component type for schema collection. Received: ${e.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let t=new ne;this.commonTables=t.collect(e),this.visitNode(e),this.consolidateTableSchemas()}finally{this.running=!1}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}reset(){this.tableSchemas=[],this.visitedNodes=new Set,this.commonTables=[]}consolidateTableSchemas(){let e=new Map;for(let t of this.tableSchemas)if(!e.has(t.name))e.set(t.name,new Set(t.columns));else{let n=e.get(t.name);t.columns.forEach(r=>n?.add(r))}this.tableSchemas=Array.from(e.entries()).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>new wn(t,Array.from(n).sort()))}handleTableSource(e,t,n){if(e.datasource instanceof M){let r=e.datasource.getSourceName(),i=this.commonTables.filter(o=>o.getSourceAliasName()===r);if(i.length>0)i[0].query.accept(this);else{let o=e.getAliasName()??r;this.processCollectTableSchema(r,o,t,n)}}else throw new Error("Datasource is not an instance of TableSource")}visitSimpleSelectQuery(e){if(e.fromClause===null)return;let r=new Ie(this.tableColumnResolver,!0,"fullName").collect(e).filter(i=>i.value instanceof E).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(o=>o.table==="").map(o=>o.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 M?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 M?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)}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){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),o=new wn(e,i);this.tableSchemas.push(o)}};var Sn=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=W.parse(e));let n=new ht(this.tableColumnResolver,this.options),r=new Ie(this.tableColumnResolver),i=m=>this.options.ignoreCaseAndUnderscore?m.toLowerCase().replace(/_/g,""):m,o=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"],a=Object.values(t);if(a.length>0&&a.every(m=>m===void 0)&&!this.options.allowAllUndefined)throw new Error("All parameters are undefined. This would result in fetching all records. Use allowAllUndefined: true option to explicitly allow this behavior.");for(let[m,v]of Object.entries(t))v!==void 0&&this.processStateParameter(m,v,e,n,r,i,o,d,c,C,g,h);function c(m,v,A,S,F,P){for(let L=0;L<A.length;L++){let w=A[L],I=w.column||v,yt=F.find(Q=>S(Q.name)===S(I));if(!yt)throw new Error(`Column '${I}' not found in query for AND condition`);let fe=yt.value;if("="in w&&w["="]!==void 0){let Q=`${v}_and_${L}_eq`,O=new T(Q,w["="]);m.appendWhere(new y(fe,"=",O))}if("min"in w&&w.min!==void 0){let Q=`${v}_and_${L}_min`,O=new T(Q,w.min);m.appendWhere(new y(fe,">=",O))}if("max"in w&&w.max!==void 0){let Q=`${v}_and_${L}_max`,O=new T(Q,w.max);m.appendWhere(new y(fe,"<=",O))}if("like"in w&&w.like!==void 0){let Q=`${v}_and_${L}_like`,O=new T(Q,w.like);m.appendWhere(new y(fe,"like",O))}if("ilike"in w&&w.ilike!==void 0){let Q=`${v}_and_${L}_ilike`,O=new T(Q,w.ilike);m.appendWhere(new y(fe,"ilike",O))}if("in"in w&&w.in!==void 0){let O=w.in.map((j,K)=>new T(`${v}_and_${L}_in_${K}`,j));m.appendWhere(new y(fe,"in",new Y(new _(O))))}if("any"in w&&w.any!==void 0){let Q=`${v}_and_${L}_any`,O=new T(Q,w.any);m.appendWhere(new y(fe,"=",new D(null,"any",O,null)))}if("<"in w&&w["<"]!==void 0){let Q=`${v}_and_${L}_lt`,O=new T(Q,w["<"]);m.appendWhere(new y(fe,"<",O))}if(">"in w&&w[">"]!==void 0){let Q=`${v}_and_${L}_gt`,O=new T(Q,w[">"]);m.appendWhere(new y(fe,">",O))}if("!="in w&&w["!="]!==void 0){let Q=`${v}_and_${L}_neq`,O=new T(Q,w["!="]);m.appendWhere(new y(fe,"!=",O))}if("<>"in w&&w["<>"]!==void 0){let Q=`${v}_and_${L}_ne`,O=new T(Q,w["<>"]);m.appendWhere(new y(fe,"<>",O))}if("<="in w&&w["<="]!==void 0){let Q=`${v}_and_${L}_le`,O=new T(Q,w["<="]);m.appendWhere(new y(fe,"<=",O))}if(">="in w&&w[">="]!==void 0){let Q=`${v}_and_${L}_ge`,O=new T(Q,w[">="]);m.appendWhere(new y(fe,">=",O))}}}function d(m,v,A,S,F,P){let L=[];for(let w=0;w<A.length;w++){let I=A[w],yt=I.column||v,fe=F.find(j=>S(j.name)===S(yt));if(!fe)throw new Error(`Column '${yt}' not found in query for OR condition`);let Q=fe.value,O=[];if("="in I&&I["="]!==void 0){let j=`${v}_or_${w}_eq`,K=new T(j,I["="]);O.push(new y(Q,"=",K))}if("min"in I&&I.min!==void 0){let j=`${v}_or_${w}_min`,K=new T(j,I.min);O.push(new y(Q,">=",K))}if("max"in I&&I.max!==void 0){let j=`${v}_or_${w}_max`,K=new T(j,I.max);O.push(new y(Q,"<=",K))}if("like"in I&&I.like!==void 0){let j=`${v}_or_${w}_like`,K=new T(j,I.like);O.push(new y(Q,"like",K))}if("ilike"in I&&I.ilike!==void 0){let j=`${v}_or_${w}_ilike`,K=new T(j,I.ilike);O.push(new y(Q,"ilike",K))}if("in"in I&&I.in!==void 0){let K=I.in.map((qn,_n)=>new T(`${v}_or_${w}_in_${_n}`,qn));O.push(new y(Q,"in",new Y(new _(K))))}if("any"in I&&I.any!==void 0){let j=`${v}_or_${w}_any`,K=new T(j,I.any);O.push(new y(Q,"=",new D(null,"any",K,null)))}if("<"in I&&I["<"]!==void 0){let j=`${v}_or_${w}_lt`,K=new T(j,I["<"]);O.push(new y(Q,"<",K))}if(">"in I&&I[">"]!==void 0){let j=`${v}_or_${w}_gt`,K=new T(j,I[">"]);O.push(new y(Q,">",K))}if("!="in I&&I["!="]!==void 0){let j=`${v}_or_${w}_neq`,K=new T(j,I["!="]);O.push(new y(Q,"!=",K))}if("<>"in I&&I["<>"]!==void 0){let j=`${v}_or_${w}_ne`,K=new T(j,I["<>"]);O.push(new y(Q,"<>",K))}if("<="in I&&I["<="]!==void 0){let j=`${v}_or_${w}_le`,K=new T(j,I["<="]);O.push(new y(Q,"<=",K))}if(">="in I&&I[">="]!==void 0){let j=`${v}_or_${w}_ge`,K=new T(j,I[">="]);O.push(new y(Q,">=",K))}if(O.length>0){let j=O[0];for(let K=1;K<O.length;K++)j=new y(j,"and",O[K]);O.length>1?L.push(new Y(j)):L.push(j)}}if(L.length>0){let w=L[0];for(let I=1;I<L.length;I++)w=new y(w,"or",L[I]);m.appendWhere(new Y(w))}}function h(m,v,A){Object.keys(m).forEach(S=>{if(!v.includes(S))throw new Error(`Unsupported operator '${S}' for state key '${A}'`)})}function C(m,v,A,S){let F=new T(A,S);m.appendWhere(new y(v,"=",F))}function g(m,v,A,S){let F=[];if("="in S){let P=new T(A,S["="]);F.push(new y(v,"=",P))}if("min"in S){let P=new T(A+"_min",S.min);F.push(new y(v,">=",P))}if("max"in S){let P=new T(A+"_max",S.max);F.push(new y(v,"<=",P))}if("like"in S){let P=new T(A+"_like",S.like);F.push(new y(v,"like",P))}if("ilike"in S){let P=new T(A+"_ilike",S.ilike);F.push(new y(v,"ilike",P))}if("in"in S){let L=S.in.map((w,I)=>new T(`${A}_in_${I}`,w));F.push(new y(v,"in",new Y(new _(L))))}if("any"in S){let P=new T(A+"_any",S.any);F.push(new y(v,"=",new D(null,"any",P,null)))}if("<"in S){let P=new T(A+"_lt",S["<"]);F.push(new y(v,"<",P))}if(">"in S){let P=new T(A+"_gt",S[">"]);F.push(new y(v,">",P))}if("!="in S){let P=new T(A+"_neq",S["!="]);F.push(new y(v,"!=",P))}if("<>"in S){let P=new T(A+"_ne",S["<>"]);F.push(new y(v,"<>",P))}if("<="in S){let P=new T(A+"_le",S["<="]);F.push(new y(v,"<=",P))}if(">="in S){let P=new T(A+"_ge",S[">="]);F.push(new y(v,">=",P))}if(F.length===1)m.appendWhere(F[0]);else if(F.length>1){let P=F[0];for(let L=1;L<F.length;L++)P=new y(P,"and",F[L]);m.appendWhere(new Y(P))}}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,o,a,l,u,c,d,h){if(this.isOrCondition(t)){let C=t.or;if(C&&C.length>0){let g=this.findTargetQueryForLogicalCondition(r,n,e,C),m=this.getAllAvailableColumns(g,i);l(g,e,C,o,m,i);return}}if(this.isAndCondition(t)){let C=t.and;if(C&&C.length>0){let g=this.findTargetQueryForLogicalCondition(r,n,e,C),m=this.getAllAvailableColumns(g,i);u(g,e,C,o,m,i);return}}if(this.isExplicitColumnMapping(t)){let C=t.column;if(C){let g=r.find(n,C);if(g.length===0)throw new Error(`Explicit column '${C}' not found in query`);for(let m of g){let A=this.getAllAvailableColumns(m,i).find(S=>o(S.name)===o(C));if(!A)throw new Error(`Explicit column '${C}' not found in query`);this.isValidatableObject(t)&&h(t,a,e),d(m,A.value,e,t)}return}}this.processRegularColumnCondition(e,t,n,r,i,o,a,c,d,h)}processRegularColumnCondition(e,t,n,r,i,o,a,l,u,c){let d=r.find(n,e);if(d.length===0)throw new Error(`Column '${e}' not found in query`);for(let h of d){let C=this.getAllAvailableColumns(h,i),g=C.find(S=>o(S.name)===o(e));if(!g)throw new Error(`Column '${e}' not found in query`);let m=g.value;this.isValidatableObject(t)&&c(t,a,e);let v=m,A=e;if(this.hasColumnMapping(t)){let S=t.column;if(S){let F=C.find(P=>o(P.name)===o(S));F&&(v=F.value,A=S)}}this.isSimpleValue(t)?l(h,v,A,t):u(h,v,A,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 o=r===r.or?"OR":"AND";throw new Error(`None of the ${o} 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 x?new Ie(this.tableColumnResolver).collect(e):e instanceof q?this.collectColumnsFromSelectQuery(e.left):[]}};var gn=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=W.parse(e)),!(e instanceof x))throw new Error("Complex queries are not supported for ORDER BY removal");return new x({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=W.parse(e)),!(e instanceof x))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(m=>m.name===l);if(!c)continue;let d=c.value;this.validateSortCondition(l,u);let h;u.desc?h="desc":h="asc";let C=null;u.nullsFirst?C="first":u.nullsLast&&(C="last");let g=new be(d,h,C);i.push(g)}let o=[];e.orderByClause?o=[...e.orderByClause.order,...i]:o=i;let a=o.length>0?new ce(o):null;return new x({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 En=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=W.parse(e)),!(e instanceof x))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 Re(new T("paging_offset",n));return new x({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=W.parse(e)),!(e instanceof x))throw new Error("Complex queries are not supported for pagination removal");return new x({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 Dn=class{constructor(e){this.tableColumnResolver=e}buildQuery(e,t={}){let n;try{n=W.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 i=new Sn(this.tableColumnResolver),o=Ve.buildSimpleQuery(r);r=i.inject(o,t.filter)}if(t.sort&&Object.keys(t.sort).length>0){let i=new gn(this.tableColumnResolver),o=Ve.buildSimpleQuery(r);r=i.inject(o,t.sort)}if(t.paging){let{page:i=1,pageSize:o}=t.paging;if(o!==void 0){let a=new En,l={page:i,pageSize:o},u=Ve.buildSimpleQuery(r);r=a.inject(u,l)}}if(t.serialize&&typeof t.serialize=="object"){let i=new fn,o=Ve.buildSimpleQuery(r);r=i.buildJsonQuery(o,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 W.parse(e),!0}catch(t){throw new Error(`Invalid SQL: ${t instanceof Error?t.message:"Unknown error"}`)}}};var Un=class{static validate(e,t){let n=typeof e=="string"?W.parse(e):e,r=Array.isArray(t)?l=>{let u=t.find(c=>c.name===l);return u?u.columns:[]}:t,o=new vn(r).collect(n),a=[];for(let l of o){let u=r(l.name);if(u.length===0){a.push(`Table '${l.name}' is not defined.`);continue}let c=l.columns.filter(d=>!u.includes(d));c.length>0&&a.push(`Table '${l.name}' contains undefined columns: ${c.join(", ")}.`)}if(a.length>0)throw new Error(a.join(`
|
|
49
|
-
`))}};var
|
|
50
|
-
`);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=[],o=[];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
|
|
51
|
-
`);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
|
|
48
|
+
3. Entity hierarchy and parentId relationships are correct`)}o.push(new E(null,new b(S.generatedColumnName)))}else h.relationshipType==="array"&&o.push(new E(null,new b(h.propertyName)))});let u=new U(null,new B(i),new _(o),null),l=s.JSON_FUNCTIONS.AGGREGATE,c=Object.values(e.columns)[0];return{jsonAgg:new U(null,new B(l),new _([u]),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 o=this.calculateEntityDepth(i,e);n.has(o)||n.set(o,new Set),this.addEntityColumnsToDepthSet(i,o,n),this.collectDescendantColumns(i.id,o,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,o,a){e.forEach(u=>{if(!t.has(u.name)){if(a&&a.has(u.name))return;this.shouldIncludeColumnInGroupBy(u.name,n,r)&&(i.push(new J(new E(null,new b(u.name)),u.name)),u.name.endsWith("_json")||o.push(new E(null,new b(u.name))))}})}shouldIncludeColumnInGroupBy(e,t,n){let r=e.endsWith("_json"),i=!0;for(let[o,a]of t.entries())if(o>=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 Sn=class{constructor(){this.selectValueCollector=new Oe(null),this.objectEntityCteBuilder=new vn,this.arrayEntityCteBuilder=new gn}validateMapping(e,t){let r=new Oe().collect(e),i=new Set(r.map(l=>l.name));for(let l in t.rootEntity.columns){let c=t.rootEntity.columns[l],d=typeof c=="string"?c:c.column;if(!i.has(d))throw new Error(`Validation Error: Column "${d}" for JSON key "${l}" in root entity "${t.rootEntity.name}" not found in the query's select list.`)}let o=new Set([t.rootEntity.id]),a=new Map;t.nestedEntities.forEach(l=>{o.add(l.id),a.has(l.parentId)||a.set(l.parentId,[]),a.get(l.parentId).push(l.id)});for(let l of t.nestedEntities){if(!o.has(l.parentId))throw new Error(`Validation Error: Parent entity with ID "${l.parentId}" for nested entity "${l.name}" (ID: ${l.id}) not found.`);for(let c in l.columns){let d=l.columns[c],h=typeof d=="string"?d:d.column;if(!i.has(h))throw new Error(`Validation Error: Column "${h}" for JSON key "${c}" in nested entity "${l.name}" (ID: ${l.id}) not found in the query's select list.`)}}let u=new Set([t.rootEntity.id,...t.nestedEntities.map(l=>l.parentId)]);for(let l of u){let c=t.nestedEntities.filter(y=>y.parentId===l);if(c.filter(y=>y.relationshipType==="array").length>1){let y=l===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(S=>S.id===l)?.name;throw new Error(`Validation Error: Parent entity "${y}" (ID: ${l}) has multiple direct array children. This is not supported.`)}let h=new Set;for(let y of c){if(h.has(y.propertyName)){let S=l===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(m=>m.id===l)?.name;throw new Error(`Validation Error: Parent entity "${S}" (ID: ${l}) has duplicate property name "${y.propertyName}" for its children.`)}h.add(y.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 x?e:Pe.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],o=r,a=new Map;a.set(t.rootEntity.id,{...t.rootEntity,isRoot:!0,propertyName:t.rootName}),t.nestedEntities.forEach(d=>a.set(d.id,{...d,isRoot:!1,propertyName:d.propertyName}));let u=this.objectEntityCteBuilder.buildObjectEntityCtes(n,a,t);i=u.ctes,o=u.lastCteAlias;let l=u.columnMappings,c=this.arrayEntityCteBuilder.buildArrayEntityCtes(i,o,a,t,l);return i=c.updatedCtes,o=c.lastCteAlias,this.buildFinalSelectQuery(i,o,a,t,l)}createInitialCte(e){let t="origin_query";return{initialCte:new X(e,new G(t,null),null),initialCteAlias:t}}buildFinalSelectQuery(e,t,n,r,i){let o=[...e],a=`cte_root_${r.rootName.toLowerCase().replace(/[^a-z0-9_]/g,"_")}`,u=n.get(r.rootEntity.id);if(!u)throw new Error(`Root entity ${r.rootEntity.id} not found`);if(r.resultFormat==="array"||!r.resultFormat){let l=this.buildEntityJsonObject(u,null,r.nestedEntities,n,i),c=new J(l,r.rootName),d=new X(new x({selectClause:new D([c]),fromClause:new $(new R(new M(null,new b(t)),null),null)}),new G(a,null),null);o.push(d);let h="jsonb_agg",y=new U(null,new B(h),new _([new E(null,new b(r.rootName))]),null);return new x({withClause:new ee(!1,o),selectClause:new D([new J(y,`${r.rootName}_array`)]),fromClause:new $(new R(new M(null,new b(a)),null),null)})}else{let l=this.buildEntityJsonObject(u,null,r.nestedEntities,n,i),c=new J(l,r.rootName),d=new X(new x({selectClause:new D([c]),fromClause:new $(new R(new M(null,new b(t)),null),null)}),new G(a,null),null);return o.push(d),new x({withClause:new ee(!1,o),selectClause:new D([new J(new E(null,new b(r.rootName)),r.rootName)]),fromClause:new $(new R(new M(null,new b(a)),null),null),limitClause:new se(new H(1))})}}buildEntityJsonObject(e,t,n,r,i){let o="jsonb_build_object",a=[];return Object.entries(e.columns).forEach(([l,c])=>{let d=typeof c=="string"?c:c.column;a.push(new H(l)),a.push(new E(null,new b(d)))}),n.filter(l=>l.parentId===e.id).forEach(l=>{let c=r.get(l.id);if(c)if(a.push(new H(l.propertyName)),l.relationshipType==="object"){let d=i.find(h=>h.entityId===c.id);if(!d)throw new Error(`Column mapping not found for entity: ${c.id}`);a.push(new E(null,new b(d.generatedColumnName)))}else l.relationshipType==="array"&&a.push(new E(null,new b(l.propertyName)))}),new U(null,new B(o),new _(a),null)}};function An(s){let e=[],t=0,n={},r=()=>`entity_${++t}`,i=l=>(n[l]||(n[l]=0),n[l]++,n[l]===1?l:`${l}_${n[l]}`),o=(l,c=null)=>{let d={},h=[];for(let[y,S]of Object.entries(l))if(typeof S=="string")d[y]=S;else if("column"in S&&typeof S.column=="string"&&!("type"in S&&(S.type==="object"||S.type==="array"))){let m=S;typeof m=="object"&&"column"in m&&(d[y]=m.column,m.type==="string"&&e.push(m.column))}else if("from"in S&&typeof S.from=="string"&&!("type"in S&&(S.type==="object"||S.type==="array"))){let m=S;typeof m=="object"&&"from"in m&&(d[y]=m.from,m.type==="string"&&e.push(m.from))}else if("type"in S&&(S.type==="object"||S.type==="array")){let m=S,w=i(y),Q=r(),g=o(m.structure,Q);h.push({id:Q,name:y.charAt(0).toUpperCase()+y.slice(1),parentId:c||"root",propertyName:w,originalPropertyName:y,relationshipType:m.type,columns:g.columns}),h.push(...g.nestedEntities.map(F=>({...F,parentId:F.parentId==="root"?Q:F.parentId})))}return{columns:d,nestedEntities:h}},a=o(s.structure),u={rootName:"root",rootEntity:{id:"root",name:"Root",columns:a.columns},nestedEntities:a.nestedEntities};return u.typeInfo=s.typeInfo,{jsonMapping:u,typeProtection:{protectedStringFields:e}}}function wr(s){let e=[];return s.typeInfo?(s.typeInfo.interface||e.push("typeInfo.interface is required"),s.typeInfo.importPath||e.push("typeInfo.importPath is required")):e.push("typeInfo is required"),(!s.structure||typeof s.structure!="object")&&e.push("structure is required and must be an object"),e}function En(s){let e={};for(let[t,n]of Object.entries(s))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 ph(s){if(!s)throw new Error("Input mapping is required");if(s.rootName&&s.rootEntity&&typeof s.rootEntity.columns=="object"&&!s.typeInfo&&!s.typeProtection&&!s.metadata&&Object.values(s.rootEntity.columns).every(t=>typeof t=="string"))return s;if(s.rootName&&s.rootEntity)return{rootName:s.rootName,rootEntity:{id:s.rootEntity.id||"root",name:s.rootEntity.name||s.rootName,columns:En(s.rootEntity.columns||{})},nestedEntities:(s.nestedEntities||[]).map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:En(e.columns||{})})),resultFormat:s.resultFormat,emptyResult:s.emptyResult};throw new Error("Unsupported mapping format")}function zn(s){return{rootName:s.rootName,rootEntity:{id:s.rootEntity.id,name:s.rootEntity.name,columns:En(s.rootEntity.columns)},nestedEntities:s.nestedEntities.map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:En(e.columns)})),resultFormat:s.resultFormat,emptyResult:s.emptyResult}}function Hn(s){let e=[],t=[],n=[];if(s.typeProtection)return{protectedStringFields:s.typeProtection.protectedStringFields||[],dateFields:s.typeProtection.dateFields,numberFields:s.typeProtection.numberFields,customTransforms:s.typeProtection.customTransforms};for(let[r,i]of Object.entries(s.rootEntity.columns))if(typeof i=="object"&&i.type){let o=i.column;switch(i.type){case"string":e.push(o);break;case"date":t.push(o);break;case"number":n.push(o);break}}for(let r of s.nestedEntities)for(let[i,o]of Object.entries(r.columns))if(typeof o=="object"&&o.type){let a=o.column;switch(o.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 Mn(s){return s!=null&&typeof s=="object"}var Bn=class{detect(e){if(!Mn(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:zn(e),typeProtection:Hn(e),originalInput:e,metadata:{typeInfo:e.typeInfo,version:e.metadata?.version,description:e.metadata?.description}}}},Rn=class{detect(e){if(!Mn(e))return!1;let t=e;return t&&t.typeInfo&&t.structure&&typeof t.typeInfo.interface=="string"}convert(e){let t=An(e);return{format:"model-driven",mapping:t.jsonMapping,typeProtection:t.typeProtection,originalInput:e,metadata:{typeInfo:e.typeInfo}}}},Vn=class{detect(e){if(!Mn(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}}},Pt=class{constructor(){this.strategies=[new Bn,new Rn,new Vn]}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 $n(s){return s.typeInfo&&s.structure?"model-driven":s.rootName&&s.rootEntity?"unified":(s.columns||s.relationships,"legacy")}function vr(s){let e={rootName:s.rootName||"root",rootEntity:{id:"root",name:s.rootName||"Root",columns:s.columns||{}},nestedEntities:[]};if(s.relationships&&typeof s.relationships=="object")for(let[t,n]of Object.entries(s.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 gr(s){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"),(s.columns||s.relationships)&&!s.rootName&&!s.rootEntity)return{format:"legacy",jsonMapping:vr(s),originalInput:s,metadata:{}};let t=new Pt().convert(s),n=t.format;return t.format==="legacy"&&s.rootName&&s.rootEntity&&(n="unified"),{format:n,jsonMapping:t.mapping,originalInput:s,metadata:{typeInfo:t.metadata?.typeInfo,typeProtection:t.typeProtection}}}function Sr(s){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 Pt().toLegacyMapping(s)}function Er(s){return $n(s)==="model-driven"}function xr(s){return $n(s)==="unified"}function br(s){return $n(s)==="legacy"}var xn=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 o=this.config.globalTransformations&&this.getGlobalTransformationForValue(r);if(o){t[n]=this.applyTransformation(r,o);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 BigInt(t),!0}catch{return!1}}}:typeof e=="string"&&/^\d{16,}$/.test(e)?{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return BigInt(t),!0}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 BigInt(e),!0}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 BigInt(t),!0}catch{return!1}}}}}}};function xh(s,e){return new xn(e||xn.createDefaultConfig()).transformResult(s)}var bh={toDate:s=>{if(s==null)return null;let e=new Date(s);return isNaN(e.getTime())?null:e},toBigInt:s=>{if(s==null)return null;try{return BigInt(s)}catch{return null}},toObject:s=>{if(s==null)return null;try{return JSON.parse(s)}catch{return null}}};var bn=class{constructor(e,t){this.name=e,this.columns=t}},Tn=class{constructor(e=null){this.tableColumnResolver=e;this.tableSchemas=[];this.visitedNodes=new Set;this.commonTables=[];this.running=!1;this.handlers=new Map,this.handlers.set(x.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(q.kind,t=>this.visitBinarySelectQuery(t))}collect(e){return this.visit(e),this.tableSchemas}visit(e){if(this.running){this.visitNode(e);return}this.reset(),this.running=!0;try{if(!(e instanceof x||e instanceof q))throw new Error(`Unsupported SQL component type for schema collection. Received: ${e.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let t=new ne;this.commonTables=t.collect(e),this.visitNode(e),this.consolidateTableSchemas()}finally{this.running=!1}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}reset(){this.tableSchemas=[],this.visitedNodes=new Set,this.commonTables=[]}consolidateTableSchemas(){let e=new Map;for(let t of this.tableSchemas)if(!e.has(t.name))e.set(t.name,new Set(t.columns));else{let n=e.get(t.name);t.columns.forEach(r=>n?.add(r))}this.tableSchemas=Array.from(e.entries()).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>new bn(t,Array.from(n).sort()))}handleTableSource(e,t,n){if(e.datasource instanceof M){let r=e.datasource.getSourceName(),i=this.commonTables.filter(o=>o.getSourceAliasName()===r);if(i.length>0)i[0].query.accept(this);else{let o=e.getAliasName()??r;this.processCollectTableSchema(r,o,t,n)}}else throw new Error("Datasource is not an instance of TableSource")}visitSimpleSelectQuery(e){if(e.fromClause===null)return;let r=new Ie(this.tableColumnResolver,!0,"fullName").collect(e).filter(i=>i.value instanceof E).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(o=>o.table==="").map(o=>o.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 M?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 M?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)}processCollectTableSchema(e,t,n,r=!1){if(this.tableColumnResolver===null&&n.filter(u=>u.table===t||r&&u.table==="").filter(u=>u.column==="*").length>0){let u=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(u)}let i=n.filter(a=>a.column!=="*").filter(a=>a.table===t||r&&a.table==="").map(a=>a.column),o=new bn(e,i);this.tableSchemas.push(o)}};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=j.parse(e));let n=new Ct(this.tableColumnResolver,this.options),r=new Ie(this.tableColumnResolver),i=m=>this.options.ignoreCaseAndUnderscore?m.toLowerCase().replace(/_/g,""):m,o=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"],a=Object.values(t);if(a.length>0&&a.every(m=>m===void 0)&&!this.options.allowAllUndefined)throw new Error("All parameters are undefined. This would result in fetching all records. Use allowAllUndefined: true option to explicitly allow this behavior.");for(let[m,w]of Object.entries(t))w!==void 0&&this.processStateParameter(m,w,e,n,r,i,o,d,c,y,S,h);function c(m,w,Q,g,F,P){for(let L=0;L<Q.length;L++){let v=Q[L],I=v.column||w,gt=F.find(A=>g(A.name)===g(I));if(!gt)throw new Error(`Column '${I}' not found in query for AND condition`);let fe=gt.value;if("="in v&&v["="]!==void 0){let A=`${w}_and_${L}_eq`,O=new T(A,v["="]);m.appendWhere(new C(fe,"=",O))}if("min"in v&&v.min!==void 0){let A=`${w}_and_${L}_min`,O=new T(A,v.min);m.appendWhere(new C(fe,">=",O))}if("max"in v&&v.max!==void 0){let A=`${w}_and_${L}_max`,O=new T(A,v.max);m.appendWhere(new C(fe,"<=",O))}if("like"in v&&v.like!==void 0){let A=`${w}_and_${L}_like`,O=new T(A,v.like);m.appendWhere(new C(fe,"like",O))}if("ilike"in v&&v.ilike!==void 0){let A=`${w}_and_${L}_ilike`,O=new T(A,v.ilike);m.appendWhere(new C(fe,"ilike",O))}if("in"in v&&v.in!==void 0){let O=v.in.map((W,K)=>new T(`${w}_and_${L}_in_${K}`,W));m.appendWhere(new C(fe,"in",new Y(new _(O))))}if("any"in v&&v.any!==void 0){let A=`${w}_and_${L}_any`,O=new T(A,v.any);m.appendWhere(new C(fe,"=",new U(null,"any",O,null)))}if("<"in v&&v["<"]!==void 0){let A=`${w}_and_${L}_lt`,O=new T(A,v["<"]);m.appendWhere(new C(fe,"<",O))}if(">"in v&&v[">"]!==void 0){let A=`${w}_and_${L}_gt`,O=new T(A,v[">"]);m.appendWhere(new C(fe,">",O))}if("!="in v&&v["!="]!==void 0){let A=`${w}_and_${L}_neq`,O=new T(A,v["!="]);m.appendWhere(new C(fe,"!=",O))}if("<>"in v&&v["<>"]!==void 0){let A=`${w}_and_${L}_ne`,O=new T(A,v["<>"]);m.appendWhere(new C(fe,"<>",O))}if("<="in v&&v["<="]!==void 0){let A=`${w}_and_${L}_le`,O=new T(A,v["<="]);m.appendWhere(new C(fe,"<=",O))}if(">="in v&&v[">="]!==void 0){let A=`${w}_and_${L}_ge`,O=new T(A,v[">="]);m.appendWhere(new C(fe,">=",O))}}}function d(m,w,Q,g,F,P){let L=[];for(let v=0;v<Q.length;v++){let I=Q[v],gt=I.column||w,fe=F.find(W=>g(W.name)===g(gt));if(!fe)throw new Error(`Column '${gt}' not found in query for OR condition`);let A=fe.value,O=[];if("="in I&&I["="]!==void 0){let W=`${w}_or_${v}_eq`,K=new T(W,I["="]);O.push(new C(A,"=",K))}if("min"in I&&I.min!==void 0){let W=`${w}_or_${v}_min`,K=new T(W,I.min);O.push(new C(A,">=",K))}if("max"in I&&I.max!==void 0){let W=`${w}_or_${v}_max`,K=new T(W,I.max);O.push(new C(A,"<=",K))}if("like"in I&&I.like!==void 0){let W=`${w}_or_${v}_like`,K=new T(W,I.like);O.push(new C(A,"like",K))}if("ilike"in I&&I.ilike!==void 0){let W=`${w}_or_${v}_ilike`,K=new T(W,I.ilike);O.push(new C(A,"ilike",K))}if("in"in I&&I.in!==void 0){let K=I.in.map((Zn,er)=>new T(`${w}_or_${v}_in_${er}`,Zn));O.push(new C(A,"in",new Y(new _(K))))}if("any"in I&&I.any!==void 0){let W=`${w}_or_${v}_any`,K=new T(W,I.any);O.push(new C(A,"=",new U(null,"any",K,null)))}if("<"in I&&I["<"]!==void 0){let W=`${w}_or_${v}_lt`,K=new T(W,I["<"]);O.push(new C(A,"<",K))}if(">"in I&&I[">"]!==void 0){let W=`${w}_or_${v}_gt`,K=new T(W,I[">"]);O.push(new C(A,">",K))}if("!="in I&&I["!="]!==void 0){let W=`${w}_or_${v}_neq`,K=new T(W,I["!="]);O.push(new C(A,"!=",K))}if("<>"in I&&I["<>"]!==void 0){let W=`${w}_or_${v}_ne`,K=new T(W,I["<>"]);O.push(new C(A,"<>",K))}if("<="in I&&I["<="]!==void 0){let W=`${w}_or_${v}_le`,K=new T(W,I["<="]);O.push(new C(A,"<=",K))}if(">="in I&&I[">="]!==void 0){let W=`${w}_or_${v}_ge`,K=new T(W,I[">="]);O.push(new C(A,">=",K))}if(O.length>0){let W=O[0];for(let K=1;K<O.length;K++)W=new C(W,"and",O[K]);O.length>1?L.push(new Y(W)):L.push(W)}}if(L.length>0){let v=L[0];for(let I=1;I<L.length;I++)v=new C(v,"or",L[I]);m.appendWhere(new Y(v))}}function h(m,w,Q){Object.keys(m).forEach(g=>{if(!w.includes(g))throw new Error(`Unsupported operator '${g}' for state key '${Q}'`)})}function y(m,w,Q,g){let F=new T(Q,g);m.appendWhere(new C(w,"=",F))}function S(m,w,Q,g){let F=[];if("="in g){let P=new T(Q,g["="]);F.push(new C(w,"=",P))}if("min"in g){let P=new T(Q+"_min",g.min);F.push(new C(w,">=",P))}if("max"in g){let P=new T(Q+"_max",g.max);F.push(new C(w,"<=",P))}if("like"in g){let P=new T(Q+"_like",g.like);F.push(new C(w,"like",P))}if("ilike"in g){let P=new T(Q+"_ilike",g.ilike);F.push(new C(w,"ilike",P))}if("in"in g){let L=g.in.map((v,I)=>new T(`${Q}_in_${I}`,v));F.push(new C(w,"in",new Y(new _(L))))}if("any"in g){let P=new T(Q+"_any",g.any);F.push(new C(w,"=",new U(null,"any",P,null)))}if("<"in g){let P=new T(Q+"_lt",g["<"]);F.push(new C(w,"<",P))}if(">"in g){let P=new T(Q+"_gt",g[">"]);F.push(new C(w,">",P))}if("!="in g){let P=new T(Q+"_neq",g["!="]);F.push(new C(w,"!=",P))}if("<>"in g){let P=new T(Q+"_ne",g["<>"]);F.push(new C(w,"<>",P))}if("<="in g){let P=new T(Q+"_le",g["<="]);F.push(new C(w,"<=",P))}if(">="in g){let P=new T(Q+"_ge",g[">="]);F.push(new C(w,">=",P))}if(F.length===1)m.appendWhere(F[0]);else if(F.length>1){let P=F[0];for(let L=1;L<F.length;L++)P=new C(P,"and",F[L]);m.appendWhere(new Y(P))}}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,o,a,u,l,c,d,h){if(this.isOrCondition(t)){let y=t.or;if(y&&y.length>0){let S=this.findTargetQueryForLogicalCondition(r,n,e,y),m=this.getAllAvailableColumns(S,i);u(S,e,y,o,m,i);return}}if(this.isAndCondition(t)){let y=t.and;if(y&&y.length>0){let S=this.findTargetQueryForLogicalCondition(r,n,e,y),m=this.getAllAvailableColumns(S,i);l(S,e,y,o,m,i);return}}if(this.isExplicitColumnMapping(t)){let y=t.column;if(y){let S=r.find(n,y);if(S.length===0)throw new Error(`Explicit column '${y}' not found in query`);for(let m of S){let Q=this.getAllAvailableColumns(m,i).find(g=>o(g.name)===o(y));if(!Q)throw new Error(`Explicit column '${y}' not found in query`);this.isValidatableObject(t)&&h(t,a,e),d(m,Q.value,e,t)}return}}this.processRegularColumnCondition(e,t,n,r,i,o,a,c,d,h)}processRegularColumnCondition(e,t,n,r,i,o,a,u,l,c){let d=r.find(n,e);if(d.length===0)throw new Error(`Column '${e}' not found in query`);for(let h of d){let y=this.getAllAvailableColumns(h,i),S=y.find(g=>o(g.name)===o(e));if(!S)throw new Error(`Column '${e}' not found in query`);let m=S.value;this.isValidatableObject(t)&&c(t,a,e);let w=m,Q=e;if(this.hasColumnMapping(t)){let g=t.column;if(g){let F=y.find(P=>o(P.name)===o(g));F&&(w=F.value,Q=g)}}this.isSimpleValue(t)?u(h,w,Q,t):l(h,w,Q,t)}}findTargetQueryForLogicalCondition(e,t,n,r){let i=r.map(a=>a.column||n).filter((a,u,l)=>l.indexOf(a)===u);for(let a of i){let u=e.find(t,a);if(u.length>0)return u[0]}let o=r===r.or?"OR":"AND";throw new Error(`None of the ${o} 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 x?new Ie(this.tableColumnResolver).collect(e):e instanceof q?this.collectColumnsFromSelectQuery(e.left):[]}};var In=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=j.parse(e)),!(e instanceof x))throw new Error("Complex queries are not supported for ORDER BY removal");return new x({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=j.parse(e)),!(e instanceof x))throw new Error("Complex queries are not supported for sorting");let r=new Ie(this.tableColumnResolver).collect(e);for(let u of Object.keys(t))if(!r.find(c=>c.name===u))throw new Error(`Column or alias '${u}' not found in current query`);let i=[];for(let[u,l]of Object.entries(t)){let c=r.find(m=>m.name===u);if(!c)continue;let d=c.value;this.validateSortCondition(u,l);let h;l.desc?h="desc":h="asc";let y=null;l.nullsFirst?y="first":l.nullsLast&&(y="last");let S=new be(d,h,y);i.push(S)}let o=[];e.orderByClause?o=[...e.orderByClause.order,...i]:o=i;let a=o.length>0?new ce(o):null;return new x({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:a,windowClause:e.windowClause,limitClause:e.limitClause,offsetClause:e.offsetClause,fetchClause:e.fetchClause,forClause:e.forClause})}validateSortCondition(e,t){if(t.asc&&t.desc)throw new Error(`Conflicting sort directions for column '${e}': both asc and desc specified`);if(t.nullsFirst&&t.nullsLast)throw new Error(`Conflicting nulls positions for column '${e}': both nullsFirst and nullsLast specified`);if(!t.asc&&!t.desc&&!t.nullsFirst&&!t.nullsLast)throw new Error(`Empty sort condition for column '${e}': at least one sort option must be specified`)}};var Pn=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=j.parse(e)),!(e instanceof x))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 Ve(new T("paging_offset",n));return new x({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=j.parse(e)),!(e instanceof x))throw new Error("Complex queries are not supported for pagination removal");return new x({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 vt=class{static extractParameterNames(e){return Ze.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[o,a]of Object.entries(t))n.includes(o)?r[o]=a:i[o]=a;return{hardcodedParams:r,dynamicFilters:i}}};var Nn=class{constructor(e={}){this.options={requireAllParameters:!0,...e}}bind(e,t){let n=e,r=vt.extractParameterNames(n);if(this.options.requireAllParameters){let i=r.filter(o=>!(o in t)||t[o]===void 0);if(i.length>0)throw new Error(`Missing values for required parameters: ${i.join(", ")}`)}for(let[i,o]of Object.entries(t))if(r.includes(i))try{qe.set(n,i,o)}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 Gn=class{constructor(e){this.tableColumnResolver=e}buildQuery(e,t={}){let n;try{n=j.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:o}=vt.separateFilters(r,t.filter);if(Object.keys(i).length>0&&(r=new Nn({requireAllParameters:!1}).bind(r,i)),Object.keys(o).length>0){let a=new kn(this.tableColumnResolver),u=Pe.buildSimpleQuery(r);r=a.inject(u,o)}}if(t.sort&&Object.keys(t.sort).length>0){let i=new In(this.tableColumnResolver),o=Pe.buildSimpleQuery(r);r=i.inject(o,t.sort)}if(t.paging){let{page:i=1,pageSize:o}=t.paging;if(o!==void 0){let a=new Pn,u={page:i,pageSize:o},l=Pe.buildSimpleQuery(r);r=a.inject(l,u)}}if(t.serialize&&typeof t.serialize=="object"){let i=new Sn,o=Pe.buildSimpleQuery(r);r=i.buildJsonQuery(o,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 j.parse(e),!0}catch(t){throw new Error(`Invalid SQL: ${t instanceof Error?t.message:"Unknown error"}`)}}};var Yn=class{static validate(e,t){let n=typeof e=="string"?j.parse(e):e,r=Array.isArray(t)?u=>{let l=t.find(c=>c.name===u);return l?l.columns:[]}:t,o=new Tn(r).collect(n),a=[];for(let u of o){let l=r(u.name);if(l.length===0){a.push(`Table '${u.name}' is not defined.`);continue}let c=u.columns.filter(d=>!l.includes(d));c.length>0&&a.push(`Table '${u.name}' contains undefined columns: ${c.join(", ")}.`)}if(a.length>0)throw new Error(a.join(`
|
|
49
|
+
`))}};var Xn=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(`
|
|
50
|
+
`);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=[],o=[];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 l=this.compareStructures(e[0],t[0],`${n}[]`);r.push(...l.errors),i.push(...l.missingProperties),o.push(...l.extraProperties)}return{isValid:r.length===0,errors:r,missingProperties:i,extraProperties:o}}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,u=t;return Object.keys(u).forEach(l=>{let c=n?`${n}.${l}`:l;if(!(l in a)){i.push(c),r.push(`Missing property: ${c}`);return}let d=a[l],h=u[l],y=this.compareStructures(d,h,c);r.push(...y.errors),i.push(...y.missingProperties),o.push(...y.extraProperties)}),Object.keys(a).forEach(l=>{let c=n?`${n}.${l}`:l;l in u||o.push(c)}),{isValid:r.length===0,errors:r,missingProperties:i,extraProperties:o}}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(`
|
|
51
|
+
`);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 Nt=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(([o,a])=>a.isPrimaryKey).map(([o,a])=>o).length===0&&t.push(`Table '${n}' has no primary key defined`),r.relationships?.forEach(o=>{e.includes(o.table)||t.push(`Table '${n}' references unknown table '${o.table}' in relationship`)})}),t.length>0)throw new Error(`Schema validation failed:\\n${t.join("\\n")}`)}getTableColumns(e){let t=this.schemas[e];return t?Object.keys(t.columns):[]}createTableColumnResolver(){return e=>this.getTableColumns(e)}createJsonMapping(e){let t=this.schemas[e];if(!t)throw new Error(`Table '${e}' not found in schema registry`);let n={};Object.entries(t.columns).forEach(([i,o])=>{n[i]=o.jsonAlias||o.name});let r=[];return t.relationships?.forEach(i=>{let o=this.schemas[i.table];if(!o)throw new Error(`Related table '${i.table}' not found in schema registry`);let a={};Object.entries(o.columns).forEach(([l,c])=>{a[l]=c.jsonAlias||c.name});let u=i.type;r.push({id:i.propertyName,name:o.displayName||i.table,parentId:e,propertyName:i.propertyName,relationshipType:u,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 kf(s){return new Nt(s)}function If(s){return new Nt(s).createTableColumnResolver()}function Pf(s,e){return new Nt(s).createJsonMapping(e)}function Tr(s){let e=[],t=r=>{let i={};for(let[o,a]of Object.entries(r))typeof a=="string"?i[o]=a:(i[o]=a.column,a.type==="string"&&e.push(a.column));return i},n={rootName:s.rootName,rootEntity:{id:s.rootEntity.id,name:s.rootEntity.name,columns:t(s.rootEntity.columns)},nestedEntities:[]};return s.typeInfo&&(n.typeInfo=s.typeInfo),s.nestedEntities&&(n.nestedEntities=s.nestedEntities.map(r=>({id:r.id,name:r.name,parentId:r.parentId,propertyName:r.propertyName,relationshipType:r.relationshipType,columns:t(r.columns)}))),{jsonMapping:n,typeProtection:{protectedStringFields:e}}}export{ve as ArrayExpression,ge as ArrayQueryExpression,Se as BetweenExpression,C as BinaryExpression,q as BinarySelectQuery,ne as CTECollector,Ke as CTENormalizer,kt as CTENotFoundError,le as CaseExpression,we as CaseKeyValuePair,ue as CastExpression,E as ColumnReference,Tt as DuplicateCTEError,qn as DuplicateDetectionMode,Gn as DynamicQueryBuilder,et as Formatter,U as FunctionCall,b as IdentifierString,Qe as InlineQuery,_e as InsertQuery,_n as InsertQueryParser,ft as InvalidCTENameError,Pt as JsonMappingConverter,Xn as JsonSchemaValidator,H as LiteralValue,T as ParameterExpression,Y as ParenExpression,Sn as PostgresJsonQueryBuilder,Ae as QualifiedName,Pe as QueryBuilder,B as RawString,Tn as SchemaCollector,Nt as SchemaManager,j as SelectQueryParser,Oe as SelectValueCollector,Ie as SelectableColumnCollector,x as SimpleSelectQuery,ht as SqlFormatter,Pn as SqlPaginationInjector,kn as SqlParamInjector,Yn as SqlSchemaValidator,In as SqlSortInjector,Je as StringSpecifierExpression,ye as SwitchCaseArgument,bn as TableSchema,Gt as TableSourceCollector,xe as TupleExpression,xn as TypeTransformationPostProcessor,bh as TypeTransformers,Ee as TypeValue,re as UnaryExpression,Ct as UpstreamSelectQueryFinder,eu as VALID_PRESETS,_ as ValueList,ae as ValuesQuery,Wn as WindowFrameBound,it as WindowFrameBoundStatic,st as WindowFrameBoundaryValue,Le as WindowFrameExpression,Me as WindowFrameSpec,jn as WindowFrameType,En as convertColumnsToLegacy,An as convertModelDrivenMapping,ph as convertToLegacyJsonMapping,Tr as convertUnifiedMapping,Pf as createJsonMappingFromSchema,kf as createSchemaManager,If as createTableColumnResolver,Hn as extractTypeProtection,br as isLegacyFormat,Er as isModelDrivenFormat,xr as isUnifiedFormat,gr as processJsonMapping,zn as toLegacyMapping,xh as transformDatabaseResult,Sr as unifyJsonMapping,wr as validateModelDrivenMapping};
|
|
52
52
|
//# sourceMappingURL=index.min.js.map
|