rawsql-ts 0.11.35-beta → 0.11.37-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.
Files changed (92) hide show
  1. package/dist/esm/index.js.map +1 -1
  2. package/dist/esm/index.min.js +28 -27
  3. package/dist/esm/index.min.js.map +3 -3
  4. package/dist/esm/src/index.d.ts +1 -0
  5. package/dist/esm/src/index.js.map +1 -1
  6. package/dist/esm/src/models/BinarySelectQuery.d.ts +2 -0
  7. package/dist/esm/src/models/BinarySelectQuery.js +2 -0
  8. package/dist/esm/src/models/BinarySelectQuery.js.map +1 -1
  9. package/dist/esm/src/models/Clause.d.ts +2 -0
  10. package/dist/esm/src/models/Clause.js +2 -0
  11. package/dist/esm/src/models/Clause.js.map +1 -1
  12. package/dist/esm/src/models/SelectQuery.d.ts +2 -0
  13. package/dist/esm/src/models/SelectQuery.js.map +1 -1
  14. package/dist/esm/src/models/SimpleSelectQuery.d.ts +2 -0
  15. package/dist/esm/src/models/SimpleSelectQuery.js +2 -0
  16. package/dist/esm/src/models/SimpleSelectQuery.js.map +1 -1
  17. package/dist/esm/src/models/ValuesQuery.d.ts +2 -0
  18. package/dist/esm/src/models/ValuesQuery.js +2 -0
  19. package/dist/esm/src/models/ValuesQuery.js.map +1 -1
  20. package/dist/esm/src/parsers/CommonTableParser.d.ts +1 -0
  21. package/dist/esm/src/parsers/CommonTableParser.js +9 -2
  22. package/dist/esm/src/parsers/CommonTableParser.js.map +1 -1
  23. package/dist/esm/src/parsers/SelectClauseParser.js +7 -1
  24. package/dist/esm/src/parsers/SelectClauseParser.js.map +1 -1
  25. package/dist/esm/src/parsers/SelectQueryParser.d.ts +6 -0
  26. package/dist/esm/src/parsers/SelectQueryParser.js +51 -12
  27. package/dist/esm/src/parsers/SelectQueryParser.js.map +1 -1
  28. package/dist/esm/src/parsers/SqlPrintTokenParser.d.ts +2 -1
  29. package/dist/esm/src/parsers/SqlPrintTokenParser.js +73 -4
  30. package/dist/esm/src/parsers/SqlPrintTokenParser.js.map +1 -1
  31. package/dist/esm/src/parsers/WithClauseParser.d.ts +1 -0
  32. package/dist/esm/src/parsers/WithClauseParser.js +27 -3
  33. package/dist/esm/src/parsers/WithClauseParser.js.map +1 -1
  34. package/dist/esm/src/transformers/CTEQueryDecomposer.d.ts +69 -0
  35. package/dist/esm/src/transformers/CTEQueryDecomposer.js +123 -0
  36. package/dist/esm/src/transformers/CTEQueryDecomposer.js.map +1 -1
  37. package/dist/esm/src/transformers/SqlFormatter.d.ts +34 -16
  38. package/dist/esm/src/transformers/SqlFormatter.js +1 -1
  39. package/dist/esm/src/transformers/SqlFormatter.js.map +1 -1
  40. package/dist/esm/src/transformers/SqlPrinter.d.ts +25 -20
  41. package/dist/esm/src/transformers/SqlPrinter.js +51 -2
  42. package/dist/esm/src/transformers/SqlPrinter.js.map +1 -1
  43. package/dist/esm/src/utils/CommentEditor.d.ts +11 -0
  44. package/dist/esm/src/utils/CommentEditor.js +141 -29
  45. package/dist/esm/src/utils/CommentEditor.js.map +1 -1
  46. package/dist/esm/tsconfig.browser.tsbuildinfo +1 -1
  47. package/dist/index.min.js +31 -30
  48. package/dist/index.min.js.map +3 -3
  49. package/dist/src/index.d.ts +1 -0
  50. package/dist/src/index.js.map +1 -1
  51. package/dist/src/models/BinarySelectQuery.d.ts +2 -0
  52. package/dist/src/models/BinarySelectQuery.js +2 -0
  53. package/dist/src/models/BinarySelectQuery.js.map +1 -1
  54. package/dist/src/models/Clause.d.ts +2 -0
  55. package/dist/src/models/Clause.js +2 -0
  56. package/dist/src/models/Clause.js.map +1 -1
  57. package/dist/src/models/SelectQuery.d.ts +2 -0
  58. package/dist/src/models/SelectQuery.js.map +1 -1
  59. package/dist/src/models/SimpleSelectQuery.d.ts +2 -0
  60. package/dist/src/models/SimpleSelectQuery.js +2 -0
  61. package/dist/src/models/SimpleSelectQuery.js.map +1 -1
  62. package/dist/src/models/ValuesQuery.d.ts +2 -0
  63. package/dist/src/models/ValuesQuery.js +2 -0
  64. package/dist/src/models/ValuesQuery.js.map +1 -1
  65. package/dist/src/parsers/CommonTableParser.d.ts +1 -0
  66. package/dist/src/parsers/CommonTableParser.js +9 -2
  67. package/dist/src/parsers/CommonTableParser.js.map +1 -1
  68. package/dist/src/parsers/SelectClauseParser.js +7 -1
  69. package/dist/src/parsers/SelectClauseParser.js.map +1 -1
  70. package/dist/src/parsers/SelectQueryParser.d.ts +6 -0
  71. package/dist/src/parsers/SelectQueryParser.js +51 -12
  72. package/dist/src/parsers/SelectQueryParser.js.map +1 -1
  73. package/dist/src/parsers/SqlPrintTokenParser.d.ts +2 -1
  74. package/dist/src/parsers/SqlPrintTokenParser.js +73 -4
  75. package/dist/src/parsers/SqlPrintTokenParser.js.map +1 -1
  76. package/dist/src/parsers/WithClauseParser.d.ts +1 -0
  77. package/dist/src/parsers/WithClauseParser.js +27 -3
  78. package/dist/src/parsers/WithClauseParser.js.map +1 -1
  79. package/dist/src/transformers/CTEQueryDecomposer.d.ts +69 -0
  80. package/dist/src/transformers/CTEQueryDecomposer.js +123 -0
  81. package/dist/src/transformers/CTEQueryDecomposer.js.map +1 -1
  82. package/dist/src/transformers/SqlFormatter.d.ts +34 -16
  83. package/dist/src/transformers/SqlFormatter.js +9 -1
  84. package/dist/src/transformers/SqlFormatter.js.map +1 -1
  85. package/dist/src/transformers/SqlPrinter.d.ts +25 -20
  86. package/dist/src/transformers/SqlPrinter.js +51 -2
  87. package/dist/src/transformers/SqlPrinter.js.map +1 -1
  88. package/dist/src/utils/CommentEditor.d.ts +11 -0
  89. package/dist/src/utils/CommentEditor.js +141 -29
  90. package/dist/src/utils/CommentEditor.js.map +1 -1
  91. package/dist/tsconfig.tsbuildinfo +1 -1
  92. package/package.json +1 -1
@@ -1,37 +1,38 @@
1
- var v=class{constructor(){this.comments=null}getKind(){return this.constructor.kind}accept(e){return e.visit(this)}toSqlString(e){return this.accept(e)}},Tr=class{constructor(){this.parameterSymbol=":";this.identifierEscape={start:'"',end:'"'};this.exportComment=!0}};var ot=class extends v{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var ge=class extends v{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},U=class extends v{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},b=class extends v{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof P?this.qualifiedName.name:new P(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(e,t){super();let n=typeof t=="string"?new P(t):t;this.qualifiedName=new _e(Pr(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},K=class extends v{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,r,i=null,s=!1,o=null){super(),this.qualifiedName=new _e(e,t),this.argument=n,this.over=r,this.withinGroup=i,this.withOrdinality=s,this.internalOrderBy=o}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},kr=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(kr||{}),Ir=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(Ir||{}),Et=class extends v{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},xt=class extends v{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},Ge=class extends v{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Be=class extends v{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},te=class extends v{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new V(e),this.expression=t}},S=class extends v{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new V(t),this.right=n}},Z=class extends v{static{this.kind=Symbol("LiteralExpression")}constructor(e,t,n){super(),this.value=e,this.isStringLiteral=n}},N=class extends v{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new V(e),this.value=t,this.index=null}},Te=class extends v{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},ke=class extends v{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},V=class extends v{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},P=class extends v{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},Y=class extends v{static{this.kind=Symbol("ParenExpression")}constructor(e){super(),this.expression=e}},ce=class extends v{static{this.kind=Symbol("CastExpression")}constructor(e,t){super(),this.input=e,this.castType=t}},ie=class extends v{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},ye=class extends v{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},ve=class extends v{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},we=class extends v{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 v{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new V(e),this.value=new Z(t)}},Ve=class extends v{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new _e(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof V?this.qualifiedName.name.value:this.qualifiedName.name.name;return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(t=>t.name).join(".")+"."+e:e}},Ie=class extends v{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}},et=class extends v{static{this.kind=Symbol("ArraySliceExpression")}constructor(e,t,n){super(),this.array=e,this.startIndex=t,this.endIndex=n}},tt=class extends v{static{this.kind=Symbol("ArrayIndexExpression")}constructor(e,t){super(),this.array=e,this.index=t}};function Pr(a){if(a==null)return null;if(typeof a=="string")return a.trim()===""?null:[new P(a)];if(Array.isArray(a)){if(a.length===0)return null;if(typeof a[0]=="string"){let e=a.filter(t=>t.trim()!=="");return e.length===0?null:e.map(t=>new P(t))}else{let e=a.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var _e=class extends v{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=Pr(e),typeof t=="string"?this.name=new V(t):this.name=t}toString(){let e=this.name instanceof V?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(t=>t.name).join(".")+"."+e:e}};var z=class extends v{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new P(t):null}},_=class extends v{static{this.kind=Symbol("SelectClause")}constructor(e,t=null,n=[]){super(),this.items=e,this.distinct=t,this.hints=n}},Tt=class extends v{static{this.kind=Symbol("Distinct")}constructor(){super()}},kt=class extends v{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},se=class extends v{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},De=class extends v{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},Pe=class extends v{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new P(e),this.expression=t}},nt=class extends v{static{this.kind=Symbol("WindowsClause")}constructor(e){super(),this.windows=e}};var pe=class extends v{static{this.kind=Symbol("OrderByClause")}constructor(e){super(),this.order=e}},Ae=class extends v{static{this.kind=Symbol("OrderByItem")}constructor(e,t,n){super(),this.value=e,this.sortDirection=t===null?"asc":t,this.nullsPosition=n}},me=class extends v{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},de=class extends v{static{this.kind=Symbol("HavingClause")}constructor(e){super(),this.condition=e}},R=class extends v{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof P?this.qualifiedName.name:new P(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(e,t){super();let n=typeof t=="string"?new P(t):t;this.qualifiedName=new _e(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof V?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof V?this.qualifiedName.name.value:this.qualifiedName.name.name}},qe=class extends v{static{this.kind=Symbol("FunctionSource")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"name"in e){let n=e;this.qualifiedName=new _e(n.namespaces,n.name)}else this.qualifiedName=new _e(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},$e=class extends v{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},W=class extends v{static{this.kind=Symbol("SubQuerySource")}constructor(e){super(),this.query=e}},B=class extends v{static{this.kind=Symbol("SourceExpression")}constructor(e,t){super(),this.datasource=e,this.aliasExpression=t}getAliasName(){return this.aliasExpression?this.aliasExpression.table.name:this.datasource instanceof R?this.datasource.getSourceName():null}},he=class extends v{static{this.kind=Symbol("JoinOnClause")}constructor(e){super(),this.condition=e}},Se=class extends v{static{this.kind=Symbol("JoinUsingClause")}constructor(e){super(),this.condition=e}},fe=class extends v{static{this.kind=Symbol("JoinItem")}constructor(e,t,n,r){super(),this.joinType=new V(e),this.source=t,this.condition=n,this.lateral=r}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof R?this.source.table.name:null}},J=class extends v{static{this.kind=Symbol("FromClause")}constructor(e,t){super(),this.source=e,this.joins=t}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof R?this.source.datasource.table.name:null}getSources(){let e=[this.source];if(this.joins)for(let t of this.joins)e.push(t.source);return e}},ne=class extends v{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new re(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},ae=class extends v{static{this.kind=Symbol("WithClause")}constructor(e,t){super(),this.recursive=e,this.tables=t}},oe=class extends v{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var Oe=class extends v{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},Ue=class extends v{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},gt=class extends v{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var Ne=class extends v{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},re=class extends v{static{this.kind=Symbol("SourceAliasExpression")}constructor(e,t){super(),this.table=new P(e),this.columns=t!==null?t.map(n=>new P(n)):null}},ln=class extends v{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new P(t):t)}},at=class extends v{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof ut?t:new ut(t.column,t.value))}},ut=class extends v{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 P(n.column):n.column;this.qualifiedName=new _e(n.namespaces,r)}else{let n=typeof e=="string"?new P(e):e;this.qualifiedName=new _e(null,n)}this.value=t}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof P?this.qualifiedName.name:new P(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},It=class extends v{static{this.kind=Symbol("UpdateClause")}constructor(e){super(),this.source=e}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof R?this.source.datasource.table.name:null}},ct=class extends v{constructor(e,t){super(),this.source=e,this.columns=t.map(n=>new P(n))}};var $=(h=>(h[h.None=0]="None",h[h.Literal=1]="Literal",h[h.Operator=2]="Operator",h[h.OpenParen=4]="OpenParen",h[h.CloseParen=8]="CloseParen",h[h.Comma=16]="Comma",h[h.Dot=32]="Dot",h[h.Identifier=64]="Identifier",h[h.Command=128]="Command",h[h.Parameter=256]="Parameter",h[h.OpenBracket=512]="OpenBracket",h[h.CloseBracket=1024]="CloseBracket",h[h.Function=2048]="Function",h[h.StringSpecifier=4096]="StringSpecifier",h[h.Type=8192]="Type",h))($||{});var ee=class{static isWhitespace(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===32||t===9||t===10||t===13}static isDigit(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57}static isHexChar(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=97&&t<=102||t>=65&&t<=70}static isOperatorSymbol(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===43||t===45||t===42||t===47||t===37||t===126||t===64||t===35||t===94||t===38||t===58||t===33||t===60||t===62||t===61||t===124||t===63}static isDelimiter(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===46||t===44||t===40||t===41||t===91||t===93||t===123||t===125||t===59||t===32||t===9||t===10||t===13?!0:t===43||t===45||t===42||t===47||t===37||t===126||t===64||t===35||t===94||t===38||t===58||t===33||t===60||t===62||t===61||t===124||t===63}static isNamedParameterPrefix(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===64||t===58||t===36}};var le=class a{static getDebugPositionInfo(e,t){let n=Math.max(0,t-5),r=Math.min(e.length,t+5),i=e.slice(n,r),s=" ".repeat(t-n)+"^";return`${i}
1
+ var v=class{constructor(){this.comments=null}getKind(){return this.constructor.kind}accept(e){return e.visit(this)}toSqlString(e){return this.accept(e)}},Tr=class{constructor(){this.parameterSymbol=":";this.identifierEscape={start:'"',end:'"'};this.exportComment=!0}};var ot=class extends v{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var ge=class extends v{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},U=class extends v{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},b=class extends v{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof P?this.qualifiedName.name:new P(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(e,t){super();let n=typeof t=="string"?new P(t):t;this.qualifiedName=new _e(Pr(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},K=class extends v{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,r,i=null,s=!1,o=null){super(),this.qualifiedName=new _e(e,t),this.argument=n,this.over=r,this.withinGroup=i,this.withOrdinality=s,this.internalOrderBy=o}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},kr=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(kr||{}),Ir=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(Ir||{}),Et=class extends v{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},xt=class extends v{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},Ge=class extends v{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Be=class extends v{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},te=class extends v{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new $(e),this.expression=t}},S=class extends v{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new $(t),this.right=n}},Z=class extends v{static{this.kind=Symbol("LiteralExpression")}constructor(e,t,n){super(),this.value=e,this.isStringLiteral=n}},N=class extends v{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new $(e),this.value=t,this.index=null}},Te=class extends v{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},ke=class extends v{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},$=class extends v{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},P=class extends v{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},Y=class extends v{static{this.kind=Symbol("ParenExpression")}constructor(e){super(),this.expression=e}},ce=class extends v{static{this.kind=Symbol("CastExpression")}constructor(e,t){super(),this.input=e,this.castType=t}},ie=class extends v{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},ye=class extends v{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},ve=class extends v{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},we=class extends v{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 v{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new $(e),this.value=new Z(t)}},Ve=class extends v{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new _e(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof $?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}},Ie=class extends v{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}},et=class extends v{static{this.kind=Symbol("ArraySliceExpression")}constructor(e,t,n){super(),this.array=e,this.startIndex=t,this.endIndex=n}},tt=class extends v{static{this.kind=Symbol("ArrayIndexExpression")}constructor(e,t){super(),this.array=e,this.index=t}};function Pr(a){if(a==null)return null;if(typeof a=="string")return a.trim()===""?null:[new P(a)];if(Array.isArray(a)){if(a.length===0)return null;if(typeof a[0]=="string"){let e=a.filter(t=>t.trim()!=="");return e.length===0?null:e.map(t=>new P(t))}else{let e=a.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var _e=class extends v{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=Pr(e),typeof t=="string"?this.name=new $(t):this.name=t}toString(){let e=this.name instanceof $?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(t=>t.name).join(".")+"."+e:e}};var z=class extends v{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new P(t):null}},_=class extends v{static{this.kind=Symbol("SelectClause")}constructor(e,t=null,n=[]){super(),this.items=e,this.distinct=t,this.hints=n}},Tt=class extends v{static{this.kind=Symbol("Distinct")}constructor(){super()}},kt=class extends v{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},se=class extends v{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},De=class extends v{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},Pe=class extends v{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new P(e),this.expression=t}},nt=class extends v{static{this.kind=Symbol("WindowsClause")}constructor(e){super(),this.windows=e}};var pe=class extends v{static{this.kind=Symbol("OrderByClause")}constructor(e){super(),this.order=e}},Ae=class extends v{static{this.kind=Symbol("OrderByItem")}constructor(e,t,n){super(),this.value=e,this.sortDirection=t===null?"asc":t,this.nullsPosition=n}},me=class extends v{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},de=class extends v{static{this.kind=Symbol("HavingClause")}constructor(e){super(),this.condition=e}},O=class extends v{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof P?this.qualifiedName.name:new P(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(e,t){super();let n=typeof t=="string"?new P(t):t;this.qualifiedName=new _e(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof $?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof $?this.qualifiedName.name.value:this.qualifiedName.name.name}},qe=class extends v{static{this.kind=Symbol("FunctionSource")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"name"in e){let n=e;this.qualifiedName=new _e(n.namespaces,n.name)}else this.qualifiedName=new _e(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},$e=class extends v{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},j=class extends v{static{this.kind=Symbol("SubQuerySource")}constructor(e){super(),this.query=e}},B=class extends v{static{this.kind=Symbol("SourceExpression")}constructor(e,t){super(),this.datasource=e,this.aliasExpression=t}getAliasName(){return this.aliasExpression?this.aliasExpression.table.name:this.datasource instanceof O?this.datasource.getSourceName():null}},he=class extends v{static{this.kind=Symbol("JoinOnClause")}constructor(e){super(),this.condition=e}},Se=class extends v{static{this.kind=Symbol("JoinUsingClause")}constructor(e){super(),this.condition=e}},fe=class extends v{static{this.kind=Symbol("JoinItem")}constructor(e,t,n,r){super(),this.joinType=new $(e),this.source=t,this.condition=n,this.lateral=r}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof O?this.source.table.name:null}},J=class extends v{static{this.kind=Symbol("FromClause")}constructor(e,t){super(),this.source=e,this.joins=t}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof O?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}},ne=class extends v{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new re(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},ae=class extends v{constructor(t,n){super();this.trailingComments=null;this.globalComments=null;this.recursive=t,this.tables=n}static{this.kind=Symbol("WithClause")}},oe=class extends v{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var Re=class extends v{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},Ue=class extends v{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},gt=class extends v{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var Ne=class extends v{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},re=class extends v{static{this.kind=Symbol("SourceAliasExpression")}constructor(e,t){super(),this.table=new P(e),this.columns=t!==null?t.map(n=>new P(n)):null}},ln=class extends v{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new P(t):t)}},at=class extends v{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof ut?t:new ut(t.column,t.value))}},ut=class extends v{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 P(n.column):n.column;this.qualifiedName=new _e(n.namespaces,r)}else{let n=typeof e=="string"?new P(e):e;this.qualifiedName=new _e(null,n)}this.value=t}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof P?this.qualifiedName.name:new P(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},It=class extends v{static{this.kind=Symbol("UpdateClause")}constructor(e){super(),this.source=e}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof O?this.source.datasource.table.name:null}},ct=class extends v{constructor(e,t){super(),this.source=e,this.columns=t.map(n=>new P(n))}};var M=(h=>(h[h.None=0]="None",h[h.Literal=1]="Literal",h[h.Operator=2]="Operator",h[h.OpenParen=4]="OpenParen",h[h.CloseParen=8]="CloseParen",h[h.Comma=16]="Comma",h[h.Dot=32]="Dot",h[h.Identifier=64]="Identifier",h[h.Command=128]="Command",h[h.Parameter=256]="Parameter",h[h.OpenBracket=512]="OpenBracket",h[h.CloseBracket=1024]="CloseBracket",h[h.Function=2048]="Function",h[h.StringSpecifier=4096]="StringSpecifier",h[h.Type=8192]="Type",h))(M||{});var ee=class{static isWhitespace(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===32||t===9||t===10||t===13}static isDigit(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57}static isHexChar(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=97&&t<=102||t>=65&&t<=70}static isOperatorSymbol(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===43||t===45||t===42||t===47||t===37||t===126||t===64||t===35||t===94||t===38||t===58||t===33||t===60||t===62||t===61||t===124||t===63}static isDelimiter(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===46||t===44||t===40||t===41||t===91||t===93||t===123||t===125||t===59||t===32||t===9||t===10||t===13?!0:t===43||t===45||t===42||t===47||t===37||t===126||t===64||t===35||t===94||t===38||t===58||t===33||t===60||t===62||t===61||t===124||t===63}static isNamedParameterPrefix(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===64||t===58||t===36}};var le=class a{static getDebugPositionInfo(e,t){let n=Math.max(0,t-5),r=Math.min(e.length,t+5),i=e.slice(n,r),s=" ".repeat(t-n)+"^";return`${i}
2
2
  ${s}`}static skipWhiteSpace(e,t){let n=e.length;for(;t+4<=n&&e.slice(t,t+4)===" ";)t+=4;for(;t<n;){let r=e.charCodeAt(t);if(r!==32&&r!==9&&r!==10&&r!==13)break;t++}return t}static readLineComment(e,t){if(t+1>=e.length)return{newPosition:t,comment:null};if(e.charCodeAt(t)===45&&e.charCodeAt(t+1)===45){let n=t;for(t+=2;t<e.length&&e.charCodeAt(t)!==10;)t++;let r=e.slice(n+2,t).trim();return{newPosition:t,comment:r}}return{newPosition:t,comment:null}}static readBlockComment(e,t){if(t+3>=e.length)return{newPosition:t,comments:null};if(e.charCodeAt(t)===47&&e.charCodeAt(t+1)===42&&e.charCodeAt(t+2)!==43){let n=t;for(t+=2;t+1<e.length;){if(e.charCodeAt(t)===42&&e.charCodeAt(t+1)===47){t+=2;let r=e.slice(n+2,t-2).replace(/\r/g,"").split(`
3
3
  `);for(let i=0;i<r.length;i++)r[i]=r[i].trim();for(;r.length>0&&r[0]==="";)r.shift();for(;r.length>0&&r[r.length-1]==="";)r.pop();return{newPosition:t,comments:r}}t++}throw new Error(`Block comment is not closed. position: ${t}`)}return{newPosition:t,comments:null}}static readWhiteSpaceAndComment(e,t){let n=[],r=e.length;for(;t<r;){let i=t;if(t=a.skipWhiteSpace(e,t),t!==i)continue;let s=e.charCodeAt(t);if(s===45){let o=a.readLineComment(e,t);if(o.newPosition!==t){t=o.newPosition,o.comment&&n.push(o.comment.trim());continue}}else if(s===47){let o=a.readBlockComment(e,t);if(o.newPosition!==t){t=o.newPosition,o.comments&&n.push(...o.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
4
  ${a.getDebugPositionInfo(e,t)}`);return n}static tryReadRegularIdentifier(e,t){let n=t;for(;t<e.length&&!ee.isDelimiter(e[t]);)t++;if(n===t)return null;for(;t+1<e.length&&e[t]==="["&&e[t+1]==="]";){let r=e.slice(0,n).trim();if(r===""||/[)]$/.test(r)||/\b(select|from|where|and|or|set|values|insert|update|delete)\s*$/i.test(r))break;t+=2}return{identifier:e.slice(n,t),newPosition:t}}};var ue=class{constructor(e,t=0){this.input=e,this.position=t}getPosition(){return this.position}setPosition(e){this.position=e}isEndOfInput(e=0){return this.position+e>=this.input.length}canRead(e=0){return!this.isEndOfInput(e)}read(e){if(this.isEndOfInput())throw new Error(`Unexpected character. expect: ${e}, actual: EndOfInput, position: ${this.position}`);let t=this.input[this.position];if(t!==e)throw new Error(`Unexpected character. expect: ${e}, actual: ${t}, position: ${this.position}`);return this.position++,t}createLexeme(e,t,n=null,r,i){let s={type:e,value:e===128||e===2||e===2048?t.toLowerCase():t,comments:n};return r!==void 0&&i!==void 0&&(s.position={startPosition:r,endPosition:i}),s}createLexemeWithPosition(e,t,n,r=null){return this.createLexeme(e,t,r,n,n+t.length)}getDebugPositionInfo(e){return le.getDebugPositionInfo(this.input,e)}};var un=class extends ue{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="*")return this.position++,this.createLexeme(64,t);let n=le.readRegularIdentifier(this.input,this.position);return this.position=n.newPosition,this.createLexeme(64,n.identifier)}};var Ee=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=le.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,s=le.readWhiteSpaceAndComment(e,n.newPosition);t=s.position;let o=[...s.lines];if(this.isEndOfInput(e,t))return r===2?{keyword:i,newPosition:t,comments:o.length>0?o:void 0}:null;for(;this.canParse(e,t);){let l=r,u=le.tryReadRegularIdentifier(e,t);if(u!==null){if(r=this.trie.pushLexeme(u.identifier.toLowerCase()),r===0){if(l===2)break;return null}i+=" "+u.identifier;let c=le.readWhiteSpaceAndComment(e,u.newPosition);if(t=c.position,o.push(...c.lines),r===3)break}else{if(l===2)break;return null}}return{keyword:i,newPosition:t,comments:o.length>0?o:void 0}}};var Je=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 qr=[["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"]],Gr=new Je(qr),fr=new Ee(Gr),cn=class extends ue{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="'"){let r=this.readSingleQuotedString();return this.createLexeme(1,r)}let n=this.tryReadKeyword();if(n)return n;if(t==="."&&this.canRead(1)&&ee.isDigit(this.input[this.position+1]))return this.createLexeme(1,this.readDigit());if(ee.isDigit(t))return this.createLexeme(1,this.readDigit());if(t==="$"&&this.isDollarQuotedString())return this.createLexeme(1,this.readDollarQuotedString());if(t==="$"&&this.canRead(1)&&ee.isDigit(this.input[this.position+1])){let r=this.position+1,i=!1;for(;r<this.input.length&&(ee.isDigit(this.input[r])||this.input[r]===","||this.input[r]===".");){if(this.input[r]==="."||this.input[r]===","){i=!0;break}r++}if(i){this.position++;let s=this.readMoneyDigit();return this.createLexeme(1,"$"+s)}}if((t==="+"||t==="-")&&this.determineSignOrOperator(e)==="sign"){let r=t;this.position++;let i=this.position;for(;this.canRead()&&ee.isWhitespace(this.input[this.position]);)this.position++;if(this.canRead()&&(ee.isDigit(this.input[this.position])||this.input[this.position]==="."&&this.canRead(1)&&ee.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=fr.parse(this.input,this.position);return e?(this.position=e.newPosition,this.createLexeme(1,e.keyword)):null}determineSignOrOperator(e){return e===null?"sign":e.type&1||e.type&64||e.type&256||e.type&8?"operator":"sign"}readDigit(){let e=this.position,t=!1,n=!1;if(this.canRead(1)&&this.input[this.position]==="0"&&"xbo".includes(this.input[this.position+1].toLowerCase())){let r=this.input[this.position+1].toLowerCase();this.position+=2;let i=r==="x";for(;this.canRead();){let s=this.input[this.position];if(ee.isDigit(s)||i&&ee.isHexChar(s))this.position++;else break}return this.input.slice(e,this.position)}for(this.input[e]==="."&&(t=!0,this.position++);this.canRead();){let r=this.input[this.position];if(r==="."&&!t)t=!0;else if((r==="e"||r==="E")&&!n)n=!0,this.canRead(1)&&(this.input[this.position+1]==="+"||this.input[this.position+1]==="-")&&this.position++;else if(!ee.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)}readMoneyDigit(){let e=this.position,t=!1;for(;this.canRead();){let n=this.input[this.position];if(n==="."&&!t)t=!0;else if(!(n===","&&!t)){if(!ee.isDigit(n))break}this.position++}if(e===this.position)throw new Error(`Unexpected character. position: ${e}
6
6
  ${this.getDebugPositionInfo(e)}`);return this.input.slice(e,this.position)}readSingleQuotedString(){let e=this.position,t=!1;for(this.read("'");this.canRead();){let n=this.input[this.position];if(this.position++,n==="\\"&&this.canRead(1)){this.position++;continue}else if(n==="'"){t=!0;break}}if(t===!1)throw new Error(`Single quote is not closed. position: ${e}
7
7
  ${this.getDebugPositionInfo(e)}`);return this.input.slice(e,this.position)}isDollarQuotedString(){if(!this.canRead(1))return!1;if(this.input[this.position+1]==="$")return!0;let e=this.position+1;for(;e<this.input.length;){let t=this.input[e];if(t==="$")return!0;if(!this.isAlphanumeric(t)&&t!=="_")return!1;e++}return!1}readDollarQuotedString(){let e=this.position;this.position++;let t="";for(;this.canRead()&&this.input[this.position]!=="$";)t+=this.input[this.position],this.position++;if(!this.canRead())throw new Error(`Unexpected end of input while reading dollar-quoted string tag at position ${e}`);this.position++;let n="$"+t+"$",r=n,i="";for(;this.canRead();){if(this.input.substring(this.position,this.position+r.length)===r)return this.position+=r.length,n+i+r;i+=this.input[this.position],this.position++}throw new Error(`Unclosed dollar-quoted string starting at position ${e}. Expected closing tag: ${r}`)}isAlphanumeric(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}};var pn=class extends ue{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(ee.isNamedParameterPrefix(t)){if(this.canRead(1)&&ee.isOperatorSymbol(this.input[this.position+1])||t===":"&&this.isInArraySliceContext()||t==="$"&&this.isDollarQuotedString())return null;if(t==="$"&&this.canRead(1)&&ee.isDigit(this.input[this.position+1])){let i=this.position+1,s=!1;for(;i<this.input.length&&(ee.isDigit(this.input[i])||this.input[i]===","||this.input[i]===".");){if(this.input[i]==="."||this.input[i]===","){s=!0;break}i++}if(s)return null}this.position++;let n=this.position;for(;this.canRead()&&!ee.isDelimiter(this.input[this.position]);)this.position++;let r=this.input.slice(n,this.position);return this.createLexeme(256,t+r)}if(t==="?"){if(this.canRead(1)){let n=this.input[this.position+1];if(n==="|"||n==="&")return null}return e&&(e.type&64||e.type&1)?null:(this.position++,this.createLexeme(256,t))}return null}isInArraySliceContext(){let e=this.position-1,t=0,n=0;for(;e>=0;){let r=this.input[e];if(r==="]")t++;else if(r==="["){if(t--,t<0){if(e>0){let i=this.input[e-1];if(/[a-zA-Z0-9_)\]]/.test(i))return!0}if(e===0)return!1;break}}else r===")"?n++:r==="("&&n--;e--}return!1}isDollarQuotedString(){if(!this.canRead(1))return!1;if(this.input[this.position+1]==="$")return!0;let e=this.position+1;for(;e<this.input.length;){let t=this.input[e];if(t==="$")return!0;if(!this.isAlphanumeric(t)&&t!=="_")return!1;e++}return!1}isAlphanumeric(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}};var mn=class a extends ue{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 a.SPECIAL_SYMBOL_TOKENS?(this.position++,this.createLexeme(a.SPECIAL_SYMBOL_TOKENS[t],t)):null}};var dn=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 Hr=new Je([["and"],["or"],["is"],["is","not"],["is","distinct","from"],["is","not","distinct","from"],["like"],["ilike"],["in"],["exists"],["between"],["not","like"],["not","ilike"],["not","in"],["not","exists"],["not","between"],["escape"],["uescape"],["similar","to"],["not","similar","to"],["similar"],["placing"],["rlike"],["regexp"],["mod"],["xor"],["not"],["both"],["leading"],["trailing"],["both","from"],["leading","from"],["trailing","from"],["year","from"],["month","from"],["day","from"],["hour","from"],["minute","from"],["second","from"],["dow","from"],["doy","from"],["isodow","from"],["quarter","from"],["week","from"],["epoch","from"],["at","time","zone"]]),Yr=new Je([["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"]]),Zr=new Ee(Hr),Xr=new Ee(Yr);var hn=class extends ue{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(ee.isOperatorSymbol(t)){let r=this.position;for(;this.canRead()&&ee.isOperatorSymbol(this.input[this.position]);){if(this.canRead(1)){let s=this.input[this.position];if(s==="-"&&this.input[this.position+1]==="-")break;if(s==="/"&&this.input[this.position+1]==="*")break}this.position++}let i=this.input.slice(r,this.position);return this.createLexeme(2,i)}let n=Xr.parse(this.input,this.position);return n!==null?(this.position=n.newPosition,this.createLexeme(8258,n.keyword)):(n=Zr.parse(this.input,this.position),n!==null?(this.position=n.newPosition,this.createLexeme(2,n.keyword)):null)}};var ei=new Je([["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"],["lateral","join"],["lateral","inner","join"],["lateral","left","join"],["lateral","left","outer","join"]]),Jt=new Je([["with"],["recursive"],["materialized"],["not","materialized"],["select"],["from"],["distinct"],["distinct","on"],["where"],["group","by"],["having"],["order","by"],["limit"],["offset"],["fetch"],["first"],["next"],["row"],["row","only"],["rows","only"],["percent"],["percent","with","ties"],["for"],["update"],["share"],["key","share"],["no","key","update"],["union"],["union","all"],["intersect"],["intersect","all"],["except"],["except","all"],["beteen"],["window"],["over"],["partition","by"],["range"],["rows"],["groups"],["within","group"],["with","ordinality"],["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"]]),ti=new Ee(Jt),Kt=new Ee(ei);var fn=class extends ue{tryRead(e){if(this.isEndOfInput())return null;let t=Kt.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(128,t.keyword);let n=ti.parse(this.input,this.position);if(n!==null)return this.position=n.newPosition,this.createLexeme(128,n.keyword,n.comments);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 ni=new Set(["e'","E'","x'","X'","b'","B'"]),ri=new Set(["u&'","U&'"]),Cn=class extends ue{tryRead(e){let t=this.position;return this.canRead(1)&&ni.has(this.input.slice(t,t+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(t,this.position))):this.canRead(2)&&ri.has(this.input.slice(t,t+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(t,this.position))):null}};var ii=new Je([["grouping","sets"],["array"]]),si=new Ee(ii),gn=class extends ue{tryRead(e){if(this.isEndOfInput())return null;let t=si.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(2048,t.keyword);let n=le.tryReadRegularIdentifier(this.input,this.position);if(!n)return null;this.position=n.newPosition;var r=le.readWhiteSpaceAndComment(this.input,this.position).position-this.position;return this.canRead(r)&&this.input[this.position+r]==="("?this.createLexeme(2048,n.identifier):null}};var oi=new Je([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),ai=new Ee(oi),yn=class extends ue{tryRead(e){if(this.isEndOfInput())return null;let t=ai.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=le.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 vn=class extends ue{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="`"){let n=this.readEscapedIdentifier("`");return this.createLexeme(64,n)}if(t==='"'){let n=this.readEscapedIdentifier('"');return this.createLexeme(64,n)}if(t==="["&&this.isSqlServerBracketIdentifier(e)){let n=this.readEscapedIdentifier("]");return this.createLexeme(64,n)}return null}isSqlServerBracketIdentifier(e){if(e?.value==="array")return!1;let t=this.position+1,n=t;for(;n<this.input.length&&this.input[n]!=="]";){let i=this.input[n];if(i===":"||i===","||i==="+"||i==="-"||i==="*"||i==="/"||i==="("||i===")")return!1;n++}if(n>=this.input.length)return!1;let r=this.input.slice(t,n).trim();return r===""?!1:/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$/.test(r)}readEscapedIdentifier(e){let t=this.position;for(this.position++;this.canRead()&&this.input[this.position]!==e;)this.position++;if(t===this.position)throw new Error(`Closing delimiter is not found. position: ${t}, delimiter: ${e}
8
- ${this.getDebugPositionInfo(t)}`);return this.position++,this.input.slice(t+1,this.position-1)}};var O=class a{constructor(e){this.input=e,this.position=0,this.readerManager=new dn(e).register(new vn(e)).register(new pn(e)).register(new Cn(e)).register(new cn(e)).register(new mn(e)).register(new fn(e)).register(new hn(e)).register(new yn(e)).register(new gn(e)).register(new un(e))}isEndOfInput(e=0){return this.position+e>=this.input.length}canRead(e=0){return!this.isEndOfInput(e)}tokenize(e){return e?.preserveFormatting?this.tokenizeWithFormatting():new a(this.input).readLexmes()}readLexmes(){return this.tokenizeBasic()}tokenizeBasic(){this.position=0;let e=Math.ceil(this.input.length/8),t=new Array(e),n=0,r=this.readComment(),i=r.lines;this.position=r.position;let s=null;for(;this.canRead()&&this.input[this.position]!==";";){let o=this.readerManager.tryRead(this.position,s);if(o===null)throw new Error(`Unexpected character. actual: ${this.input[this.position]}, position: ${this.position}
8
+ ${this.getDebugPositionInfo(t)}`);return this.position++,this.input.slice(t+1,this.position-1)}};var R=class a{constructor(e){this.input=e,this.position=0,this.readerManager=new dn(e).register(new vn(e)).register(new pn(e)).register(new Cn(e)).register(new cn(e)).register(new mn(e)).register(new fn(e)).register(new hn(e)).register(new yn(e)).register(new gn(e)).register(new un(e))}isEndOfInput(e=0){return this.position+e>=this.input.length}canRead(e=0){return!this.isEndOfInput(e)}tokenize(e){return e?.preserveFormatting?this.tokenizeWithFormatting():new a(this.input).readLexmes()}readLexmes(){return this.tokenizeBasic()}tokenizeBasic(){this.position=0;let e=Math.ceil(this.input.length/8),t=new Array(e),n=0,r=this.readComment(),i=r.lines;this.position=r.position;let s=null;for(;this.canRead()&&this.input[this.position]!==";";){let o=this.readerManager.tryRead(this.position,s);if(o===null)throw new Error(`Unexpected character. actual: ${this.input[this.position]}, position: ${this.position}
9
9
  ${this.getDebugPositionInfo(this.position)}`);this.position=this.readerManager.getMaxPosition();let l=this.readComment();this.position=l.position,o.type&16||o.type&2?l.lines.length>0&&i.push(...l.lines):((i.length>0||l.lines.length>0)&&this.addCommentsToToken(o,i,l.lines),i=[]),t[n++]=o,s=o}if(i.length>0&&n>0){let o=t[n-1];o.comments===null&&(o.comments=[]),o.comments.push(...i)}return n===e?t:t.slice(0,n)}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 le.readWhiteSpaceAndComment(this.input,this.position)}getDebugPositionInfo(e){return le.getDebugPositionInfo(this.input,e)}tokenizeWithFormatting(){let e=this.tokenizeBasic();return this.mapToFormattingLexemes(e)}mapToFormattingLexemes(e){if(e.length===0)return[];let t=[],n=0;for(let i of e){n=this.skipWhitespaceAndComments(n);let s=this.findLexemeAtPosition(i,n);if(s)t.push(s),n=s.endPosition;else{let o={startPosition:n,endPosition:n+i.value.length};t.push(o),n=o.endPosition}}let r=[];for(let i=0;i<e.length;i++){let s=e[i],o=t[i],l=i<e.length-1?t[i+1].startPosition:this.input.length,u=this.input.slice(o.endPosition,l),c=this.extractCommentsFromWhitespace(u),p={...s,followingWhitespace:u,inlineComments:c,position:{startPosition:o.startPosition,endPosition:o.endPosition,...this.getLineColumnInfo(o.startPosition,o.endPosition)}};r.push(p)}return r}findLexemeAtPosition(e,t){if(t>=this.input.length)return null;let n=[e.value,e.value.toUpperCase(),e.value.toLowerCase()];for(let r of n)if(t+r.length<=this.input.length&&this.input.substring(t,t+r.length)===r&&this.isValidLexemeMatch(r,t))return{startPosition:t,endPosition:t+r.length};return null}isValidLexemeMatch(e,t){if(t>0){let r=this.input[t-1];if(this.isAlphanumericUnderscore(r))return!1}let n=t+e.length;if(n<this.input.length){let r=this.input[n];if(this.isAlphanumericUnderscore(r))return!1}return!0}isAlphanumericUnderscore(e){let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95}isWhitespace(e){let t=e.charCodeAt(0);return t===32||t===9||t===10||t===13}extractCommentsFromWhitespace(e){let t=[],n=0;for(;n<e.length;){let r=n,i=le.readWhiteSpaceAndComment(e,n);i.lines.length>0&&t.push(...i.lines),n=i.position,n===r&&n++}return t}skipWhitespaceAndComments(e){let t=e;for(;t<this.input.length;){let n=this.input[t];if(this.isWhitespace(n)){t++;continue}if(t<this.input.length-1&&this.input[t]==="-"&&this.input[t+1]==="-"){for(;t<this.input.length&&this.input[t]!==`
10
10
  `&&this.input[t]!=="\r";)t++;continue}if(t<this.input.length-1&&this.input[t]==="/"&&this.input[t+1]==="*"){for(t+=2;t<this.input.length-1;){if(this.input[t]==="*"&&this.input[t+1]==="/"){t+=2;break}t++}continue}break}return t}getLineColumnInfo(e,t){let n=this.getLineColumn(e),r=this.getLineColumn(t);return{startLine:n.line,startColumn:n.column,endLine:r.line,endColumn:r.column}}getLineColumn(e){let t=1,n=1;for(let r=0;r<Math.min(e,this.input.length);r++)this.input[r]===`
11
- `?(t++,n=1):n++;return{line:t,column:n}}};var Me=class a{static parseFromLexeme(e,t){let{identifiers:n,newIndex:r}=a.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:i,name:s}=a.extractNamespacesAndName(n),o=0;return r>t&&(o=e[r-1].type),{namespaces:i,name:new P(s),newIndex:r,lastTokenType:o}}static parse(e){let n=new O(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 wn=class{static parseFromLexeme(e,t){let{namespaces:n,name:r,newIndex:i}=Me.parseFromLexeme(e,t);return{value:new b(n,r),newIndex:i}}};var _t=class{static parseFromLexeme(e,t){let n=t,r=e[n].value,i,s=fr.parse(r.toLowerCase(),0);if(s){let o=new V(s.keyword);return n++,{value:o,newIndex:n}}if(/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(r))return i=Number(r),n++,{value:new Z(i),newIndex:n};{/^\$[^$]*\$[\s\S]*\$[^$]*\$$/.test(r)?i=r:r.startsWith("'")&&r.endsWith("'")?i=r.slice(1,-1):i=r;let o=r.startsWith("'")&&r.endsWith("'");return n++,{value:new Z(i,void 0,o),newIndex:n}}}};var Sn=class{static parseFromLexeme(e,t){let n=t;if(n+1<e.length&&e[n].type&4&&(e[n+1].value==="select"||e[n+1].value==="values"||e[n+1].value==="with")){n+=1;let r=A.parseFromLexeme(e,n);if(n=r.newIndex,n>=e.length||e[n].type!==8)throw new Error(`Expected ')' at index ${n}, but found ${e[n].value}`);let i=e[n].comments;n++;let s=new ge(r.value);return i&&i.length>0&&(s.comments=i),{value:s,newIndex:n}}else{let r=k.parseArgument(4,8,e,t);return n=r.newIndex,{value:new Y(r.value),newIndex:n}}}};var bn=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 b(null,"*"),newIndex:n};let i=k.parseFromLexeme(e,n);return n=i.newIndex,{value:new te(r,i.value),newIndex:n}}throw new Error(`Invalid unary expression at index ${t}: ${e[t].value}`)}};var En=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 N(r);return n++,{value:i,newIndex:n}}};var xn=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 Tn=class{static parseFromLexeme(e,t){let n=t,r=e[n];return r.value==="case"?(n++,this.parseCaseExpression(e,n)):r.value==="case when"?(n++,this.parseCaseWhenExpression(e,n)):this.parseModifierUnaryExpression(e,n)}static parseModifierUnaryExpression(e,t){let n=t;if(n<e.length&&e[n].type&128){let r=e[n].value;n++;let i=k.parseFromLexeme(e,n);return{value:new te(r,i.value),newIndex:i.newIndex}}throw new Error(`Invalid modifier unary expression at index ${n}, Lexeme: ${e[n].value}`)}static parseCaseExpression(e,t){let n=t,r=k.parseFromLexeme(e,n);n=r.newIndex;let i=this.parseSwitchCaseArgument(e,n,[]);return n=i.newIndex,{value:new ie(r.value,i.value),newIndex:n}}static parseCaseWhenExpression(e,t){let n=t,r=this.parseCaseConditionValuePair(e,n);n=r.newIndex;let i=[r.value],s=this.parseSwitchCaseArgument(e,n,i);return n=s.newIndex,{value:new ie(null,s.value),newIndex:n}}static parseSwitchCaseArgument(e,t,n){let r=t,i=[...n],s=null;for(;r<e.length&&this.isCommandWithValue(e[r],"when");){r++;let l=this.parseCaseConditionValuePair(e,r);r=l.newIndex,i.push(l.value)}if(r<e.length&&this.isCommandWithValue(e[r],"else")){r++;let l=k.parseFromLexeme(e,r);s=l.value,r=l.newIndex}if(r<e.length&&this.isCommandWithValue(e[r],"end"))r++;else throw new Error(`The CASE expression requires 'end' keyword at the end (index ${r})`);if(i.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${r})`);return{value:new Te(i,s),newIndex:r}}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,r=k.parseFromLexeme(e,n);if(n=r.newIndex,n>=e.length||!(e[n].type&128)||e[n].value!=="then")throw new Error(`Expected 'then' after WHEN condition at index ${n}`);n++;let i=k.parseFromLexeme(e,n);return n=i.newIndex,{value:new ke(r.value,i.value),newIndex:n}}};var rt=class{static parse(e){let n=new O(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The ORDER BY clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="order by")throw new Error(`Syntax error at position ${n}: Expected 'ORDER BY' keyword but found "${e[n].value}". ORDER BY clauses must start with the ORDER BY keywords.`);n++;let r=[],i=this.parseItem(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=this.parseItem(e,n);r.push(s.value),n=s.newIndex}if(r.length===0)throw new Error(`Syntax error at position ${t}: No ordering expressions found. The ORDER BY clause requires at least one expression to order by.`);return{value:new pe(r),newIndex:n}}static parseItem(e,t){let n=t,r=k.parseFromLexeme(e,n),i=r.value;if(n=r.newIndex,n>=e.length)return{value:i,newIndex:n};let s=n>=e.length?null:e[n].value==="asc"?(n++,"asc"):e[n].value==="desc"?(n++,"desc"):null,o=n>=e.length?null:e[n].value==="nulls first"?(n++,"first"):e[n].value==="nulls last"?(n++,"last"):null;return s===null&&o===null?{value:i,newIndex:n}:{value:new Ae(i,s,o),newIndex:n}}};var kn=class{static parse(e){let n=new O(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The PARTITION BY clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="partition by")throw new Error(`Syntax error at position ${n}: Expected 'PARTITION BY' keyword but found "${e[n].value}". PARTITION BY clauses must start with the PARTITION BY keywords.`);n++;let r=[],i=k.parseFromLexeme(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=k.parseFromLexeme(e,n);r.push(s.value),n=s.newIndex}if(r.length===0)throw new Error(`Syntax error at position ${t}: No partition expressions found. The PARTITION BY clause requires at least one expression to partition by.`);return r.length===1?{value:new De(r[0]),newIndex:n}:{value:new De(new U(r)),newIndex:n}}};var Pt=class{static parse(e){let n=new O(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The window frame expression is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].type!==4)throw new Error(`Syntax error at position ${n}: Expected opening parenthesis '(' but found "${e[n].value}".`);n++;let r=null,i=null,s=null;if(n<e.length&&e[n].value==="partition by"){let o=kn.parseFromLexeme(e,n);r=o.value,n=o.newIndex}if(n<e.length&&e[n].value==="order by"){let o=rt.parseFromLexeme(e,n);i=o.value,n=o.newIndex}if(n<e.length&&this.isFrameTypeKeyword(e[n].value)){let o=this.parseFrameSpec(e,n);s=o.value,n=o.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 Be(r,i,s),newIndex:n}}static isFrameTypeKeyword(e){let t=e;return t==="rows"||t==="range"||t==="groups"}static parseFrameSpec(e,t){let n=t,r=e[n].value,i;switch(r){case"rows":i="rows";break;case"range":i="range";break;case"groups":i="groups";break;default:throw new Error(`Syntax error at position ${n}: Invalid frame type "${e[n].value}". Expected one of: ROWS, RANGE, GROUPS.`)}if(n++,n<e.length&&e[n].value==="between"){n++;let s=this.parseFrameBoundary(e,n),o=s.value;if(n=s.newIndex,n>=e.length||e[n].value!=="and")throw new Error(`Syntax error at position ${n}: Expected 'AND' keyword in BETWEEN clause.`);n++;let l=this.parseFrameBoundary(e,n),u=l.value;return n=l.newIndex,{value:new Ge(i,o,u),newIndex:n}}else{let s=this.parseFrameBoundary(e,n),o=s.value;return n=s.newIndex,{value:new Ge(i,o,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 Et(i),newIndex:n+1}}else if(n<e.length&&e[n].type&1){let r=k.parseFromLexeme(e,n);if(n=r.newIndex,n<e.length&&e[n].type&128){let i=e[n].value,s;if(i==="preceding")s=!1;else if(i==="following")s=!0;else throw new Error(`Syntax error at position ${n}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`);return n++,{value:new xt(r.value,s),newIndex:n}}else throw new Error(`Syntax error at position ${n}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`)}throw new Error(`Syntax error at position ${n}: Expected a valid frame boundary component.`)}};var zt=class{static parse(e){let n=new O(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 P(r),newIndex:n}}if(e[n].type&4)return Pt.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 a extends Error{constructor(t,n,r){super(t);this.index=n;this.context=r;this.name="ParseError"}static fromUnparsedLexemes(t,n,r){let i=Math.max(0,n-2),s=Math.min(t.length,n+3),o=t.slice(i,s).map((u,c)=>{let p=c+i===n?">":" ",d=$[u.type]||u.type;return`${p} ${c+i}:${u.value} [${d}]`}).join(`
11
+ `?(t++,n=1):n++;return{line:t,column:n}}};var Me=class a{static parseFromLexeme(e,t){let{identifiers:n,newIndex:r}=a.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:i,name:s}=a.extractNamespacesAndName(n),o=0;return r>t&&(o=e[r-1].type),{namespaces:i,name:new P(s),newIndex:r,lastTokenType:o}}static parse(e){let n=new R(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 wn=class{static parseFromLexeme(e,t){let{namespaces:n,name:r,newIndex:i}=Me.parseFromLexeme(e,t);return{value:new b(n,r),newIndex:i}}};var _t=class{static parseFromLexeme(e,t){let n=t,r=e[n].value,i,s=fr.parse(r.toLowerCase(),0);if(s){let o=new $(s.keyword);return n++,{value:o,newIndex:n}}if(/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(r))return i=Number(r),n++,{value:new Z(i),newIndex:n};{/^\$[^$]*\$[\s\S]*\$[^$]*\$$/.test(r)?i=r:r.startsWith("'")&&r.endsWith("'")?i=r.slice(1,-1):i=r;let o=r.startsWith("'")&&r.endsWith("'");return n++,{value:new Z(i,void 0,o),newIndex:n}}}};var Sn=class{static parseFromLexeme(e,t){let n=t;if(n+1<e.length&&e[n].type&4&&(e[n+1].value==="select"||e[n+1].value==="values"||e[n+1].value==="with")){n+=1;let r=A.parseFromLexeme(e,n);if(n=r.newIndex,n>=e.length||e[n].type!==8)throw new Error(`Expected ')' at index ${n}, but found ${e[n].value}`);let i=e[n].comments;n++;let s=new ge(r.value);return i&&i.length>0&&(s.comments=i),{value:s,newIndex:n}}else{let r=I.parseArgument(4,8,e,t);return n=r.newIndex,{value:new Y(r.value),newIndex:n}}}};var bn=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 b(null,"*"),newIndex:n};let i=I.parseFromLexeme(e,n);return n=i.newIndex,{value:new te(r,i.value),newIndex:n}}throw new Error(`Invalid unary expression at index ${t}: ${e[t].value}`)}};var En=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 N(r);return n++,{value:i,newIndex:n}}};var xn=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 Tn=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=I.parseFromLexeme(e,n);return{value:new te(r,i.value),newIndex:i.newIndex}}throw new Error(`Invalid modifier unary expression at index ${n}, Lexeme: ${e[n].value}`)}static parseCaseExpression(e,t){let n=t,r=I.parseFromLexeme(e,n);n=r.newIndex;let i=this.parseSwitchCaseArgument(e,n,[]);return n=i.newIndex,{value:new ie(r.value,i.value),newIndex:n}}static parseCaseWhenExpression(e,t){let n=t,r=this.parseCaseConditionValuePair(e,n);n=r.newIndex;let i=[r.value],s=this.parseSwitchCaseArgument(e,n,i);return n=s.newIndex,{value:new ie(null,s.value),newIndex:n}}static parseSwitchCaseArgument(e,t,n){let r=t,i=[...n],s=null;for(;r<e.length&&this.isCommandWithValue(e[r],"when");){r++;let l=this.parseCaseConditionValuePair(e,r);r=l.newIndex,i.push(l.value)}if(r<e.length&&this.isCommandWithValue(e[r],"else")){r++;let l=I.parseFromLexeme(e,r);s=l.value,r=l.newIndex}if(r<e.length&&this.isCommandWithValue(e[r],"end"))r++;else throw new Error(`The CASE expression requires 'end' keyword at the end (index ${r})`);if(i.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${r})`);return{value:new Te(i,s),newIndex:r}}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,r=I.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=I.parseFromLexeme(e,n);return n=i.newIndex,{value:new ke(r.value,i.value),newIndex:n}}};var rt=class{static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The ORDER BY clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="order by")throw new Error(`Syntax error at position ${n}: Expected 'ORDER BY' keyword but found "${e[n].value}". ORDER BY clauses must start with the ORDER BY keywords.`);n++;let r=[],i=this.parseItem(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=this.parseItem(e,n);r.push(s.value),n=s.newIndex}if(r.length===0)throw new Error(`Syntax error at position ${t}: No ordering expressions found. The ORDER BY clause requires at least one expression to order by.`);return{value:new pe(r),newIndex:n}}static parseItem(e,t){let n=t,r=I.parseFromLexeme(e,n),i=r.value;if(n=r.newIndex,n>=e.length)return{value:i,newIndex:n};let s=n>=e.length?null:e[n].value==="asc"?(n++,"asc"):e[n].value==="desc"?(n++,"desc"):null,o=n>=e.length?null:e[n].value==="nulls first"?(n++,"first"):e[n].value==="nulls last"?(n++,"last"):null;return s===null&&o===null?{value:i,newIndex:n}:{value:new Ae(i,s,o),newIndex:n}}};var kn=class{static parse(e){let n=new R(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=I.parseFromLexeme(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=I.parseFromLexeme(e,n);r.push(s.value),n=s.newIndex}if(r.length===0)throw new Error(`Syntax error at position ${t}: No partition expressions found. The PARTITION BY clause requires at least one expression to partition by.`);return r.length===1?{value:new De(r[0]),newIndex:n}:{value:new De(new U(r)),newIndex:n}}};var Pt=class{static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The window frame expression is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].type!==4)throw new Error(`Syntax error at position ${n}: Expected opening parenthesis '(' but found "${e[n].value}".`);n++;let r=null,i=null,s=null;if(n<e.length&&e[n].value==="partition by"){let o=kn.parseFromLexeme(e,n);r=o.value,n=o.newIndex}if(n<e.length&&e[n].value==="order by"){let o=rt.parseFromLexeme(e,n);i=o.value,n=o.newIndex}if(n<e.length&&this.isFrameTypeKeyword(e[n].value)){let o=this.parseFrameSpec(e,n);s=o.value,n=o.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 Be(r,i,s),newIndex:n}}static isFrameTypeKeyword(e){let t=e;return t==="rows"||t==="range"||t==="groups"}static parseFrameSpec(e,t){let n=t,r=e[n].value,i;switch(r){case"rows":i="rows";break;case"range":i="range";break;case"groups":i="groups";break;default:throw new Error(`Syntax error at position ${n}: Invalid frame type "${e[n].value}". Expected one of: ROWS, RANGE, GROUPS.`)}if(n++,n<e.length&&e[n].value==="between"){n++;let s=this.parseFrameBoundary(e,n),o=s.value;if(n=s.newIndex,n>=e.length||e[n].value!=="and")throw new Error(`Syntax error at position ${n}: Expected 'AND' keyword in BETWEEN clause.`);n++;let l=this.parseFrameBoundary(e,n),u=l.value;return n=l.newIndex,{value:new Ge(i,o,u),newIndex:n}}else{let s=this.parseFrameBoundary(e,n),o=s.value;return n=s.newIndex,{value:new Ge(i,o,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 Et(i),newIndex:n+1}}else if(n<e.length&&e[n].type&1){let r=I.parseFromLexeme(e,n);if(n=r.newIndex,n<e.length&&e[n].type&128){let i=e[n].value,s;if(i==="preceding")s=!1;else if(i==="following")s=!0;else throw new Error(`Syntax error at position ${n}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`);return n++,{value:new xt(r.value,s),newIndex:n}}else throw new Error(`Syntax error at position ${n}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`)}throw new Error(`Syntax error at position ${n}: Expected a valid frame boundary component.`)}};var zt=class{static parse(e){let n=new R(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 P(r),newIndex:n}}if(e[n].type&4)return Pt.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 a extends Error{constructor(t,n,r){super(t);this.index=n;this.context=r;this.name="ParseError"}static fromUnparsedLexemes(t,n,r){let i=Math.max(0,n-2),s=Math.min(t.length,n+3),o=t.slice(i,s).map((u,c)=>{let p=c+i===n?">":" ",m=M[u.type]||u.type;return`${p} ${c+i}:${u.value} [${m}]`}).join(`
12
12
  `),l=`${r} Unparsed lexeme remains at index ${n}: ${t[n].value}
13
13
  Context:
14
- ${o}`;return new a(l,n,o)}};var ze=class{static{this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY=new Set(["string_agg","array_agg","json_agg","jsonb_agg","json_object_agg","jsonb_object_agg","xmlagg"])}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 ye(r.value),newIndex:n}}else if(n+1<e.length&&e[n+1].type&4){n++,n++;let r=A.parseFromLexeme(e,n);return n=r.newIndex,n++,{value:new ve(r.value),newIndex:n}}throw new Error(`Invalid ARRAY syntax at index ${n}, expected ARRAY[... or ARRAY(...)`)}static parseFromLexeme(e,t){let n=t,r=e[n];return r.value==="array"?this.parseArrayExpression(e,n):r.value==="substring"||r.value==="overlay"?this.parseKeywordFunction(e,n,[{key:"from",required:!1},{key:"for",required:!1}]):r.value==="cast"?this.parseKeywordFunction(e,n,[{key:"as",required:!0}]):r.value==="trim"?this.parseKeywordFunction(e,n,[{key:"from",required:!1}]):this.parseFunctionCall(e,n)}static tryParseBinaryExpression(e,t,n,r=!0,i=!0){let s=t;if(s<e.length&&e[s].type&2){let o=e[s].value.toLowerCase();if(!r&&o==="and"||!i&&o==="or")return null;if(s++,o==="between")return this.parseBetweenExpression(e,s,n,!1);if(o==="not between")return this.parseBetweenExpression(e,s,n,!0);if(o==="::"){let c=this.parseTypeValue(e,s);return s=c.newIndex,{value:new ce(n,c.value),newIndex:s}}let l=k.parseFromLexeme(e,s);return s=l.newIndex,{value:new S(n,o,l.value),newIndex:s}}return null}static parseBetweenExpression(e,t,n,r){let i=t,s=k.parseFromLexeme(e,i,!1);if(i=s.newIndex,i<e.length&&e[i].type&2&&e[i].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${i}`);i++;let o=this.parseBetweenUpperBound(e,i);return i=o.newIndex,{value:new we(n,s.value,o.value,r),newIndex:i}}static parseBetweenUpperBound(e,t){return k.parseFromLexeme(e,t,!1,!1)}static parseFunctionCall(e,t){let n=t,r=Me.parseFromLexeme(e,n),i=r.namespaces,s=r.name;if(n=r.newIndex,n<e.length&&e[n].type&4){let o=s.name.toLowerCase(),l,u=null,c=null;if(this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY.has(o)){let f=this.parseAggregateArguments(e,n);l={value:f.arguments,newIndex:f.newIndex},c=f.orderByClause,u=f.closingComments}else{let f=this.parseArgumentWithComments(e,n);l={value:f.value,newIndex:f.newIndex},u=f.closingComments}n=l.newIndex;let p=null;if(n<e.length&&e[n].value==="within group"){let f=this.parseWithinGroupClause(e,n);p=f.value,n=f.newIndex}let d=!1;if(n<e.length&&e[n].value==="with ordinality"&&(d=!0,n++),n<e.length&&e[n].value==="over"){let f=zt.parseFromLexeme(e,n);n=f.newIndex;let y=new K(i,s.name,l.value,f.value,p,d,c);return u&&u.length>0&&(y.comments=u),{value:y,newIndex:n}}else{let f=new K(i,s.name,l.value,null,p,d,c);return u&&u.length>0&&(f.comments=u),{value:f,newIndex:n}}}else throw be.fromUnparsedLexemes(e,n,`Expected opening parenthesis after function name '${s.name}'.`)}static parseKeywordFunction(e,t,n){let r=t,i=Me.parseFromLexeme(e,r),s=i.namespaces,o=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:p}of n)if(r<e.length&&e[r].type&128&&e[r].value===c)if(r++,r<e.length&&e[r].type&8192){let d=this.parseTypeValue(e,r);u=new S(u,c,d.value),r=d.newIndex}else{let d=k.parseFromLexeme(e,r);u=new S(u,c,d.value),r=d.newIndex}else if(p)throw be.fromUnparsedLexemes(e,r,`Keyword '${c}' is required for ${o.name} function.`);if(r<e.length&&e[r].type&8){r++;let c=null;if(r<e.length&&e[r].value==="within group"){let d=this.parseWithinGroupClause(e,r);c=d.value,r=d.newIndex}let p=!1;if(r<e.length&&e[r].value==="with ordinality"&&(p=!0,r++),r<e.length&&e[r].value==="over"){r++;let d=zt.parseFromLexeme(e,r);return r=d.newIndex,{value:new K(s,o.name,u,d.value,c,p,null),newIndex:r}}else return{value:new K(s,o.name,u,null,c,p,null),newIndex:r}}else throw be.fromUnparsedLexemes(e,r,`Missing closing parenthesis for function '${o.name}'.`)}else throw be.fromUnparsedLexemes(e,r,`Missing opening parenthesis for function '${o.name}'.`)}static parseTypeValue(e,t){let n=t,{namespaces:r,name:i,newIndex:s}=Me.parseFromLexeme(e,n);if(n=s,n<e.length&&e[n].type&4){let o=k.parseArgument(4,8,e,n);return n=o.newIndex,{value:new Ve(r,new V(i.name),o.value),newIndex:n}}else return{value:new Ve(r,new V(i.name)),newIndex:n}}static parseWithinGroupClause(e,t){let n=t;if(n>=e.length||e[n].value!=="within group")throw new Error(`Expected 'WITHIN GROUP' at index ${n}`);if(n++,n>=e.length||!(e[n].type&4))throw new Error(`Expected '(' after 'WITHIN GROUP' at index ${n}`);n++;let r=rt.parseFromLexeme(e,n);if(n=r.newIndex,n>=e.length||!(e[n].type&8))throw new Error(`Expected ')' after WITHIN GROUP ORDER BY clause at index ${n}`);return n++,{value:r.value,newIndex:n}}static parseAggregateArguments(e,t){let n=t,r=[],i=null;if(n>=e.length||!(e[n].type&4))throw be.fromUnparsedLexemes(e,n,"Expected opening parenthesis.");if(n++,n<e.length&&e[n].type&8){let u=e[n].comments;return n++,{arguments:new U([]),orderByClause:null,closingComments:u,newIndex:n}}if(n<e.length&&e[n].value==="*"){let u=new b(null,"*");if(n++,n<e.length&&e[n].type&8){let c=e[n].comments;return n++,{arguments:u,orderByClause:null,closingComments:c,newIndex:n}}else throw be.fromUnparsedLexemes(e,n,"Expected closing parenthesis after wildcard '*'.")}let s=k.parseFromLexeme(e,n);for(n=s.newIndex,r.push(s.value);n<e.length&&(e[n].type&16||e[n].value==="order by");){if(e[n].value==="order by"){let u=rt.parseFromLexeme(e,n);n=u.newIndex,i=u.value;break}if(e[n].type&16){if(n++,n<e.length&&e[n].value==="order by"){let c=rt.parseFromLexeme(e,n);n=c.newIndex,i=c.value;break}let u=k.parseFromLexeme(e,n);n=u.newIndex,r.push(u.value)}}if(n>=e.length||!(e[n].type&8))throw be.fromUnparsedLexemes(e,n,"Expected closing parenthesis.");let o=e[n].comments;return n++,{arguments:r.length===1?r[0]:new U(r),orderByClause:i,closingComments:o,newIndex:n}}static parseArgumentWithComments(e,t){let n=t;if(n>=e.length||!(e[n].type&4))throw be.fromUnparsedLexemes(e,n,"Expected opening parenthesis.");n++;let r=[];if(n<e.length&&e[n].type&8){let l=e[n].comments;return n++,{value:new U([]),closingComments:l,newIndex:n}}if(n<e.length&&e[n].value==="*"){let l=new b(null,"*");if(n++,n>=e.length||!(e[n].type&8))throw be.fromUnparsedLexemes(e,n,"Expected closing parenthesis after wildcard '*'.");let u=e[n].comments;return n++,{value:l,closingComments:u,newIndex:n}}let i=k.parseFromLexeme(e,n);for(n=i.newIndex,r.push(i.value);n<e.length&&e[n].type&16;){n++;let l=k.parseFromLexeme(e,n);n=l.newIndex,r.push(l.value)}if(n>=e.length||!(e[n].type&8))throw be.fromUnparsedLexemes(e,n,"Expected closing parenthesis.");let s=e[n].comments;return n++,{value:r.length===1?r[0]:new U(r),closingComments:s,newIndex:n}}};var yt=class{static{this.precedenceMap={or:1,and:2,"=":10,"!=":10,"<>":10,"<":10,"<=":10,">":10,">=":10,like:10,ilike:10,"not like":10,"not ilike":10,"similar to":10,"not similar to":10,in:10,"not in":10,is:10,"is not":10,"->":10,"->>":10,"#>":10,"#>>":10,"@>":10,"<@":10,"?":10,"?|":10,"?&":10,"~":10,"~*":10,"!~":10,"!~*":10,rlike:10,regexp:10,mod:30,xor:2,between:15,"not between":15,"+":20,"-":20,"*":30,"/":30,"%":30,"^":40,"::":50,"unary+":100,"unary-":100,not:100}}static getPrecedence(e){let t=this.precedenceMap[e.toLowerCase()];return t!==void 0?t:0}static hasHigherOrEqualPrecedence(e,t){return this.getPrecedence(e)>=this.getPrecedence(t)}static isLogicalOperator(e){let t=e.toLowerCase();return t==="and"||t==="or"}static isBetweenOperator(e){let t=e.toLowerCase();return t==="between"||t==="not between"}static isComparisonOperator(e){let t=e.toLowerCase();return["=","!=","<>","<",">","<=",">=","like","ilike","similar to","in","not in","->","->>","#>","#>>","@>","<@","?","?|","?&","~","~*","!~","!~*","rlike","regexp"].includes(t)}};var k=class{static parse(e){let n=new O(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw be.fromUnparsedLexemes(n,r.newIndex,"[ValueParser]");return r.value}static parseFromLexeme(e,t,n=!0,r=!0){return this.parseExpressionWithPrecedence(e,t,0,n,r)}static parseExpressionWithPrecedence(e,t,n,r=!0,i=!0){let s=t,o=e[s].comments,l=this.parseItem(e,s);l.value.comments===null&&o&&o.length>0&&(l.value.comments=o),s=l.newIndex;let u=l.value,c=this.parseArrayAccess(e,s,u);for(u=c.value,s=c.newIndex;s<e.length&&e[s].type&2;){let d=e[s].value;if(!r&&d.toLowerCase()==="and"||!i&&d.toLowerCase()==="or")break;let f=yt.getPrecedence(d);if(f<n)break;if(s++,yt.isBetweenOperator(d)){let M=ze.parseBetweenExpression(e,s,u,d.toLowerCase().includes("not"));u=M.value,s=M.newIndex;continue}if(d==="::"){let M=ze.parseTypeValue(e,s);u=new ce(u,M.value),s=M.newIndex;continue}let y=f+1,h=this.parseExpressionWithPrecedence(e,s,y,r,i);s=h.newIndex,u=new S(u,d,h.value)}return{value:u,newIndex:s}}static parseItem(e,t){let n=t;if(n>=e.length)throw new Error(`Unexpected end of lexemes at index ${t}`);let r=e[n];if(r.type&64&&r.type&2&&r.type&8192){if(n+1<e.length&&e[n+1].type&4)if(this.isTypeConstructor(e,n+1,r.value)){let o=ze.parseTypeValue(e,n);return{value:o.value,newIndex:o.newIndex}}else return ze.parseFromLexeme(e,n);let i=wn.parseFromLexeme(e,n);if(i.newIndex>=e.length)return i;if(e[i.newIndex].type&1){let o=_t.parseFromLexeme(e,i.newIndex);return{value:new te(e[n].value,o.value),newIndex:o.newIndex}}return i}else if(r.type&64){let{namespaces:i,name:s,newIndex:o}=Me.parseFromLexeme(e,n);if(e[o-1].type&2048)return ze.parseFromLexeme(e,n);if(e[o-1].type&8192)if(o<e.length&&e[o].type&4)if(this.isTypeConstructor(e,o,s.name)){let u=ze.parseTypeValue(e,n);return{value:u.value,newIndex:u.newIndex}}else return ze.parseFromLexeme(e,n);else return{value:new Ve(i,s),newIndex:o};return{value:new b(i,s),newIndex:o}}else{if(r.type&1)return _t.parseFromLexeme(e,n);if(r.type&4)return Sn.parseFromLexeme(e,n);if(r.type&2048)return ze.parseFromLexeme(e,n);if(r.type&2)return bn.parseFromLexeme(e,n);if(r.type&256)return En.parseFromLexeme(e,n);if(r.type&4096)return xn.parseFromLexeme(e,n);if(r.type&128)return Tn.parseFromLexeme(e,n);if(r.type&512){let{namespaces:i,name:s,newIndex:o}=Me.parseFromLexeme(e,n);return{value:new b(i,s),newIndex:o}}else if(r.type&8192){let{namespaces:i,name:s,newIndex:o}=Me.parseFromLexeme(e,n);if(o<e.length&&e[o].type&4)if(this.isTypeConstructor(e,o,s.name)){let l=ze.parseTypeValue(e,n);return{value:l.value,newIndex:l.newIndex}}else return ze.parseFromLexeme(e,n);else return{value:new Ve(i,s),newIndex:o}}}throw be.fromUnparsedLexemes(e,n,"[ValueParser] Invalid lexeme.")}static parseArgument(e,t,n,r){let i=r,s=[];if(i<n.length&&n[i].type===e){if(i++,i<n.length&&n[i].type===t)return i++,{value:new U([]),newIndex:i};if(i<n.length&&n[i].value==="*"){let l=new b(null,"*");if(i++,i<n.length&&n[i].type===t)return i++,{value:l,newIndex:i};throw be.fromUnparsedLexemes(n,i,"Expected closing parenthesis after wildcard '*'.")}let o=this.parseFromLexeme(n,i);for(i=o.newIndex,s.push(o.value);i<n.length&&n[i].type&16;){i++;let l=this.parseFromLexeme(n,i);i=l.newIndex,s.push(l.value)}if(i<n.length&&n[i].type===t)return i++,s.length===1?{value:s[0],newIndex:i}:{value:new U(s),newIndex:i};throw be.fromUnparsedLexemes(n,i,"Missing closing parenthesis.")}throw be.fromUnparsedLexemes(n,r,"Expected opening parenthesis.")}static parseArrayAccess(e,t,n){let r=t,i=n;for(;r<e.length&&e[r].type&512&&!this.isSqlServerBracketIdentifier(e,r);){if(r++,r>=e.length)throw new Error(`Expected array index or slice after '[' at index ${r-1}`);if(e[r].type&1024)throw new Error(`Empty array access brackets not supported at index ${r}`);let s=null,o=!1;if(e[r].type&2&&e[r].value===":")o=!0,r++;else{let l=yt.getPrecedence(":"),u=this.parseExpressionWithPrecedence(e,r,l+1);s=u.value,r=u.newIndex,r<e.length&&e[r].type&2&&e[r].value===":"&&(o=!0,r++)}if(o){let l=null;if(r<e.length&&!(e[r].type&1024)){let u=yt.getPrecedence(":"),c=this.parseExpressionWithPrecedence(e,r,u+1);l=c.value,r=c.newIndex}if(r>=e.length||!(e[r].type&1024))throw new Error(`Expected ']' after array slice at index ${r}`);r++,i=new et(i,s,l)}else{if(!s){let l=this.parseFromLexeme(e,r);s=l.value,r=l.newIndex}if(r>=e.length||!(e[r].type&1024))throw new Error(`Expected ']' after array index at index ${r}`);r++,i=new tt(i,s)}}return{value:i,newIndex:r}}static isSqlServerBracketIdentifier(e,t){let n=t+1;if(n>=e.length)return!1;for(;n<e.length&&!(e[n].type&1024);){let s=e[n];if(s.type&64||s.type&2&&s.value==="."){n++;continue}return!1}if(n>=e.length)return!1;let r=n;if(r+1<e.length){let s=e[r+1];if(s.type&2&&s.value===".")return!0}n=t+1;let i=!0;for(;n<r;){let s=e[n];if(!(s.type&64||s.type&2&&s.value===".")){i=!1;break}n++}return i}static isTypeConstructor(e,t,n){let r=["NUMERIC","DECIMAL","VARCHAR","CHAR","CHARACTER","TIMESTAMP","TIME","INTERVAL"],i=n.toUpperCase();if(r.includes(i))return!0;if(i==="DATE"){let s=t+1;if(s<e.length){let o=e[s];return!(o.type&1&&typeof o.value=="string"&&isNaN(Number(o.value)))}}return!1}};var X=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(C.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(Q.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(Ce.kind,e=>this.visitValuesQuery(e)),this.handlers.set(ae.kind,e=>this.visitWithClause(e)),this.handlers.set(ne.kind,e=>this.visitCommonTable(e)),this.handlers.set(z.kind,e=>this.visitSelectItem(e)),this.handlers.set(P.kind,e=>this.visitIdentifierString(e)),this.handlers.set(V.kind,e=>this.visitRawString(e)),this.handlers.set(b.kind,e=>this.visitColumnReference(e)),this.handlers.set(N.kind,e=>this.visitParameterExpression(e)),this.handlers.set(Z.kind,e=>this.visitLiteralValue(e)),this.handlers.set(B.kind,e=>this.visitSourceExpression(e)),this.handlers.set(R.kind,e=>this.visitTableSource(e)),this.handlers.set(qe.kind,e=>this.visitFunctionSource(e)),this.handlers.set($e.kind,e=>this.visitParenSource(e)),this.handlers.set(W.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(ge.kind,e=>this.visitInlineQuery(e)),this.handlers.set(J.kind,e=>this.visitFromClause(e)),this.handlers.set(fe.kind,e=>this.visitJoinClause(e)),this.handlers.set(he.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Se.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(S.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ie.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ke.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(Te.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(we.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(K.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ye.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ve.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(Ie.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ce.kind,e=>this.visitCastExpression(e)),this.handlers.set(Be.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Ge.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Ve.kind,e=>this.visitTypeValue(e)),this.handlers.set(U.kind,e=>this.visitValueList(e)),this.handlers.set(je.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(_.kind,e=>this.visitSelectClause(e)),this.handlers.set(me.kind,e=>this.visitGroupByClause(e)),this.handlers.set(de.kind,e=>this.visitHavingClause(e)),this.handlers.set(pe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Pe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Ne.kind,e=>this.visitForClause(e)),this.handlers.set(Ae.kind,e=>this.visitOrderByItem(e)),this.handlers.set(De.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 At=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(C.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(Q.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(Ce.kind,e=>this.visitValuesQuery(e)),this.handlers.set(z.kind,e=>this.visitSelectItem(e)),this.handlers.set(P.kind,e=>this.visitIdentifierString(e)),this.handlers.set(V.kind,e=>this.visitRawString(e)),this.handlers.set(b.kind,e=>this.visitColumnReference(e)),this.handlers.set(N.kind,e=>this.visitParameterExpression(e)),this.handlers.set(Z.kind,e=>this.visitLiteralValue(e)),this.handlers.set(B.kind,e=>this.visitSourceExpression(e)),this.handlers.set(R.kind,e=>this.visitTableSource(e)),this.handlers.set($e.kind,e=>this.visitParenSource(e)),this.handlers.set(W.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(ge.kind,e=>this.visitInlineQuery(e)),this.handlers.set(J.kind,e=>this.visitFromClause(e)),this.handlers.set(fe.kind,e=>this.visitJoinClause(e)),this.handlers.set(he.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Se.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(S.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ie.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ke.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(Te.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(we.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(K.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ye.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ve.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(Ie.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ce.kind,e=>this.visitCastExpression(e)),this.handlers.set(Be.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Ge.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Ve.kind,e=>this.visitTypeValue(e)),this.handlers.set(U.kind,e=>this.visitValueList(e)),this.handlers.set(et.kind,e=>this.visitArraySliceExpression(e)),this.handlers.set(tt.kind,e=>this.visitArrayIndexExpression(e)),this.handlers.set(je.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(_.kind,e=>this.visitSelectClause(e)),this.handlers.set(me.kind,e=>this.visitGroupByClause(e)),this.handlers.set(de.kind,e=>this.visitHavingClause(e)),this.handlers.set(pe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Pe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Ne.kind,e=>this.visitForClause(e)),this.handlers.set(Ae.kind,e=>this.visitOrderByItem(e)),this.handlers.set(De.kind,e=>this.visitPartitionByClause(e))}reset(){this.visitedNodes.clear()}execute(e){return this.reset(),this.visit(e)}visit(e){if(!this.isRootVisit)return this.visitNode(e);this.reset(),this.isRootVisit=!1;try{return this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return e;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t)return t(e);let n=e.getKind()?.toString()||"unknown",r=e.constructor?.name||"unknown";throw new Error(`[CTEDisabler] No handler for ${r} with kind ${n}.`)}visitSimpleSelectQuery(e){return e.withClause&&e.withClause.tables.forEach(t=>{this.visit(t.query)}),e.withClause=null,e.selectClause=this.visit(e.selectClause),e.fromClause=e.fromClause?this.visit(e.fromClause):null,e.whereClause=e.whereClause?this.visit(e.whereClause):null,e.groupByClause=e.groupByClause?this.visit(e.groupByClause):null,e.havingClause=e.havingClause?this.visit(e.havingClause):null,e.orderByClause=e.orderByClause?this.visit(e.orderByClause):null,e.windowClause&&(e.windowClause=new nt(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 Ce(t)}visitSelectClause(e){let t=e.items.map(n=>this.visit(n));return new _(t,e.distinct)}visitFromClause(e){let t=this.visit(e.source),n=e.joins?e.joins.map(r=>this.visit(r)):null;return new J(t,n)}visitSubQuerySource(e){let t=this.visit(e.query);return new W(t)}visitInlineQuery(e){let t=this.visit(e.selectQuery);return new ge(t)}visitJoinClause(e){let t=this.visit(e.source),n=e.condition?this.visit(e.condition):null;return new fe(e.joinType.value,t,n,e.lateral)}visitJoinOnClause(e){let t=this.visit(e.condition);return new he(t)}visitJoinUsingClause(e){let t=this.visit(e.condition);return new Se(t)}visitWhereClause(e){let t=this.visit(e.condition);return new se(t)}visitGroupByClause(e){let t=e.grouping.map(n=>this.visit(n));return new me(t)}visitHavingClause(e){let t=this.visit(e.condition);return new de(t)}visitOrderByClause(e){let t=e.order.map(n=>this.visit(n));return new pe(t)}visitWindowFrameClause(e){let t=this.visit(e.expression);return new Pe(e.name.name,t)}visitLimitClause(e){let t=this.visit(e.value);return new oe(t)}visitForClause(e){return new Ne(e.lockMode)}visitParenExpression(e){let t=this.visit(e.expression);return new Y(t)}visitBinaryExpression(e){let t=this.visit(e.left),n=this.visit(e.right);return new S(t,e.operator.value,n)}visitUnaryExpression(e){let t=this.visit(e.expression);return new te(e.operator.value,t)}visitCaseExpression(e){let t=e.condition?this.visit(e.condition):null,n=this.visit(e.switchCase);return new ie(t,n)}visitSwitchCaseArgument(e){let t=e.cases.map(r=>this.visit(r)),n=e.elseValue?this.visit(e.elseValue):null;return new Te(t,n)}visitCaseKeyValuePair(e){let t=this.visit(e.key),n=this.visit(e.value);return new ke(t,n)}visitBetweenExpression(e){let t=this.visit(e.expression),n=this.visit(e.lower),r=this.visit(e.upper);return new we(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 K(e.namespaces,e.name,t,n)}visitArrayExpression(e){let t=this.visit(e.expression);return new ye(t)}visitArrayQueryExpression(e){let t=this.visit(e.query);return new ve(t)}visitTupleExpression(e){let t=e.values.map(n=>this.visit(n));return new Ie(t)}visitCastExpression(e){let t=this.visit(e.input),n=this.visit(e.castType);return new ce(t,n)}visitTypeValue(e){let t=e.argument?this.visit(e.argument):null;return new Ve(e.namespaces,e.name,t)}visitSelectItem(e){let t=this.visit(e.value);return new z(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 B(t,n)}visitTableSource(e){return e}visitParenSource(e){let t=this.visit(e.source);return new $e(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 Be(t,n,r)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new Ae(t,e.sortDirection,e.nullsPosition)}visitValueList(e){let t=e.values.map(n=>this.visit(n));return new U(t)}visitArraySliceExpression(e){return e}visitArrayIndexExpression(e){return e}visitStringSpecifierExpression(e){return e}visitPartitionByClause(e){let t=this.visit(e.value);return new De(t)}};var He=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(C.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(Q.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(Ce.kind,t=>this.visitValuesQuery(t)),this.handlers.set(ae.kind,t=>this.visitWithClause(t)),this.handlers.set(ne.kind,t=>this.visitCommonTable(t)),this.handlers.set(J.kind,t=>this.visitFromClause(t)),this.handlers.set(fe.kind,t=>this.visitJoinClause(t)),this.handlers.set(he.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(Se.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(B.kind,t=>this.visitSourceExpression(t)),this.handlers.set(R.kind,t=>this.visitTableSource(t)),this.handlers.set(qe.kind,t=>this.visitFunctionSource(t)),this.handlers.set($e.kind,t=>this.visitParenSource(t)),this.handlers.set(W.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(ge.kind,t=>this.visitInlineQuery(t)),e||(this.handlers.set(se.kind,t=>this.visitWhereClause(t)),this.handlers.set(me.kind,t=>this.visitGroupByClause(t)),this.handlers.set(de.kind,t=>this.visitHavingClause(t)),this.handlers.set(pe.kind,t=>this.visitOrderByClause(t)),this.handlers.set(Pe.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(oe.kind,t=>this.visitLimitClause(t)),this.handlers.set(Oe.kind,t=>this.visitOffsetClause(t)),this.handlers.set(Ue.kind,t=>this.visitFetchClause(t)),this.handlers.set(Ne.kind,t=>this.visitForClause(t)),this.handlers.set(Ae.kind,t=>this.visitOrderByItem(t)),this.handlers.set(_.kind,t=>this.visitSelectClause(t)),this.handlers.set(z.kind,t=>this.visitSelectItem(t)),this.handlers.set(Y.kind,t=>this.visitParenExpression(t)),this.handlers.set(S.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(te.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(ie.kind,t=>this.visitCaseExpression(t)),this.handlers.set(ke.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(Te.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(we.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(K.kind,t=>this.visitFunctionCall(t)),this.handlers.set(ye.kind,t=>this.visitArrayExpression(t)),this.handlers.set(ve.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(Ie.kind,t=>this.visitTupleExpression(t)),this.handlers.set(ce.kind,t=>this.visitCastExpression(t)),this.handlers.set(U.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 V?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof V?e.qualifiedName.name.value:e.qualifiedName.name.name}collect(e){return this.visit(e),this.getTableSources()}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.selectableOnly||this.collectCTEs(e),this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}collectCTEs(e){let t=new X;t.visit(e);let n=t.getCommonTables();for(let r of n)this.cteNames.add(r.aliasExpression.table.name)}visitSimpleSelectQuery(e){if(e.fromClause&&e.fromClause.accept(this),!this.selectableOnly){if(e.withClause&&e.withClause.accept(this),e.whereClause&&e.whereClause.accept(this),e.groupByClause&&e.groupByClause.accept(this),e.havingClause&&e.havingClause.accept(this),e.orderByClause&&e.orderByClause.accept(this),e.windowClause)for(let t of e.windowClause.windows)t.accept(this);e.limitClause&&e.limitClause.accept(this),e.offsetClause&&e.offsetClause.accept(this),e.fetchClause&&e.fetchClause.accept(this),e.forClause&&e.forClause.accept(this),e.selectClause.accept(this)}}visitBinarySelectQuery(e){e.left.accept(this),e.right.accept(this)}visitValuesQuery(e){if(!this.selectableOnly)for(let t of e.tuples)t.accept(this)}visitWithClause(e){if(!this.selectableOnly)for(let t of e.tables)t.accept(this)}visitCommonTable(e){this.selectableOnly||e.query.accept(this)}visitFromClause(e){if(e.source.accept(this),e.joins)for(let t of e.joins)t.accept(this)}visitSourceExpression(e){e.datasource.accept(this)}visitTableSource(e){let t=this.getTableIdentifier(e);!this.tableNameMap.has(t)&&!this.isCTETable(e.table.name)&&(this.tableNameMap.set(t,!0),this.tableSources.push(e))}visitFunctionSource(e){e.argument&&this.visitValueComponent(e.argument)}visitValueComponent(e){e.accept(this)}isCTETable(e){return this.cteNames.has(e)}visitParenSource(e){e.source.accept(this)}visitSubQuerySource(e){this.selectableOnly||e.query.accept(this)}visitInlineQuery(e){this.selectableOnly||e.selectQuery.accept(this)}visitJoinClause(e){e.source.accept(this),!this.selectableOnly&&e.condition&&e.condition.accept(this)}visitJoinOnClause(e){this.selectableOnly||e.condition.accept(this)}visitJoinUsingClause(e){this.selectableOnly||e.condition.accept(this)}visitWhereClause(e){e.condition.accept(this)}visitGroupByClause(e){for(let t of e.grouping)t.accept(this)}visitHavingClause(e){e.condition.accept(this)}visitOrderByClause(e){for(let t of e.order)t.accept(this)}visitWindowFrameClause(e){e.expression.accept(this)}visitLimitClause(e){e.value.accept(this)}visitOffsetClause(e){e.value.accept(this)}visitFetchClause(e){e.expression.accept(this)}visitForClause(e){}visitOrderByItem(e){e.value.accept(this)}visitSelectClause(e){for(let t of e.items)t.accept(this)}visitSelectItem(e){e.value.accept(this)}visitParenExpression(e){e.expression.accept(this)}visitBinaryExpression(e){e.left.accept(this),e.right.accept(this)}visitUnaryExpression(e){e.expression.accept(this)}visitCaseExpression(e){e.condition&&e.condition.accept(this),e.switchCase.accept(this)}visitSwitchCaseArgument(e){for(let t of e.cases)t.accept(this);e.elseValue&&e.elseValue.accept(this)}visitCaseKeyValuePair(e){e.key.accept(this),e.value.accept(this)}visitBetweenExpression(e){e.expression.accept(this),e.lower.accept(this),e.upper.accept(this)}visitFunctionCall(e){e.argument&&e.argument.accept(this),e.over&&e.over.accept(this)}visitArrayExpression(e){e.expression.accept(this)}visitArrayQueryExpression(e){e.query.accept(this)}visitTupleExpression(e){for(let t of e.values)t.accept(this)}visitCastExpression(e){e.input.accept(this),e.castType.accept(this)}visitValueList(e){for(let t of e.values)t.accept(this)}visitStringSpecifierExpression(e){}};var pt=class extends v{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 m=class{constructor(e,t="",n=""){this.innerTokens=[];this.type=e,this.text=t,this.containerType=n}};var mt=class{static collect(e){let t=[];function n(r){if(!(!r||typeof r!="object")){r.constructor&&r.constructor.kind===N.kind&&t.push(r);for(let i of Object.keys(r)){let s=r[i];Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&s.constructor&&s.constructor.kind&&n(s)}}}return n(e),t}};var In=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var Pn=class{constructor(e){this.prefix=e?.prefix??":",this.suffix=e?.suffix??"",this.style=e?.style??"named"}decorate(e,t){let n="";return this.style==="anonymous"?n=this.prefix:this.style==="indexed"?n=this.prefix+t:this.style==="named"&&(n=this.prefix+e+this.suffix),e=n,e}};var Nt=class extends v{static{this.kind=Symbol("UpdateQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.updateClause=e.updateClause,this.setClause=e.setClause instanceof at?e.setClause:new at(e.setClause),this.whereClause=e.whereClause??null,this.fromClause=e.fromClause??null,this.returningClause=e.returning??null}};var Ke=class a{constructor(e=null,t=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=e??null,this.commonTableCollector=new X,this.commonTables=[],this.initialCommonTables=t,this.handlers=new Map,this.handlers.set(C.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(_.kind,n=>this.visitSelectClause(n)),this.handlers.set(B.kind,n=>this.visitSourceExpression(n)),this.handlers.set(J.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 b&&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 b&&r.value.namespaces).map(r=>r.value.getNamespace());if(e.fromClause){let r=e.fromClause.getSourceAliasName();if(r&&n.includes(r)&&this.processFromClause(e.fromClause,!1),e.fromClause.joins)for(let i of e.fromClause.joins){let s=i.getSourceAliasName();s&&n.includes(s)&&this.processJoinClause(i)}}this.selectValues=this.selectValues.filter(r=>r.name!=="*")}processFromClause(e,t){if(e){let n=e.getSourceAliasName();if(this.processSourceExpression(n,e.source),e.joins&&t)for(let r of e.joins)this.processJoinClause(r)}}processJoinClause(e){let t=e.getSourceAliasName();this.processSourceExpression(t,e.source)}processSourceExpression(e,t){let n=this.commonTables.find(r=>r.aliasExpression.table.name===e);if(n){let r=this.commonTables.filter(o=>o.aliasExpression.table.name!==e);new a(this.tableColumnResolver,r).collect(n.query).forEach(o=>{this.addSelectValueAsUnique(o.name,new b(e?[e]:null,o.name))})}else new a(this.tableColumnResolver,this.commonTables).collect(t).forEach(s=>{this.addSelectValueAsUnique(s.name,new b(e?[e]:null,s.name))})}visitSelectClause(e){for(let t of e.items)this.processSelectItem(t)}processSelectItem(e){if(e.identifier)this.addSelectValueAsUnique(e.identifier.name,e.value);else if(e.value instanceof b){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 b(t?[t]:null,n.name))});return}else if(e.datasource instanceof R){if(this.tableColumnResolver){let t=e.datasource.getSourceName();this.tableColumnResolver(t).forEach(n=>{this.addSelectValueAsUnique(n,new b([t],n))})}return}else if(e.datasource instanceof W){let t=e.getAliasName();new a(this.tableColumnResolver,this.commonTables).collect(e.datasource.query).forEach(i=>{this.addSelectValueAsUnique(i.name,new b(t?[t]:null,i.name))});return}else if(e.datasource instanceof $e)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 Lt=class extends v{static{this.kind=Symbol("CreateTableQuery")}constructor(e){super(),this.tableName=new P(e.tableName),this.isTemporary=e.isTemporary??!1,this.asSelectQuery=e.asSelectQuery}getSelectQuery(){let e;return this.asSelectQuery?e=new Ke().collect(this.asSelectQuery).map(r=>new z(r.value,r.name)):e=[new z(new V("*"))],new C({selectClause:new _(e),fromClause:new J(new B(new R(null,this.tableName.name),null),null)})}getCountQuery(){return new C({selectClause:new _([new z(new K(null,"count",new b(null,"*"),null))]),fromClause:new J(new B(new R(null,this.tableName.name),null),null)})}};var Lr={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"}},An=class a{constructor(e){this.handlers=new Map;this.index=1;e?.preset&&(e={...e.preset,...e}),this.parameterDecorator=new Pn({prefix:typeof e?.parameterSymbol=="string"?e.parameterSymbol:e?.parameterSymbol?.start??":",suffix:typeof e?.parameterSymbol=="object"?e.parameterSymbol.end:"",style:e?.parameterStyle??"named"}),this.identifierDecorator=new In({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.handlers.set(U.kind,t=>this.visitValueList(t)),this.handlers.set(b.kind,t=>this.visitColumnReference(t)),this.handlers.set(_e.kind,t=>this.visitQualifiedName(t)),this.handlers.set(K.kind,t=>this.visitFunctionCall(t)),this.handlers.set(te.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(S.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(Z.kind,t=>this.visitLiteralValue(t)),this.handlers.set(N.kind,t=>this.visitParameterExpression(t)),this.handlers.set(Te.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(ke.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(V.kind,t=>this.visitRawString(t)),this.handlers.set(P.kind,t=>this.visitIdentifierString(t)),this.handlers.set(Y.kind,t=>this.visitParenExpression(t)),this.handlers.set(ce.kind,t=>this.visitCastExpression(t)),this.handlers.set(ie.kind,t=>this.visitCaseExpression(t)),this.handlers.set(ye.kind,t=>this.visitArrayExpression(t)),this.handlers.set(ve.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(et.kind,t=>this.visitArraySliceExpression(t)),this.handlers.set(tt.kind,t=>this.visitArrayIndexExpression(t)),this.handlers.set(we.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(je.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(Ve.kind,t=>this.visitTypeValue(t)),this.handlers.set(Ie.kind,t=>this.visitTupleExpression(t)),this.handlers.set(ge.kind,t=>this.visitInlineQuery(t)),this.handlers.set(Be.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(Ge.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(Et.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(xt.kind,t=>this.visitWindowFrameBoundaryValue(t)),this.handlers.set(De.kind,t=>this.visitPartitionByClause(t)),this.handlers.set(pe.kind,t=>this.visitOrderByClause(t)),this.handlers.set(Ae.kind,t=>this.visitOrderByItem(t)),this.handlers.set(z.kind,t=>this.visitSelectItem(t)),this.handlers.set(_.kind,t=>this.visitSelectClause(t)),this.handlers.set(Tt.kind,t=>this.visitDistinct(t)),this.handlers.set(kt.kind,t=>this.visitDistinctOn(t)),this.handlers.set(pt.kind,t=>this.visitHintClause(t)),this.handlers.set(R.kind,t=>this.visitTableSource(t)),this.handlers.set(qe.kind,t=>this.visitFunctionSource(t)),this.handlers.set(B.kind,t=>this.visitSourceExpression(t)),this.handlers.set(re.kind,t=>this.visitSourceAliasExpression(t)),this.handlers.set(J.kind,t=>this.visitFromClause(t)),this.handlers.set(fe.kind,t=>this.visitJoinClause(t)),this.handlers.set(he.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(Se.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(se.kind,t=>this.visitWhereClause(t)),this.handlers.set(me.kind,t=>this.visitGroupByClause(t)),this.handlers.set(de.kind,t=>this.visitHavingClause(t)),this.handlers.set(nt.kind,t=>this.visitWindowClause(t)),this.handlers.set(Pe.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(oe.kind,t=>this.visitLimitClause(t)),this.handlers.set(Oe.kind,t=>this.visitOffsetClause(t)),this.handlers.set(Ue.kind,t=>this.visitFetchClause(t)),this.handlers.set(gt.kind,t=>this.visitFetchExpression(t)),this.handlers.set(Ne.kind,t=>this.visitForClause(t)),this.handlers.set(ae.kind,t=>this.visitWithClause(t)),this.handlers.set(ne.kind,t=>this.visitCommonTable(t)),this.handlers.set(C.kind,t=>this.visitSimpleQuery(t)),this.handlers.set(W.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(Q.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(Ce.kind,t=>this.visitValuesQuery(t)),this.handlers.set(Ie.kind,t=>this.visitTupleExpression(t)),this.handlers.set(ot.kind,t=>this.visitInsertQuery(t)),this.handlers.set(ct.kind,t=>this.visitInsertClause(t)),this.handlers.set(Nt.kind,t=>this.visitUpdateQuery(t)),this.handlers.set(It.kind,t=>this.visitUpdateClause(t)),this.handlers.set(at.kind,t=>this.visitSetClause(t)),this.handlers.set(ut.kind,t=>this.visitSetClauseItem(t)),this.handlers.set(ln.kind,t=>this.visitReturningClause(t)),this.handlers.set(Lt.kind,t=>this.visitCreateTableQuery(t))}static{this.SPACE_TOKEN=new m(10," ")}static{this.COMMA_TOKEN=new m(3,",")}static{this.ARGUMENT_SPLIT_COMMA_TOKEN=new m(11,",")}static{this.PAREN_OPEN_TOKEN=new m(4,"(")}static{this.PAREN_CLOSE_TOKEN=new m(4,")")}static{this.DOT_TOKEN=new m(8,".")}visitBinarySelectQuery(e){let t=new m(0,"");return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,e.operator.value,"BinarySelectQueryOperator")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}static commaSpaceTokens(){return[a.COMMA_TOKEN,a.SPACE_TOKEN]}static argumentCommaSpaceTokens(){return[a.ARGUMENT_SPLIT_COMMA_TOKEN,a.SPACE_TOKEN]}visitQualifiedName(e){let t=new m(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(a.DOT_TOKEN);return t.innerTokens.push(e.name.accept(this)),t}visitPartitionByClause(e){let t=new m(1,"partition by","PartitionByClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOrderByClause(e){let t=new m(1,"order by","OrderByClause");t.innerTokens.push(a.SPACE_TOKEN);for(let n=0;n<e.order.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.order[n]));return t}visitOrderByItem(e){let t=new m(0,"","OrderByItem");return t.innerTokens.push(this.visit(e.value)),e.sortDirection&&e.sortDirection!=="asc"&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"desc"))),e.nullsPosition&&(e.nullsPosition==="first"?(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"nulls first"))):e.nullsPosition==="last"&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"nulls last")))),t}parse(e){this.index=1;let t=this.visit(e),n=mt.collect(e).sort((i,s)=>(i.index??0)-(s.index??0)),r=this.parameterDecorator.style;if(r==="named"){let i={};for(let s of n){let o=s.name.value;if(i.hasOwnProperty(o)){if(i[o]!==s.value)throw new Error(`Duplicate parameter name '${o}' with different values detected during query composition.`);continue}i[o]=s.value}return{token:t,params:i}}else if(r==="indexed"){let i=n.map(s=>s.value);return{token:t,params:i}}else if(r==="anonymous"){let i=n.map(s=>s.value);return{token:t,params:i}}return{token:t,params:[]}}visit(e){let t=this.handlers.get(e.getKind());if(t){let n=t(e);return this.addCommentsToToken(n,e.comments),n}throw new Error(`[SqlPrintTokenParser] No handler for kind: ${e.getKind().toString()}`)}addCommentsToToken(e,t){if(!t||t.length===0)return;let n=this.createCommentBlocks(t);n.length>0&&this.insertCommentBlocksWithSpacing(e,n)}createCommentBlocks(e){let t=[];for(let n of e)n.trim()&&t.push(this.createSingleCommentBlock(n));return t}createSingleCommentBlock(e){let t=new m(0,"","CommentBlock"),n=new m(6,this.formatBlockComment(e));t.innerTokens.push(n);let r=new m(12,"");t.innerTokens.push(r);let i=new m(10," ");return t.innerTokens.push(i),t}insertCommentBlocksWithSpacing(e,t){if(e.innerTokens.unshift(...t),this.shouldAddSeparatorSpace(e.containerType)){let r=new m(10," ");e.innerTokens.splice(t.length,0,r),e.innerTokens.length>t.length+1&&e.innerTokens[t.length+1].type===10&&e.innerTokens.splice(t.length+1,1)}else e.innerTokens.length>t.length&&e.innerTokens[t.length].type===10&&e.innerTokens.splice(t.length,1)}shouldAddSeparatorSpace(e){return this.isClauseLevelContainer(e)}isClauseLevelContainer(e){switch(e){case"SelectClause":case"FromClause":case"WhereClause":case"GroupByClause":case"HavingClause":case"OrderByClause":case"LimitClause":case"OffsetClause":case"WithClause":case"SimpleSelectQuery":return!0;default:return!1}}formatBlockComment(e){return`/* ${e} */`}visitValueList(e){let t=new m(0,"","ValueList");for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...a.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t}visitColumnReference(e){let t=new m(0,"","ColumnReference");return t.innerTokens.push(e.qualifiedName.accept(this)),t}visitFunctionCall(e){let t=new m(0,"","FunctionCall");if(t.innerTokens.push(e.qualifiedName.accept(this)),t.innerTokens.push(a.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),e.internalOrderBy&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.internalOrderBy))),e.comments&&e.comments.length>0){let n=new m(4,")");this.addCommentsToToken(n,e.comments),t.innerTokens.push(n),e.comments=null}else t.innerTokens.push(a.PAREN_CLOSE_TOKEN);return e.withOrdinality&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"with ordinality"))),e.over&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"over")),e.over instanceof P?(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.over.accept(this))):(t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.over)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN))),t}visitUnaryExpression(e){let t=new m(0,"","UnaryExpression");return t.innerTokens.push(this.visit(e.operator)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.expression)),t}visitBinaryExpression(e){let t=new m(0,"","BinaryExpression");return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(5,e.operator.value)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}visitLiteralValue(e){let t;return e.value===null?t="null":e.isStringLiteral?t=`'${e.value.replace(/'/g,"''")}'`:typeof e.value=="string"?t=e.value:t=e.value.toString(),new m(2,t,"LiteralValue")}visitParameterExpression(e){e.index=this.index;let t=this.parameterDecorator.decorate(e.name.value,e.index),n=new m(7,t);return this.index++,n}visitSwitchCaseArgument(e){let t=new m(0,"","SwitchCaseArgument");for(let n of e.cases)t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(n.accept(this));return e.elseValue&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.createElseToken(e.elseValue))),t}createElseToken(e){let t=new m(0,"","ElseClause");t.innerTokens.push(new m(1,"else")),t.innerTokens.push(a.SPACE_TOKEN);let n=new m(0,"","CaseElseValue");return n.innerTokens.push(this.visit(e)),t.innerTokens.push(n),t}visitCaseKeyValuePair(e){let t=new m(0,"","CaseKeyValuePair");t.innerTokens.push(new m(1,"when")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.key)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"then")),t.innerTokens.push(a.SPACE_TOKEN);let n=new m(0,"","CaseThenValue");return n.innerTokens.push(this.visit(e.value)),t.innerTokens.push(n),t}visitRawString(e){return new m(2,e.value,"RawString")}visitIdentifierString(e){let t=e.name==="*"?e.name:this.identifierDecorator.decorate(e.name);return new m(2,t,"IdentifierString")}visitParenExpression(e){let t=new m(0,"","ParenExpression");return t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitCastExpression(e){let t=new m(0,"","CastExpression");return t.innerTokens.push(this.visit(e.input)),t.innerTokens.push(new m(5,"::")),t.innerTokens.push(this.visit(e.castType)),t}visitCaseExpression(e){let t=new m(0,"","CaseExpression");return t.innerTokens.push(new m(1,"case")),e.condition&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition))),t.innerTokens.push(this.visit(e.switchCase)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"end")),t}visitArrayExpression(e){let t=new m(0,"","ArrayExpression");return t.innerTokens.push(new m(1,"array")),t.innerTokens.push(new m(4,"[")),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(new m(4,"]")),t}visitArrayQueryExpression(e){let t=new m(0,"","ArrayExpression");return t.innerTokens.push(new m(1,"array")),t.innerTokens.push(new m(4,"(")),t.innerTokens.push(this.visit(e.query)),t.innerTokens.push(new m(4,")")),t}visitArraySliceExpression(e){let t=new m(0,"","ArrayExpression");return t.innerTokens.push(this.visit(e.array)),t.innerTokens.push(new m(4,"[")),e.startIndex&&t.innerTokens.push(this.visit(e.startIndex)),t.innerTokens.push(new m(5,":")),e.endIndex&&t.innerTokens.push(this.visit(e.endIndex)),t.innerTokens.push(new m(4,"]")),t}visitArrayIndexExpression(e){let t=new m(0,"","ArrayExpression");return t.innerTokens.push(this.visit(e.array)),t.innerTokens.push(new m(4,"[")),t.innerTokens.push(this.visit(e.index)),t.innerTokens.push(new m(4,"]")),t}visitBetweenExpression(e){let t=new m(0,"","BetweenExpression");return t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(a.SPACE_TOKEN),e.negated&&(t.innerTokens.push(new m(1,"not")),t.innerTokens.push(a.SPACE_TOKEN)),t.innerTokens.push(new m(1,"between")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.lower)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"and")),t.innerTokens.push(a.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 m(2,t+n,"StringSpecifierExpression")}visitTypeValue(e){let t=new m(0,"","TypeValue");return t.innerTokens.push(e.qualifiedName.accept(this)),e.argument&&(t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN)),t}visitTupleExpression(e){let t=new m(0,"","TupleExpression");t.innerTokens.push(a.PAREN_OPEN_TOKEN);for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...a.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitWindowFrameExpression(e){let t=new m(0,"","WindowFrameExpression"),n=!0;return e.partition&&(t.innerTokens.push(this.visit(e.partition)),n=!1),e.order&&(n?n=!1:t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.order))),e.frameSpec&&(n?n=!1:t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.frameSpec))),t}visitWindowFrameSpec(e){let t=new m(0,"","WindowFrameSpec");return t.innerTokens.push(new m(1,e.frameType)),e.endBound===null?(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this))):(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"between")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"and")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.endBound.accept(this))),t}visitWindowFrameBoundaryValue(e){let t=new m(0,"","WindowFrameBoundaryValue");return t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,e.isFollowing?"following":"preceding")),t}visitWindowFrameBoundStatic(e){return new m(1,e.bound)}visitSelectItem(e){let t=new m(0,"","SelectItem");if(t.innerTokens.push(this.visit(e.value)),!e.identifier)return t;if(e.value instanceof b){let n=e.value.column.name;if(e.identifier.name===n)return t}return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"as")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.identifier)),t}visitSelectClause(e){let t=new m(1,"select","SelectClause"),n="select";for(let r of e.hints)n+=" "+this.visit(r).text;if(e.distinct){let r=e.distinct.accept(this);if(r.innerTokens&&r.innerTokens.length>0){let i=r.text;for(let s of r.innerTokens)i+=this.flattenTokenText(s);n+=" "+i}else n+=" "+r.text}t.text=n,t.innerTokens.push(a.SPACE_TOKEN);for(let r=0;r<e.items.length;r++)r>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[r]));return t}flattenTokenText(e){let t=e.text;if(e.innerTokens)for(let n of e.innerTokens)t+=this.flattenTokenText(n);return t}visitHintClause(e){return new m(2,e.getFullHint())}visitDistinct(e){return new m(1,"distinct")}visitDistinctOn(e){let t=new m(0,"","DistinctOn");return t.innerTokens.push(new m(1,"distinct on")),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(a.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 m(2,t);return e.identifier&&(e.identifier.name,e.table.name),n}visitSourceExpression(e){let t=new m(0,"","SourceExpression");if(t.innerTokens.push(e.datasource.accept(this)),!e.aliasExpression)return t;if(e.datasource instanceof R){let n=e.datasource.table.name;return e.aliasExpression.table.name===n||(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"as")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this))),t}else return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"as")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this)),t}visitFromClause(e){let t=new m(1,"from","FromClause");if(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.joins)for(let n=0;n<e.joins.length;n++)t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.joins[n]));return t}visitJoinClause(e){let t=new m(0,"","JoinClause");return t.innerTokens.push(new m(1,e.joinType.value)),e.lateral&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"lateral"))),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.condition&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition))),t}visitJoinOnClause(e){let t=new m(0,"","JoinOnClause");return t.innerTokens.push(new m(1,"on")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitJoinUsingClause(e){let t=new m(0,"","JoinUsingClause");return t.innerTokens.push(new m(1,"using")),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.condition)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitFunctionSource(e){let t=new m(0,"","FunctionSource");return t.innerTokens.push(e.qualifiedName.accept(this)),t.innerTokens.push(a.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitSourceAliasExpression(e){let t=new m(0,"","SourceAliasExpression");if(t.innerTokens.push(this.visit(e.table)),e.columns){t.innerTokens.push(a.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...a.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));t.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return t}visitWhereClause(e){let t=new m(1,"where","WhereClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitGroupByClause(e){let t=new m(1,"group by","GroupByClause");t.innerTokens.push(a.SPACE_TOKEN);for(let n=0;n<e.grouping.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.grouping[n]));return t}visitHavingClause(e){let t=new m(1,"having","HavingClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitWindowClause(e){let t=new m(1,"window","WindowClause");t.innerTokens.push(a.SPACE_TOKEN);for(let n=0;n<e.windows.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.windows[n]));return t}visitWindowFrameClause(e){let t=new m(0,"","WindowFrameClause");return t.innerTokens.push(e.name.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"as")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitLimitClause(e){let t=new m(1,"limit","LimitClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOffsetClause(e){let t=new m(1,"offset","OffsetClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitFetchClause(e){let t=new m(1,"fetch","FetchClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.expression)),t}visitFetchExpression(e){let t=new m(0,"","FetchExpression");return t.innerTokens.push(new m(1,e.type)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.count.accept(this)),e.unit&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,e.unit))),t}visitForClause(e){let t=new m(1,"for","ForClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,e.lockMode)),t}visitWithClause(e){let t=new m(1,"with","WithClause");t.innerTokens.push(a.SPACE_TOKEN),e.recursive&&(t.innerTokens.push(new m(1,"recursive")),t.innerTokens.push(a.SPACE_TOKEN));for(let n=0;n<e.tables.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(e.tables[n].accept(this));return t.innerTokens.push(a.SPACE_TOKEN),t}visitCommonTable(e){let t=new m(0,"","CommonTable");t.innerTokens.push(e.aliasExpression.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"as")),t.innerTokens.push(a.SPACE_TOKEN),e.materialized!==null&&(e.materialized?t.innerTokens.push(new m(1,"materialized")):t.innerTokens.push(new m(1,"not materialized")),t.innerTokens.push(a.SPACE_TOKEN)),t.innerTokens.push(a.PAREN_OPEN_TOKEN);let n=new m(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitSimpleQuery(e){let t=new m(0,"","SimpleSelectQuery");return e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(e.selectClause.accept(this)),e.fromClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this)),e.whereClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.groupByClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.groupByClause.accept(this))),e.havingClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.havingClause.accept(this))),e.orderByClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.orderByClause.accept(this))),e.windowClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.windowClause.accept(this))),e.limitClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.limitClause.accept(this))),e.offsetClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.offsetClause.accept(this))),e.fetchClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.fetchClause.accept(this))),e.forClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.forClause.accept(this)))),t}visitSubQuerySource(e){let t=new m(0,"");t.innerTokens.push(a.PAREN_OPEN_TOKEN);let n=new m(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitValuesQuery(e){let t=new m(1,"values","ValuesQuery");t.innerTokens.push(a.SPACE_TOKEN);let n=new m(0,"","Values");for(let r=0;r<e.tuples.length;r++)r>0&&n.innerTokens.push(...a.commaSpaceTokens()),n.innerTokens.push(e.tuples[r].accept(this));return t.innerTokens.push(n),t}visitInlineQuery(e){let t=new m(0,"");t.innerTokens.push(a.PAREN_OPEN_TOKEN);let n=new m(0,"","InlineQuery");if(n.innerTokens.push(e.selectQuery.accept(this)),t.innerTokens.push(n),e.comments&&e.comments.length>0){let r=new m(4,")");this.addCommentsToToken(r,e.comments),t.innerTokens.push(r),e.comments=null}else t.innerTokens.push(a.PAREN_CLOSE_TOKEN);return t}visitInsertQuery(e){let t=new m(0,"","InsertQuery");return t.innerTokens.push(this.visit(e.insertClause)),e.selectQuery&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.selectQuery))),t}visitInsertClause(e){let t=new m(0,"");if(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"insert into")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),e.columns.length>0){t.innerTokens.push(a.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(e.columns[n].accept(this));t.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return t}visitUpdateQuery(e){let t=new m(0,"","UpdateQuery");return e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(e.updateClause.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.setClause.accept(this)),e.fromClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this))),e.whereClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.returningClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.returningClause.accept(this))),t}visitUpdateClause(e){let t=new m(1,"update","UpdateClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t}visitSetClause(e){let t=new m(1,"set","SelectClause");t.innerTokens.push(a.SPACE_TOKEN);for(let n=0;n<e.items.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[n]));return t}visitSetClauseItem(e){let t=new m(0,"","SetClauseItem");return t.innerTokens.push(e.column.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(5,"=")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.value.accept(this)),t}visitReturningClause(e){let t=new m(1,"returning","ReturningClause");t.innerTokens.push(a.SPACE_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));return t}visitCreateTableQuery(e){let t=new m(1,e.isTemporary?"create temporary table":"create table","CreateTableQuery");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.tableName.accept(this)),e.asSelectQuery&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new m(1,"as")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.asSelectQuery.accept(this))),t}};var qt=class{constructor(e=" ",t=0,n=`\r
15
- `){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 Cr(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.")}},Cr=class{constructor(e,t){this.level=e,this.text=t}};var Nn=class a{constructor(e){this.insideWithClause=!1;this.indentChar=e?.indentChar??"",this.indentSize=e?.indentSize??0,this.newline=e?.newline??" ",this.commaBreak=e?.commaBreak??"none",this.andBreak=e?.andBreak??"none",this.keywordCase=e?.keywordCase??"none",this.exportComment=e?.exportComment??!1,this.strictCommentPlacement=e?.strictCommentPlacement??!1,this.withClauseStyle=e?.withClauseStyle??"standard",this.linePrinter=new qt(this.indentChar,this.indentSize,this.newline),this.indentIncrementContainers=new Set(e?.indentIncrementContainerTypes??["SelectClause","FromClause","WhereClause","GroupByClause","HavingClause","WindowFrameExpression","PartitionByClause","OrderByClause","WindowClause","LimitClause","OffsetClause","SubQuerySource","BinarySelectQueryOperator","Values","WithClause","SwitchCaseArgument","CaseKeyValuePair","CaseThenValue","ElseClause","CaseElseValue","SimpleSelectQuery"])}print(e,t=0){return this.linePrinter=new qt(this.indentChar,this.indentSize,this.newline),this.insideWithClause=!1,this.linePrinter.lines.length>0&&t!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=t),this.appendToken(e,t,void 0),this.linePrinter.print()}appendToken(e,t,n){let r=this.insideWithClause;if(e.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"&&(this.insideWithClause=!0),this.shouldSkipToken(e))return;let i=this.linePrinter.getCurrentLine();if(e.type===1)this.handleKeywordToken(e,t);else if(e.type===3)this.handleCommaToken(e,t,n);else if(e.type===5&&e.text.toLowerCase()==="and")this.handleAndOperatorToken(e,t);else if(e.containerType==="JoinClause")this.handleJoinClauseToken(e,t);else if(e.type===6)this.exportComment&&this.linePrinter.appendText(e.text);else if(e.type===10)this.handleSpaceToken(e,n);else if(e.type===12)this.handleCommentNewlineToken(e,t);else if(e.containerType==="CommonTable"&&this.withClauseStyle==="cte-oneline"){this.handleCteOnelineToken(e,t);return}else this.linePrinter.appendText(e.text);if(e.keywordTokens&&e.keywordTokens.length>0)for(let o=0;o<e.keywordTokens.length;o++){let l=e.keywordTokens[o];this.appendToken(l,t,e.containerType)}let s=t;!this.isOnelineMode()&&i.text!==""&&this.indentIncrementContainers.has(e.containerType)&&(this.insideWithClause&&this.withClauseStyle==="full-oneline"||(s++,this.linePrinter.appendNewline(s)));for(let o=0;o<e.innerTokens.length;o++){let l=e.innerTokens[o];this.appendToken(l,s,e.containerType)}if(e.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"){this.insideWithClause=!1,this.linePrinter.appendNewline(t);return}s!==t&&(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t))}shouldSkipToken(e){return e.type===12?!1:(!e.innerTokens||e.innerTokens.length===0)&&e.text===""}applyKeywordCase(e){return this.keywordCase==="upper"?e.toUpperCase():this.keywordCase==="lower"?e.toLowerCase():e}handleKeywordToken(e,t){let n=this.applyKeywordCase(e.text);this.linePrinter.appendText(n)}handleCommaToken(e,t,n){let r=e.text;this.insideWithClause&&this.withClauseStyle==="full-oneline"?this.linePrinter.appendText(r):this.withClauseStyle==="cte-oneline"&&n==="WithClause"?(this.linePrinter.appendText(r),this.linePrinter.appendNewline(t)):this.commaBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)):this.commaBreak==="after"?(this.linePrinter.appendText(r),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t)):this.linePrinter.appendText(r)}handleAndOperatorToken(e,t){let n=this.applyKeywordCase(e.text);this.andBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(n)):this.andBreak==="after"?(this.linePrinter.appendText(n),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t)):this.linePrinter.appendText(n)}handleJoinClauseToken(e,t){let n=this.applyKeywordCase(e.text);this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(n)}handleSpaceToken(e,t){this.shouldSkipCommentBlockSpace(t)||this.linePrinter.appendText(e.text)}shouldSkipCommentBlockSpace(e){return e==="CommentBlock"&&this.insideWithClause&&this.withClauseStyle==="full-oneline"}handleCommentNewlineToken(e,t){this.shouldSkipCommentNewline()||this.isOnelineMode()||this.linePrinter.appendNewline(t)}shouldSkipCommentNewline(){return this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.withClauseStyle==="cte-oneline"}isOnelineMode(){return this.newline===" "}handleCteOnelineToken(e,t){let r=this.createCteOnelinePrinter().print(e,t),i=this.cleanDuplicateSpaces(r);this.linePrinter.appendText(i)}createCteOnelinePrinter(){return new a({indentChar:"",indentSize:0,newline:" ",commaBreak:this.commaBreak,andBreak:this.andBreak,keywordCase:this.keywordCase,exportComment:this.exportComment,strictCommentPlacement:this.strictCommentPlacement,withClauseStyle:"standard"})}cleanDuplicateSpaces(e){return e.replace(/\s{2,}/g," ")}};var Hu=["mysql","postgres","sqlserver","sqlite"],Fe=class{constructor(e={}){let t=e.preset?Lr[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 An(n),this.printer=new Nn(e)}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var dt=class{constructor(){this.sqlFormatter=new Fe({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(e,t=null){return t&&(this.sqlFormatter=new Fe(t)),this.sqlFormatter.format(e).formattedSql}formatWithParameters(e,t=null){t&&(this.sqlFormatter=new Fe(t));let n=this.sqlFormatter.format(e);return{sql:n.formattedSql,params:n.params}}visit(e){return this.format(e)}};var Ln=class{constructor(){this.sourceCollector=new He(!0),this.cteCollector=new X,this.formatter=new dt}build(e){if(e.length===0)return new ae(!1,e);let t=this.resolveDuplicateNames(e),{tableMap:n,recursiveCTEs:r,dependencies:i}=this.buildDependencyGraph(t),s=this.sortCommonTables(t,n,r,i);return new ae(r.size>0,s)}resolveDuplicateNames(e){let t=new Map;for(let r of e){let i=r.aliasExpression.table.name;t.has(i)||t.set(i,[]),t.get(i).push(r)}let n=[];for(let[r,i]of Array.from(t.entries())){if(i.length===1){n.push(i[0]);continue}let s=i.map(l=>this.formatter.format(l.query));if(new Set(s).size===1)n.push(i[0]);else throw new Error(`CTE name conflict detected: '${r}' has multiple different definitions`)}return n}buildDependencyGraph(e){let t=new Map;for(let s of e)t.set(s.aliasExpression.table.name,s);let n=new Set,r=new Map,i=new Map;for(let s of e){let o=s.aliasExpression.table.name,l=this.sourceCollector.collect(s.query);for(let c of l)if(c.table.name===o){n.add(o);break}r.has(o)||r.set(o,new Set);let u=this.cteCollector.collect(s.query);for(let c of u){let p=c.aliasExpression.table.name;t.has(p)&&(r.get(o).add(p),i.has(p)||i.set(p,new Set),i.get(p).add(o))}}return{tableMap:t,recursiveCTEs:n,dependencies:r}}sortCommonTables(e,t,n,r){let i=[],s=[],o=new Set,l=new Set,u=c=>{if(o.has(c))return;if(l.has(c))throw new Error(`Circular reference detected in CTE: ${c}`);l.add(c);let p=r.get(c)||new Set;for(let d of Array.from(p))u(d);l.delete(c),o.add(c),n.has(c)?i.push(t.get(c)):s.push(t.get(c))};for(let c of e){let p=c.aliasExpression.table.name;o.has(p)||u(p)}return[...i,...s]}};var Qn=class{constructor(){this.nameConflictResolver=new Ln,this.cteCollector=new X}inject(e,t){if(t.length===0)return e;t.push(...this.cteCollector.collect(e));let n=this.nameConflictResolver.build(t);if(e instanceof C)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 C)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 it=class{constructor(){}static normalize(e){let n=new X().collect(e);return n.length===0?e:(new At().execute(e),new Qn().inject(e,n))}};var vt=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))(vt||{}),xe=class a{constructor(e,t=!1,n="columnNameOnly",r){this.selectValues=[];this.visitedNodes=new Set;this.uniqueKeys=new Set;this.isRootVisit=!0;this.tableColumnResolver=null;this.commonTables=[];this.initializeProperties(e,t,n,r),this.initializeHandlers()}initializeProperties(e,t,n,r){this.tableColumnResolver=e??null,this.includeWildCard=t,this.commonTableCollector=new X,this.commonTables=[],this.duplicateDetection=n,this.options=r||{}}initializeHandlers(){this.handlers=new Map,this.handlers.set(C.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(Q.kind,e=>this.visitBinarySelectQuery(e)),this.initializeClauseHandlers(),this.initializeValueComponentHandlers()}initializeClauseHandlers(){this.handlers.set(_.kind,e=>this.visitSelectClause(e)),this.handlers.set(J.kind,e=>this.visitFromClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(me.kind,e=>this.visitGroupByClause(e)),this.handlers.set(de.kind,e=>this.visitHavingClause(e)),this.handlers.set(pe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Pe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Oe.kind,e=>this.offsetClause(e)),this.handlers.set(Ue.kind,e=>this.visitFetchClause(e)),this.handlers.set(he.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Se.kind,e=>this.visitJoinUsingClause(e))}initializeValueComponentHandlers(){this.handlers.set(b.kind,e=>this.visitColumnReference(e)),this.handlers.set(S.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(K.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ge.kind,e=>this.visitInlineQuery(e)),this.handlers.set(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(ie.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ce.kind,e=>this.visitCastExpression(e)),this.handlers.set(we.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(ye.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ve.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(et.kind,e=>this.visitArraySliceExpression(e)),this.handlers.set(tt.kind,e=>this.visitArrayIndexExpression(e)),this.handlers.set(U.kind,e=>this.visitValueList(e)),this.handlers.set(Be.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(De.kind,e=>this.visitPartitionByClause(e))}getValues(){return this.selectValues}collect(e){if(!e)throw new Error("Input argument cannot be null or undefined");this.visit(e);let t=this.getValues();return this.reset(),t}reset(){this.selectValues=[],this.visitedNodes.clear(),this.uniqueKeys.clear(),this.commonTables=[]}addSelectValueAsUnique(e,t){let n=this.generateUniqueKey(e,t);this.uniqueKeys.has(n)||(this.uniqueKeys.add(n),this.selectValues.push({name:e,value:t}))}generateUniqueKey(e,t){if(this.duplicateDetection==="columnNameOnly")return this.normalizeColumnName(e);{let n="";t&&typeof t.getNamespace=="function"&&(n=t.getNamespace()||"");let r=n?n+"."+e:e;return this.normalizeColumnName(r)}}normalizeColumnName(e){if(typeof e!="string")throw new Error("Column name must be a string");return this.options.ignoreCaseAndUnderscore?e.toLowerCase().replace(/_/g,""):e}visit(e){if(!this.isRootVisit){this.visitNode(e);return}if(!(e instanceof C||e instanceof Q))throw new Error("Root visit requires a SimpleSelectQuery or BinarySelectQuery.");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)){this.visitedNodes.add(e);try{let t=this.handlers.get(e.getKind());t&&t(e)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`Error processing SQL component of type ${e.getKind().toString()}: ${n}`)}}}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)}visitBinarySelectQuery(e){e.left instanceof C?this.visitSimpleSelectQuery(e.left):e.left instanceof Q&&this.visitBinarySelectQuery(e.left),e.right instanceof C?this.visitSimpleSelectQuery(e.right):e.right instanceof Q&&this.visitBinarySelectQuery(e.right)}visitSelectClause(e){for(let t of e.items)if(t.identifier)this.addSelectValueAsUnique(t.identifier.name,t.value);else if(t.value instanceof b){let n=t.value.column.name;n!=="*"?this.addSelectValueAsUnique(n,t.value):this.includeWildCard&&this.addSelectValueAsUnique(n,t.value)}else t.value.accept(this)}visitFromClause(e){let n=new Ke(this.tableColumnResolver,this.commonTables).collect(e);for(let r of n)this.addSelectValueAsUnique(r.name,r.value);if(this.options.upstream&&this.collectUpstreamColumns(e),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),e.withinGroup&&e.withinGroup.accept(this),e.internalOrderBy&&e.internalOrderBy.accept(this)}visitInlineQuery(e){e.selectQuery&&this.visitNode(e.selectQuery)}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)}visitArraySliceExpression(e){e.array&&e.array.accept(this),e.startIndex&&e.startIndex.accept(this),e.endIndex&&e.endIndex.accept(this)}visitArrayIndexExpression(e){e.array&&e.array.accept(this),e.index&&e.index.accept(this)}visitValueList(e){if(e.values&&Array.isArray(e.values))for(let t of e.values)t&&t.accept(this)}visitPartitionByClause(e){e.value.accept(this)}collectUpstreamColumns(e){if(this.collectAllAvailableCTEColumns(),this.collectUpstreamColumnsFromSource(e.source),e.joins)for(let t of e.joins)this.collectUpstreamColumnsFromSource(t.source)}collectUpstreamColumnsFromSource(e){if(e.datasource instanceof R){let t=this.findCTEByName(e.datasource.table.name);t?this.collectUpstreamColumnsFromCTE(t):this.collectUpstreamColumnsFromTable(e.datasource)}else e.datasource instanceof W?this.collectUpstreamColumnsFromSubquery(e.datasource):e.datasource instanceof $e&&this.collectUpstreamColumnsFromSource(new B(e.datasource.source,null))}collectUpstreamColumnsFromTable(e){if(this.tableColumnResolver){let t=e.table.name,n=this.tableColumnResolver(t);for(let r of n){let i=new b(e.table.name,r);this.addSelectValueAsUnique(r,i)}}}collectUpstreamColumnsFromSubquery(e){if(e.query instanceof C){let n=new a(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!0}).collect(e.query);for(let r of n)this.addSelectValueAsUnique(r.name,r.value)}}collectUpstreamColumnsFromCTE(e){if(e.query instanceof C){let n=new a(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!1}).collect(e.query);for(let r of n)r.name!=="*"&&this.addSelectValueAsUnique(r.name,r.value)}}collectAllAvailableCTEColumns(){for(let e of this.commonTables)this.collectUpstreamColumnsFromCTE(e)}findCTEByName(e){return this.commonTables.find(t=>t.getSourceAliasName()===e)||null}};var wt=class a{static parse(e){let n=new O(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=Me.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=Me.parseFromLexeme(e,n);return r.lastTokenType&2048?a.parseFunctionSource(e,r):a.parseTableSource(r)}static parseTableSource(e){let{namespaces:t,name:n,newIndex:r}=e;return{value:new R(t,n.name),newIndex:r}}static parseFunctionSource(e,t){let n=t.newIndex,{namespaces:r,name:i}=t,s=k.parseArgument(4,8,e,n);n=s.newIndex;let o=i.name;return{value:new qe({namespaces:r,name:o},s.value),newIndex:n}}static parseParenSource(e,t){let n=t;if(n++,n>=e.length)throw new Error(`Syntax error: Unexpected end of input at position ${n}. Expected a subquery or nested expression after opening parenthesis.`);let r=e[n].value;if(r==="select"||r==="values"||r==="with"){let i=this.parseSubQuerySource(e,n);if(n=i.newIndex,n<e.length&&e[n].type==8)n++;else throw new Error(`Syntax error at position ${n}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:i.value,newIndex:n}}else if(e[n].type==4){let i=this.parseParenSource(e,n);if(n=i.newIndex,n<e.length&&e[n].type==8)n++;else throw new Error(`Syntax error at position ${n}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:i.value,newIndex:n}}throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword, 'VALUES' keyword, or opening parenthesis '(' but found "${e[n].value}".`)}static parseSubQuerySource(e,t){let n=t,{value:r,newIndex:i}=A.parseFromLexeme(e,n);return n=i,{value:new W(r),newIndex:n}}};var Gt=class extends Error{constructor(t){super(`CTE '${t}' already exists in the query`);this.cteName=t;this.name="DuplicateCTEError"}},Qt=class extends Error{constructor(t,n){super(`Invalid CTE name '${t}': ${n}`);this.cteName=t;this.name="InvalidCTENameError"}},Ht=class extends Error{constructor(t){super(`CTE '${t}' not found in the query`);this.cteName=t;this.name="CTENotFoundError"}};var Rt=class{constructor(e,t){this.options=t||{},this.tableColumnResolver=e,this.columnCollector=new xe(this.tableColumnResolver,!1,"fullName",{upstream:!0})}find(e,t){let n=typeof t=="string"?[t]:t,i=new X().collect(e),s=new Map;for(let o of i)s.set(o.getSourceAliasName(),o);return this.findUpstream(e,n,s)}handleTableSource(e,t,n){let r=n.get(e.table.name);if(r){let i=new Map(n);i.delete(e.table.name);let s=this.findUpstream(r.query,t,i);return s.length===0?null:s}return null}handleSubQuerySource(e,t,n){let r=this.findUpstream(e.query,t,n);return r.length===0?null:r}processFromClauseBranches(e,t,n){let r=e.getSources();if(r.length===0)return null;let i=[],s=!0,o=0;for(let l of r){let u=l.datasource,c=null;if(u instanceof R)c=this.handleTableSource(u,t,n),o++;else if(u instanceof W)c=this.handleSubQuerySource(u,t,n),o++;else{if(u instanceof Ce)continue;s=!1;break}if(c===null){s=!1;break}i.push(c)}return s&&i.length===o?i.flat():null}findUpstream(e,t,n){if(e instanceof C){let r=e.fromClause;if(r){let c=this.processFromClauseBranches(r,t,n);if(c&&c.length>0)return c}let i=this.columnCollector.collect(e).map(c=>c.name),s=this.collectCTEColumns(e,n),o=[...i,...s],l=c=>this.options.ignoreCaseAndUnderscore?c.toLowerCase().replace(/_/g,""):c;return t.every(c=>o.some(p=>l(p)===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 C)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 St=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 re(r,i),newIndex:n}}return{value:new re(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 Ye=class{static parse(e){let n=new O(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=wt.parseTableSourceFromLexemes(e,t);return{value:new B(n.value,null),newIndex:n.newIndex}}static parseFromLexeme(e,t){let n=t,r=wt.parseFromLexeme(e,n);if(n=r.newIndex,n<e.length){if(e[n].value==="as"){n++;let s=St.parseFromLexeme(e,n);return n=s.newIndex,{value:new B(r.value,s.value),newIndex:n}}if(n<e.length&&this.isTokenTypeAliasCandidate(e[n].type)){let s=St.parseFromLexeme(e,n);return n=s.newIndex,{value:new B(r.value,s.value),newIndex:n}}}return{value:new B(r.value,null),newIndex:n}}static isTokenTypeAliasCandidate(e){return(e&64)!==0||(e&2048)!==0}};var We=class a{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 Ce?a.buildSimpleQuery(i):i,r=new Q(n(e[0]),t,n(e[1]));it.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 C)return e;if(e instanceof Q)return a.buildSimpleBinaryQuery(e);if(e instanceof Ce)return a.buildSimpleValuesQuery(e);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(e){let t=a.extractAndRemoveOrderByFromBinaryQuery(e),n=new W(e),r=new B(n,new re("bq",null)),i=new J(r,null),s=a.createSelectAllClause(),o=new C({selectClause:s,fromClause:i,orderByClause:t});return it.normalize(o)}static extractAndRemoveOrderByFromBinaryQuery(e){return a.findAndRemoveRightmostOrderBy(e)}static findAndRemoveRightmostOrderBy(e){if(e instanceof Q){let t=a.findAndRemoveRightmostOrderBy(e.right);return t||a.findAndRemoveRightmostOrderBy(e.left)}else if(e instanceof C){let t=e.orderByClause;if(t)return e.orderByClause=null,t}return null}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 W(e),r=new B(n,new re("vq",e.columnAliases)),i=new J(r,null),s=e.columnAliases.map(l=>new z(new b("vq",l),l)),o=new _(s,null);return new C({selectClause:o,fromClause:i})}static createSelectAllClause(){let e=new b(null,"*"),t=new z(e,"*");return new _([t],null)}static buildCreateTableQuery(e,t,n=!1){return new Lt({tableName:t,isTemporary:n,asSelectQuery:e})}static buildInsertQuery(e,t){let n,r=e.selectClause.items.length;if(n=new Ke().collect(e).map(l=>l.name),!n.length||r!==n.length)throw new Error(`Columns cannot be inferred from the selectQuery. Make sure you are not using wildcards or unnamed columns.
14
+ ${o}`;return new a(l,n,o)}};var ze=class{static{this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY=new Set(["string_agg","array_agg","json_agg","jsonb_agg","json_object_agg","jsonb_object_agg","xmlagg"])}static parseArrayExpression(e,t){let n=t;if(n+1<e.length&&e[n+1].type&512){n++;let r=I.parseArgument(512,1024,e,n);return n=r.newIndex,{value:new ye(r.value),newIndex:n}}else if(n+1<e.length&&e[n+1].type&4){n++,n++;let r=A.parseFromLexeme(e,n);return n=r.newIndex,n++,{value:new ve(r.value),newIndex:n}}throw new Error(`Invalid ARRAY syntax at index ${n}, expected ARRAY[... or ARRAY(...)`)}static parseFromLexeme(e,t){let n=t,r=e[n];return r.value==="array"?this.parseArrayExpression(e,n):r.value==="substring"||r.value==="overlay"?this.parseKeywordFunction(e,n,[{key:"from",required:!1},{key:"for",required:!1}]):r.value==="cast"?this.parseKeywordFunction(e,n,[{key:"as",required:!0}]):r.value==="trim"?this.parseKeywordFunction(e,n,[{key:"from",required:!1}]):this.parseFunctionCall(e,n)}static tryParseBinaryExpression(e,t,n,r=!0,i=!0){let s=t;if(s<e.length&&e[s].type&2){let o=e[s].value.toLowerCase();if(!r&&o==="and"||!i&&o==="or")return null;if(s++,o==="between")return this.parseBetweenExpression(e,s,n,!1);if(o==="not between")return this.parseBetweenExpression(e,s,n,!0);if(o==="::"){let c=this.parseTypeValue(e,s);return s=c.newIndex,{value:new ce(n,c.value),newIndex:s}}let l=I.parseFromLexeme(e,s);return s=l.newIndex,{value:new S(n,o,l.value),newIndex:s}}return null}static parseBetweenExpression(e,t,n,r){let i=t,s=I.parseFromLexeme(e,i,!1);if(i=s.newIndex,i<e.length&&e[i].type&2&&e[i].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${i}`);i++;let o=this.parseBetweenUpperBound(e,i);return i=o.newIndex,{value:new we(n,s.value,o.value,r),newIndex:i}}static parseBetweenUpperBound(e,t){return I.parseFromLexeme(e,t,!1,!1)}static parseFunctionCall(e,t){let n=t,r=Me.parseFromLexeme(e,n),i=r.namespaces,s=r.name;if(n=r.newIndex,n<e.length&&e[n].type&4){let o=s.name.toLowerCase(),l,u=null,c=null;if(this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY.has(o)){let f=this.parseAggregateArguments(e,n);l={value:f.arguments,newIndex:f.newIndex},c=f.orderByClause,u=f.closingComments}else{let f=this.parseArgumentWithComments(e,n);l={value:f.value,newIndex:f.newIndex},u=f.closingComments}n=l.newIndex;let p=null;if(n<e.length&&e[n].value==="within group"){let f=this.parseWithinGroupClause(e,n);p=f.value,n=f.newIndex}let m=!1;if(n<e.length&&e[n].value==="with ordinality"&&(m=!0,n++),n<e.length&&e[n].value==="over"){let f=zt.parseFromLexeme(e,n);n=f.newIndex;let g=new K(i,s.name,l.value,f.value,p,m,c);return u&&u.length>0&&(g.comments=u),{value:g,newIndex:n}}else{let f=new K(i,s.name,l.value,null,p,m,c);return u&&u.length>0&&(f.comments=u),{value:f,newIndex:n}}}else throw be.fromUnparsedLexemes(e,n,`Expected opening parenthesis after function name '${s.name}'.`)}static parseKeywordFunction(e,t,n){let r=t,i=Me.parseFromLexeme(e,r),s=i.namespaces,o=i.name;if(r=i.newIndex,r<e.length&&e[r].type&4){r++;let l=I.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:p}of n)if(r<e.length&&e[r].type&128&&e[r].value===c)if(r++,r<e.length&&e[r].type&8192){let m=this.parseTypeValue(e,r);u=new S(u,c,m.value),r=m.newIndex}else{let m=I.parseFromLexeme(e,r);u=new S(u,c,m.value),r=m.newIndex}else if(p)throw be.fromUnparsedLexemes(e,r,`Keyword '${c}' is required for ${o.name} function.`);if(r<e.length&&e[r].type&8){r++;let c=null;if(r<e.length&&e[r].value==="within group"){let m=this.parseWithinGroupClause(e,r);c=m.value,r=m.newIndex}let p=!1;if(r<e.length&&e[r].value==="with ordinality"&&(p=!0,r++),r<e.length&&e[r].value==="over"){r++;let m=zt.parseFromLexeme(e,r);return r=m.newIndex,{value:new K(s,o.name,u,m.value,c,p,null),newIndex:r}}else return{value:new K(s,o.name,u,null,c,p,null),newIndex:r}}else throw be.fromUnparsedLexemes(e,r,`Missing closing parenthesis for function '${o.name}'.`)}else throw be.fromUnparsedLexemes(e,r,`Missing opening parenthesis for function '${o.name}'.`)}static parseTypeValue(e,t){let n=t,{namespaces:r,name:i,newIndex:s}=Me.parseFromLexeme(e,n);if(n=s,n<e.length&&e[n].type&4){let o=I.parseArgument(4,8,e,n);return n=o.newIndex,{value:new Ve(r,new $(i.name),o.value),newIndex:n}}else return{value:new Ve(r,new $(i.name)),newIndex:n}}static parseWithinGroupClause(e,t){let n=t;if(n>=e.length||e[n].value!=="within group")throw new Error(`Expected 'WITHIN GROUP' at index ${n}`);if(n++,n>=e.length||!(e[n].type&4))throw new Error(`Expected '(' after 'WITHIN GROUP' at index ${n}`);n++;let r=rt.parseFromLexeme(e,n);if(n=r.newIndex,n>=e.length||!(e[n].type&8))throw new Error(`Expected ')' after WITHIN GROUP ORDER BY clause at index ${n}`);return n++,{value:r.value,newIndex:n}}static parseAggregateArguments(e,t){let n=t,r=[],i=null;if(n>=e.length||!(e[n].type&4))throw be.fromUnparsedLexemes(e,n,"Expected opening parenthesis.");if(n++,n<e.length&&e[n].type&8){let u=e[n].comments;return n++,{arguments:new U([]),orderByClause:null,closingComments:u,newIndex:n}}if(n<e.length&&e[n].value==="*"){let u=new b(null,"*");if(n++,n<e.length&&e[n].type&8){let c=e[n].comments;return n++,{arguments:u,orderByClause:null,closingComments:c,newIndex:n}}else throw be.fromUnparsedLexemes(e,n,"Expected closing parenthesis after wildcard '*'.")}let s=I.parseFromLexeme(e,n);for(n=s.newIndex,r.push(s.value);n<e.length&&(e[n].type&16||e[n].value==="order by");){if(e[n].value==="order by"){let u=rt.parseFromLexeme(e,n);n=u.newIndex,i=u.value;break}if(e[n].type&16){if(n++,n<e.length&&e[n].value==="order by"){let c=rt.parseFromLexeme(e,n);n=c.newIndex,i=c.value;break}let u=I.parseFromLexeme(e,n);n=u.newIndex,r.push(u.value)}}if(n>=e.length||!(e[n].type&8))throw be.fromUnparsedLexemes(e,n,"Expected closing parenthesis.");let o=e[n].comments;return n++,{arguments:r.length===1?r[0]:new U(r),orderByClause:i,closingComments:o,newIndex:n}}static parseArgumentWithComments(e,t){let n=t;if(n>=e.length||!(e[n].type&4))throw be.fromUnparsedLexemes(e,n,"Expected opening parenthesis.");n++;let r=[];if(n<e.length&&e[n].type&8){let l=e[n].comments;return n++,{value:new U([]),closingComments:l,newIndex:n}}if(n<e.length&&e[n].value==="*"){let l=new b(null,"*");if(n++,n>=e.length||!(e[n].type&8))throw be.fromUnparsedLexemes(e,n,"Expected closing parenthesis after wildcard '*'.");let u=e[n].comments;return n++,{value:l,closingComments:u,newIndex:n}}let i=I.parseFromLexeme(e,n);for(n=i.newIndex,r.push(i.value);n<e.length&&e[n].type&16;){n++;let l=I.parseFromLexeme(e,n);n=l.newIndex,r.push(l.value)}if(n>=e.length||!(e[n].type&8))throw be.fromUnparsedLexemes(e,n,"Expected closing parenthesis.");let s=e[n].comments;return n++,{value:r.length===1?r[0]:new U(r),closingComments:s,newIndex:n}}};var yt=class{static{this.precedenceMap={or:1,and:2,"=":10,"!=":10,"<>":10,"<":10,"<=":10,">":10,">=":10,like:10,ilike:10,"not like":10,"not ilike":10,"similar to":10,"not similar to":10,in:10,"not in":10,is:10,"is not":10,"->":10,"->>":10,"#>":10,"#>>":10,"@>":10,"<@":10,"?":10,"?|":10,"?&":10,"~":10,"~*":10,"!~":10,"!~*":10,rlike:10,regexp:10,mod:30,xor:2,between:15,"not between":15,"+":20,"-":20,"*":30,"/":30,"%":30,"^":40,"::":50,"unary+":100,"unary-":100,not:100}}static getPrecedence(e){let t=this.precedenceMap[e.toLowerCase()];return t!==void 0?t:0}static hasHigherOrEqualPrecedence(e,t){return this.getPrecedence(e)>=this.getPrecedence(t)}static isLogicalOperator(e){let t=e.toLowerCase();return t==="and"||t==="or"}static isBetweenOperator(e){let t=e.toLowerCase();return t==="between"||t==="not between"}static isComparisonOperator(e){let t=e.toLowerCase();return["=","!=","<>","<",">","<=",">=","like","ilike","similar to","in","not in","->","->>","#>","#>>","@>","<@","?","?|","?&","~","~*","!~","!~*","rlike","regexp"].includes(t)}};var I=class{static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw be.fromUnparsedLexemes(n,r.newIndex,"[ValueParser]");return r.value}static parseFromLexeme(e,t,n=!0,r=!0){return this.parseExpressionWithPrecedence(e,t,0,n,r)}static parseExpressionWithPrecedence(e,t,n,r=!0,i=!0){let s=t,o=e[s].comments,l=this.parseItem(e,s);l.value.comments===null&&o&&o.length>0&&(l.value.comments=o),s=l.newIndex;let u=l.value,c=this.parseArrayAccess(e,s,u);for(u=c.value,s=c.newIndex;s<e.length&&e[s].type&2;){let m=e[s].value;if(!r&&m.toLowerCase()==="and"||!i&&m.toLowerCase()==="or")break;let f=yt.getPrecedence(m);if(f<n)break;if(s++,yt.isBetweenOperator(m)){let W=ze.parseBetweenExpression(e,s,u,m.toLowerCase().includes("not"));u=W.value,s=W.newIndex;continue}if(m==="::"){let W=ze.parseTypeValue(e,s);u=new ce(u,W.value),s=W.newIndex;continue}let g=f+1,h=this.parseExpressionWithPrecedence(e,s,g,r,i);s=h.newIndex,u=new S(u,m,h.value)}return{value:u,newIndex:s}}static parseItem(e,t){let n=t;if(n>=e.length)throw new Error(`Unexpected end of lexemes at index ${t}`);let r=e[n];if(r.type&64&&r.type&2&&r.type&8192){if(n+1<e.length&&e[n+1].type&4)if(this.isTypeConstructor(e,n+1,r.value)){let o=ze.parseTypeValue(e,n);return{value:o.value,newIndex:o.newIndex}}else return ze.parseFromLexeme(e,n);let i=wn.parseFromLexeme(e,n);if(i.newIndex>=e.length)return i;if(e[i.newIndex].type&1){let o=_t.parseFromLexeme(e,i.newIndex);return{value:new te(e[n].value,o.value),newIndex:o.newIndex}}return i}else if(r.type&64){let{namespaces:i,name:s,newIndex:o}=Me.parseFromLexeme(e,n);if(e[o-1].type&2048)return ze.parseFromLexeme(e,n);if(e[o-1].type&8192)if(o<e.length&&e[o].type&4)if(this.isTypeConstructor(e,o,s.name)){let u=ze.parseTypeValue(e,n);return{value:u.value,newIndex:u.newIndex}}else return ze.parseFromLexeme(e,n);else return{value:new Ve(i,s),newIndex:o};return{value:new b(i,s),newIndex:o}}else{if(r.type&1)return _t.parseFromLexeme(e,n);if(r.type&4)return Sn.parseFromLexeme(e,n);if(r.type&2048)return ze.parseFromLexeme(e,n);if(r.type&2)return bn.parseFromLexeme(e,n);if(r.type&256)return En.parseFromLexeme(e,n);if(r.type&4096)return xn.parseFromLexeme(e,n);if(r.type&128)return Tn.parseFromLexeme(e,n);if(r.type&512){let{namespaces:i,name:s,newIndex:o}=Me.parseFromLexeme(e,n);return{value:new b(i,s),newIndex:o}}else if(r.type&8192){let{namespaces:i,name:s,newIndex:o}=Me.parseFromLexeme(e,n);if(o<e.length&&e[o].type&4)if(this.isTypeConstructor(e,o,s.name)){let l=ze.parseTypeValue(e,n);return{value:l.value,newIndex:l.newIndex}}else return ze.parseFromLexeme(e,n);else return{value:new Ve(i,s),newIndex:o}}}throw be.fromUnparsedLexemes(e,n,"[ValueParser] Invalid lexeme.")}static parseArgument(e,t,n,r){let i=r,s=[];if(i<n.length&&n[i].type===e){if(i++,i<n.length&&n[i].type===t)return i++,{value:new U([]),newIndex:i};if(i<n.length&&n[i].value==="*"){let l=new b(null,"*");if(i++,i<n.length&&n[i].type===t)return i++,{value:l,newIndex:i};throw be.fromUnparsedLexemes(n,i,"Expected closing parenthesis after wildcard '*'.")}let o=this.parseFromLexeme(n,i);for(i=o.newIndex,s.push(o.value);i<n.length&&n[i].type&16;){i++;let l=this.parseFromLexeme(n,i);i=l.newIndex,s.push(l.value)}if(i<n.length&&n[i].type===t)return i++,s.length===1?{value:s[0],newIndex:i}:{value:new U(s),newIndex:i};throw be.fromUnparsedLexemes(n,i,"Missing closing parenthesis.")}throw be.fromUnparsedLexemes(n,r,"Expected opening parenthesis.")}static parseArrayAccess(e,t,n){let r=t,i=n;for(;r<e.length&&e[r].type&512&&!this.isSqlServerBracketIdentifier(e,r);){if(r++,r>=e.length)throw new Error(`Expected array index or slice after '[' at index ${r-1}`);if(e[r].type&1024)throw new Error(`Empty array access brackets not supported at index ${r}`);let s=null,o=!1;if(e[r].type&2&&e[r].value===":")o=!0,r++;else{let l=yt.getPrecedence(":"),u=this.parseExpressionWithPrecedence(e,r,l+1);s=u.value,r=u.newIndex,r<e.length&&e[r].type&2&&e[r].value===":"&&(o=!0,r++)}if(o){let l=null;if(r<e.length&&!(e[r].type&1024)){let u=yt.getPrecedence(":"),c=this.parseExpressionWithPrecedence(e,r,u+1);l=c.value,r=c.newIndex}if(r>=e.length||!(e[r].type&1024))throw new Error(`Expected ']' after array slice at index ${r}`);r++,i=new et(i,s,l)}else{if(!s){let l=this.parseFromLexeme(e,r);s=l.value,r=l.newIndex}if(r>=e.length||!(e[r].type&1024))throw new Error(`Expected ']' after array index at index ${r}`);r++,i=new tt(i,s)}}return{value:i,newIndex:r}}static isSqlServerBracketIdentifier(e,t){let n=t+1;if(n>=e.length)return!1;for(;n<e.length&&!(e[n].type&1024);){let s=e[n];if(s.type&64||s.type&2&&s.value==="."){n++;continue}return!1}if(n>=e.length)return!1;let r=n;if(r+1<e.length){let s=e[r+1];if(s.type&2&&s.value===".")return!0}n=t+1;let i=!0;for(;n<r;){let s=e[n];if(!(s.type&64||s.type&2&&s.value===".")){i=!1;break}n++}return i}static isTypeConstructor(e,t,n){let r=["NUMERIC","DECIMAL","VARCHAR","CHAR","CHARACTER","TIMESTAMP","TIME","INTERVAL"],i=n.toUpperCase();if(r.includes(i))return!0;if(i==="DATE"){let s=t+1;if(s<e.length){let o=e[s];return!(o.type&1&&typeof o.value=="string"&&isNaN(Number(o.value)))}}return!1}};var X=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(C.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(Q.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(Ce.kind,e=>this.visitValuesQuery(e)),this.handlers.set(ae.kind,e=>this.visitWithClause(e)),this.handlers.set(ne.kind,e=>this.visitCommonTable(e)),this.handlers.set(z.kind,e=>this.visitSelectItem(e)),this.handlers.set(P.kind,e=>this.visitIdentifierString(e)),this.handlers.set($.kind,e=>this.visitRawString(e)),this.handlers.set(b.kind,e=>this.visitColumnReference(e)),this.handlers.set(N.kind,e=>this.visitParameterExpression(e)),this.handlers.set(Z.kind,e=>this.visitLiteralValue(e)),this.handlers.set(B.kind,e=>this.visitSourceExpression(e)),this.handlers.set(O.kind,e=>this.visitTableSource(e)),this.handlers.set(qe.kind,e=>this.visitFunctionSource(e)),this.handlers.set($e.kind,e=>this.visitParenSource(e)),this.handlers.set(j.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(ge.kind,e=>this.visitInlineQuery(e)),this.handlers.set(J.kind,e=>this.visitFromClause(e)),this.handlers.set(fe.kind,e=>this.visitJoinClause(e)),this.handlers.set(he.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Se.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(S.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ie.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ke.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(Te.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(we.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(K.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ye.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ve.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(Ie.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ce.kind,e=>this.visitCastExpression(e)),this.handlers.set(Be.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Ge.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Ve.kind,e=>this.visitTypeValue(e)),this.handlers.set(U.kind,e=>this.visitValueList(e)),this.handlers.set(je.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(_.kind,e=>this.visitSelectClause(e)),this.handlers.set(me.kind,e=>this.visitGroupByClause(e)),this.handlers.set(de.kind,e=>this.visitHavingClause(e)),this.handlers.set(pe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Pe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Ne.kind,e=>this.visitForClause(e)),this.handlers.set(Ae.kind,e=>this.visitOrderByItem(e)),this.handlers.set(De.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 At=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(C.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(Q.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(Ce.kind,e=>this.visitValuesQuery(e)),this.handlers.set(z.kind,e=>this.visitSelectItem(e)),this.handlers.set(P.kind,e=>this.visitIdentifierString(e)),this.handlers.set($.kind,e=>this.visitRawString(e)),this.handlers.set(b.kind,e=>this.visitColumnReference(e)),this.handlers.set(N.kind,e=>this.visitParameterExpression(e)),this.handlers.set(Z.kind,e=>this.visitLiteralValue(e)),this.handlers.set(B.kind,e=>this.visitSourceExpression(e)),this.handlers.set(O.kind,e=>this.visitTableSource(e)),this.handlers.set($e.kind,e=>this.visitParenSource(e)),this.handlers.set(j.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(ge.kind,e=>this.visitInlineQuery(e)),this.handlers.set(J.kind,e=>this.visitFromClause(e)),this.handlers.set(fe.kind,e=>this.visitJoinClause(e)),this.handlers.set(he.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Se.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(S.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ie.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ke.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(Te.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(we.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(K.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ye.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ve.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(Ie.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ce.kind,e=>this.visitCastExpression(e)),this.handlers.set(Be.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(Ge.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(Ve.kind,e=>this.visitTypeValue(e)),this.handlers.set(U.kind,e=>this.visitValueList(e)),this.handlers.set(et.kind,e=>this.visitArraySliceExpression(e)),this.handlers.set(tt.kind,e=>this.visitArrayIndexExpression(e)),this.handlers.set(je.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(_.kind,e=>this.visitSelectClause(e)),this.handlers.set(me.kind,e=>this.visitGroupByClause(e)),this.handlers.set(de.kind,e=>this.visitHavingClause(e)),this.handlers.set(pe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Pe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Ne.kind,e=>this.visitForClause(e)),this.handlers.set(Ae.kind,e=>this.visitOrderByItem(e)),this.handlers.set(De.kind,e=>this.visitPartitionByClause(e))}reset(){this.visitedNodes.clear()}execute(e){return this.reset(),this.visit(e)}visit(e){if(!this.isRootVisit)return this.visitNode(e);this.reset(),this.isRootVisit=!1;try{return this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return e;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t)return t(e);let n=e.getKind()?.toString()||"unknown",r=e.constructor?.name||"unknown";throw new Error(`[CTEDisabler] No handler for ${r} with kind ${n}.`)}visitSimpleSelectQuery(e){return e.withClause&&e.withClause.tables.forEach(t=>{this.visit(t.query)}),e.withClause=null,e.selectClause=this.visit(e.selectClause),e.fromClause=e.fromClause?this.visit(e.fromClause):null,e.whereClause=e.whereClause?this.visit(e.whereClause):null,e.groupByClause=e.groupByClause?this.visit(e.groupByClause):null,e.havingClause=e.havingClause?this.visit(e.havingClause):null,e.orderByClause=e.orderByClause?this.visit(e.orderByClause):null,e.windowClause&&(e.windowClause=new nt(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 Ce(t)}visitSelectClause(e){let t=e.items.map(n=>this.visit(n));return new _(t,e.distinct)}visitFromClause(e){let t=this.visit(e.source),n=e.joins?e.joins.map(r=>this.visit(r)):null;return new J(t,n)}visitSubQuerySource(e){let t=this.visit(e.query);return new j(t)}visitInlineQuery(e){let t=this.visit(e.selectQuery);return new ge(t)}visitJoinClause(e){let t=this.visit(e.source),n=e.condition?this.visit(e.condition):null;return new fe(e.joinType.value,t,n,e.lateral)}visitJoinOnClause(e){let t=this.visit(e.condition);return new he(t)}visitJoinUsingClause(e){let t=this.visit(e.condition);return new Se(t)}visitWhereClause(e){let t=this.visit(e.condition);return new se(t)}visitGroupByClause(e){let t=e.grouping.map(n=>this.visit(n));return new me(t)}visitHavingClause(e){let t=this.visit(e.condition);return new de(t)}visitOrderByClause(e){let t=e.order.map(n=>this.visit(n));return new pe(t)}visitWindowFrameClause(e){let t=this.visit(e.expression);return new Pe(e.name.name,t)}visitLimitClause(e){let t=this.visit(e.value);return new oe(t)}visitForClause(e){return new Ne(e.lockMode)}visitParenExpression(e){let t=this.visit(e.expression);return new Y(t)}visitBinaryExpression(e){let t=this.visit(e.left),n=this.visit(e.right);return new S(t,e.operator.value,n)}visitUnaryExpression(e){let t=this.visit(e.expression);return new te(e.operator.value,t)}visitCaseExpression(e){let t=e.condition?this.visit(e.condition):null,n=this.visit(e.switchCase);return new ie(t,n)}visitSwitchCaseArgument(e){let t=e.cases.map(r=>this.visit(r)),n=e.elseValue?this.visit(e.elseValue):null;return new Te(t,n)}visitCaseKeyValuePair(e){let t=this.visit(e.key),n=this.visit(e.value);return new ke(t,n)}visitBetweenExpression(e){let t=this.visit(e.expression),n=this.visit(e.lower),r=this.visit(e.upper);return new we(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 K(e.namespaces,e.name,t,n)}visitArrayExpression(e){let t=this.visit(e.expression);return new ye(t)}visitArrayQueryExpression(e){let t=this.visit(e.query);return new ve(t)}visitTupleExpression(e){let t=e.values.map(n=>this.visit(n));return new Ie(t)}visitCastExpression(e){let t=this.visit(e.input),n=this.visit(e.castType);return new ce(t,n)}visitTypeValue(e){let t=e.argument?this.visit(e.argument):null;return new Ve(e.namespaces,e.name,t)}visitSelectItem(e){let t=this.visit(e.value);return new z(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 B(t,n)}visitTableSource(e){return e}visitParenSource(e){let t=this.visit(e.source);return new $e(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 Be(t,n,r)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new Ae(t,e.sortDirection,e.nullsPosition)}visitValueList(e){let t=e.values.map(n=>this.visit(n));return new U(t)}visitArraySliceExpression(e){return e}visitArrayIndexExpression(e){return e}visitStringSpecifierExpression(e){return e}visitPartitionByClause(e){let t=this.visit(e.value);return new De(t)}};var He=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(C.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(Q.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(Ce.kind,t=>this.visitValuesQuery(t)),this.handlers.set(ae.kind,t=>this.visitWithClause(t)),this.handlers.set(ne.kind,t=>this.visitCommonTable(t)),this.handlers.set(J.kind,t=>this.visitFromClause(t)),this.handlers.set(fe.kind,t=>this.visitJoinClause(t)),this.handlers.set(he.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(Se.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(B.kind,t=>this.visitSourceExpression(t)),this.handlers.set(O.kind,t=>this.visitTableSource(t)),this.handlers.set(qe.kind,t=>this.visitFunctionSource(t)),this.handlers.set($e.kind,t=>this.visitParenSource(t)),this.handlers.set(j.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(ge.kind,t=>this.visitInlineQuery(t)),e||(this.handlers.set(se.kind,t=>this.visitWhereClause(t)),this.handlers.set(me.kind,t=>this.visitGroupByClause(t)),this.handlers.set(de.kind,t=>this.visitHavingClause(t)),this.handlers.set(pe.kind,t=>this.visitOrderByClause(t)),this.handlers.set(Pe.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(oe.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(Ne.kind,t=>this.visitForClause(t)),this.handlers.set(Ae.kind,t=>this.visitOrderByItem(t)),this.handlers.set(_.kind,t=>this.visitSelectClause(t)),this.handlers.set(z.kind,t=>this.visitSelectItem(t)),this.handlers.set(Y.kind,t=>this.visitParenExpression(t)),this.handlers.set(S.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(te.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(ie.kind,t=>this.visitCaseExpression(t)),this.handlers.set(ke.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(Te.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(we.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(K.kind,t=>this.visitFunctionCall(t)),this.handlers.set(ye.kind,t=>this.visitArrayExpression(t)),this.handlers.set(ve.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(Ie.kind,t=>this.visitTupleExpression(t)),this.handlers.set(ce.kind,t=>this.visitCastExpression(t)),this.handlers.set(U.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 $?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof $?e.qualifiedName.name.value:e.qualifiedName.name.name}collect(e){return this.visit(e),this.getTableSources()}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.selectableOnly||this.collectCTEs(e),this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}collectCTEs(e){let t=new X;t.visit(e);let n=t.getCommonTables();for(let r of n)this.cteNames.add(r.aliasExpression.table.name)}visitSimpleSelectQuery(e){if(e.fromClause&&e.fromClause.accept(this),!this.selectableOnly){if(e.withClause&&e.withClause.accept(this),e.whereClause&&e.whereClause.accept(this),e.groupByClause&&e.groupByClause.accept(this),e.havingClause&&e.havingClause.accept(this),e.orderByClause&&e.orderByClause.accept(this),e.windowClause)for(let t of e.windowClause.windows)t.accept(this);e.limitClause&&e.limitClause.accept(this),e.offsetClause&&e.offsetClause.accept(this),e.fetchClause&&e.fetchClause.accept(this),e.forClause&&e.forClause.accept(this),e.selectClause.accept(this)}}visitBinarySelectQuery(e){e.left.accept(this),e.right.accept(this)}visitValuesQuery(e){if(!this.selectableOnly)for(let t of e.tuples)t.accept(this)}visitWithClause(e){if(!this.selectableOnly)for(let t of e.tables)t.accept(this)}visitCommonTable(e){this.selectableOnly||e.query.accept(this)}visitFromClause(e){if(e.source.accept(this),e.joins)for(let t of e.joins)t.accept(this)}visitSourceExpression(e){e.datasource.accept(this)}visitTableSource(e){let t=this.getTableIdentifier(e);!this.tableNameMap.has(t)&&!this.isCTETable(e.table.name)&&(this.tableNameMap.set(t,!0),this.tableSources.push(e))}visitFunctionSource(e){e.argument&&this.visitValueComponent(e.argument)}visitValueComponent(e){e.accept(this)}isCTETable(e){return this.cteNames.has(e)}visitParenSource(e){e.source.accept(this)}visitSubQuerySource(e){this.selectableOnly||e.query.accept(this)}visitInlineQuery(e){this.selectableOnly||e.selectQuery.accept(this)}visitJoinClause(e){e.source.accept(this),!this.selectableOnly&&e.condition&&e.condition.accept(this)}visitJoinOnClause(e){this.selectableOnly||e.condition.accept(this)}visitJoinUsingClause(e){this.selectableOnly||e.condition.accept(this)}visitWhereClause(e){e.condition.accept(this)}visitGroupByClause(e){for(let t of e.grouping)t.accept(this)}visitHavingClause(e){e.condition.accept(this)}visitOrderByClause(e){for(let t of e.order)t.accept(this)}visitWindowFrameClause(e){e.expression.accept(this)}visitLimitClause(e){e.value.accept(this)}visitOffsetClause(e){e.value.accept(this)}visitFetchClause(e){e.expression.accept(this)}visitForClause(e){}visitOrderByItem(e){e.value.accept(this)}visitSelectClause(e){for(let t of e.items)t.accept(this)}visitSelectItem(e){e.value.accept(this)}visitParenExpression(e){e.expression.accept(this)}visitBinaryExpression(e){e.left.accept(this),e.right.accept(this)}visitUnaryExpression(e){e.expression.accept(this)}visitCaseExpression(e){e.condition&&e.condition.accept(this),e.switchCase.accept(this)}visitSwitchCaseArgument(e){for(let t of e.cases)t.accept(this);e.elseValue&&e.elseValue.accept(this)}visitCaseKeyValuePair(e){e.key.accept(this),e.value.accept(this)}visitBetweenExpression(e){e.expression.accept(this),e.lower.accept(this),e.upper.accept(this)}visitFunctionCall(e){e.argument&&e.argument.accept(this),e.over&&e.over.accept(this)}visitArrayExpression(e){e.expression.accept(this)}visitArrayQueryExpression(e){e.query.accept(this)}visitTupleExpression(e){for(let t of e.values)t.accept(this)}visitCastExpression(e){e.input.accept(this),e.castType.accept(this)}visitValueList(e){for(let t of e.values)t.accept(this)}visitStringSpecifierExpression(e){}};var pt=class extends v{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 d=class{constructor(e,t="",n=""){this.innerTokens=[];this.type=e,this.text=t,this.containerType=n}};var mt=class{static collect(e){let t=[];function n(r){if(!(!r||typeof r!="object")){r.constructor&&r.constructor.kind===N.kind&&t.push(r);for(let i of Object.keys(r)){let s=r[i];Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&s.constructor&&s.constructor.kind&&n(s)}}}return n(e),t}};var In=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var Pn=class{constructor(e){this.prefix=e?.prefix??":",this.suffix=e?.suffix??"",this.style=e?.style??"named"}decorate(e,t){let n="";return this.style==="anonymous"?n=this.prefix:this.style==="indexed"?n=this.prefix+t:this.style==="named"&&(n=this.prefix+e+this.suffix),e=n,e}};var Nt=class extends v{static{this.kind=Symbol("UpdateQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.updateClause=e.updateClause,this.setClause=e.setClause instanceof at?e.setClause:new at(e.setClause),this.whereClause=e.whereClause??null,this.fromClause=e.fromClause??null,this.returningClause=e.returning??null}};var Ke=class a{constructor(e=null,t=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=e??null,this.commonTableCollector=new X,this.commonTables=[],this.initialCommonTables=t,this.handlers=new Map,this.handlers.set(C.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(_.kind,n=>this.visitSelectClause(n)),this.handlers.set(B.kind,n=>this.visitSourceExpression(n)),this.handlers.set(J.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 b&&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 b&&r.value.namespaces).map(r=>r.value.getNamespace());if(e.fromClause){let r=e.fromClause.getSourceAliasName();if(r&&n.includes(r)&&this.processFromClause(e.fromClause,!1),e.fromClause.joins)for(let i of e.fromClause.joins){let s=i.getSourceAliasName();s&&n.includes(s)&&this.processJoinClause(i)}}this.selectValues=this.selectValues.filter(r=>r.name!=="*")}processFromClause(e,t){if(e){let n=e.getSourceAliasName();if(this.processSourceExpression(n,e.source),e.joins&&t)for(let r of e.joins)this.processJoinClause(r)}}processJoinClause(e){let t=e.getSourceAliasName();this.processSourceExpression(t,e.source)}processSourceExpression(e,t){let n=this.commonTables.find(r=>r.aliasExpression.table.name===e);if(n){let r=this.commonTables.filter(o=>o.aliasExpression.table.name!==e);new a(this.tableColumnResolver,r).collect(n.query).forEach(o=>{this.addSelectValueAsUnique(o.name,new b(e?[e]:null,o.name))})}else new a(this.tableColumnResolver,this.commonTables).collect(t).forEach(s=>{this.addSelectValueAsUnique(s.name,new b(e?[e]:null,s.name))})}visitSelectClause(e){for(let t of e.items)this.processSelectItem(t)}processSelectItem(e){if(e.identifier)this.addSelectValueAsUnique(e.identifier.name,e.value);else if(e.value instanceof b){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 b(t?[t]:null,n.name))});return}else if(e.datasource instanceof O){if(this.tableColumnResolver){let t=e.datasource.getSourceName();this.tableColumnResolver(t).forEach(n=>{this.addSelectValueAsUnique(n,new b([t],n))})}return}else if(e.datasource instanceof j){let t=e.getAliasName();new a(this.tableColumnResolver,this.commonTables).collect(e.datasource.query).forEach(i=>{this.addSelectValueAsUnique(i.name,new b(t?[t]:null,i.name))});return}else if(e.datasource instanceof $e)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 Lt=class extends v{static{this.kind=Symbol("CreateTableQuery")}constructor(e){super(),this.tableName=new P(e.tableName),this.isTemporary=e.isTemporary??!1,this.asSelectQuery=e.asSelectQuery}getSelectQuery(){let e;return this.asSelectQuery?e=new Ke().collect(this.asSelectQuery).map(r=>new z(r.value,r.name)):e=[new z(new $("*"))],new C({selectClause:new _(e),fromClause:new J(new B(new O(null,this.tableName.name),null),null)})}getCountQuery(){return new C({selectClause:new _([new z(new K(null,"count",new b(null,"*"),null))]),fromClause:new J(new B(new O(null,this.tableName.name),null),null)})}};var Lr={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"}},An=class a{constructor(e){this.handlers=new Map;this.index=1;e?.preset&&(e={...e.preset,...e}),this.parameterDecorator=new Pn({prefix:typeof e?.parameterSymbol=="string"?e.parameterSymbol:e?.parameterSymbol?.start??":",suffix:typeof e?.parameterSymbol=="object"?e.parameterSymbol.end:"",style:e?.parameterStyle??"named"}),this.identifierDecorator=new In({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.handlers.set(U.kind,t=>this.visitValueList(t)),this.handlers.set(b.kind,t=>this.visitColumnReference(t)),this.handlers.set(_e.kind,t=>this.visitQualifiedName(t)),this.handlers.set(K.kind,t=>this.visitFunctionCall(t)),this.handlers.set(te.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(S.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(Z.kind,t=>this.visitLiteralValue(t)),this.handlers.set(N.kind,t=>this.visitParameterExpression(t)),this.handlers.set(Te.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(ke.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set($.kind,t=>this.visitRawString(t)),this.handlers.set(P.kind,t=>this.visitIdentifierString(t)),this.handlers.set(Y.kind,t=>this.visitParenExpression(t)),this.handlers.set(ce.kind,t=>this.visitCastExpression(t)),this.handlers.set(ie.kind,t=>this.visitCaseExpression(t)),this.handlers.set(ye.kind,t=>this.visitArrayExpression(t)),this.handlers.set(ve.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(et.kind,t=>this.visitArraySliceExpression(t)),this.handlers.set(tt.kind,t=>this.visitArrayIndexExpression(t)),this.handlers.set(we.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(je.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(Ve.kind,t=>this.visitTypeValue(t)),this.handlers.set(Ie.kind,t=>this.visitTupleExpression(t)),this.handlers.set(ge.kind,t=>this.visitInlineQuery(t)),this.handlers.set(Be.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(Ge.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(Et.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(xt.kind,t=>this.visitWindowFrameBoundaryValue(t)),this.handlers.set(De.kind,t=>this.visitPartitionByClause(t)),this.handlers.set(pe.kind,t=>this.visitOrderByClause(t)),this.handlers.set(Ae.kind,t=>this.visitOrderByItem(t)),this.handlers.set(z.kind,t=>this.visitSelectItem(t)),this.handlers.set(_.kind,t=>this.visitSelectClause(t)),this.handlers.set(Tt.kind,t=>this.visitDistinct(t)),this.handlers.set(kt.kind,t=>this.visitDistinctOn(t)),this.handlers.set(pt.kind,t=>this.visitHintClause(t)),this.handlers.set(O.kind,t=>this.visitTableSource(t)),this.handlers.set(qe.kind,t=>this.visitFunctionSource(t)),this.handlers.set(B.kind,t=>this.visitSourceExpression(t)),this.handlers.set(re.kind,t=>this.visitSourceAliasExpression(t)),this.handlers.set(J.kind,t=>this.visitFromClause(t)),this.handlers.set(fe.kind,t=>this.visitJoinClause(t)),this.handlers.set(he.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(Se.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(se.kind,t=>this.visitWhereClause(t)),this.handlers.set(me.kind,t=>this.visitGroupByClause(t)),this.handlers.set(de.kind,t=>this.visitHavingClause(t)),this.handlers.set(nt.kind,t=>this.visitWindowClause(t)),this.handlers.set(Pe.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(oe.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(gt.kind,t=>this.visitFetchExpression(t)),this.handlers.set(Ne.kind,t=>this.visitForClause(t)),this.handlers.set(ae.kind,t=>this.visitWithClause(t)),this.handlers.set(ne.kind,t=>this.visitCommonTable(t)),this.handlers.set(C.kind,t=>this.visitSimpleQuery(t)),this.handlers.set(j.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(Q.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(Ce.kind,t=>this.visitValuesQuery(t)),this.handlers.set(Ie.kind,t=>this.visitTupleExpression(t)),this.handlers.set(ot.kind,t=>this.visitInsertQuery(t)),this.handlers.set(ct.kind,t=>this.visitInsertClause(t)),this.handlers.set(Nt.kind,t=>this.visitUpdateQuery(t)),this.handlers.set(It.kind,t=>this.visitUpdateClause(t)),this.handlers.set(at.kind,t=>this.visitSetClause(t)),this.handlers.set(ut.kind,t=>this.visitSetClauseItem(t)),this.handlers.set(ln.kind,t=>this.visitReturningClause(t)),this.handlers.set(Lt.kind,t=>this.visitCreateTableQuery(t))}static{this.SPACE_TOKEN=new d(10," ")}static{this.COMMA_TOKEN=new d(3,",")}static{this.ARGUMENT_SPLIT_COMMA_TOKEN=new d(11,",")}static{this.PAREN_OPEN_TOKEN=new d(4,"(")}static{this.PAREN_CLOSE_TOKEN=new d(4,")")}static{this.DOT_TOKEN=new d(8,".")}visitBinarySelectQuery(e){let t=new d(0,"");if(e.headerComments&&e.headerComments.length>0){let n=this.createCommentBlocks(e.headerComments);t.innerTokens.push(...n),t.innerTokens.push(a.SPACE_TOKEN)}return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,e.operator.value,"BinarySelectQueryOperator")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}static commaSpaceTokens(){return[a.COMMA_TOKEN,a.SPACE_TOKEN]}static argumentCommaSpaceTokens(){return[a.ARGUMENT_SPLIT_COMMA_TOKEN,a.SPACE_TOKEN]}visitQualifiedName(e){let t=new d(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(a.DOT_TOKEN);return t.innerTokens.push(e.name.accept(this)),t}visitPartitionByClause(e){let t=new d(1,"partition by","PartitionByClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOrderByClause(e){let t=new d(1,"order by","OrderByClause");t.innerTokens.push(a.SPACE_TOKEN);for(let n=0;n<e.order.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.order[n]));return t}visitOrderByItem(e){let t=new d(0,"","OrderByItem");return t.innerTokens.push(this.visit(e.value)),e.sortDirection&&e.sortDirection!=="asc"&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"desc"))),e.nullsPosition&&(e.nullsPosition==="first"?(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"nulls first"))):e.nullsPosition==="last"&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"nulls last")))),t}parse(e){this.index=1;let t=this.visit(e),n=mt.collect(e).sort((i,s)=>(i.index??0)-(s.index??0)),r=this.parameterDecorator.style;if(r==="named"){let i={};for(let s of n){let o=s.name.value;if(i.hasOwnProperty(o)){if(i[o]!==s.value)throw new Error(`Duplicate parameter name '${o}' with different values detected during query composition.`);continue}i[o]=s.value}return{token:t,params:i}}else if(r==="indexed"){let i=n.map(s=>s.value);return{token:t,params:i}}else if(r==="anonymous"){let i=n.map(s=>s.value);return{token:t,params:i}}return{token:t,params:[]}}visit(e){let t=this.handlers.get(e.getKind());if(t){let n=t(e);return("handlesOwnComments"in e&&typeof e.handlesOwnComments=="function"?e.handlesOwnComments():e.getKind()===C.kind)||this.addCommentsToToken(n,e.comments),n}throw new Error(`[SqlPrintTokenParser] No handler for kind: ${e.getKind().toString()}`)}addCommentsToToken(e,t){if(!t||t.length===0)return;let n=this.createCommentBlocks(t);n.length>0&&this.insertCommentBlocksWithSpacing(e,n)}createCommentBlocks(e){let t=[];for(let n of e)n.trim()&&t.push(this.createSingleCommentBlock(n));return t}createSingleCommentBlock(e){let t=new d(0,"","CommentBlock"),n=new d(6,this.formatBlockComment(e));t.innerTokens.push(n);let r=new d(12,"");t.innerTokens.push(r);let i=new d(10," ");return t.innerTokens.push(i),t}insertCommentBlocksWithSpacing(e,t){if(e.containerType==="SelectItem"){e.innerTokens.length>0&&e.innerTokens[e.innerTokens.length-1].type!==10&&e.innerTokens.push(a.SPACE_TOKEN),e.innerTokens.push(...t);return}if(e.containerType==="SelectClause"){e.innerTokens.unshift(a.SPACE_TOKEN,...t);return}if(e.innerTokens.unshift(...t),this.shouldAddSeparatorSpace(e.containerType)){let r=new d(10," ");e.innerTokens.splice(t.length,0,r),e.innerTokens.length>t.length+1&&e.innerTokens[t.length+1].type===10&&e.innerTokens.splice(t.length+1,1)}else e.innerTokens.length>t.length&&e.innerTokens[t.length].type===10&&e.innerTokens.splice(t.length,1)}shouldAddSeparatorSpace(e){return this.isClauseLevelContainer(e)}isClauseLevelContainer(e){switch(e){case"SelectClause":case"FromClause":case"WhereClause":case"GroupByClause":case"HavingClause":case"OrderByClause":case"LimitClause":case"OffsetClause":case"WithClause":case"SimpleSelectQuery":return!0;default:return!1}}formatBlockComment(e){let t=e.replace(/\*\//g,"*").replace(/\/\*/g,"*").replace(/\r?\n/g," ").trim();return t?`/* ${t} */`:""}visitValueList(e){let t=new d(0,"","ValueList");for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...a.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t}visitColumnReference(e){let t=new d(0,"","ColumnReference");return t.innerTokens.push(e.qualifiedName.accept(this)),t}visitFunctionCall(e){let t=new d(0,"","FunctionCall");if(t.innerTokens.push(e.qualifiedName.accept(this)),t.innerTokens.push(a.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),e.internalOrderBy&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.internalOrderBy))),e.comments&&e.comments.length>0){let n=new d(4,")");this.addCommentsToToken(n,e.comments),t.innerTokens.push(n),e.comments=null}else t.innerTokens.push(a.PAREN_CLOSE_TOKEN);return e.withOrdinality&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"with ordinality"))),e.over&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"over")),e.over instanceof P?(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.over.accept(this))):(t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.over)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN))),t}visitUnaryExpression(e){let t=new d(0,"","UnaryExpression");return t.innerTokens.push(this.visit(e.operator)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.expression)),t}visitBinaryExpression(e){let t=new d(0,"","BinaryExpression");return t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(5,e.operator.value)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}visitLiteralValue(e){let t;return e.value===null?t="null":e.isStringLiteral?t=`'${e.value.replace(/'/g,"''")}'`:typeof e.value=="string"?t=e.value:t=e.value.toString(),new d(2,t,"LiteralValue")}visitParameterExpression(e){e.index=this.index;let t=this.parameterDecorator.decorate(e.name.value,e.index),n=new d(7,t);return this.index++,n}visitSwitchCaseArgument(e){let t=new d(0,"","SwitchCaseArgument");for(let n of e.cases)t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(n.accept(this));return e.elseValue&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.createElseToken(e.elseValue))),t}createElseToken(e){let t=new d(0,"","ElseClause");t.innerTokens.push(new d(1,"else")),t.innerTokens.push(a.SPACE_TOKEN);let n=new d(0,"","CaseElseValue");return n.innerTokens.push(this.visit(e)),t.innerTokens.push(n),t}visitCaseKeyValuePair(e){let t=new d(0,"","CaseKeyValuePair");t.innerTokens.push(new d(1,"when")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.key)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"then")),t.innerTokens.push(a.SPACE_TOKEN);let n=new d(0,"","CaseThenValue");return n.innerTokens.push(this.visit(e.value)),t.innerTokens.push(n),t}visitRawString(e){return new d(2,e.value,"RawString")}visitIdentifierString(e){let t=e.name==="*"?e.name:this.identifierDecorator.decorate(e.name);return new d(2,t,"IdentifierString")}visitParenExpression(e){let t=new d(0,"","ParenExpression");return t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitCastExpression(e){let t=new d(0,"","CastExpression");return t.innerTokens.push(this.visit(e.input)),t.innerTokens.push(new d(5,"::")),t.innerTokens.push(this.visit(e.castType)),t}visitCaseExpression(e){let t=new d(0,"","CaseExpression");return t.innerTokens.push(new d(1,"case")),e.condition&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition))),t.innerTokens.push(this.visit(e.switchCase)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"end")),t}visitArrayExpression(e){let t=new d(0,"","ArrayExpression");return t.innerTokens.push(new d(1,"array")),t.innerTokens.push(new d(4,"[")),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(new d(4,"]")),t}visitArrayQueryExpression(e){let t=new d(0,"","ArrayExpression");return t.innerTokens.push(new d(1,"array")),t.innerTokens.push(new d(4,"(")),t.innerTokens.push(this.visit(e.query)),t.innerTokens.push(new d(4,")")),t}visitArraySliceExpression(e){let t=new d(0,"","ArrayExpression");return t.innerTokens.push(this.visit(e.array)),t.innerTokens.push(new d(4,"[")),e.startIndex&&t.innerTokens.push(this.visit(e.startIndex)),t.innerTokens.push(new d(5,":")),e.endIndex&&t.innerTokens.push(this.visit(e.endIndex)),t.innerTokens.push(new d(4,"]")),t}visitArrayIndexExpression(e){let t=new d(0,"","ArrayExpression");return t.innerTokens.push(this.visit(e.array)),t.innerTokens.push(new d(4,"[")),t.innerTokens.push(this.visit(e.index)),t.innerTokens.push(new d(4,"]")),t}visitBetweenExpression(e){let t=new d(0,"","BetweenExpression");return t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(a.SPACE_TOKEN),e.negated&&(t.innerTokens.push(new d(1,"not")),t.innerTokens.push(a.SPACE_TOKEN)),t.innerTokens.push(new d(1,"between")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.lower)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"and")),t.innerTokens.push(a.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 d(2,t+n,"StringSpecifierExpression")}visitTypeValue(e){let t=new d(0,"","TypeValue");return t.innerTokens.push(e.qualifiedName.accept(this)),e.argument&&(t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN)),t}visitTupleExpression(e){let t=new d(0,"","TupleExpression");t.innerTokens.push(a.PAREN_OPEN_TOKEN);for(let n=0;n<e.values.length;n++)n>0&&t.innerTokens.push(...a.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitWindowFrameExpression(e){let t=new d(0,"","WindowFrameExpression"),n=!0;return e.partition&&(t.innerTokens.push(this.visit(e.partition)),n=!1),e.order&&(n?n=!1:t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.order))),e.frameSpec&&(n?n=!1:t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.frameSpec))),t}visitWindowFrameSpec(e){let t=new d(0,"","WindowFrameSpec");return t.innerTokens.push(new d(1,e.frameType)),e.endBound===null?(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this))):(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"between")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.startBound.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"and")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.endBound.accept(this))),t}visitWindowFrameBoundaryValue(e){let t=new d(0,"","WindowFrameBoundaryValue");return t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,e.isFollowing?"following":"preceding")),t}visitWindowFrameBoundStatic(e){return new d(1,e.bound)}visitSelectItem(e){let t=new d(0,"","SelectItem");if(t.innerTokens.push(this.visit(e.value)),!e.identifier)return t;if(e.value instanceof b){let n=e.value.column.name;if(e.identifier.name===n)return t}return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"as")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.identifier)),t}visitSelectClause(e){let t=new d(1,"select","SelectClause"),n="select";for(let r of e.hints)n+=" "+this.visit(r).text;if(e.distinct){let r=e.distinct.accept(this);if(r.innerTokens&&r.innerTokens.length>0){let i=r.text;for(let s of r.innerTokens)i+=this.flattenTokenText(s);n+=" "+i}else n+=" "+r.text}t.text=n,t.innerTokens.push(a.SPACE_TOKEN);for(let r=0;r<e.items.length;r++)r>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[r]));return t}flattenTokenText(e){let t=e.text;if(e.innerTokens)for(let n of e.innerTokens)t+=this.flattenTokenText(n);return t}visitHintClause(e){return new d(2,e.getFullHint())}visitDistinct(e){return new d(1,"distinct")}visitDistinctOn(e){let t=new d(0,"","DistinctOn");return t.innerTokens.push(new d(1,"distinct on")),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(e.value.accept(this)),t.innerTokens.push(a.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 d(2,t);return e.identifier&&(e.identifier.name,e.table.name),n}visitSourceExpression(e){let t=new d(0,"","SourceExpression");if(t.innerTokens.push(e.datasource.accept(this)),!e.aliasExpression)return t;if(e.datasource instanceof O){let n=e.datasource.table.name;return e.aliasExpression.table.name===n||(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"as")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this))),t}else return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"as")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.aliasExpression.accept(this)),t}visitFromClause(e){let t=new d(1,"from","FromClause");if(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.joins)for(let n=0;n<e.joins.length;n++)t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.joins[n]));return t}visitJoinClause(e){let t=new d(0,"","JoinClause");return t.innerTokens.push(new d(1,e.joinType.value)),e.lateral&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"lateral"))),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.source)),e.condition&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition))),t}visitJoinOnClause(e){let t=new d(0,"","JoinOnClause");return t.innerTokens.push(new d(1,"on")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitJoinUsingClause(e){let t=new d(0,"","JoinUsingClause");return t.innerTokens.push(new d(1,"using")),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.condition)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitFunctionSource(e){let t=new d(0,"","FunctionSource");return t.innerTokens.push(e.qualifiedName.accept(this)),t.innerTokens.push(a.PAREN_OPEN_TOKEN),e.argument&&t.innerTokens.push(this.visit(e.argument)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitSourceAliasExpression(e){let t=new d(0,"","SourceAliasExpression");if(t.innerTokens.push(this.visit(e.table)),e.columns){t.innerTokens.push(a.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...a.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));t.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return t}visitWhereClause(e){let t=new d(1,"where","WhereClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitGroupByClause(e){let t=new d(1,"group by","GroupByClause");t.innerTokens.push(a.SPACE_TOKEN);for(let n=0;n<e.grouping.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.grouping[n]));return t}visitHavingClause(e){let t=new d(1,"having","HavingClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.condition)),t}visitWindowClause(e){let t=new d(1,"window","WindowClause");t.innerTokens.push(a.SPACE_TOKEN);for(let n=0;n<e.windows.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.windows[n]));return t}visitWindowFrameClause(e){let t=new d(0,"","WindowFrameClause");return t.innerTokens.push(e.name.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"as")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitLimitClause(e){let t=new d(1,"limit","LimitClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitOffsetClause(e){let t=new d(1,"offset","OffsetClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.value)),t}visitFetchClause(e){let t=new d(1,"fetch","FetchClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.expression)),t}visitFetchExpression(e){let t=new d(0,"","FetchExpression");return t.innerTokens.push(new d(1,e.type)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.count.accept(this)),e.unit&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,e.unit))),t}visitForClause(e){let t=new d(1,"for","ForClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,e.lockMode)),t}visitWithClause(e){let t=new d(1,"with","WithClause");t.innerTokens.push(a.SPACE_TOKEN),e.recursive&&(t.innerTokens.push(new d(1,"recursive")),t.innerTokens.push(a.SPACE_TOKEN));for(let n=0;n<e.tables.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(e.tables[n].accept(this));return t.innerTokens.push(a.SPACE_TOKEN),t}visitCommonTable(e){let t=new d(0,"","CommonTable");t.innerTokens.push(e.aliasExpression.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"as")),t.innerTokens.push(a.SPACE_TOKEN),e.materialized!==null&&(e.materialized?t.innerTokens.push(new d(1,"materialized")):t.innerTokens.push(new d(1,"not materialized")),t.innerTokens.push(a.SPACE_TOKEN)),t.innerTokens.push(a.PAREN_OPEN_TOKEN);let n=new d(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitSimpleQuery(e){let t=new d(0,"","SimpleSelectQuery");if(e.headerComments&&e.headerComments.length>0){let n=this.createCommentBlocks(e.headerComments);t.innerTokens.push(...n),e.withClause&&t.innerTokens.push(a.SPACE_TOKEN)}if(e.withClause&&t.innerTokens.push(e.withClause.accept(this)),e.comments&&e.comments.length>0){let n=this.createCommentBlocks(e.comments);t.innerTokens.push(...n),e.selectClause&&t.innerTokens.push(a.SPACE_TOKEN)}return t.innerTokens.push(e.selectClause.accept(this)),e.fromClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this)),e.whereClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.groupByClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.groupByClause.accept(this))),e.havingClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.havingClause.accept(this))),e.orderByClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.orderByClause.accept(this))),e.windowClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.windowClause.accept(this))),e.limitClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.limitClause.accept(this))),e.offsetClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.offsetClause.accept(this))),e.fetchClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.fetchClause.accept(this))),e.forClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.forClause.accept(this)))),t}visitSubQuerySource(e){let t=new d(0,"");t.innerTokens.push(a.PAREN_OPEN_TOKEN);let n=new d(0,"","SubQuerySource");return n.innerTokens.push(e.query.accept(this)),t.innerTokens.push(n),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t}visitValuesQuery(e){let t=new d(1,"values","ValuesQuery");if(e.headerComments&&e.headerComments.length>0){let r=this.createCommentBlocks(e.headerComments);for(let i of r)t.innerTokens.push(i),t.innerTokens.push(a.SPACE_TOKEN)}t.innerTokens.push(a.SPACE_TOKEN);let n=new d(0,"","Values");for(let r=0;r<e.tuples.length;r++)r>0&&n.innerTokens.push(...a.commaSpaceTokens()),n.innerTokens.push(e.tuples[r].accept(this));return t.innerTokens.push(n),this.addCommentsToToken(t,e.comments),t}visitInlineQuery(e){let t=new d(0,"");t.innerTokens.push(a.PAREN_OPEN_TOKEN);let n=new d(0,"","InlineQuery");if(n.innerTokens.push(e.selectQuery.accept(this)),t.innerTokens.push(n),e.comments&&e.comments.length>0){let r=new d(4,")");this.addCommentsToToken(r,e.comments),t.innerTokens.push(r),e.comments=null}else t.innerTokens.push(a.PAREN_CLOSE_TOKEN);return t}visitInsertQuery(e){let t=new d(0,"","InsertQuery");return t.innerTokens.push(this.visit(e.insertClause)),e.selectQuery&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.selectQuery))),t}visitInsertClause(e){let t=new d(0,"");if(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"insert into")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),e.columns.length>0){t.innerTokens.push(a.PAREN_OPEN_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(e.columns[n].accept(this));t.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return t}visitUpdateQuery(e){let t=new d(0,"","UpdateQuery");return e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(e.updateClause.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.setClause.accept(this)),e.fromClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.fromClause.accept(this))),e.whereClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),e.returningClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.returningClause.accept(this))),t}visitUpdateClause(e){let t=new d(1,"update","UpdateClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t}visitSetClause(e){let t=new d(1,"set","SelectClause");t.innerTokens.push(a.SPACE_TOKEN);for(let n=0;n<e.items.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[n]));return t}visitSetClauseItem(e){let t=new d(0,"","SetClauseItem");return t.innerTokens.push(e.column.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(5,"=")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.value.accept(this)),t}visitReturningClause(e){let t=new d(1,"returning","ReturningClause");t.innerTokens.push(a.SPACE_TOKEN);for(let n=0;n<e.columns.length;n++)n>0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));return t}visitCreateTableQuery(e){let t=new d(1,e.isTemporary?"create temporary table":"create table","CreateTableQuery");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.tableName.accept(this)),e.asSelectQuery&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"as")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.asSelectQuery.accept(this))),t}};var qt=class{constructor(e=" ",t=0,n=`\r
15
+ `){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 Cr(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.")}},Cr=class{constructor(e,t){this.level=e,this.text=t}};var Nn=class a{constructor(e){this.insideWithClause=!1;this.indentChar=e?.indentChar??"",this.indentSize=e?.indentSize??0,this.newline=e?.newline??" ",this.commaBreak=e?.commaBreak??"none",this.andBreak=e?.andBreak??"none",this.keywordCase=e?.keywordCase??"none",this.exportComment=e?.exportComment??!1,this.strictCommentPlacement=e?.strictCommentPlacement??!1,this.withClauseStyle=e?.withClauseStyle??"standard",this.parenthesesOneLine=e?.parenthesesOneLine??!1,this.betweenOneLine=e?.betweenOneLine??!1,this.valuesOneLine=e?.valuesOneLine??!1,this.joinOneLine=e?.joinOneLine??!1,this.caseOneLine=e?.caseOneLine??!1,this.subqueryOneLine=e?.subqueryOneLine??!1,this.linePrinter=new qt(this.indentChar,this.indentSize,this.newline),this.indentIncrementContainers=new Set(e?.indentIncrementContainerTypes??["SelectClause","FromClause","WhereClause","GroupByClause","HavingClause","WindowFrameExpression","PartitionByClause","OrderByClause","WindowClause","LimitClause","OffsetClause","SubQuerySource","BinarySelectQueryOperator","Values","WithClause","SwitchCaseArgument","CaseKeyValuePair","CaseThenValue","ElseClause","CaseElseValue","SimpleSelectQuery"])}print(e,t=0){return this.linePrinter=new qt(this.indentChar,this.indentSize,this.newline),this.insideWithClause=!1,this.linePrinter.lines.length>0&&t!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=t),this.appendToken(e,t,void 0),this.linePrinter.print()}appendToken(e,t,n){let r=this.insideWithClause;if(e.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"&&(this.insideWithClause=!0),this.shouldSkipToken(e))return;let i=this.linePrinter.getCurrentLine();if(e.type===1)this.handleKeywordToken(e,t);else if(e.type===3)this.handleCommaToken(e,t,n);else if(e.type===5&&e.text.toLowerCase()==="and")this.handleAndOperatorToken(e,t);else if(e.containerType==="JoinClause")this.handleJoinClauseToken(e,t);else if(e.type===6)this.exportComment&&this.linePrinter.appendText(e.text);else if(e.type===10)this.handleSpaceToken(e,n);else if(e.type===12)this.handleCommentNewlineToken(e,t);else if(e.containerType==="CommonTable"&&this.withClauseStyle==="cte-oneline"){this.handleCteOnelineToken(e,t);return}else if(e.containerType==="ParenExpression"&&this.parenthesesOneLine||e.containerType==="BetweenExpression"&&this.betweenOneLine||e.containerType==="Values"&&this.valuesOneLine||e.containerType==="JoinOnClause"&&this.joinOneLine||e.containerType==="CaseExpression"&&this.caseOneLine||e.containerType==="InlineQuery"&&this.subqueryOneLine){this.handleOnelineToken(e,t);return}else this.linePrinter.appendText(e.text);if(e.keywordTokens&&e.keywordTokens.length>0)for(let o=0;o<e.keywordTokens.length;o++){let l=e.keywordTokens[o];this.appendToken(l,t,e.containerType)}let s=t;!this.isOnelineMode()&&i.text!==""&&this.indentIncrementContainers.has(e.containerType)&&(this.insideWithClause&&this.withClauseStyle==="full-oneline"||(s++,this.linePrinter.appendNewline(s)));for(let o=0;o<e.innerTokens.length;o++){let l=e.innerTokens[o];this.appendToken(l,s,e.containerType)}if(e.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"){this.insideWithClause=!1,this.linePrinter.appendNewline(t);return}s!==t&&(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t))}shouldSkipToken(e){return e.type===12?!1:(!e.innerTokens||e.innerTokens.length===0)&&e.text===""}applyKeywordCase(e){return this.keywordCase==="upper"?e.toUpperCase():this.keywordCase==="lower"?e.toLowerCase():e}handleKeywordToken(e,t){let n=this.applyKeywordCase(e.text);this.linePrinter.appendText(n)}handleCommaToken(e,t,n){let r=e.text;this.insideWithClause&&this.withClauseStyle==="full-oneline"?this.linePrinter.appendText(r):this.withClauseStyle==="cte-oneline"&&n==="WithClause"?(this.linePrinter.appendText(r),this.linePrinter.appendNewline(t)):this.commaBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)):this.commaBreak==="after"?(this.linePrinter.appendText(r),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t)):this.linePrinter.appendText(r)}handleAndOperatorToken(e,t){let n=this.applyKeywordCase(e.text);this.andBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(n)):this.andBreak==="after"?(this.linePrinter.appendText(n),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t)):this.linePrinter.appendText(n)}handleJoinClauseToken(e,t){let n=this.applyKeywordCase(e.text);this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(n)}handleSpaceToken(e,t){this.shouldSkipCommentBlockSpace(t)||this.linePrinter.appendText(e.text)}shouldSkipCommentBlockSpace(e){return e==="CommentBlock"&&this.insideWithClause&&this.withClauseStyle==="full-oneline"}handleCommentNewlineToken(e,t){this.shouldSkipCommentNewline()||this.isOnelineMode()||this.linePrinter.appendNewline(t)}shouldSkipCommentNewline(){return this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.withClauseStyle==="cte-oneline"}isOnelineMode(){return this.newline===" "}handleCteOnelineToken(e,t){let r=this.createCteOnelinePrinter().print(e,t),i=this.cleanDuplicateSpaces(r);this.linePrinter.appendText(i)}createCteOnelinePrinter(){return new a({indentChar:"",indentSize:0,newline:" ",commaBreak:this.commaBreak,andBreak:this.andBreak,keywordCase:this.keywordCase,exportComment:this.exportComment,strictCommentPlacement:this.strictCommentPlacement,withClauseStyle:"standard"})}handleOnelineToken(e,t){let r=this.createOnelinePrinter().print(e,t),i=this.cleanDuplicateSpaces(r);this.linePrinter.appendText(i)}createOnelinePrinter(){return new a({indentChar:"",indentSize:0,newline:" ",commaBreak:"none",andBreak:"none",keywordCase:this.keywordCase,exportComment:this.exportComment,strictCommentPlacement:this.strictCommentPlacement,withClauseStyle:"standard",parenthesesOneLine:!1,betweenOneLine:!1,valuesOneLine:!1,joinOneLine:!1,caseOneLine:!1,subqueryOneLine:!1})}cleanDuplicateSpaces(e){return e.replace(/\s{2,}/g," ")}};var Hu=["mysql","postgres","sqlserver","sqlite"],Fe=class{constructor(e={}){let t=e.preset?Lr[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 An(n),this.printer=new Nn({...e,parenthesesOneLine:e.parenthesesOneLine,betweenOneLine:e.betweenOneLine,valuesOneLine:e.valuesOneLine,joinOneLine:e.joinOneLine,caseOneLine:e.caseOneLine,subqueryOneLine:e.subqueryOneLine})}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var dt=class{constructor(){this.sqlFormatter=new Fe({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(e,t=null){return t&&(this.sqlFormatter=new Fe(t)),this.sqlFormatter.format(e).formattedSql}formatWithParameters(e,t=null){t&&(this.sqlFormatter=new Fe(t));let n=this.sqlFormatter.format(e);return{sql:n.formattedSql,params:n.params}}visit(e){return this.format(e)}};var Ln=class{constructor(){this.sourceCollector=new He(!0),this.cteCollector=new X,this.formatter=new dt}build(e){if(e.length===0)return new ae(!1,e);let t=this.resolveDuplicateNames(e),{tableMap:n,recursiveCTEs:r,dependencies:i}=this.buildDependencyGraph(t),s=this.sortCommonTables(t,n,r,i);return new ae(r.size>0,s)}resolveDuplicateNames(e){let t=new Map;for(let r of e){let i=r.aliasExpression.table.name;t.has(i)||t.set(i,[]),t.get(i).push(r)}let n=[];for(let[r,i]of Array.from(t.entries())){if(i.length===1){n.push(i[0]);continue}let s=i.map(l=>this.formatter.format(l.query));if(new Set(s).size===1)n.push(i[0]);else throw new Error(`CTE name conflict detected: '${r}' has multiple different definitions`)}return n}buildDependencyGraph(e){let t=new Map;for(let s of e)t.set(s.aliasExpression.table.name,s);let n=new Set,r=new Map,i=new Map;for(let s of e){let o=s.aliasExpression.table.name,l=this.sourceCollector.collect(s.query);for(let c of l)if(c.table.name===o){n.add(o);break}r.has(o)||r.set(o,new Set);let u=this.cteCollector.collect(s.query);for(let c of u){let p=c.aliasExpression.table.name;t.has(p)&&(r.get(o).add(p),i.has(p)||i.set(p,new Set),i.get(p).add(o))}}return{tableMap:t,recursiveCTEs:n,dependencies:r}}sortCommonTables(e,t,n,r){let i=[],s=[],o=new Set,l=new Set,u=c=>{if(o.has(c))return;if(l.has(c))throw new Error(`Circular reference detected in CTE: ${c}`);l.add(c);let p=r.get(c)||new Set;for(let m of Array.from(p))u(m);l.delete(c),o.add(c),n.has(c)?i.push(t.get(c)):s.push(t.get(c))};for(let c of e){let p=c.aliasExpression.table.name;o.has(p)||u(p)}return[...i,...s]}};var Qn=class{constructor(){this.nameConflictResolver=new Ln,this.cteCollector=new X}inject(e,t){if(t.length===0)return e;t.push(...this.cteCollector.collect(e));let n=this.nameConflictResolver.build(t);if(e instanceof C)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 C)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 it=class{constructor(){}static normalize(e){let n=new X().collect(e);return n.length===0?e:(new At().execute(e),new Qn().inject(e,n))}};var vt=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))(vt||{}),xe=class a{constructor(e,t=!1,n="columnNameOnly",r){this.selectValues=[];this.visitedNodes=new Set;this.uniqueKeys=new Set;this.isRootVisit=!0;this.tableColumnResolver=null;this.commonTables=[];this.initializeProperties(e,t,n,r),this.initializeHandlers()}initializeProperties(e,t,n,r){this.tableColumnResolver=e??null,this.includeWildCard=t,this.commonTableCollector=new X,this.commonTables=[],this.duplicateDetection=n,this.options=r||{}}initializeHandlers(){this.handlers=new Map,this.handlers.set(C.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(Q.kind,e=>this.visitBinarySelectQuery(e)),this.initializeClauseHandlers(),this.initializeValueComponentHandlers()}initializeClauseHandlers(){this.handlers.set(_.kind,e=>this.visitSelectClause(e)),this.handlers.set(J.kind,e=>this.visitFromClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(me.kind,e=>this.visitGroupByClause(e)),this.handlers.set(de.kind,e=>this.visitHavingClause(e)),this.handlers.set(pe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Pe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Re.kind,e=>this.offsetClause(e)),this.handlers.set(Ue.kind,e=>this.visitFetchClause(e)),this.handlers.set(he.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Se.kind,e=>this.visitJoinUsingClause(e))}initializeValueComponentHandlers(){this.handlers.set(b.kind,e=>this.visitColumnReference(e)),this.handlers.set(S.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(K.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ge.kind,e=>this.visitInlineQuery(e)),this.handlers.set(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(ie.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ce.kind,e=>this.visitCastExpression(e)),this.handlers.set(we.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(ye.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ve.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(et.kind,e=>this.visitArraySliceExpression(e)),this.handlers.set(tt.kind,e=>this.visitArrayIndexExpression(e)),this.handlers.set(U.kind,e=>this.visitValueList(e)),this.handlers.set(Be.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(De.kind,e=>this.visitPartitionByClause(e))}getValues(){return this.selectValues}collect(e){if(!e)throw new Error("Input argument cannot be null or undefined");this.visit(e);let t=this.getValues();return this.reset(),t}reset(){this.selectValues=[],this.visitedNodes.clear(),this.uniqueKeys.clear(),this.commonTables=[]}addSelectValueAsUnique(e,t){let n=this.generateUniqueKey(e,t);this.uniqueKeys.has(n)||(this.uniqueKeys.add(n),this.selectValues.push({name:e,value:t}))}generateUniqueKey(e,t){if(this.duplicateDetection==="columnNameOnly")return this.normalizeColumnName(e);{let n="";t&&typeof t.getNamespace=="function"&&(n=t.getNamespace()||"");let r=n?n+"."+e:e;return this.normalizeColumnName(r)}}normalizeColumnName(e){if(typeof e!="string")throw new Error("Column name must be a string");return this.options.ignoreCaseAndUnderscore?e.toLowerCase().replace(/_/g,""):e}visit(e){if(!this.isRootVisit){this.visitNode(e);return}if(!(e instanceof C||e instanceof Q))throw new Error("Root visit requires a SimpleSelectQuery or BinarySelectQuery.");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)){this.visitedNodes.add(e);try{let t=this.handlers.get(e.getKind());t&&t(e)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`Error processing SQL component of type ${e.getKind().toString()}: ${n}`)}}}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)}visitBinarySelectQuery(e){e.left instanceof C?this.visitSimpleSelectQuery(e.left):e.left instanceof Q&&this.visitBinarySelectQuery(e.left),e.right instanceof C?this.visitSimpleSelectQuery(e.right):e.right instanceof Q&&this.visitBinarySelectQuery(e.right)}visitSelectClause(e){for(let t of e.items)if(t.identifier)this.addSelectValueAsUnique(t.identifier.name,t.value);else if(t.value instanceof b){let n=t.value.column.name;n!=="*"?this.addSelectValueAsUnique(n,t.value):this.includeWildCard&&this.addSelectValueAsUnique(n,t.value)}else t.value.accept(this)}visitFromClause(e){let n=new Ke(this.tableColumnResolver,this.commonTables).collect(e);for(let r of n)this.addSelectValueAsUnique(r.name,r.value);if(this.options.upstream&&this.collectUpstreamColumns(e),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),e.withinGroup&&e.withinGroup.accept(this),e.internalOrderBy&&e.internalOrderBy.accept(this)}visitInlineQuery(e){e.selectQuery&&this.visitNode(e.selectQuery)}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)}visitArraySliceExpression(e){e.array&&e.array.accept(this),e.startIndex&&e.startIndex.accept(this),e.endIndex&&e.endIndex.accept(this)}visitArrayIndexExpression(e){e.array&&e.array.accept(this),e.index&&e.index.accept(this)}visitValueList(e){if(e.values&&Array.isArray(e.values))for(let t of e.values)t&&t.accept(this)}visitPartitionByClause(e){e.value.accept(this)}collectUpstreamColumns(e){if(this.collectAllAvailableCTEColumns(),this.collectUpstreamColumnsFromSource(e.source),e.joins)for(let t of e.joins)this.collectUpstreamColumnsFromSource(t.source)}collectUpstreamColumnsFromSource(e){if(e.datasource instanceof O){let t=this.findCTEByName(e.datasource.table.name);t?this.collectUpstreamColumnsFromCTE(t):this.collectUpstreamColumnsFromTable(e.datasource)}else e.datasource instanceof j?this.collectUpstreamColumnsFromSubquery(e.datasource):e.datasource instanceof $e&&this.collectUpstreamColumnsFromSource(new B(e.datasource.source,null))}collectUpstreamColumnsFromTable(e){if(this.tableColumnResolver){let t=e.table.name,n=this.tableColumnResolver(t);for(let r of n){let i=new b(e.table.name,r);this.addSelectValueAsUnique(r,i)}}}collectUpstreamColumnsFromSubquery(e){if(e.query instanceof C){let n=new a(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!0}).collect(e.query);for(let r of n)this.addSelectValueAsUnique(r.name,r.value)}}collectUpstreamColumnsFromCTE(e){if(e.query instanceof C){let n=new a(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!1}).collect(e.query);for(let r of n)r.name!=="*"&&this.addSelectValueAsUnique(r.name,r.value)}}collectAllAvailableCTEColumns(){for(let e of this.commonTables)this.collectUpstreamColumnsFromCTE(e)}findCTEByName(e){return this.commonTables.find(t=>t.getSourceAliasName()===e)||null}};var wt=class a{static parse(e){let n=new R(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=Me.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=Me.parseFromLexeme(e,n);return r.lastTokenType&2048?a.parseFunctionSource(e,r):a.parseTableSource(r)}static parseTableSource(e){let{namespaces:t,name:n,newIndex:r}=e;return{value:new O(t,n.name),newIndex:r}}static parseFunctionSource(e,t){let n=t.newIndex,{namespaces:r,name:i}=t,s=I.parseArgument(4,8,e,n);n=s.newIndex;let o=i.name;return{value:new qe({namespaces:r,name:o},s.value),newIndex:n}}static parseParenSource(e,t){let n=t;if(n++,n>=e.length)throw new Error(`Syntax error: Unexpected end of input at position ${n}. Expected a subquery or nested expression after opening parenthesis.`);let r=e[n].value;if(r==="select"||r==="values"||r==="with"){let i=this.parseSubQuerySource(e,n);if(n=i.newIndex,n<e.length&&e[n].type==8)n++;else throw new Error(`Syntax error at position ${n}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:i.value,newIndex:n}}else if(e[n].type==4){let i=this.parseParenSource(e,n);if(n=i.newIndex,n<e.length&&e[n].type==8)n++;else throw new Error(`Syntax error at position ${n}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:i.value,newIndex:n}}throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword, 'VALUES' keyword, or opening parenthesis '(' but found "${e[n].value}".`)}static parseSubQuerySource(e,t){let n=t,{value:r,newIndex:i}=A.parseFromLexeme(e,n);return n=i,{value:new j(r),newIndex:n}}};var Gt=class extends Error{constructor(t){super(`CTE '${t}' already exists in the query`);this.cteName=t;this.name="DuplicateCTEError"}},Qt=class extends Error{constructor(t,n){super(`Invalid CTE name '${t}': ${n}`);this.cteName=t;this.name="InvalidCTENameError"}},Ht=class extends Error{constructor(t){super(`CTE '${t}' not found in the query`);this.cteName=t;this.name="CTENotFoundError"}};var Ot=class{constructor(e,t){this.options=t||{},this.tableColumnResolver=e,this.columnCollector=new xe(this.tableColumnResolver,!1,"fullName",{upstream:!0})}find(e,t){let n=typeof t=="string"?[t]:t,i=new X().collect(e),s=new Map;for(let o of i)s.set(o.getSourceAliasName(),o);return this.findUpstream(e,n,s)}handleTableSource(e,t,n){let r=n.get(e.table.name);if(r){let i=new Map(n);i.delete(e.table.name);let s=this.findUpstream(r.query,t,i);return s.length===0?null:s}return null}handleSubQuerySource(e,t,n){let r=this.findUpstream(e.query,t,n);return r.length===0?null:r}processFromClauseBranches(e,t,n){let r=e.getSources();if(r.length===0)return null;let i=[],s=!0,o=0;for(let l of r){let u=l.datasource,c=null;if(u instanceof O)c=this.handleTableSource(u,t,n),o++;else if(u instanceof j)c=this.handleSubQuerySource(u,t,n),o++;else{if(u instanceof Ce)continue;s=!1;break}if(c===null){s=!1;break}i.push(c)}return s&&i.length===o?i.flat():null}findUpstream(e,t,n){if(e instanceof C){let r=e.fromClause;if(r){let c=this.processFromClauseBranches(r,t,n);if(c&&c.length>0)return c}let i=this.columnCollector.collect(e).map(c=>c.name),s=this.collectCTEColumns(e,n),o=[...i,...s],l=c=>this.options.ignoreCaseAndUnderscore?c.toLowerCase().replace(/_/g,""):c;return t.every(c=>o.some(p=>l(p)===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 C)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 St=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 re(r,i),newIndex:n}}return{value:new re(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 Ye=class{static parse(e){let n=new R(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=wt.parseTableSourceFromLexemes(e,t);return{value:new B(n.value,null),newIndex:n.newIndex}}static parseFromLexeme(e,t){let n=t,r=wt.parseFromLexeme(e,n);if(n=r.newIndex,n<e.length){if(e[n].value==="as"){n++;let s=St.parseFromLexeme(e,n);return n=s.newIndex,{value:new B(r.value,s.value),newIndex:n}}if(n<e.length&&this.isTokenTypeAliasCandidate(e[n].type)){let s=St.parseFromLexeme(e,n);return n=s.newIndex,{value:new B(r.value,s.value),newIndex:n}}}return{value:new B(r.value,null),newIndex:n}}static isTokenTypeAliasCandidate(e){return(e&64)!==0||(e&2048)!==0}};var We=class a{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 Ce?a.buildSimpleQuery(i):i,r=new Q(n(e[0]),t,n(e[1]));it.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 C)return e;if(e instanceof Q)return a.buildSimpleBinaryQuery(e);if(e instanceof Ce)return a.buildSimpleValuesQuery(e);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(e){let t=a.extractAndRemoveOrderByFromBinaryQuery(e),n=new j(e),r=new B(n,new re("bq",null)),i=new J(r,null),s=a.createSelectAllClause(),o=new C({selectClause:s,fromClause:i,orderByClause:t});return it.normalize(o)}static extractAndRemoveOrderByFromBinaryQuery(e){return a.findAndRemoveRightmostOrderBy(e)}static findAndRemoveRightmostOrderBy(e){if(e instanceof Q){let t=a.findAndRemoveRightmostOrderBy(e.right);return t||a.findAndRemoveRightmostOrderBy(e.left)}else if(e instanceof C){let t=e.orderByClause;if(t)return e.orderByClause=null,t}return null}static buildSimpleValuesQuery(e){let t=e.tuples.length>0?e.tuples[0].values.length:0;if(e.tuples.length===0)throw new Error("Empty VALUES clause cannot be converted to a SimpleSelectQuery");if(!e.columnAliases)throw new Error("Column aliases are required to convert a VALUES clause to SimpleSelectQuery. Please specify column aliases.");if(e.columnAliases.length!==t)throw new Error(`The number of column aliases (${e.columnAliases.length}) does not match the number of columns in the first tuple (${t}).`);let n=new j(e),r=new B(n,new re("vq",e.columnAliases)),i=new J(r,null),s=e.columnAliases.map(l=>new z(new b("vq",l),l)),o=new _(s,null);return new C({selectClause:o,fromClause:i})}static createSelectAllClause(){let e=new b(null,"*"),t=new z(e,"*");return new _([t],null)}static buildCreateTableQuery(e,t,n=!1){return new Lt({tableName:t,isTemporary:n,asSelectQuery:e})}static buildInsertQuery(e,t){let n,r=e.selectClause.items.length;if(n=new Ke().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.
16
16
  Select clause column count: ${r}, Columns with valid names: ${n.length}
17
- Detected column names: [${n.join(", ")}]`);let o=Ye.parse(t);return new ot({insertClause:new ct(o,n),selectQuery:e})}static buildUpdateQuery(e,t,n,r){let i=new It(Ye.parse(n)),s=Array.isArray(r)?r:[r],l=new Ke().collect(e),c=new X().collect(e);new At().execute(e);for(let I of s)if(!l.some(T=>T.name===I))throw new Error(`Primary key column '${I}' is not present in selectQuery select list.`);let d=i.getSourceAliasName();if(!d)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let y=l.filter(I=>!s.includes(I.name)).map(I=>new ut(I.name,new b(d,I.name))),h=new at(y),M=new J(e.toSource(t),null),H=null;for(let I of s){let T=new S(new b(d,I),"=",new b(t,I));H=H?new S(H,"and",T):T}let x=new se(H);return new Nt({updateClause:i,setClause:h,fromClause:M,whereClause:x,withClause:c.length>0?new ae(!1,c):void 0})}};var st=class{static set(e,t,n){let r=mt.collect(e),i=!1;for(let s of r)s.name.value===t&&(s.value=n,i=!0);if(!i)throw new Error(`Parameter '${t}' not found in query.`)}};var C=class extends v{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 We.buildBinaryQuery([this,n],t)}appendWhereRaw(t){let n=k.parse(t);this.appendWhere(n)}appendWhere(t){this.whereClause?this.whereClause.condition=new S(this.whereClause.condition,"and",t):this.whereClause=new se(t)}appendHavingRaw(t){let n=k.parse(t);this.appendHaving(n)}appendHaving(t){this.havingClause?this.havingClause.condition=new S(this.havingClause.condition,"and",t):this.havingClause=new de(t)}innerJoinRaw(t,n,r,i=null){this.joinSourceRaw("inner join",t,n,r,i)}leftJoinRaw(t,n,r,i=null){this.joinSourceRaw("left join",t,n,r,i)}rightJoinRaw(t,n,r,i=null){this.joinSourceRaw("right join",t,n,r,i)}innerJoin(t,n,r=null){this.joinSource("inner join",t,n,r)}leftJoin(t,n,r=null){this.joinSource("left join",t,n,r)}rightJoin(t,n,r=null){this.joinSource("right join",t,n,r)}joinSourceRaw(t,n,r,i,s=null){let o=wt.parse(n),l=new B(o,new re(r,null));this.joinSource(t,l,i,s)}joinSource(t,n,r,i=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let s=Array.isArray(r)?r:[r],l=new xe(i).collect(this),u=null,c=0,p=n.getAliasName();if(!p)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let y of l)if(s.some(h=>h==y.name)){let h=new S(y.value,"=",new b([p],y.name));u?u=new S(u,"and",h):u=h,c++}if(!u||c!==s.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${s.join(", ")}`);let d=new he(u),f=new fe(t,n,d,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(f):this.fromClause.joins=[f]),it.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 B(new W(this),new re(t,null))}appendWith(t){let n=Array.isArray(t)?t:[t];this.withClause?this.withClause.tables.push(...n):this.withClause=new ae(!1,n),it.normalize(this)}appendWithRaw(t,n){let r=A.parse(t),i=new ne(r,n,null);this.appendWith(i)}overrideSelectItemExpr(t,n){let r=this.selectClause.items.filter(u=>u.identifier?.name===t);if(r.length===0)throw new Error(`Column ${t} not found in the query`);if(r.length>1)throw new Error(`Duplicate column name ${t} found in the query`);let i=r[0],o=new dt().visit(i.value),l=n(o);i.value=k.parse(l)}appendWhereExpr(t,n,r){if(r&&r.upstream){let s=new Rt().find(this,[t]),o=new xe,l=new dt;for(let u of s){let c=o.collect(u).filter(d=>d.name===t).map(d=>d.value);if(c.length!==1)throw new Error(`Expected exactly one expression for column '${t}'`);let p=l.format(c[0]);u.appendWhereRaw(n(p))}}else{let i=new xe,s=new dt,o=i.collect(this).filter(u=>u.name===t).map(u=>u.value);if(o.length!==1)throw new Error(`Expected exactly one expression for column '${t}'`);let l=s.format(o[0]);this.appendWhereRaw(n(l))}}setParameter(t,n){return st.set(this,t,n),this}toSimpleQuery(){return this}addCTE(t,n,r){if(!t||t.trim()==="")throw new Qt(t,"name cannot be empty or whitespace-only");if(this.hasCTE(t))throw new Gt(t);let i=r?.materialized??null,s=new ne(n,t,i);return this.appendWith(s),this.cteNameCache.add(t),this}removeCTE(t){if(!this.hasCTE(t))throw new Ht(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 Qt(t,"name cannot be empty or whitespace-only");this.hasCTE(t)&&this.removeCTE(t);let i=r?.materialized??null,s=new ne(n,t,i);return this.appendWith(s),this.cteNameCache.add(t),this}};var Q=class a extends v{static{this.kind=Symbol("BinarySelectQuery")}constructor(e,t,n){super(),this.left=e,this.operator=new V(t),this.right=n}union(e){return this.appendSelectQuery("union",e)}unionAll(e){return this.appendSelectQuery("union all",e)}intersect(e){return this.appendSelectQuery("intersect",e)}intersectAll(e){return this.appendSelectQuery("intersect all",e)}except(e){return this.appendSelectQuery("except",e)}exceptAll(e){return this.appendSelectQuery("except all",e)}appendSelectQuery(e,t){return this.left=new a(this.left,this.operator.value,this.right),this.operator=new V(e),this.right=t,it.normalize(this),this}unionRaw(e){let t=A.parse(e);return this.union(t)}unionAllRaw(e){let t=A.parse(e);return this.unionAll(t)}intersectRaw(e){let t=A.parse(e);return this.intersect(t)}intersectAllRaw(e){let t=A.parse(e);return this.intersectAll(t)}exceptRaw(e){let t=A.parse(e);return this.except(t)}exceptAllRaw(e){let t=A.parse(e);return this.exceptAll(t)}toSource(e="subq"){return new B(new W(this),new re(e,null))}setParameter(e,t){return st.set(this,e,t),this}toSimpleQuery(){return We.buildSimpleQuery(this)}};var Ce=class extends v{static{this.kind=Symbol("ValuesQuery")}constructor(e,t=null){super(),this.tuples=e,this.columnAliases=t}toSimpleQuery(){return We.buildSimpleQuery(this)}setParameter(e,t){return st.set(this,e,t),this}};var Rn=class{static parse(e){let n=new O(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The SELECT clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=null,i=n<e.length?e[n].comments:null;if(e[n].value!=="select")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword but found "${e[n].value}". SELECT clauses must start with the SELECT keyword.`);n++;let s=[];for(;n<e.length&&pt.isHintClause(e[n].value);){let u=pt.extractHintContent(e[n].value);s.push(new pt(u)),n++}if(n<e.length&&e[n].value==="distinct")n++,r=new Tt;else if(n<e.length&&e[n].value==="distinct on"){n++;let u=k.parseArgument(4,8,e,n);r=new kt(u.value),n=u.newIndex}let o=[],l=On.parseItem(e,n);for(o.push(l.value),n=l.newIndex;n<e.length&&e[n].type&16;){n++;let u=On.parseItem(e,n);o.push(u.value),n=u.newIndex}if(o.length===0)throw new Error(`Syntax error at position ${t}: No select items found. The SELECT clause requires at least one expression to select.`);{let u=new _(o,r,s);return u.comments=i,{value:u,newIndex:n}}}},On=class{static parse(e){let n=new O(e).readLexmes(),r=this.parseItem(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The select item is complete but there are additional tokens.`);return r.value}static parseItem(e,t){let n=t,r=k.parseFromLexeme(e,n),i=r.value;if(n=r.newIndex,n<e.length&&e[n].value==="as"&&n++,n<e.length&&e[n].type&64){let s=e[n].value;return n++,{value:new z(i,s),newIndex:n}}else if(i instanceof b&&i.column.name!=="*")return{value:new z(i,i.column.name),newIndex:n};return{value:new z(i),newIndex:n}}};var Fn=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 he(r.value),newIndex:n}}return null}};var Bn=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 Se(i),newIndex:n}}return null}};var Vn=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!!Kt.parse(e,0)}static parseLateral(e,t){let n=t;return n<e.length&&e[n].value==="lateral"?(n++,{value:!0,newIndex:n}):{value:!1,newIndex:n}}static isJoinCommand(e,t){return t>=e.length?!1:!!(e[t].type&16||this.isJoinKeyword(e[t].value)===!0)}static parseJoinClause(e,t){let n=t,r=e[n].value===","?"cross join":e[n].value;n++;let i=this.parseLateral(e,n),s=i.value;n=i.newIndex;let o=Ye.parseFromLexeme(e,n);if(n=o.newIndex,n<e.length){let u=Fn.tryParse(e,n);if(u)return{value:new fe(r,o.value,u.value,s),newIndex:u.newIndex};let c=Bn.tryParse(e,n);if(c)return{value:new fe(r,o.value,c.value,s),newIndex:c.newIndex}}return{value:new fe(r,o.value,null,s),newIndex:n}}};var Ot=class{static collectClauseComments(e,t,n){if(t>=e.length||e[t].value.toLowerCase()!==n.toLowerCase())return null;let r=[];e[t].comments&&r.push(...e[t].comments);let i=t-1;for(;i>=0;){let s=e[i];if(s.comments&&s.comments.length>0){let o=s.comments.filter(l=>{let u=l.toLowerCase();return u.includes(n.toLowerCase())||u.includes("\u306E")||u.includes("\u30B3\u30E1\u30F3\u30C8")});o.length>0&&(r.unshift(...o),s.comments=s.comments.filter(l=>!o.includes(l)),s.comments.length===0&&(s.comments=null));break}if(this.isSignificantSqlKeyword(s.value))break;i--}return r.length>0?r:null}static isSignificantSqlKeyword(e){return new Set(["select","from","where","group by","having","order by","limit","offset"]).has(e.toLowerCase())}};var $n=class{static parse(e){let n=new O(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=Ot.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=Ye.parseFromLexeme(e,n);n=i.newIndex;let s=Vn.tryParse(e,n);if(n=s?.newIndex||n,s!==null){let o=new J(i.value,s.value);return o.comments=r,{value:o,newIndex:n}}else{let o=new J(i.value,null);return o.comments=r,{value:o,newIndex:n}}}};var Mn=class{static parse(e){let n=new O(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=Ot.collectClauseComments(e,n,"where");if(e[n].value!=="where")throw new Error(`Syntax error at position ${n}: Expected 'WHERE' keyword but found "${e[n].value}". WHERE clauses must start with the WHERE keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'WHERE' keyword. The WHERE clause requires a condition expression.");let i=k.parseFromLexeme(e,n),s=new se(i.value);return s.comments=r,{value:s,newIndex:i.newIndex}}};var Wn=class{static parse(e){let n=new O(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The GROUP BY clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="group by")throw new Error(`Syntax error at position ${n}: Expected 'GROUP BY' keyword but found "${e[n].value}". GROUP BY clauses must start with the GROUP BY keywords.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'GROUP BY' keyword. The GROUP BY clause requires at least one expression to group by.");let r=[],i=this.parseItem(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=this.parseItem(e,n);r.push(s.value),n=s.newIndex}if(r.length===0)throw new Error(`Syntax error at position ${t}: No grouping expressions found. The GROUP BY clause requires at least one expression to group by.`);return{value:new me(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 jn=class{static parse(e){let n=new O(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 de(r.value),newIndex:r.newIndex}}};var Dn=class{static parse(e){let n=new O(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The WINDOW clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="window")throw new Error(`Syntax error at position ${n}: Expected 'WINDOW' keyword but found "${e[n].value}". WINDOW clauses must start with the WINDOW keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'WINDOW' keyword. The WINDOW clause requires at least one window definition.");let r=[];for(;n<e.length;){if(n>=e.length||e[n].type!==64)throw new Error("Syntax error: Expected window name after 'WINDOW' keyword.");let i=e[n].value;if(n++,n>=e.length||e[n].value!=="as")throw new Error(`Syntax error at position ${n}: Expected 'AS' keyword after window name.`);n++;let s=Pt.parseFromLexeme(e,n);if(n=s.newIndex,r.push(new Pe(i,s.value)),n<e.length&&e[n].type&16)n++;else break}if(r.length===0)throw new Error("At least one WINDOW clause is required after WINDOW keyword.");return{value:new nt(r),newIndex:n}}};var Un=class{static parse(e){let n=new O(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The LIMIT clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="limit")throw new Error(`Syntax error at position ${n}: Expected 'LIMIT' keyword but found "${e[n].value}". LIMIT clauses must start with the LIMIT keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'LIMIT' keyword. The LIMIT clause requires a numeric expression.");let r=k.parseFromLexeme(e,n);return n=r.newIndex,{value:new oe(r.value),newIndex:n}}};var Jn=class{static parse(e){let n=new O(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The FOR clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].value.toLowerCase()!=="for")throw new Error(`Syntax error at position ${n}: Expected 'FOR' keyword but found "${e[n].value}". FOR clauses must start with the FOR keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FOR' keyword. The FOR clause requires a lock mode specification.");let r=e[n].value,i;switch(r){case"update":i="update",n++;break;case"share":i="share",n++;break;case"key share":i="key share",n++;break;case"no key update":i="no key update",n++;break;default:throw new Error(`Syntax error at position ${n}: Invalid lock mode "${r}". Valid lock modes are: UPDATE, SHARE, KEY SHARE, NO KEY UPDATE.`)}return{value:new Ne(i),newIndex:n}}};var Yt=class{static parse(e){let n=new O(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The CommonTable definition is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=n<e.length?e[n].comments:null,i=St.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length&&e[n].value!=="as")throw new Error(`Syntax error at position ${n}: Expected 'AS' keyword after CTE name but found "${e[n].value}".`);n++;let s=null;if(n<e.length){let c=e[n].value;c==="materialized"?(s=!0,n++):c==="not materialized"&&(s=!1,n++)}if(n<e.length&&e[n].type!==4)throw new Error(`Syntax error at position ${n}: Expected '(' after CTE name but found "${e[n].value}".`);let o=e[n].comments;n++;let l=A.parseFromLexeme(e,n);if(n=l.newIndex,o&&o.length>0&&(l.value.comments?l.value.comments=[...o,...l.value.comments]:l.value.comments=o),n<e.length&&e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected ')' after CTE query but found "${e[n].value}".`);n++;let u=new ne(l.value,i.value,s);return u.comments=r,{value:u,newIndex:n}}};var Ft=class{static parse(e){let n=new O(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The WITH clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=n<e.length?e[n].comments:null;if(n<e.length&&e[n].value.toLowerCase()==="with")n++;else throw new Error(`Syntax error at position ${n}: Expected WITH keyword.`);let i=n<e.length&&e[n].value.toLowerCase()==="recursive";i&&n++;let s=[],o=Yt.parseFromLexeme(e,n);for(s.push(o.value),n=o.newIndex;n<e.length&&e[n].type&16;){n++;let u=Yt.parseFromLexeme(e,n);s.push(u.value),n=u.newIndex}let l=new ae(i,s);return l.comments=r,{value:l,newIndex:n}}};var Kn=class{static parse(e){let n=new O(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 o=this.parseTuple(e,n);r.push(o.value),n=o.newIndex}return{value:new Ce(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 Ie([]),newIndex:n};let i=k.parseFromLexeme(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after comma in tuple expression.");let s=k.parseFromLexeme(e,n);r.push(s.value),n=s.newIndex}if(n>=e.length||e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected closing parenthesis but found "${n<e.length?e[n].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);return n++,{value:new Ie(r),newIndex:n}}};var _n=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=gr.parseFromLexeme(e,n),i=r.value;return n=r.newIndex,{value:new Ue(i),newIndex:n}}},gr=class{static parseFromLexeme(e,t){let n=t,r,i=e[n].value;if(i==="first")r="first";else if(i==="next")r="next";else throw new Error(`Syntax error at position ${n}: Expected 'FIRST' or 'NEXT' after 'FETCH' but found "${e[n].value}".`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT'.");let s=null,o=null;if(e[n].value==="row only"||e[n].value==="rows only")return s=new Z(1),o="rows only",n++,{value:new gt(r,s,o),newIndex:n};let l=k.parseFromLexeme(e,n);if(s=l.value,n=l.newIndex,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT <count>'.");if(e[n].value==="rows only"?(o="rows only",n++):e[n].value==="percent"?(o="percent",n++):e[n].value==="percent with ties"&&(o="percent with ties",n++),!o)throw new Error("Syntax error: Expected 'ROWS ONLY', 'PERCENT', or 'PERCENT WITH TIES' after 'FETCH FIRST|NEXT <count>'.");return{value:new gt(r,s,o),newIndex:n}}};var zn=class{static parse(e){let n=new O(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 Oe(r.value),newIndex:n}}};var Le=class{static{this.SQL_COMMANDS=new Set(["select","from","where","and","or","order","by","group","having","limit","offset","as","on","inner","left","right","join","union","insert","update","delete","into","values","set"])}static findLexemeAtLineColumn(e,t){let n=this.lineColumnToCharOffset(e,t);return n===-1?null:this.findLexemeAtPosition(e,n)}static findLexemeAtPosition(e,t){if(t<0||t>=e.length)return null;let n=this.getAllLexemesWithPosition(e);for(let r of n)if(r.position&&t>=r.position.startPosition&&t<r.position.endPosition)return r;return null}static getAllLexemesWithPosition(e){if(!e?.trim())return[];try{let t=[],n=0;for(;n<e.length&&(n=this.skipWhitespaceAndComments(e,n),!(n>=e.length));){let r=this.parseNextToken(e,n);r?(t.push(r),n=r.position.endPosition):n++}return t}catch{return[]}}static skipWhitespaceAndComments(e,t){return le.readWhiteSpaceAndComment(e,t).position}static parseNextToken(e,t){let n=e[t];return n==="'"||n==='"'?this.parseStringLiteral(e,t):/[=<>!+\-*/%().*]/.test(n)?this.parseOperator(e,t):n===","?this.createLexeme(16,",",t,t+1):/[a-zA-Z0-9_]/.test(n)?this.parseWordToken(e,t):null}static parseStringLiteral(e,t){let n=e[t],r=t+1,i=n;for(;r<e.length&&e[r]!==n;)i+=e[r++];return r<e.length&&(i+=e[r++]),this.createLexeme(1,i,t,r)}static parseOperator(e,t){let n=e[t],r=t+1;r<e.length&&/[=<>!]/.test(e[r])&&/[=<>!]/.test(n)&&(n+=e[r++]);let i=this.getOperatorTokenType(n);return this.createLexeme(i,n,t,r)}static parseWordToken(e,t){let n=t,r="";for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)r+=e[n++];let i=this.getWordTokenType(r,e,n),s=this.shouldLowercase(i)?r.toLowerCase():r;return this.createLexeme(i,s,t,n)}static getOperatorTokenType(e){switch(e){case"(":return 4;case")":return 8;case"*":return 64;default:return 2}}static getWordTokenType(e,t,n){let r=e.toLowerCase();if(this.SQL_COMMANDS.has(r))return 128;let i=this.skipWhitespaceAndComments(t,n);return i<t.length&&t[i]==="("?2048:64}static shouldLowercase(e){return!!(e&128)||!!(e&2)||!!(e&2048)}static createLexeme(e,t,n,r){return{type:e,value:t,comments:null,position:{startPosition:n,endPosition:r}}}static lineColumnToCharOffset(e,t){if(t.line<1||t.column<1)return-1;let n=e.split(`
17
+ Detected column names: [${n.join(", ")}]`);let o=Ye.parse(t);return new ot({insertClause:new ct(o,n),selectQuery:e})}static buildUpdateQuery(e,t,n,r){let i=new It(Ye.parse(n)),s=Array.isArray(r)?r:[r],l=new Ke().collect(e),c=new X().collect(e);new At().execute(e);for(let k of s)if(!l.some(x=>x.name===k))throw new Error(`Primary key column '${k}' is not present in selectQuery select list.`);let m=i.getSourceAliasName();if(!m)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let g=l.filter(k=>!s.includes(k.name)).map(k=>new ut(k.name,new b(m,k.name))),h=new at(g),W=new J(e.toSource(t),null),G=null;for(let k of s){let x=new S(new b(m,k),"=",new b(t,k));G=G?new S(G,"and",x):x}let E=new se(G);return new Nt({updateClause:i,setClause:h,fromClause:W,whereClause:E,withClause:c.length>0?new ae(!1,c):void 0})}};var st=class{static set(e,t,n){let r=mt.collect(e),i=!1;for(let s of r)s.name.value===t&&(s.value=n,i=!0);if(!i)throw new Error(`Parameter '${t}' not found in query.`)}};var C=class extends v{constructor(t){super();this.__selectQueryType="SelectQuery";this.headerComments=null;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 We.buildBinaryQuery([this,n],t)}appendWhereRaw(t){let n=I.parse(t);this.appendWhere(n)}appendWhere(t){this.whereClause?this.whereClause.condition=new S(this.whereClause.condition,"and",t):this.whereClause=new se(t)}appendHavingRaw(t){let n=I.parse(t);this.appendHaving(n)}appendHaving(t){this.havingClause?this.havingClause.condition=new S(this.havingClause.condition,"and",t):this.havingClause=new de(t)}innerJoinRaw(t,n,r,i=null){this.joinSourceRaw("inner join",t,n,r,i)}leftJoinRaw(t,n,r,i=null){this.joinSourceRaw("left join",t,n,r,i)}rightJoinRaw(t,n,r,i=null){this.joinSourceRaw("right join",t,n,r,i)}innerJoin(t,n,r=null){this.joinSource("inner join",t,n,r)}leftJoin(t,n,r=null){this.joinSource("left join",t,n,r)}rightJoin(t,n,r=null){this.joinSource("right join",t,n,r)}joinSourceRaw(t,n,r,i,s=null){let o=wt.parse(n),l=new B(o,new re(r,null));this.joinSource(t,l,i,s)}joinSource(t,n,r,i=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let s=Array.isArray(r)?r:[r],l=new xe(i).collect(this),u=null,c=0,p=n.getAliasName();if(!p)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let g of l)if(s.some(h=>h==g.name)){let h=new S(g.value,"=",new b([p],g.name));u?u=new S(u,"and",h):u=h,c++}if(!u||c!==s.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${s.join(", ")}`);let m=new he(u),f=new fe(t,n,m,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(f):this.fromClause.joins=[f]),it.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 B(new j(this),new re(t,null))}appendWith(t){let n=Array.isArray(t)?t:[t];this.withClause?this.withClause.tables.push(...n):this.withClause=new ae(!1,n),it.normalize(this)}appendWithRaw(t,n){let r=A.parse(t),i=new ne(r,n,null);this.appendWith(i)}overrideSelectItemExpr(t,n){let r=this.selectClause.items.filter(u=>u.identifier?.name===t);if(r.length===0)throw new Error(`Column ${t} not found in the query`);if(r.length>1)throw new Error(`Duplicate column name ${t} found in the query`);let i=r[0],o=new dt().visit(i.value),l=n(o);i.value=I.parse(l)}appendWhereExpr(t,n,r){if(r&&r.upstream){let s=new Ot().find(this,[t]),o=new xe,l=new dt;for(let u of s){let c=o.collect(u).filter(m=>m.name===t).map(m=>m.value);if(c.length!==1)throw new Error(`Expected exactly one expression for column '${t}'`);let p=l.format(c[0]);u.appendWhereRaw(n(p))}}else{let i=new xe,s=new dt,o=i.collect(this).filter(u=>u.name===t).map(u=>u.value);if(o.length!==1)throw new Error(`Expected exactly one expression for column '${t}'`);let l=s.format(o[0]);this.appendWhereRaw(n(l))}}setParameter(t,n){return st.set(this,t,n),this}toSimpleQuery(){return this}addCTE(t,n,r){if(!t||t.trim()==="")throw new Qt(t,"name cannot be empty or whitespace-only");if(this.hasCTE(t))throw new Gt(t);let i=r?.materialized??null,s=new ne(n,t,i);return this.appendWith(s),this.cteNameCache.add(t),this}removeCTE(t){if(!this.hasCTE(t))throw new Ht(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 Qt(t,"name cannot be empty or whitespace-only");this.hasCTE(t)&&this.removeCTE(t);let i=r?.materialized??null,s=new ne(n,t,i);return this.appendWith(s),this.cteNameCache.add(t),this}};var Q=class a extends v{constructor(t,n,r){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.left=t,this.operator=new $(n),this.right=r}static{this.kind=Symbol("BinarySelectQuery")}union(t){return this.appendSelectQuery("union",t)}unionAll(t){return this.appendSelectQuery("union all",t)}intersect(t){return this.appendSelectQuery("intersect",t)}intersectAll(t){return this.appendSelectQuery("intersect all",t)}except(t){return this.appendSelectQuery("except",t)}exceptAll(t){return this.appendSelectQuery("except all",t)}appendSelectQuery(t,n){return this.left=new a(this.left,this.operator.value,this.right),this.operator=new $(t),this.right=n,it.normalize(this),this}unionRaw(t){let n=A.parse(t);return this.union(n)}unionAllRaw(t){let n=A.parse(t);return this.unionAll(n)}intersectRaw(t){let n=A.parse(t);return this.intersect(n)}intersectAllRaw(t){let n=A.parse(t);return this.intersectAll(n)}exceptRaw(t){let n=A.parse(t);return this.except(n)}exceptAllRaw(t){let n=A.parse(t);return this.exceptAll(n)}toSource(t="subq"){return new B(new j(this),new re(t,null))}setParameter(t,n){return st.set(this,t,n),this}toSimpleQuery(){return We.buildSimpleQuery(this)}};var Ce=class extends v{constructor(t,n=null){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.tuples=t,this.columnAliases=n}static{this.kind=Symbol("ValuesQuery")}toSimpleQuery(){return We.buildSimpleQuery(this)}setParameter(t,n){return st.set(this,t,n),this}};var On=class{static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The SELECT clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=null,i=n<e.length?e[n].comments:null;if(e[n].value!=="select")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword but found "${e[n].value}". SELECT clauses must start with the SELECT keyword.`);n++;let s=[];for(;n<e.length&&pt.isHintClause(e[n].value);){let u=pt.extractHintContent(e[n].value);s.push(new pt(u)),n++}if(n<e.length&&e[n].value==="distinct")n++,r=new Tt;else if(n<e.length&&e[n].value==="distinct on"){n++;let u=I.parseArgument(4,8,e,n);r=new kt(u.value),n=u.newIndex}let o=[],l=Rn.parseItem(e,n);for(o.push(l.value),n=l.newIndex;n<e.length&&e[n].type&16;){n++;let u=Rn.parseItem(e,n);o.push(u.value),n=u.newIndex}if(o.length===0)throw new Error(`Syntax error at position ${t}: No select items found. The SELECT clause requires at least one expression to select.`);{let u=new _(o,r,s);return u.comments=i,{value:u,newIndex:n}}}},Rn=class{static parse(e){let n=new R(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=I.parseFromLexeme(e,n),i=r.value;if(n=r.newIndex,n<e.length&&e[n].value==="as"&&n++,n<e.length&&e[n].type&64){let s=e[n].value,o=e[n].comments;n++;let l=new z(i,s);return o&&o.length>0&&(l.comments=o),{value:l,newIndex:n}}else if(i instanceof b&&i.column.name!=="*")return{value:new z(i,i.column.name),newIndex:n};return{value:new z(i),newIndex:n}}};var Fn=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="on"){n++;let r=I.parseFromLexeme(e,n);return n=r.newIndex,{value:new he(r.value),newIndex:n}}return null}};var Bn=class{static tryParse(e,t){let n=t;if(n<e.length&&e[n].value==="using"){n++;let r=I.parseArgument(4,8,e,n),i=r.value;return n=r.newIndex,{value:new Se(i),newIndex:n}}return null}};var Vn=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!!Kt.parse(e,0)}static parseLateral(e,t){let n=t;return n<e.length&&e[n].value==="lateral"?(n++,{value:!0,newIndex:n}):{value:!1,newIndex:n}}static isJoinCommand(e,t){return t>=e.length?!1:!!(e[t].type&16||this.isJoinKeyword(e[t].value)===!0)}static parseJoinClause(e,t){let n=t,r=e[n].value===","?"cross join":e[n].value;n++;let i=this.parseLateral(e,n),s=i.value;n=i.newIndex;let o=Ye.parseFromLexeme(e,n);if(n=o.newIndex,n<e.length){let u=Fn.tryParse(e,n);if(u)return{value:new fe(r,o.value,u.value,s),newIndex:u.newIndex};let c=Bn.tryParse(e,n);if(c)return{value:new fe(r,o.value,c.value,s),newIndex:c.newIndex}}return{value:new fe(r,o.value,null,s),newIndex:n}}};var Rt=class{static collectClauseComments(e,t,n){if(t>=e.length||e[t].value.toLowerCase()!==n.toLowerCase())return null;let r=[];e[t].comments&&r.push(...e[t].comments);let i=t-1;for(;i>=0;){let s=e[i];if(s.comments&&s.comments.length>0){let o=s.comments.filter(l=>{let u=l.toLowerCase();return u.includes(n.toLowerCase())||u.includes("\u306E")||u.includes("\u30B3\u30E1\u30F3\u30C8")});o.length>0&&(r.unshift(...o),s.comments=s.comments.filter(l=>!o.includes(l)),s.comments.length===0&&(s.comments=null));break}if(this.isSignificantSqlKeyword(s.value))break;i--}return r.length>0?r:null}static isSignificantSqlKeyword(e){return new Set(["select","from","where","group by","having","order by","limit","offset"]).has(e.toLowerCase())}};var $n=class{static parse(e){let n=new R(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=Rt.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=Ye.parseFromLexeme(e,n);n=i.newIndex;let s=Vn.tryParse(e,n);if(n=s?.newIndex||n,s!==null){let o=new J(i.value,s.value);return o.comments=r,{value:o,newIndex:n}}else{let o=new J(i.value,null);return o.comments=r,{value:o,newIndex:n}}}};var Mn=class{static parse(e){let n=new R(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=Rt.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=I.parseFromLexeme(e,n),s=new se(i.value);return s.comments=r,{value:s,newIndex:i.newIndex}}};var Wn=class{static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The GROUP BY clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="group by")throw new Error(`Syntax error at position ${n}: Expected 'GROUP BY' keyword but found "${e[n].value}". GROUP BY clauses must start with the GROUP BY keywords.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'GROUP BY' keyword. The GROUP BY clause requires at least one expression to group by.");let r=[],i=this.parseItem(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=this.parseItem(e,n);r.push(s.value),n=s.newIndex}if(r.length===0)throw new Error(`Syntax error at position ${t}: No grouping expressions found. The GROUP BY clause requires at least one expression to group by.`);return{value:new me(r),newIndex:n}}static parseItem(e,t){let n=t,r=I.parseFromLexeme(e,n),i=r.value;return n=r.newIndex,{value:i,newIndex:n}}};var jn=class{static parse(e){let n=new R(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=I.parseFromLexeme(e,n);return{value:new de(r.value),newIndex:r.newIndex}}};var Dn=class{static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The WINDOW clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="window")throw new Error(`Syntax error at position ${n}: Expected 'WINDOW' keyword but found "${e[n].value}". WINDOW clauses must start with the WINDOW keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'WINDOW' keyword. The WINDOW clause requires at least one window definition.");let r=[];for(;n<e.length;){if(n>=e.length||e[n].type!==64)throw new Error("Syntax error: Expected window name after 'WINDOW' keyword.");let i=e[n].value;if(n++,n>=e.length||e[n].value!=="as")throw new Error(`Syntax error at position ${n}: Expected 'AS' keyword after window name.`);n++;let s=Pt.parseFromLexeme(e,n);if(n=s.newIndex,r.push(new Pe(i,s.value)),n<e.length&&e[n].type&16)n++;else break}if(r.length===0)throw new Error("At least one WINDOW clause is required after WINDOW keyword.");return{value:new nt(r),newIndex:n}}};var Un=class{static parse(e){let n=new R(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=I.parseFromLexeme(e,n);return n=r.newIndex,{value:new oe(r.value),newIndex:n}}};var Jn=class{static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The FOR clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].value.toLowerCase()!=="for")throw new Error(`Syntax error at position ${n}: Expected 'FOR' keyword but found "${e[n].value}". FOR clauses must start with the FOR keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FOR' keyword. The FOR clause requires a lock mode specification.");let r=e[n].value,i;switch(r){case"update":i="update",n++;break;case"share":i="share",n++;break;case"key share":i="key share",n++;break;case"no key update":i="no key update",n++;break;default:throw new Error(`Syntax error at position ${n}: Invalid lock mode "${r}". Valid lock modes are: UPDATE, SHARE, KEY SHARE, NO KEY UPDATE.`)}return{value:new Ne(i),newIndex:n}}};var Yt=class{static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The CommonTable definition is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=n<e.length?e[n].comments:null,i=St.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length&&e[n].value!=="as")throw new Error(`Syntax error at position ${n}: Expected 'AS' keyword after CTE name but found "${e[n].value}".`);n++;let s=null;if(n<e.length){let p=e[n].value;p==="materialized"?(s=!0,n++):p==="not materialized"&&(s=!1,n++)}if(n<e.length&&e[n].type!==4)throw new Error(`Syntax error at position ${n}: Expected '(' after CTE name but found "${e[n].value}".`);let o=e[n].comments;n++;let l=A.parseFromLexeme(e,n);if(n=l.newIndex,o&&o.length>0&&(l.value.comments?l.value.comments=[...o,...l.value.comments]:l.value.comments=o),n<e.length&&e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected ')' after CTE query but found "${e[n].value}".`);let u=e[n].comments;n++;let c=new ne(l.value,i.value,s);return c.comments=r,{value:c,newIndex:n,trailingComments:u&&u.length>0?u:null}}};var Ft=class{static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The WITH clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t,r=n<e.length?e[n].comments:null,i=null,s=null;if(r&&r.length>0&&(i=[...r],s=null),n<e.length&&e[n].value.toLowerCase()==="with")n++;else throw new Error(`Syntax error at position ${n}: Expected WITH keyword.`);let o=n<e.length&&e[n].value.toLowerCase()==="recursive";o&&n++;let l=[],u=Yt.parseFromLexeme(e,n);l.push(u.value),n=u.newIndex;let c=[];for(u.trailingComments&&c.push(...u.trailingComments);n<e.length&&e[n].type&16;){n++;let m=Yt.parseFromLexeme(e,n);l.push(m.value),n=m.newIndex,m.trailingComments&&c.push(...m.trailingComments)}let p=new ae(o,l);return p.comments=s,c.length>0&&(p.trailingComments=c),{value:p,newIndex:n,headerComments:i}}};var Kn=class{static parse(e){let n=new R(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 o=this.parseTuple(e,n);r.push(o.value),n=o.newIndex}return{value:new Ce(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 Ie([]),newIndex:n};let i=I.parseFromLexeme(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after comma in tuple expression.");let s=I.parseFromLexeme(e,n);r.push(s.value),n=s.newIndex}if(n>=e.length||e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected closing parenthesis but found "${n<e.length?e[n].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);return n++,{value:new Ie(r),newIndex:n}}};var _n=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=gr.parseFromLexeme(e,n),i=r.value;return n=r.newIndex,{value:new Ue(i),newIndex:n}}},gr=class{static parseFromLexeme(e,t){let n=t,r,i=e[n].value;if(i==="first")r="first";else if(i==="next")r="next";else throw new Error(`Syntax error at position ${n}: Expected 'FIRST' or 'NEXT' after 'FETCH' but found "${e[n].value}".`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT'.");let s=null,o=null;if(e[n].value==="row only"||e[n].value==="rows only")return s=new Z(1),o="rows only",n++,{value:new gt(r,s,o),newIndex:n};let l=I.parseFromLexeme(e,n);if(s=l.value,n=l.newIndex,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT <count>'.");if(e[n].value==="rows only"?(o="rows only",n++):e[n].value==="percent"?(o="percent",n++):e[n].value==="percent with ties"&&(o="percent with ties",n++),!o)throw new Error("Syntax error: Expected 'ROWS ONLY', 'PERCENT', or 'PERCENT WITH TIES' after 'FETCH FIRST|NEXT <count>'.");return{value:new gt(r,s,o),newIndex:n}}};var zn=class{static parse(e){let n=new R(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=I.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 Le=class{static{this.SQL_COMMANDS=new Set(["select","from","where","and","or","order","by","group","having","limit","offset","as","on","inner","left","right","join","union","insert","update","delete","into","values","set"])}static findLexemeAtLineColumn(e,t){let n=this.lineColumnToCharOffset(e,t);return n===-1?null:this.findLexemeAtPosition(e,n)}static findLexemeAtPosition(e,t){if(t<0||t>=e.length)return null;let n=this.getAllLexemesWithPosition(e);for(let r of n)if(r.position&&t>=r.position.startPosition&&t<r.position.endPosition)return r;return null}static getAllLexemesWithPosition(e){if(!e?.trim())return[];try{let t=[],n=0;for(;n<e.length&&(n=this.skipWhitespaceAndComments(e,n),!(n>=e.length));){let r=this.parseNextToken(e,n);r?(t.push(r),n=r.position.endPosition):n++}return t}catch{return[]}}static skipWhitespaceAndComments(e,t){return le.readWhiteSpaceAndComment(e,t).position}static parseNextToken(e,t){let n=e[t];return n==="'"||n==='"'?this.parseStringLiteral(e,t):/[=<>!+\-*/%().*]/.test(n)?this.parseOperator(e,t):n===","?this.createLexeme(16,",",t,t+1):/[a-zA-Z0-9_]/.test(n)?this.parseWordToken(e,t):null}static parseStringLiteral(e,t){let n=e[t],r=t+1,i=n;for(;r<e.length&&e[r]!==n;)i+=e[r++];return r<e.length&&(i+=e[r++]),this.createLexeme(1,i,t,r)}static parseOperator(e,t){let n=e[t],r=t+1;r<e.length&&/[=<>!]/.test(e[r])&&/[=<>!]/.test(n)&&(n+=e[r++]);let i=this.getOperatorTokenType(n);return this.createLexeme(i,n,t,r)}static parseWordToken(e,t){let n=t,r="";for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)r+=e[n++];let i=this.getWordTokenType(r,e,n),s=this.shouldLowercase(i)?r.toLowerCase():r;return this.createLexeme(i,s,t,n)}static getOperatorTokenType(e){switch(e){case"(":return 4;case")":return 8;case"*":return 64;default:return 2}}static getWordTokenType(e,t,n){let r=e.toLowerCase();if(this.SQL_COMMANDS.has(r))return 128;let i=this.skipWhitespaceAndComments(t,n);return i<t.length&&t[i]==="("?2048:64}static shouldLowercase(e){return!!(e&128)||!!(e&2)||!!(e&2048)}static createLexeme(e,t,n,r){return{type:e,value:t,comments:null,position:{startPosition:n,endPosition:r}}}static lineColumnToCharOffset(e,t){if(t.line<1||t.column<1)return-1;let n=e.split(`
18
18
  `);if(t.line>n.length)return-1;let r=n[t.line-1];if(t.column>r.length+1)return-1;let i=0;for(let s=0;s<t.line-1;s++)i+=n[s].length+1;return i+=t.column-1,i}static charOffsetToLineColumn(e,t){if(t<0||t>e.length)return null;let n=e.split(`
19
19
  `),r=0;for(let i=0;i<n.length;i++){let s=n[i].length;if(t<r+s)return{line:i+1,column:t-r+1};if(t===r+s&&i<n.length-1)return{line:i+2,column:1};r+=s+1}if(t===e.length){let i=n[n.length-1];return{line:n.length,column:i.length+1}}return null}};var ht=class{static analyzeCursorPosition(e,t){let n=this.extractCTERegions(e),i=this.calculateExtendedCTEBoundaries(e,n).find(s=>t>=s.startPosition&&t<s.extendedEndPosition);return i?{isInCTE:!0,cteRegion:{name:i.name,startPosition:i.startPosition,endPosition:i.endPosition,sqlContent:i.sqlContent},executableSQL:i.sqlContent}:{isInCTE:!1,cteRegion:null,executableSQL:this.extractMainQuery(e,n)}}static getCursorCte(e,t){try{let n=this.analyzeCursorPosition(e,t);return n.isInCTE&&n.cteRegion?.name||null}catch{return null}}static getCursorCteAt(e,t,n){try{let r=this.lineColumnToPosition(e,t,n);return r===-1?null:this.getCursorCte(e,r)}catch{return null}}static lineColumnToPosition(e,t,n){if(t<1||n<1)return-1;let r=e.split(`
20
20
  `);if(t>r.length)return-1;let i=r[t-1];if(n>i.length+1)return-1;let s=0;for(let o=0;o<t-1;o++)s+=r[o].length+1;return s+=n-1,s}static positionToLineColumn(e,t){if(t<0||t>e.length)return null;let r=e.substring(0,t).split(`
21
- `);return{line:r.length,column:r[r.length-1].length+1}}static extractCTERegions(e){let t=Le.getAllLexemesWithPosition(e),n=[],r=0,i=!1;for(;r<t.length;){let s=t[r];if(s.value.toLowerCase()==="with"&&!i){i=!0,r++;continue}if(i&&s.value.toLowerCase()==="recursive"){r++;continue}if(i&&s.type===64&&r+1<t.length&&t[r+1].value.toLowerCase()==="as"){let o=s.value,l=s.position.startPosition,u=r+2;for(;u<t.length&&t[u].value!=="(";)u++;if(u<t.length){let c=this.findMatchingParen(t,u);if(c){let p=c.endPosition,d=this.extractCTESQL(e,t,u,c.index);n.push({name:o,startPosition:l,endPosition:p,sqlContent:d}),r=c.index+1;continue}}}if(i&&s.value.toLowerCase()==="select"&&this.isMainQuerySelect(t,r))break;r++}return n}static findMatchingParen(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){if(e[r].value==="("?n++:e[r].value===")"&&n--,n===0)return{index:r,endPosition:e[r].position.endPosition};r++}return null}static extractCTESQL(e,t,n,r){let i=t[n+1].position.startPosition,s=t[r-1].position.endPosition;return e.substring(i,s).trim()}static isMainQuerySelect(e,t){let n=0;for(let r=t-1;r>=0;r--)e[r].value===")"?n++:e[r].value==="("&&n--;return n===0}static calculateExtendedCTEBoundaries(e,t){return t.length===0?[]:t.map((n,r)=>{let i;return r<t.length-1?i=t[r+1].startPosition:i=this.findMainQueryStart(e,n.endPosition),{...n,extendedEndPosition:i}})}static findMainQueryStart(e,t){let n=t;for(;n<e.length;){if(e.substring(n).toLowerCase().trim().startsWith("select")){let i=e.toLowerCase().indexOf("select",n);return i!==-1?i:n}n++}return e.length}static extractMainQuery(e,t){if(t.length===0)return e.trim();let i=t[t.length-1].endPosition;for(;i<e.length&&!e.substring(i).toLowerCase().trim().startsWith("select");)i++;return e.substring(i).trim()}static getCTEPositions(e){let t=this.extractCTERegions(e),n=[];if(t.forEach(r=>{n.push({name:r.name,startPosition:r.startPosition,type:"CTE"})}),t.length>0){let i=t[t.length-1].endPosition;for(;i<e.length;){if(e.substring(i).toLowerCase().trim().startsWith("select")){n.push({name:"MAIN_QUERY",startPosition:i,type:"MAIN_QUERY"});break}i++}}else n.push({name:"MAIN_QUERY",startPosition:0,type:"MAIN_QUERY"});return n}};var A=class{static parse(e){let n=new O(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 calculateCharacterPosition(e,t,n){if(n>=t.length)return e.length;let r=t[n];if(r.position?.startPosition!==void 0)return r.position.startPosition;let i=0;for(let l=0;l<n;l++){let u=t[l].value,c=e.indexOf(u,i);c!==-1&&(i=c+u.length)}let s=t[n].value,o=e.indexOf(s,i);return o!==-1?o:i}static analyze(e){let t=[];try{t=new O(e).readLexmes();let r=this.parseFromLexeme(t,0);if(r.newIndex<t.length){let i=t.slice(r.newIndex).map(l=>l.value),s=t[r.newIndex],o=this.calculateCharacterPosition(e,t,r.newIndex);return{success:!1,query:r.value,error:`Syntax error: Unexpected token "${s.value}" at character position ${o}. The SELECT query is complete but there are additional tokens.`,errorPosition:o,remainingTokens:i}}return{success:!0,query:r.value}}catch(n){let r,i=n instanceof Error?n.message:String(n),s=i.match(/position (\d+)/);if(s){let o=parseInt(s[1],10);r=this.calculateCharacterPosition(e,t,o)}return{success:!1,error:i,errorPosition:r}}}static async parseAsync(e){return Promise.resolve(this.parse(e))}static{this.unionCommandSet=new Set(["union","union all","intersect","intersect all","except","except all"])}static{this.selectCommandSet=new Set(["with","select"])}static parseFromLexeme(e,t){let n=t;if(n>=e.length)throw new Error(`Syntax error: Unexpected end of input at position ${t}.`);let r=e[n].value;if(!this.selectCommandSet.has(r)&&r!=="values")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' or 'VALUES' keyword but found "${e[n].value}".`);let i=this.selectCommandSet.has(r)?this.parseSimpleSelectQuery(e,n):this.parseValuesQuery(e,n),s=i.value;for(n=i.newIndex;n<e.length&&this.unionCommandSet.has(e[n].value.toLowerCase());){let o=e[n],l=o.value.toLowerCase(),u=o.comments;if(n++,n>=e.length)throw new Error(`Syntax error at position ${n}: Expected a query after '${l.toUpperCase()}' but found end of input.`);let c=e[n].value.toLowerCase();if(this.selectCommandSet.has(c)){let p=this.parseSimpleSelectQuery(e,n),d=new Q(s,l,p.value);u&&u.length>0&&(p.value.comments?p.value.comments=[...u,...p.value.comments]:p.value.comments=u),s=d,n=p.newIndex}else if(c==="values"){let p=this.parseValuesQuery(e,n),d=new Q(s,l,p.value);u&&u.length>0&&(p.value.comments?p.value.comments=[...u,...p.value.comments]:p.value.comments=u),s=d,n=p.newIndex}else throw new Error(`Syntax error at position ${n}: Expected 'SELECT' or 'VALUES' after '${l.toUpperCase()}' but found "${e[n].value}".`)}return{value:s,newIndex:n}}static parseSimpleSelectQuery(e,t){let n=t,r=null;n<e.length&&e[n].value==="with"&&(r=Ft.parseFromLexeme(e,n),n=r.newIndex);let i=n<e.length?e[n].comments:null;if(n>=e.length||e[n].value!=="select")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword but found "${n<e.length?e[n].value:"end of input"}". SELECT queries must start with the SELECT keyword.`);let s=Rn.parseFromLexeme(e,n);n=s.newIndex,i&&s.value.comments&&JSON.stringify(i)===JSON.stringify(s.value.comments)&&(s.value.comments=null);let o=null;n<e.length&&e[n].value==="from"&&(o=$n.parseFromLexeme(e,n),n=o.newIndex);let l=null;n<e.length&&e[n].value==="where"&&(l=Mn.parseFromLexeme(e,n),n=l.newIndex);let u=null;n<e.length&&e[n].value==="group by"&&(u=Wn.parseFromLexeme(e,n),n=u.newIndex);let c=null;n<e.length&&e[n].value==="having"&&(c=jn.parseFromLexeme(e,n),n=c.newIndex);let p=null;n<e.length&&e[n].value==="window"&&(p=Dn.parseFromLexeme(e,n),n=p.newIndex);let d=null;n<e.length&&e[n].value==="order by"&&(d=rt.parseFromLexeme(e,n),n=d.newIndex);let f=null;n<e.length&&e[n].value==="limit"&&(f=Un.parseFromLexeme(e,n),n=f.newIndex);let y=null;n<e.length&&e[n].value==="offset"&&(y=zn.parseFromLexeme(e,n),n=y.newIndex);let h=null;n<e.length&&e[n].value==="fetch"&&(h=_n.parseFromLexeme(e,n),n=h.newIndex);let M=null;n<e.length&&e[n].value.toLowerCase()==="for"&&(M=Jn.parseFromLexeme(e,n),n=M.newIndex);let H=new C({withClause:r?r.value:null,selectClause:s.value,fromClause:o?o.value:null,whereClause:l?l.value:null,groupByClause:u?u.value:null,havingClause:c?c.value:null,orderByClause:d?d.value:null,windowClause:p?p.value:null,limitClause:f?f.value:null,offsetClause:y?y.value:null,fetchClause:h?h.value:null,forClause:M?M.value:null});return H.comments=i,{value:H,newIndex:n}}static parseValuesQuery(e,t){let n=Kn.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}static getCursorCte(e,t){return ht.getCursorCte(e,t)}static getCursorCteAt(e,t,n){return ht.getCursorCteAt(e,t,n)}static positionToLineColumn(e,t){return ht.positionToLineColumn(e,t)}};var Qr=class{static parse(e){let n=new O(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=Ye.parseTableSourceFromLexemes(e,n);n=i.newIndex;let s=[];if(e[n]?.type===4){for(n++;n<e.length&&e[n].type===64&&(s.push(e[n].value),n++,e[n]?.type===16);)n++;if(e[n]?.type!==8)throw new Error(`Syntax error at position ${n}: Expected ')' after column list.`);n++}let o=A.parseFromLexeme(e,n);if(r)if(o.value instanceof C)o.value.withClause=r;else throw new Error("WITH clause is not supported in this context.");return n=o.newIndex,{value:new ot({insertClause:new ct(i.value,s),selectQuery:o.value}),newIndex:n}}};var qn=class{constructor(){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(C.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(Q.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(Ce.kind,e=>this.visitValuesQuery(e)),this.handlers.set(J.kind,e=>this.visitFromClause(e)),this.handlers.set(fe.kind,e=>this.visitJoinClause(e)),this.handlers.set(he.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Se.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(B.kind,e=>this.visitSourceExpression(e)),this.handlers.set(R.kind,e=>this.visitTableSource(e)),this.handlers.set(qe.kind,e=>this.visitFunctionSource(e)),this.handlers.set($e.kind,e=>this.visitParenSource(e)),this.handlers.set(W.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(ge.kind,e=>this.visitInlineQuery(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(me.kind,e=>this.visitGroupByClause(e)),this.handlers.set(de.kind,e=>this.visitHavingClause(e)),this.handlers.set(pe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Pe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Oe.kind,e=>this.visitOffsetClause(e)),this.handlers.set(Ue.kind,e=>this.visitFetchClause(e)),this.handlers.set(Ne.kind,e=>this.visitForClause(e)),this.handlers.set(Ae.kind,e=>this.visitOrderByItem(e)),this.handlers.set(_.kind,e=>this.visitSelectClause(e)),this.handlers.set(z.kind,e=>this.visitSelectItem(e)),this.handlers.set(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(S.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ie.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ke.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(Te.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(we.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(K.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ye.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ve.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(Ie.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ce.kind,e=>this.visitCastExpression(e)),this.handlers.set(U.kind,e=>this.visitValueList(e)),this.handlers.set(je.kind,e=>this.visitStringSpecifierExpression(e))}collect(e){return this.visit(e),this.getTableSources()}getTableSources(){return this.tableSources}reset(){this.tableSources=[],this.tableNameMap.clear(),this.visitedNodes.clear()}getTableIdentifier(e){return e.qualifiedName.namespaces&&e.qualifiedName.namespaces.length>0?e.qualifiedName.namespaces.map(t=>t.name).join(".")+"."+(e.qualifiedName.name instanceof V?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof V?e.qualifiedName.name.value:e.qualifiedName.name.name}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){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.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){for(let t of e.tuples)t.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.tableNameMap.set(t,!0),this.tableSources.push(e))}visitFunctionSource(e){e.argument&&this.visitValueComponent(e.argument)}visitValueComponent(e){e.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)}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 ft=class a{constructor(){this.dependencyGraph=null;this.cteMap=new Map;this.sourceCollector=new He(!1),this.cteReferenceCollector=new qn,this.cteCollector=new X}static{this.ERROR_MESSAGES={NOT_ANALYZED:"Must call analyzeDependencies first",CIRCULAR_REFERENCE:"Circular reference detected in CTE"}}static{this.MAIN_QUERY_NAME="MAIN_QUERY"}analyzeDependencies(e){let t=this.cteCollector.collect(e);return this.buildCTEMap(t),this.dependencyGraph=this.buildDependencyGraph(t,e),this.dependencyGraph}getDependencies(e){this.ensureAnalyzed();let t=this.findNodeByName(e);return t?[...t.dependencies]:[]}getDependents(e){this.ensureAnalyzed();let t=this.findNodeByName(e);return t?[...t.dependents]:[]}getMainQueryDependencies(){this.ensureAnalyzed();let e=this.findNodeByName(a.MAIN_QUERY_NAME);return e?[...e.dependencies]:[]}getNodesByType(e){return this.ensureAnalyzed(),this.dependencyGraph.nodes.filter(t=>t.type===e)}getMainQueryNode(){return this.ensureAnalyzed(),this.findNodeByName(a.MAIN_QUERY_NAME)}hasCircularDependency(){this.ensureAnalyzed();try{return this.getExecutionOrder(),!1}catch(e){if(e instanceof Error&&e.message.includes(a.ERROR_MESSAGES.CIRCULAR_REFERENCE))return!0;throw e}}getExecutionOrder(){this.ensureAnalyzed();let e=new Set,t=new Set,n=[],r=new Map;for(let s of this.dependencyGraph.nodes)r.set(s.name,new Set(s.dependencies));let i=s=>{if(e.has(s))return;if(t.has(s))throw new Error(`${a.ERROR_MESSAGES.CIRCULAR_REFERENCE}: ${s}`);t.add(s);let o=r.get(s)||new Set;for(let l of o)i(l);t.delete(s),e.add(s),n.push(s)};for(let s of this.dependencyGraph.nodes)e.has(s.name)||i(s.name);return n}buildDependencyGraph(e,t){let n=[],r=[],i=new Map,s=new Map;for(let l of e){let u=a.getCTEName(l);i.set(u,new Set),s.set(u,new Set)}i.set(a.MAIN_QUERY_NAME,new Set),s.set(a.MAIN_QUERY_NAME,new Set);for(let l of e){let u=a.getCTEName(l),c=this.sourceCollector.collect(l.query);for(let p of c){let d=p.table.name;this.cteMap.has(d)&&d!==u&&(i.get(u).add(d),s.get(d).add(u),r.push({from:u,to:d}))}}let o=this.getMainQueryWithoutCTE(t);if(o){let l=this.cteReferenceCollector.collect(o);for(let u of l){let c=u.table.name;this.cteMap.has(c)&&(i.get(a.MAIN_QUERY_NAME).add(c),s.get(c).add(a.MAIN_QUERY_NAME),r.push({from:a.MAIN_QUERY_NAME,to:c}))}}for(let l of e){let u=a.getCTEName(l);n.push({name:u,type:"CTE",cte:l,dependencies:Array.from(i.get(u)||new Set),dependents:Array.from(s.get(u)||new Set)})}return n.push({name:a.MAIN_QUERY_NAME,type:"ROOT",cte:null,dependencies:Array.from(i.get(a.MAIN_QUERY_NAME)||new Set),dependents:Array.from(s.get(a.MAIN_QUERY_NAME)||new Set)}),{nodes:n,edges:r}}ensureAnalyzed(){if(!this.dependencyGraph)throw new Error(a.ERROR_MESSAGES.NOT_ANALYZED)}buildCTEMap(e){this.cteMap.clear();for(let t of e){let n=a.getCTEName(t);this.cteMap.set(n,t)}}findNodeByName(e){return this.dependencyGraph?.nodes.find(t=>t.name===e)}getMainQueryWithoutCTE(e){return e.withClause?new C({selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,limitClause:e.limitClause,offsetClause:e.offsetClause,fetchClause:e.fetchClause,forClause:e.forClause,windowClause:e.windowClause}):e}static getCTEName(e){return e.aliasExpression.table.name}};var Gn=class{static addComment(e,t){e.comments||(e.comments=[]),e.comments.push(t)}static editComment(e,t,n){if(!e.comments||t<0||t>=e.comments.length)throw new Error(`Invalid comment index: ${t}. Component has ${e.comments?.length||0} comments.`);e.comments[t]=n}static deleteComment(e,t){if(!e.comments||t<0||t>=e.comments.length)throw new Error(`Invalid comment index: ${t}. Component has ${e.comments?.length||0} comments.`);e.comments.splice(t,1),e.comments.length===0&&(e.comments=null)}static deleteAllComments(e){e.comments=null}static getComments(e){return e.comments||[]}static findComponentsWithComment(e,t,n=!1){let r=[],i=n?t:t.toLowerCase(),s=o=>{o&&o instanceof v&&o.comments&&o.comments.some(l=>(n?l:l.toLowerCase()).includes(i))&&r.push(o);for(let l in o)o[l]&&typeof o[l]=="object"&&(Array.isArray(o[l])?o[l].forEach(s):s(o[l]))};return s(e),r}static replaceInComments(e,t,n,r=!1){let i=0,s=o=>{if(o&&o instanceof v&&o.comments)for(let l=0;l<o.comments.length;l++){let u=o.comments[l],c=r?"g":"gi",p=new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c),d=u.replace(p,n);d!==u&&(o.comments[l]=d,i++)}for(let l in o)o[l]&&typeof o[l]=="object"&&(Array.isArray(o[l])?o[l].forEach(s):s(o[l]))};return s(e),i}static countComments(e){let t=0,n=r=>{r&&r instanceof v&&r.comments&&(t+=r.comments.length);for(let i in r)r[i]&&typeof r[i]=="object"&&(Array.isArray(r[i])?r[i].forEach(n):n(r[i]))};return n(e),t}static getAllComments(e){let t=[],n=r=>{r&&r instanceof v&&r.comments&&r.comments.forEach((i,s)=>{t.push({comment:i,component:r,index:s})});for(let i in r)r[i]&&typeof r[i]=="object"&&(Array.isArray(r[i])?r[i].forEach(n):n(r[i]))};return n(e),t}};var lt=class{constructor(e,t){this.name=e,this.columns=t}},Bt=class{constructor(e=null,t=!1){this.tableColumnResolver=e;this.allowWildcardWithoutResolver=t;this.tableSchemas=[];this.visitedNodes=new Set;this.commonTables=[];this.running=!1;this.unresolvedColumns=[];this.analysisError=void 0;this.isAnalyzeMode=!1;this.handlers=new Map,this.handlers.set(C.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(Q.kind,n=>this.visitBinarySelectQuery(n))}collect(e){return this.visit(e),this.tableSchemas}analyze(e){this.isAnalyzeMode=!0;try{return this.visit(e),{success:this.unresolvedColumns.length===0&&!this.analysisError,schemas:this.tableSchemas,unresolvedColumns:this.unresolvedColumns,error:this.analysisError}}finally{this.isAnalyzeMode=!1}}visit(e){if(this.running){this.visitNode(e);return}this.reset(),this.running=!0;try{if(!(e instanceof C||e instanceof Q))throw new Error(`Unsupported SQL component type for schema collection. Received: ${e.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let t=new X;this.commonTables=t.collect(e),this.visitNode(e),this.consolidateTableSchemas()}finally{this.running=!1}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}reset(){this.tableSchemas=[],this.visitedNodes=new Set,this.commonTables=[],this.unresolvedColumns=[],this.analysisError=void 0}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 lt(t,Array.from(n).sort()))}handleSourceExpression(e,t,n){if(e.datasource instanceof R){let r=e.datasource.getSourceName(),i=this.commonTables.filter(s=>s.getSourceAliasName()===r);if(i.length>0){i[0].query.accept(this);let s=e.getAliasName()??r;this.processCTETableSchema(i[0],s,t,n)}else{let s=e.getAliasName()??r;this.processCollectTableSchema(r,s,t,n)}}else e.datasource instanceof W&&this.visitNode(e.datasource.query)}visitSimpleSelectQuery(e){if(e.fromClause===null)return;let n=new xe(this.tableColumnResolver,!0,"fullName").collect(e),r;if(this.allowWildcardWithoutResolver){let i=this.getSelectClauseColumns(e);r=n.filter(s=>s.value instanceof b).map(s=>s.value).filter(s=>{let o=s.getNamespace(),l=s.column.name;return i.some(u=>{if(u.value instanceof b){let c=u.value.getNamespace(),p=u.value.column.name;if(c===o&&p===l)return!0;if(p==="*"){if(this.allowWildcardWithoutResolver&&this.tableColumnResolver===null)return!1;if(c===""||c===o)return!0}}return!1})}).map(s=>({table:s.getNamespace(),column:s.column.name}))}else r=n.filter(i=>i.value instanceof b).map(i=>i.value).map(i=>({table:i.getNamespace(),column:i.column.name}));if(e.fromClause.joins!==null&&e.fromClause.joins.length>0){let i=r.filter(s=>s.table==="").map(s=>s.column);if(i.length>0)if(this.isAnalyzeMode)this.unresolvedColumns.push(...i),this.analysisError=`Column reference(s) without table name found in query: ${i.join(", ")}`;else throw new Error(`Column reference(s) without table name found in query: ${i.join(", ")}`)}if(e.fromClause.source.datasource instanceof R?this.handleSourceExpression(e.fromClause.source,r,!0):e.fromClause.source.datasource instanceof W&&e.fromClause.source.datasource.query.accept(this),e.fromClause?.joins)for(let i of e.fromClause.joins)i.source.datasource instanceof R?this.handleSourceExpression(i.source,r,!1):i.source.datasource instanceof W&&i.source.datasource.query.accept(this)}visitBinarySelectQuery(e){this.visitNode(e.left),this.visitNode(e.right)}getSelectClauseColumns(e){if(!e.selectClause)return[];let t=[];for(let n of e.selectClause.items)if(n.value instanceof b){let r=n.value.column.name;t.push({name:r,value:n.value})}return t}processCollectTableSchema(e,t,n,r=!1){if(this.tableColumnResolver===null&&n.filter(l=>l.table===t||r&&l.table==="").filter(l=>l.column==="*").length>0&&!this.allowWildcardWithoutResolver){let l=e?`Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards. Target table: ${e}`:"Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards.";if(this.isAnalyzeMode){this.analysisError=l;let u=n.filter(c=>c.table===t||r&&c.table==="").filter(c=>c.column==="*").map(c=>c.table?`${c.table}.*`:"*");this.unresolvedColumns.push(...u)}else throw new Error(l)}let i=n.filter(o=>o.column!=="*").filter(o=>o.table===t||r&&o.table==="").map(o=>o.column),s=new lt(e,i);this.tableSchemas.push(s)}processCTETableSchema(e,t,n,r=!1){let i=e.getSourceAliasName(),s=this.getCTEColumns(e),o=n.filter(c=>c.table===t||r&&c.table==="").map(c=>c.column);if(o.includes("*")){if(this.tableColumnResolver!==null){let c=this.tableColumnResolver(i);if(c.length>0){let p=new lt(i,c);this.tableSchemas.push(p);return}}if(s.length>0){let c=new lt(i,s);this.tableSchemas.push(c);return}else if(this.allowWildcardWithoutResolver){let c=new lt(i,[]);this.tableSchemas.push(c);return}else{let c=`Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards. Target table: ${i}`;if(this.isAnalyzeMode)this.analysisError=c,this.unresolvedColumns.push(t?`${t}.*`:"*");else throw new Error(c);return}}let l=o.filter(c=>c!=="*");if(this.isAnalyzeMode){let c=s;if(this.tableColumnResolver){let p=this.tableColumnResolver(i);p.length>0&&(c=p)}if(c.length>0){let p=l.filter(d=>!c.includes(d));p.length>0&&(this.unresolvedColumns.push(...p),this.analysisError||(this.analysisError=`Undefined column(s) found in CTE "${i}": ${p.join(", ")}`))}else if(!this.allowWildcardWithoutResolver){let p=l;p.length>0&&(this.unresolvedColumns.push(...p),this.analysisError||(this.analysisError=`Undefined column(s) found in CTE "${i}": ${p.join(", ")}`))}}let u=new lt(i,l);this.tableSchemas.push(u)}getCTEColumns(e){try{return e.query instanceof C&&e.query.selectClause?this.extractColumnsFromSelectItems(e.query.selectClause.items,e):this.extractColumnsUsingCollector(e.query)}catch{return[]}}extractColumnsFromSelectItems(e,t){let n=[];for(let r of e)if(r.value instanceof b){let i=r.identifier?.name||r.value.column.name;if(r.value.column.name==="*"){let s=this.resolveWildcardInCTE(r.value,t);if(s===null)return[];n.push(...s)}else n.push(i)}else r.identifier&&n.push(r.identifier.name);return this.removeDuplicates(n)}resolveWildcardInCTE(e,t){let n=e.getNamespace();return n?this.resolveQualifiedWildcard(n):this.resolveUnqualifiedWildcard(t)}resolveQualifiedWildcard(e){let t=this.commonTables.find(n=>n.getSourceAliasName()===e);if(t){let n=this.getCTEColumns(t);if(n.length>0)return n}return null}resolveUnqualifiedWildcard(e){if(!(e.query instanceof C)||!e.query.fromClause)return null;let t=e.query.fromClause.source;return t.datasource instanceof R?this.resolveTableWildcard(t.datasource.table.name):(t.datasource instanceof W,null)}resolveTableWildcard(e){if(this.tableColumnResolver){let t=this.tableColumnResolver(e);if(t.length>0)return t}return this.allowWildcardWithoutResolver,null}extractColumnsUsingCollector(e){return new xe(null,!0,"fullName").collect(e).filter(r=>r.value instanceof b).map(r=>r.value).map(r=>r.column.name).filter((r,i,s)=>s.indexOf(r)===i)}removeDuplicates(e){return e.filter((t,n,r)=>r.indexOf(t)===n)}};var Hn=class{static validate(e,t){let n=typeof e=="string"?A.parse(e):e,r=Array.isArray(t)?l=>{let u=t.find(c=>c.name===l);return u?u.columns:[]}:t,s=new Bt(r).collect(n),o=[];for(let l of s){let u=r(l.name);if(u.length===0){o.push(`Table '${l.name}' is not defined.`);continue}let c=l.columns.filter(p=>!u.includes(p));c.length>0&&o.push(`Table '${l.name}' contains undefined columns: ${c.join(", ")}.`)}if(o.length>0)throw new Error(o.join(`
22
- `))}};var Yn=class{constructor(e={}){this.knownCTENames=[];this.options=e,this.formatter=new Fe(e),this.dependencyAnalyzer=new ft}compose(e,t){if(e.length===0)return t;this.knownCTENames=e.map(p=>p.name);let n=e.map(p=>({name:p.name,query:this.extractPureQuery(p.query,p.name)})),r=this.buildTempQueryForAnalysis(n,t),i=this.dependencyAnalyzer.analyzeDependencies(r),s=this.sortCTEsByDependencies(n,i),o=this.detectRecursiveFromOriginalQueries(e),l=s.map(p=>`${p.name} as (${p.query})`),c=`${o?"with recursive":"with"} ${l.join(", ")} ${t}`;return this.options.validateSchema&&this.options.schema&&this.validateComposedQuery(c),this.formatFinalQuery(c)}extractPureQuery(e,t){if(!/^\s*with\s+/i.test(e)||/^\s*with\s+recursive\s+/i.test(e))return e;try{let i=A.parse(e);if(i.withClause&&i.withClause.tables){let s=this.getKnownCTENames();if(i.withClause.tables.map(u=>this.getCTEName(u)).every(u=>s.includes(u))){let u=new C({selectClause:i.selectClause,fromClause:i.fromClause,whereClause:i.whereClause,groupByClause:i.groupByClause,havingClause:i.havingClause,orderByClause:i.orderByClause,windowClause:i.windowClause,limitClause:i.limitClause,offsetClause:i.offsetClause,fetchClause:i.fetchClause,forClause:i.forClause,withClause:void 0});return new Fe({identifierEscape:{start:"",end:""}}).format(u).formattedSql}}}catch{}return e}getKnownCTENames(){return this.knownCTENames||[]}getCTEName(e){return e.aliasExpression.table.name}extractCTEWithRegex(e,t){let n=new RegExp(`${t}\\s+as\\s*\\(`,"i"),r=e.match(n);if(!r)return e;let i=r.index+r[0].length,s=1,o=i;for(;o<e.length&&s>0;){let l=e[o];l==="("?s++:l===")"&&s--,o++}return s===0?e.substring(i,o-1).trim():e}buildTempQueryForAnalysis(e,t){let r=`with ${e.map(i=>`${i.name} as (${i.query})`).join(", ")} ${t}`;try{return A.parse(r)}catch(i){throw new Error(`Failed to parse temporary query for dependency analysis: ${i}`)}}sortCTEsByDependencies(e,t){let n=new Map;return e.forEach(r=>n.set(r.name,r.query)),t.nodes.map(r=>({name:r.name,query:n.get(r.name)||""})).filter(r=>r.query!=="")}detectRecursiveFromOriginalQueries(e){return e.some(t=>t.query.toLowerCase().includes("with recursive"))}detectRecursiveCTEs(e){return e.withClause?this.formatter.format(e).formattedSql.toLowerCase().includes("with recursive"):!1}validateComposedQuery(e){try{let t=A.parse(e),n=Object.entries(this.options.schema).map(([r,i])=>({name:r,columns:i}));Hn.validate(t,n)}catch(t){throw t instanceof Error?new Error(`Schema validation failed: ${t.message}`):t}}formatFinalQuery(e){if(this.options.preset||this.options.keywordCase)try{let t=A.parse(e);return this.formatter.format(t).formattedSql}catch{return e}return e}};var Rr=class a{static{this.ERROR_MESSAGES={CIRCULAR_REFERENCE:"Circular reference detected in non-recursive CTEs",PARSING_FAILED:"Failed to parse query for comment injection"}}static{this.COMMENT_TEXTS={AUTO_GENERATED:"Auto-generated by CTE decomposer",ORIGINAL_CTE:"Original CTE:",DEPENDENCIES:"Dependencies:",DEPENDENTS:"Dependents:",RECURSIVE_TYPE:"Type: Recursive CTE",NONE:"none"}}constructor(e={}){this.options=e,this.dependencyAnalyzer=new ft,this.cteCollector=new X,this.formatter=new Fe(e)}decompose(e){let t=this.cteCollector.collect(e);if(t.length===0)return[];let n=this.findRecursiveCTEs(e,t),r=this.dependencyAnalyzer.analyzeDependencies(e);return this.validateCircularDependencies(n.length>0),this.processCTENodes(e,r.nodes,n)}synchronize(e,t){if(e.length===0)return[];let n=this.flattenNestedWithClauses(e),r={...this.options,addComments:void 0},s=new Yn(r).compose(n,t),o=A.parse(s);return this.decompose(o)}flattenNestedWithClauses(e){let t=[],n=new Map;for(let i of e)try{if(/^\s*with\s+/i.test(i.query)){let o=A.parse(i.query);if(o.withClause&&o.withClause.tables){for(let p of o.withClause.tables){let d=this.getCTEName(p);if(!n.has(d)){let y=new Fe({identifierEscape:{start:"",end:""}}).format(p.query).formattedSql;n.set(d,y)}}let l=new C({selectClause:o.selectClause,fromClause:o.fromClause,whereClause:o.whereClause,groupByClause:o.groupByClause,havingClause:o.havingClause,orderByClause:o.orderByClause,windowClause:o.windowClause,limitClause:o.limitClause,offsetClause:o.offsetClause,fetchClause:o.fetchClause,forClause:o.forClause,withClause:void 0}),c=new Fe({identifierEscape:{start:"",end:""}}).format(l).formattedSql;t.push({name:i.name,query:c})}else t.push(i)}else t.push(i)}catch{t.push(i)}let r=[];for(let[i,s]of n)r.push({name:i,query:s});return r.push(...t),r}validateCircularDependencies(e){if(this.dependencyAnalyzer.hasCircularDependency()&&!e)throw new Error(a.ERROR_MESSAGES.CIRCULAR_REFERENCE)}processCTENodes(e,t,n){let r=[];for(let i of t){if(i.type==="ROOT")continue;n.includes(i.name)?r.push(this.createRecursiveCTE(i,e)):r.push(this.createStandardCTE(i,t))}return r}createRecursiveCTE(e,t){let n=this.formatter.format(t).formattedSql,r=e.dependents.filter(s=>s!=="MAIN_QUERY"),i=this.addCommentsToQuery(n,e.name,e.dependencies,e.dependents,!0);return{name:e.name,query:i,dependencies:[...e.dependencies],dependents:r,isRecursive:!0}}createStandardCTE(e,t){let n=this.buildExecutableQuery(e,t),r=this.addCommentsToQuery(n,e.name,e.dependencies,e.dependents,!1),i=e.dependents.filter(s=>s!=="MAIN_QUERY");return{name:e.name,query:r,dependencies:[...e.dependencies],dependents:i,isRecursive:!1}}buildExecutableQuery(e,t){if(e.type==="ROOT"||!e.cte)throw new Error(`Cannot build executable query for ROOT node: ${e.name}`);let n=this.collectRequiredCTEs(e,t);if(n.length===0)return this.formatter.format(e.cte.query).formattedSql;let r=this.buildWithClause(n),i=this.formatter.format(e.cte.query).formattedSql;return`${r} ${i}`}collectRequiredCTEs(e,t){let n=new Set,r=[],i=new Map;for(let o of t)i.set(o.name,o);let s=o=>{if(n.has(o))return;n.add(o);let l=i.get(o);if(l){for(let u of l.dependencies)s(u);o!==e.name&&l.type!=="ROOT"&&r.push(l)}};for(let o of e.dependencies)s(o);return r}buildWithClause(e){return e.length===0?"":`with ${e.map(n=>{if(n.type==="ROOT"||!n.cte)throw new Error(`Cannot include ROOT node in WITH clause: ${n.name}`);let r=n.name,i=this.formatter.format(n.cte.query).formattedSql;return`${r} as (${i})`}).join(", ")}`}findRecursiveCTEs(e,t){return!e.withClause||!this.isRecursiveWithClause(e)?[]:t.map(n=>this.getCTEName(n))}isRecursiveWithClause(e){return this.formatter.format(e).formattedSql.toLowerCase().includes("with recursive")}addCommentsToQuery(e,t,n,r,i){if(this.options.addComments!==!0)return e;try{let s=A.parse(e);return this.generateComments(t,n,r,i).forEach(u=>{Gn.addComment(s,u)}),new Fe({...this.options,exportComment:!0}).format(s).formattedSql}catch(s){return console.warn(`${a.ERROR_MESSAGES.PARSING_FAILED}: ${s}`),this.addTextCommentsToQuery(e,t,n,r,i)}}generateComments(e,t,n,r){let{AUTO_GENERATED:i,ORIGINAL_CTE:s,DEPENDENCIES:o,DEPENDENTS:l,RECURSIVE_TYPE:u,NONE:c}=a.COMMENT_TEXTS,p=[];p.push(i),p.push(`${s} ${e}`),r&&p.push(u);let d=t.length>0?t.join(", "):c;p.push(`${o} ${d}`);let f=n.filter(h=>h!=="MAIN_QUERY"),y=f.length>0?f.join(", "):c;return p.push(`${l} ${y}`),p}addTextCommentsToQuery(e,t,n,r,i){return`${this.generateComments(t,n,r,i).map(l=>`-- ${l}`).join(`
21
+ `);return{line:r.length,column:r[r.length-1].length+1}}static extractCTERegions(e){let t=Le.getAllLexemesWithPosition(e),n=[],r=0,i=!1;for(;r<t.length;){let s=t[r];if(s.value.toLowerCase()==="with"&&!i){i=!0,r++;continue}if(i&&s.value.toLowerCase()==="recursive"){r++;continue}if(i&&s.type===64&&r+1<t.length&&t[r+1].value.toLowerCase()==="as"){let o=s.value,l=s.position.startPosition,u=r+2;for(;u<t.length&&t[u].value!=="(";)u++;if(u<t.length){let c=this.findMatchingParen(t,u);if(c){let p=c.endPosition,m=this.extractCTESQL(e,t,u,c.index);n.push({name:o,startPosition:l,endPosition:p,sqlContent:m}),r=c.index+1;continue}}}if(i&&s.value.toLowerCase()==="select"&&this.isMainQuerySelect(t,r))break;r++}return n}static findMatchingParen(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){if(e[r].value==="("?n++:e[r].value===")"&&n--,n===0)return{index:r,endPosition:e[r].position.endPosition};r++}return null}static extractCTESQL(e,t,n,r){let i=t[n+1].position.startPosition,s=t[r-1].position.endPosition;return e.substring(i,s).trim()}static isMainQuerySelect(e,t){let n=0;for(let r=t-1;r>=0;r--)e[r].value===")"?n++:e[r].value==="("&&n--;return n===0}static calculateExtendedCTEBoundaries(e,t){return t.length===0?[]:t.map((n,r)=>{let i;return r<t.length-1?i=t[r+1].startPosition:i=this.findMainQueryStart(e,n.endPosition),{...n,extendedEndPosition:i}})}static findMainQueryStart(e,t){let n=t;for(;n<e.length;){if(e.substring(n).toLowerCase().trim().startsWith("select")){let i=e.toLowerCase().indexOf("select",n);return i!==-1?i:n}n++}return e.length}static extractMainQuery(e,t){if(t.length===0)return e.trim();let i=t[t.length-1].endPosition;for(;i<e.length&&!e.substring(i).toLowerCase().trim().startsWith("select");)i++;return e.substring(i).trim()}static getCTEPositions(e){let t=this.extractCTERegions(e),n=[];if(t.forEach(r=>{n.push({name:r.name,startPosition:r.startPosition,type:"CTE"})}),t.length>0){let i=t[t.length-1].endPosition;for(;i<e.length;){if(e.substring(i).toLowerCase().trim().startsWith("select")){n.push({name:"MAIN_QUERY",startPosition:i,type:"MAIN_QUERY"});break}i++}}else n.push({name:"MAIN_QUERY",startPosition:0,type:"MAIN_QUERY"});return n}};var A=class{static parse(e){let n=new R(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 calculateCharacterPosition(e,t,n){if(n>=t.length)return e.length;let r=t[n];if(r.position?.startPosition!==void 0)return r.position.startPosition;let i=0;for(let l=0;l<n;l++){let u=t[l].value,c=e.indexOf(u,i);c!==-1&&(i=c+u.length)}let s=t[n].value,o=e.indexOf(s,i);return o!==-1?o:i}static analyze(e){let t=[];try{t=new R(e).readLexmes();let r=this.parseFromLexeme(t,0);if(r.newIndex<t.length){let i=t.slice(r.newIndex).map(l=>l.value),s=t[r.newIndex],o=this.calculateCharacterPosition(e,t,r.newIndex);return{success:!1,query:r.value,error:`Syntax error: Unexpected token "${s.value}" at character position ${o}. The SELECT query is complete but there are additional tokens.`,errorPosition:o,remainingTokens:i}}return{success:!0,query:r.value}}catch(n){let r,i=n instanceof Error?n.message:String(n),s=i.match(/position (\d+)/);if(s){let o=parseInt(s[1],10);r=this.calculateCharacterPosition(e,t,o)}return{success:!1,error:i,errorPosition:r}}}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 transferHeaderComments(e,t){e.headerComments&&(t.headerComments=e.headerComments,e.headerComments=null)}static parseFromLexeme(e,t){let n=t;if(n>=e.length)throw new Error(`Syntax error: Unexpected end of input at position ${t}.`);let r=e[n].value;if(!this.selectCommandSet.has(r)&&r!=="values")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' or 'VALUES' keyword but found "${e[n].value}".`);let i=this.selectCommandSet.has(r)?this.parseSimpleSelectQuery(e,n):this.parseValuesQuery(e,n),s=i.value;for(n=i.newIndex;n<e.length&&this.unionCommandSet.has(e[n].value.toLowerCase());){let o=e[n],l=o.value.toLowerCase(),u=o.comments;if(n++,n>=e.length)throw new Error(`Syntax error at position ${n}: Expected a query after '${l.toUpperCase()}' but found end of input.`);let c=e[n].value.toLowerCase();if(this.selectCommandSet.has(c)){let p=this.parseSimpleSelectQuery(e,n),m=new Q(s,l,p.value);this.transferHeaderComments(s,m),u&&u.length>0&&(p.value.comments?p.value.comments=[...u,...p.value.comments]:p.value.comments=u),s=m,n=p.newIndex}else if(c==="values"){let p=this.parseValuesQuery(e,n),m=new Q(s,l,p.value);this.transferHeaderComments(s,m),u&&u.length>0&&(p.value.comments?p.value.comments=[...u,...p.value.comments]:p.value.comments=u),s=m,n=p.newIndex}else throw new Error(`Syntax error at position ${n}: Expected 'SELECT' or 'VALUES' after '${l.toUpperCase()}' but found "${e[n].value}".`)}return{value:s,newIndex:n}}static parseSimpleSelectQuery(e,t){let n=t,r=null,i=[];n<e.length&&e[n].value==="with"&&(r=Ft.parseFromLexeme(e,n),n=r.newIndex,r.headerComments&&i.push(...r.headerComments));let s=[];r?.value.trailingComments&&s.push(...r.value.trailingComments);let o=[...s],l=n;for(;l<e.length&&e[l].value.toLowerCase()!=="select";){let V=e[l].comments;V&&V.length>0&&o.push(...V),l++}if(n>=e.length||e[n].value!=="select")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' keyword but found "${n<e.length?e[n].value:"end of input"}". SELECT queries must start with the SELECT keyword.`);let u=e[n].comments;u&&u.length>0&&(i.push(...u),e[n].comments=null);let c=On.parseFromLexeme(e,n);n=c.newIndex;let p=null;n<e.length&&e[n].value==="from"&&(p=$n.parseFromLexeme(e,n),n=p.newIndex);let m=null;n<e.length&&e[n].value==="where"&&(m=Mn.parseFromLexeme(e,n),n=m.newIndex);let f=null;n<e.length&&e[n].value==="group by"&&(f=Wn.parseFromLexeme(e,n),n=f.newIndex);let g=null;n<e.length&&e[n].value==="having"&&(g=jn.parseFromLexeme(e,n),n=g.newIndex);let h=null;n<e.length&&e[n].value==="window"&&(h=Dn.parseFromLexeme(e,n),n=h.newIndex);let W=null;n<e.length&&e[n].value==="order by"&&(W=rt.parseFromLexeme(e,n),n=W.newIndex);let G=null;n<e.length&&e[n].value==="limit"&&(G=Un.parseFromLexeme(e,n),n=G.newIndex);let E=null;n<e.length&&e[n].value==="offset"&&(E=zn.parseFromLexeme(e,n),n=E.newIndex);let y=null;n<e.length&&e[n].value==="fetch"&&(y=_n.parseFromLexeme(e,n),n=y.newIndex);let k=null;n<e.length&&e[n].value.toLowerCase()==="for"&&(k=Jn.parseFromLexeme(e,n),n=k.newIndex);let x=new C({withClause:r?r.value:null,selectClause:c.value,fromClause:p?p.value:null,whereClause:m?m.value:null,groupByClause:f?f.value:null,havingClause:g?g.value:null,orderByClause:W?W.value:null,windowClause:h?h.value:null,limitClause:G?G.value:null,offsetClause:E?E.value:null,fetchClause:y?y.value:null,forClause:k?k.value:null});return x.comments=o.length>0?o:null,x.headerComments=i.length>0?i:null,{value:x,newIndex:n}}static parseValuesQuery(e,t){let n=Kn.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}static getCursorCte(e,t){return ht.getCursorCte(e,t)}static getCursorCteAt(e,t,n){return ht.getCursorCteAt(e,t,n)}static positionToLineColumn(e,t){return ht.positionToLineColumn(e,t)}};var Qr=class{static parse(e){let n=new R(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=Ye.parseTableSourceFromLexemes(e,n);n=i.newIndex;let s=[];if(e[n]?.type===4){for(n++;n<e.length&&e[n].type===64&&(s.push(e[n].value),n++,e[n]?.type===16);)n++;if(e[n]?.type!==8)throw new Error(`Syntax error at position ${n}: Expected ')' after column list.`);n++}let o=A.parseFromLexeme(e,n);if(r)if(o.value instanceof C)o.value.withClause=r;else throw new Error("WITH clause is not supported in this context.");return n=o.newIndex,{value:new ot({insertClause:new ct(i.value,s),selectQuery:o.value}),newIndex:n}}};var qn=class{constructor(){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(C.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(Q.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(Ce.kind,e=>this.visitValuesQuery(e)),this.handlers.set(J.kind,e=>this.visitFromClause(e)),this.handlers.set(fe.kind,e=>this.visitJoinClause(e)),this.handlers.set(he.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Se.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(B.kind,e=>this.visitSourceExpression(e)),this.handlers.set(O.kind,e=>this.visitTableSource(e)),this.handlers.set(qe.kind,e=>this.visitFunctionSource(e)),this.handlers.set($e.kind,e=>this.visitParenSource(e)),this.handlers.set(j.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(ge.kind,e=>this.visitInlineQuery(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(me.kind,e=>this.visitGroupByClause(e)),this.handlers.set(de.kind,e=>this.visitHavingClause(e)),this.handlers.set(pe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Pe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Re.kind,e=>this.visitOffsetClause(e)),this.handlers.set(Ue.kind,e=>this.visitFetchClause(e)),this.handlers.set(Ne.kind,e=>this.visitForClause(e)),this.handlers.set(Ae.kind,e=>this.visitOrderByItem(e)),this.handlers.set(_.kind,e=>this.visitSelectClause(e)),this.handlers.set(z.kind,e=>this.visitSelectItem(e)),this.handlers.set(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(S.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ie.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ke.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(Te.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(we.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(K.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ye.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ve.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(Ie.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ce.kind,e=>this.visitCastExpression(e)),this.handlers.set(U.kind,e=>this.visitValueList(e)),this.handlers.set(je.kind,e=>this.visitStringSpecifierExpression(e))}collect(e){return this.visit(e),this.getTableSources()}getTableSources(){return this.tableSources}reset(){this.tableSources=[],this.tableNameMap.clear(),this.visitedNodes.clear()}getTableIdentifier(e){return e.qualifiedName.namespaces&&e.qualifiedName.namespaces.length>0?e.qualifiedName.namespaces.map(t=>t.name).join(".")+"."+(e.qualifiedName.name instanceof $?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof $?e.qualifiedName.name.value:e.qualifiedName.name.name}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){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.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){for(let t of e.tuples)t.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.tableNameMap.set(t,!0),this.tableSources.push(e))}visitFunctionSource(e){e.argument&&this.visitValueComponent(e.argument)}visitValueComponent(e){e.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)}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 ft=class a{constructor(){this.dependencyGraph=null;this.cteMap=new Map;this.sourceCollector=new He(!1),this.cteReferenceCollector=new qn,this.cteCollector=new X}static{this.ERROR_MESSAGES={NOT_ANALYZED:"Must call analyzeDependencies first",CIRCULAR_REFERENCE:"Circular reference detected in CTE"}}static{this.MAIN_QUERY_NAME="MAIN_QUERY"}analyzeDependencies(e){let t=this.cteCollector.collect(e);return this.buildCTEMap(t),this.dependencyGraph=this.buildDependencyGraph(t,e),this.dependencyGraph}getDependencies(e){this.ensureAnalyzed();let t=this.findNodeByName(e);return t?[...t.dependencies]:[]}getDependents(e){this.ensureAnalyzed();let t=this.findNodeByName(e);return t?[...t.dependents]:[]}getMainQueryDependencies(){this.ensureAnalyzed();let e=this.findNodeByName(a.MAIN_QUERY_NAME);return e?[...e.dependencies]:[]}getNodesByType(e){return this.ensureAnalyzed(),this.dependencyGraph.nodes.filter(t=>t.type===e)}getMainQueryNode(){return this.ensureAnalyzed(),this.findNodeByName(a.MAIN_QUERY_NAME)}hasCircularDependency(){this.ensureAnalyzed();try{return this.getExecutionOrder(),!1}catch(e){if(e instanceof Error&&e.message.includes(a.ERROR_MESSAGES.CIRCULAR_REFERENCE))return!0;throw e}}getExecutionOrder(){this.ensureAnalyzed();let e=new Set,t=new Set,n=[],r=new Map;for(let s of this.dependencyGraph.nodes)r.set(s.name,new Set(s.dependencies));let i=s=>{if(e.has(s))return;if(t.has(s))throw new Error(`${a.ERROR_MESSAGES.CIRCULAR_REFERENCE}: ${s}`);t.add(s);let o=r.get(s)||new Set;for(let l of o)i(l);t.delete(s),e.add(s),n.push(s)};for(let s of this.dependencyGraph.nodes)e.has(s.name)||i(s.name);return n}buildDependencyGraph(e,t){let n=[],r=[],i=new Map,s=new Map;for(let l of e){let u=a.getCTEName(l);i.set(u,new Set),s.set(u,new Set)}i.set(a.MAIN_QUERY_NAME,new Set),s.set(a.MAIN_QUERY_NAME,new Set);for(let l of e){let u=a.getCTEName(l),c=this.sourceCollector.collect(l.query);for(let p of c){let m=p.table.name;this.cteMap.has(m)&&m!==u&&(i.get(u).add(m),s.get(m).add(u),r.push({from:u,to:m}))}}let o=this.getMainQueryWithoutCTE(t);if(o){let l=this.cteReferenceCollector.collect(o);for(let u of l){let c=u.table.name;this.cteMap.has(c)&&(i.get(a.MAIN_QUERY_NAME).add(c),s.get(c).add(a.MAIN_QUERY_NAME),r.push({from:a.MAIN_QUERY_NAME,to:c}))}}for(let l of e){let u=a.getCTEName(l);n.push({name:u,type:"CTE",cte:l,dependencies:Array.from(i.get(u)||new Set),dependents:Array.from(s.get(u)||new Set)})}return n.push({name:a.MAIN_QUERY_NAME,type:"ROOT",cte:null,dependencies:Array.from(i.get(a.MAIN_QUERY_NAME)||new Set),dependents:Array.from(s.get(a.MAIN_QUERY_NAME)||new Set)}),{nodes:n,edges:r}}ensureAnalyzed(){if(!this.dependencyGraph)throw new Error(a.ERROR_MESSAGES.NOT_ANALYZED)}buildCTEMap(e){this.cteMap.clear();for(let t of e){let n=a.getCTEName(t);this.cteMap.set(n,t)}}findNodeByName(e){return this.dependencyGraph?.nodes.find(t=>t.name===e)}getMainQueryWithoutCTE(e){return e.withClause?new C({selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,limitClause:e.limitClause,offsetClause:e.offsetClause,fetchClause:e.fetchClause,forClause:e.forClause,windowClause:e.windowClause}):e}static getCTEName(e){return e.aliasExpression.table.name}};var Gn=class{static addComment(e,t){if(this.isSelectQuery(e)){let n=e;n.headerComments||(n.headerComments=[]),n.headerComments.push(t)}else e.comments||(e.comments=[]),e.comments.push(t)}static isSelectQuery(e){return"__selectQueryType"in e&&e.__selectQueryType==="SelectQuery"}static editComment(e,t,n){if(this.isSelectQuery(e)){let r=e;if(!r.headerComments||t<0||t>=r.headerComments.length)throw new Error(`Invalid comment index: ${t}. Component has ${r.headerComments?.length||0} comments.`);r.headerComments[t]=n}else{if(!e.comments||t<0||t>=e.comments.length)throw new Error(`Invalid comment index: ${t}. Component has ${e.comments?.length||0} comments.`);e.comments[t]=n}}static deleteComment(e,t){if(this.isSelectQuery(e)){let n=e;if(!n.headerComments||t<0||t>=n.headerComments.length)throw new Error(`Invalid comment index: ${t}. Component has ${n.headerComments?.length||0} comments.`);n.headerComments.splice(t,1),n.headerComments.length===0&&(n.headerComments=null)}else{if(!e.comments||t<0||t>=e.comments.length)throw new Error(`Invalid comment index: ${t}. Component has ${e.comments?.length||0} comments.`);e.comments.splice(t,1),e.comments.length===0&&(e.comments=null)}}static deleteAllComments(e){if(this.isSelectQuery(e)){let t=e;t.headerComments=null}else e.comments=null}static getComments(e){return this.isSelectQuery(e)?e.headerComments||[]:e.comments||[]}static findComponentsWithComment(e,t,n=!1){let r=[],i=n?t:t.toLowerCase(),s=o=>{if(o&&o instanceof v){let l=!1;if(o.comments&&o.comments.some(u=>(n?u:u.toLowerCase()).includes(i))&&(l=!0),this.isSelectQuery(o)){let u=o;u.headerComments&&u.headerComments.some(c=>(n?c:c.toLowerCase()).includes(i))&&(l=!0)}l&&r.push(o)}for(let l in o)o[l]&&typeof o[l]=="object"&&(Array.isArray(o[l])?o[l].forEach(s):s(o[l]))};return s(e),r}static replaceInComments(e,t,n,r=!1){let i=0,s=o=>{if(o&&o instanceof v){if(o.comments)for(let l=0;l<o.comments.length;l++){let u=o.comments[l],c=r?"g":"gi",p=new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c),m=u.replace(p,n);m!==u&&(o.comments[l]=m,i++)}if(this.isSelectQuery(o)){let l=o;if(l.headerComments)for(let u=0;u<l.headerComments.length;u++){let c=l.headerComments[u],p=r?"g":"gi",m=new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),p),f=c.replace(m,n);f!==c&&(l.headerComments[u]=f,i++)}}}for(let l in o)o[l]&&typeof o[l]=="object"&&(Array.isArray(o[l])?o[l].forEach(s):s(o[l]))};return s(e),i}static countComments(e){let t=0,n=r=>{if(r&&r instanceof v&&(r.comments&&(t+=r.comments.length),this.isSelectQuery(r))){let i=r;i.headerComments&&(t+=i.headerComments.length)}for(let i in r)r[i]&&typeof r[i]=="object"&&(Array.isArray(r[i])?r[i].forEach(n):n(r[i]))};return n(e),t}static getAllComments(e){let t=[],n=r=>{if(r&&r instanceof v&&(r.comments&&r.comments.forEach((i,s)=>{t.push({comment:i,component:r,index:s})}),this.isSelectQuery(r))){let i=r;i.headerComments&&i.headerComments.forEach((s,o)=>{t.push({comment:s,component:r,index:o})})}for(let i in r)r[i]&&typeof r[i]=="object"&&(Array.isArray(r[i])?r[i].forEach(n):n(r[i]))};return n(e),t}};var lt=class{constructor(e,t){this.name=e,this.columns=t}},Bt=class{constructor(e=null,t=!1){this.tableColumnResolver=e;this.allowWildcardWithoutResolver=t;this.tableSchemas=[];this.visitedNodes=new Set;this.commonTables=[];this.running=!1;this.unresolvedColumns=[];this.analysisError=void 0;this.isAnalyzeMode=!1;this.handlers=new Map,this.handlers.set(C.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(Q.kind,n=>this.visitBinarySelectQuery(n))}collect(e){return this.visit(e),this.tableSchemas}analyze(e){this.isAnalyzeMode=!0;try{return this.visit(e),{success:this.unresolvedColumns.length===0&&!this.analysisError,schemas:this.tableSchemas,unresolvedColumns:this.unresolvedColumns,error:this.analysisError}}finally{this.isAnalyzeMode=!1}}visit(e){if(this.running){this.visitNode(e);return}this.reset(),this.running=!0;try{if(!(e instanceof C||e instanceof Q))throw new Error(`Unsupported SQL component type for schema collection. Received: ${e.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let t=new X;this.commonTables=t.collect(e),this.visitNode(e),this.consolidateTableSchemas()}finally{this.running=!1}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}reset(){this.tableSchemas=[],this.visitedNodes=new Set,this.commonTables=[],this.unresolvedColumns=[],this.analysisError=void 0}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 lt(t,Array.from(n).sort()))}handleSourceExpression(e,t,n){if(e.datasource instanceof O){let r=e.datasource.getSourceName(),i=this.commonTables.filter(s=>s.getSourceAliasName()===r);if(i.length>0){i[0].query.accept(this);let s=e.getAliasName()??r;this.processCTETableSchema(i[0],s,t,n)}else{let s=e.getAliasName()??r;this.processCollectTableSchema(r,s,t,n)}}else e.datasource instanceof j&&this.visitNode(e.datasource.query)}visitSimpleSelectQuery(e){if(e.fromClause===null)return;let n=new xe(this.tableColumnResolver,!0,"fullName").collect(e),r;if(this.allowWildcardWithoutResolver){let i=this.getSelectClauseColumns(e);r=n.filter(s=>s.value instanceof b).map(s=>s.value).filter(s=>{let o=s.getNamespace(),l=s.column.name;return i.some(u=>{if(u.value instanceof b){let c=u.value.getNamespace(),p=u.value.column.name;if(c===o&&p===l)return!0;if(p==="*"){if(this.allowWildcardWithoutResolver&&this.tableColumnResolver===null)return!1;if(c===""||c===o)return!0}}return!1})}).map(s=>({table:s.getNamespace(),column:s.column.name}))}else r=n.filter(i=>i.value instanceof b).map(i=>i.value).map(i=>({table:i.getNamespace(),column:i.column.name}));if(e.fromClause.joins!==null&&e.fromClause.joins.length>0){let i=r.filter(s=>s.table==="").map(s=>s.column);if(i.length>0)if(this.isAnalyzeMode)this.unresolvedColumns.push(...i),this.analysisError=`Column reference(s) without table name found in query: ${i.join(", ")}`;else throw new Error(`Column reference(s) without table name found in query: ${i.join(", ")}`)}if(e.fromClause.source.datasource instanceof O?this.handleSourceExpression(e.fromClause.source,r,!0):e.fromClause.source.datasource instanceof j&&e.fromClause.source.datasource.query.accept(this),e.fromClause?.joins)for(let i of e.fromClause.joins)i.source.datasource instanceof O?this.handleSourceExpression(i.source,r,!1):i.source.datasource instanceof j&&i.source.datasource.query.accept(this)}visitBinarySelectQuery(e){this.visitNode(e.left),this.visitNode(e.right)}getSelectClauseColumns(e){if(!e.selectClause)return[];let t=[];for(let n of e.selectClause.items)if(n.value instanceof b){let r=n.value.column.name;t.push({name:r,value:n.value})}return t}processCollectTableSchema(e,t,n,r=!1){if(this.tableColumnResolver===null&&n.filter(l=>l.table===t||r&&l.table==="").filter(l=>l.column==="*").length>0&&!this.allowWildcardWithoutResolver){let l=e?`Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards. Target table: ${e}`:"Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards.";if(this.isAnalyzeMode){this.analysisError=l;let u=n.filter(c=>c.table===t||r&&c.table==="").filter(c=>c.column==="*").map(c=>c.table?`${c.table}.*`:"*");this.unresolvedColumns.push(...u)}else throw new Error(l)}let i=n.filter(o=>o.column!=="*").filter(o=>o.table===t||r&&o.table==="").map(o=>o.column),s=new lt(e,i);this.tableSchemas.push(s)}processCTETableSchema(e,t,n,r=!1){let i=e.getSourceAliasName(),s=this.getCTEColumns(e),o=n.filter(c=>c.table===t||r&&c.table==="").map(c=>c.column);if(o.includes("*")){if(this.tableColumnResolver!==null){let c=this.tableColumnResolver(i);if(c.length>0){let p=new lt(i,c);this.tableSchemas.push(p);return}}if(s.length>0){let c=new lt(i,s);this.tableSchemas.push(c);return}else if(this.allowWildcardWithoutResolver){let c=new lt(i,[]);this.tableSchemas.push(c);return}else{let c=`Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards. Target table: ${i}`;if(this.isAnalyzeMode)this.analysisError=c,this.unresolvedColumns.push(t?`${t}.*`:"*");else throw new Error(c);return}}let l=o.filter(c=>c!=="*");if(this.isAnalyzeMode){let c=s;if(this.tableColumnResolver){let p=this.tableColumnResolver(i);p.length>0&&(c=p)}if(c.length>0){let p=l.filter(m=>!c.includes(m));p.length>0&&(this.unresolvedColumns.push(...p),this.analysisError||(this.analysisError=`Undefined column(s) found in CTE "${i}": ${p.join(", ")}`))}else if(!this.allowWildcardWithoutResolver){let p=l;p.length>0&&(this.unresolvedColumns.push(...p),this.analysisError||(this.analysisError=`Undefined column(s) found in CTE "${i}": ${p.join(", ")}`))}}let u=new lt(i,l);this.tableSchemas.push(u)}getCTEColumns(e){try{return e.query instanceof C&&e.query.selectClause?this.extractColumnsFromSelectItems(e.query.selectClause.items,e):this.extractColumnsUsingCollector(e.query)}catch{return[]}}extractColumnsFromSelectItems(e,t){let n=[];for(let r of e)if(r.value instanceof b){let i=r.identifier?.name||r.value.column.name;if(r.value.column.name==="*"){let s=this.resolveWildcardInCTE(r.value,t);if(s===null)return[];n.push(...s)}else n.push(i)}else r.identifier&&n.push(r.identifier.name);return this.removeDuplicates(n)}resolveWildcardInCTE(e,t){let n=e.getNamespace();return n?this.resolveQualifiedWildcard(n):this.resolveUnqualifiedWildcard(t)}resolveQualifiedWildcard(e){let t=this.commonTables.find(n=>n.getSourceAliasName()===e);if(t){let n=this.getCTEColumns(t);if(n.length>0)return n}return null}resolveUnqualifiedWildcard(e){if(!(e.query instanceof C)||!e.query.fromClause)return null;let t=e.query.fromClause.source;return t.datasource instanceof O?this.resolveTableWildcard(t.datasource.table.name):(t.datasource instanceof j,null)}resolveTableWildcard(e){if(this.tableColumnResolver){let t=this.tableColumnResolver(e);if(t.length>0)return t}return this.allowWildcardWithoutResolver,null}extractColumnsUsingCollector(e){return new xe(null,!0,"fullName").collect(e).filter(r=>r.value instanceof b).map(r=>r.value).map(r=>r.column.name).filter((r,i,s)=>s.indexOf(r)===i)}removeDuplicates(e){return e.filter((t,n,r)=>r.indexOf(t)===n)}};var Hn=class{static validate(e,t){let n=typeof e=="string"?A.parse(e):e,r=Array.isArray(t)?l=>{let u=t.find(c=>c.name===l);return u?u.columns:[]}:t,s=new Bt(r).collect(n),o=[];for(let l of s){let u=r(l.name);if(u.length===0){o.push(`Table '${l.name}' is not defined.`);continue}let c=l.columns.filter(p=>!u.includes(p));c.length>0&&o.push(`Table '${l.name}' contains undefined columns: ${c.join(", ")}.`)}if(o.length>0)throw new Error(o.join(`
22
+ `))}};var Yn=class{constructor(e={}){this.knownCTENames=[];this.options=e,this.formatter=new Fe(e),this.dependencyAnalyzer=new ft}compose(e,t){if(e.length===0)return t;this.knownCTENames=e.map(p=>p.name);let n=e.map(p=>({name:p.name,query:this.extractPureQuery(p.query,p.name)})),r=this.buildTempQueryForAnalysis(n,t),i=this.dependencyAnalyzer.analyzeDependencies(r),s=this.sortCTEsByDependencies(n,i),o=this.detectRecursiveFromOriginalQueries(e),l=s.map(p=>`${p.name} as (${p.query})`),c=`${o?"with recursive":"with"} ${l.join(", ")} ${t}`;return this.options.validateSchema&&this.options.schema&&this.validateComposedQuery(c),this.formatFinalQuery(c)}extractPureQuery(e,t){if(!/^\s*with\s+/i.test(e)||/^\s*with\s+recursive\s+/i.test(e))return e;try{let i=A.parse(e);if(i.withClause&&i.withClause.tables){let s=this.getKnownCTENames();if(i.withClause.tables.map(u=>this.getCTEName(u)).every(u=>s.includes(u))){let u=new C({selectClause:i.selectClause,fromClause:i.fromClause,whereClause:i.whereClause,groupByClause:i.groupByClause,havingClause:i.havingClause,orderByClause:i.orderByClause,windowClause:i.windowClause,limitClause:i.limitClause,offsetClause:i.offsetClause,fetchClause:i.fetchClause,forClause:i.forClause,withClause:void 0});return new Fe({identifierEscape:{start:"",end:""}}).format(u).formattedSql}}}catch{}return e}getKnownCTENames(){return this.knownCTENames||[]}getCTEName(e){return e.aliasExpression.table.name}extractCTEWithRegex(e,t){let n=new RegExp(`${t}\\s+as\\s*\\(`,"i"),r=e.match(n);if(!r)return e;let i=r.index+r[0].length,s=1,o=i;for(;o<e.length&&s>0;){let l=e[o];l==="("?s++:l===")"&&s--,o++}return s===0?e.substring(i,o-1).trim():e}buildTempQueryForAnalysis(e,t){let r=`with ${e.map(i=>`${i.name} as (${i.query})`).join(", ")} ${t}`;try{return A.parse(r)}catch(i){throw new Error(`Failed to parse temporary query for dependency analysis: ${i}`)}}sortCTEsByDependencies(e,t){let n=new Map;return e.forEach(r=>n.set(r.name,r.query)),t.nodes.map(r=>({name:r.name,query:n.get(r.name)||""})).filter(r=>r.query!=="")}detectRecursiveFromOriginalQueries(e){return e.some(t=>t.query.toLowerCase().includes("with recursive"))}detectRecursiveCTEs(e){return e.withClause?this.formatter.format(e).formattedSql.toLowerCase().includes("with recursive"):!1}validateComposedQuery(e){try{let t=A.parse(e),n=Object.entries(this.options.schema).map(([r,i])=>({name:r,columns:i}));Hn.validate(t,n)}catch(t){throw t instanceof Error?new Error(`Schema validation failed: ${t.message}`):t}}formatFinalQuery(e){if(this.options.preset||this.options.keywordCase)try{let t=A.parse(e);return this.formatter.format(t).formattedSql}catch{return e}return e}};var Or=class a{static{this.ERROR_MESSAGES={CIRCULAR_REFERENCE:"Circular reference detected in non-recursive CTEs",PARSING_FAILED:"Failed to parse query for comment injection"}}static{this.COMMENT_TEXTS={AUTO_GENERATED:"Auto-generated by CTE decomposer",ORIGINAL_CTE:"Original CTE:",DEPENDENCIES:"Dependencies:",DEPENDENTS:"Dependents:",RECURSIVE_TYPE:"Type: Recursive CTE",NONE:"none"}}constructor(e={}){this.options=e,this.dependencyAnalyzer=new ft,this.cteCollector=new X,this.formatter=new Fe(e)}decompose(e){let t=this.cteCollector.collect(e);if(t.length===0)return[];let n=this.findRecursiveCTEs(e,t),r=this.dependencyAnalyzer.analyzeDependencies(e);return this.validateCircularDependencies(n.length>0),this.processCTENodes(e,r.nodes,n)}synchronize(e,t){if(e.length===0)return[];let n=this.flattenNestedWithClauses(e),r={...this.options,addComments:void 0},s=new Yn(r).compose(n,t),o=A.parse(s);return this.decompose(o)}extractCTE(e,t){let n=[],r=this.cteCollector.collect(e);if(r.length===0)throw new Error("Query does not contain any CTEs");if(!r.find(g=>this.getCTEName(g)===t))throw new Error(`CTE not found in query: ${t}`);if(this.findRecursiveCTEs(e,r).includes(t))return n.push("Recursive CTE restoration requires the full query context"),{name:t,executableSql:this.formatter.format(e).formattedSql,dependencies:this.getAllCTENames(r).filter(g=>g!==t),warnings:n};let l=this.dependencyAnalyzer.analyzeDependencies(e);if(this.dependencyAnalyzer.hasCircularDependency())throw new Error("Circular dependency detected in CTEs");let u=l.nodes.find(g=>g.name===t);if(!u||!u.cte)throw new Error(`CTE not found in dependency graph: ${t}`);let c=this.buildExecutableQuery(u,l.nodes),m=this.collectRequiredCTEs(u,l.nodes).map(g=>g.name),f=this.options.addComments?this.addRestorationComments(c,u,n):c;return{name:t,executableSql:f,dependencies:m,warnings:n}}flattenNestedWithClauses(e){let t=[],n=new Map;for(let i of e)try{if(/^\s*with\s+/i.test(i.query)){let o=A.parse(i.query);if(o.withClause&&o.withClause.tables){for(let p of o.withClause.tables){let m=this.getCTEName(p);if(!n.has(m)){let g=new Fe({identifierEscape:{start:"",end:""}}).format(p.query).formattedSql;n.set(m,g)}}let l=new C({selectClause:o.selectClause,fromClause:o.fromClause,whereClause:o.whereClause,groupByClause:o.groupByClause,havingClause:o.havingClause,orderByClause:o.orderByClause,windowClause:o.windowClause,limitClause:o.limitClause,offsetClause:o.offsetClause,fetchClause:o.fetchClause,forClause:o.forClause,withClause:void 0}),c=new Fe({identifierEscape:{start:"",end:""}}).format(l).formattedSql;t.push({name:i.name,query:c})}else t.push(i)}else t.push(i)}catch{t.push(i)}let r=[];for(let[i,s]of n)r.push({name:i,query:s});return r.push(...t),r}validateCircularDependencies(e){if(this.dependencyAnalyzer.hasCircularDependency()&&!e)throw new Error(a.ERROR_MESSAGES.CIRCULAR_REFERENCE)}processCTENodes(e,t,n){let r=[];for(let i of t){if(i.type==="ROOT")continue;n.includes(i.name)?r.push(this.createRecursiveCTE(i,e)):r.push(this.createStandardCTE(i,t))}return r}createRecursiveCTE(e,t){let n=this.formatter.format(t).formattedSql,r=e.dependents.filter(s=>s!=="MAIN_QUERY"),i=this.addCommentsToQuery(n,e.name,e.dependencies,e.dependents,!0);return{name:e.name,query:i,dependencies:[...e.dependencies],dependents:r,isRecursive:!0}}createStandardCTE(e,t){let n=this.buildExecutableQuery(e,t),r=this.addCommentsToQuery(n,e.name,e.dependencies,e.dependents,!1),i=e.dependents.filter(s=>s!=="MAIN_QUERY");return{name:e.name,query:r,dependencies:[...e.dependencies],dependents:i,isRecursive:!1}}buildExecutableQuery(e,t){if(e.type==="ROOT"||!e.cte)throw new Error(`Cannot build executable query for ROOT node: ${e.name}`);let n=this.collectRequiredCTEs(e,t);if(n.length===0)return this.formatter.format(e.cte.query).formattedSql;let r=this.buildWithClause(n),i=this.formatter.format(e.cte.query).formattedSql;return`${r} ${i}`}collectRequiredCTEs(e,t){let n=new Set,r=[],i=new Map;for(let o of t)i.set(o.name,o);let s=o=>{if(n.has(o))return;n.add(o);let l=i.get(o);if(l){for(let u of l.dependencies)s(u);o!==e.name&&l.type!=="ROOT"&&r.push(l)}};for(let o of e.dependencies)s(o);return r}buildWithClause(e){return e.length===0?"":`with ${e.map(n=>{if(n.type==="ROOT"||!n.cte)throw new Error(`Cannot include ROOT node in WITH clause: ${n.name}`);let r=n.name,i=this.formatter.format(n.cte.query).formattedSql;return`${r} as (${i})`}).join(", ")}`}findRecursiveCTEs(e,t){return!e.withClause||!this.isRecursiveWithClause(e)?[]:t.map(n=>this.getCTEName(n))}isRecursiveWithClause(e){return this.formatter.format(e).formattedSql.toLowerCase().includes("with recursive")}addCommentsToQuery(e,t,n,r,i){if(this.options.addComments!==!0)return e;try{let s=A.parse(e);return this.generateComments(t,n,r,i).forEach(u=>{Gn.addComment(s,u)}),new Fe({...this.options,exportComment:!0}).format(s).formattedSql}catch(s){return console.warn(`${a.ERROR_MESSAGES.PARSING_FAILED}: ${s}`),this.addTextCommentsToQuery(e,t,n,r,i)}}generateComments(e,t,n,r){let{AUTO_GENERATED:i,ORIGINAL_CTE:s,DEPENDENCIES:o,DEPENDENTS:l,RECURSIVE_TYPE:u,NONE:c}=a.COMMENT_TEXTS,p=[];p.push(i),p.push(`${s} ${e}`),r&&p.push(u);let m=t.length>0?t.join(", "):c;p.push(`${o} ${m}`);let f=n.filter(h=>h!=="MAIN_QUERY"),g=f.length>0?f.join(", "):c;return p.push(`${l} ${g}`),p}addTextCommentsToQuery(e,t,n,r,i){return`${this.generateComments(t,n,r,i).map(l=>`-- ${l}`).join(`
23
23
  `)}
24
- ${e}`}getCTEName(e){return e.aliasExpression.table.name}};var Vt=class{constructor(){this.columnReferences=[];this.visitedNodes=new Set;this.handlers=new Map,this.handlers.set(ae.kind,e=>this.visitWithClause(e)),this.handlers.set(ne.kind,e=>this.visitCommonTable(e)),this.handlers.set(_.kind,e=>this.visitSelectClause(e)),this.handlers.set(J.kind,e=>this.visitFromClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(me.kind,e=>this.visitGroupByClause(e)),this.handlers.set(de.kind,e=>this.visitHavingClause(e)),this.handlers.set(pe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(nt.kind,e=>this.visitWindowsClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Oe.kind,e=>this.visitOffsetClause(e)),this.handlers.set(Ue.kind,e=>this.visitFetchClause(e)),this.handlers.set(Ne.kind,e=>this.visitForClause(e)),this.handlers.set(fe.kind,e=>this.visitJoinClause(e)),this.handlers.set(he.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Se.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(B.kind,e=>this.visitSourceExpression(e)),this.handlers.set(W.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(b.kind,e=>this.visitColumnReference(e)),this.handlers.set(S.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(K.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ie.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ce.kind,e=>this.visitCastExpression(e)),this.handlers.set(we.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(ge.kind,e=>this.visitInlineQuery(e)),this.handlers.set(ye.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ve.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(U.kind,e=>this.visitValueList(e)),this.handlers.set(Be.kind,e=>this.visitWindowFrameExpression(e))}collect(e){return this.columnReferences=[],this.visitedNodes.clear(),e instanceof C?this.collectFromSimpleQuery(e):e instanceof Q?this.collectFromSimpleQuery(e.toSimpleQuery()):e.accept(this),[...this.columnReferences]}collectFromSimpleQuery(e){if(e.withClause&&e.withClause.tables)for(let t of e.withClause.tables)this.collectFromSimpleQuery(t.query);if(this.collectFromSelectClause(e.selectClause),e.fromClause&&this.collectFromFromClause(e.fromClause),e.whereClause&&this.collectFromValueComponent(e.whereClause.condition),e.groupByClause&&e.groupByClause.grouping)for(let t of e.groupByClause.grouping)this.collectFromValueComponent(t);if(e.havingClause&&this.collectFromValueComponent(e.havingClause.condition),e.orderByClause&&e.orderByClause.order)for(let t of e.orderByClause.order)typeof t=="object"&&"value"in t&&t.value?this.collectFromValueComponent(t.value):this.collectFromValueComponent(t)}collectFromSelectClause(e){for(let t of e.items)this.collectFromValueComponent(t.value)}collectFromFromClause(e){if(this.collectFromSourceExpression(e.source),e.joins)for(let t of e.joins)this.collectFromSourceExpression(t.source),t.condition&&this.collectFromValueComponent(t.condition.condition)}collectFromSourceExpression(e){e.datasource instanceof W&&(e.datasource.query instanceof C?this.collectFromSimpleQuery(e.datasource.query):e.datasource.query instanceof Q&&this.collectFromSimpleQuery(e.datasource.query.toSimpleQuery()))}collectFromValueComponent(e){if(e instanceof b)this.columnReferences.push(e);else if(e instanceof S)this.collectFromValueComponent(e.left),this.collectFromValueComponent(e.right);else if(e instanceof te)this.collectFromValueComponent(e.expression);else if(e instanceof K&&e.argument)this.collectFromValueComponent(e.argument);else if(e instanceof ie){if(e.condition&&this.collectFromValueComponent(e.condition),e.switchCase&&e.switchCase.cases)for(let t of e.switchCase.cases)this.collectFromValueComponent(t.key),this.collectFromValueComponent(t.value);e.switchCase&&e.switchCase.elseValue&&this.collectFromValueComponent(e.switchCase.elseValue)}else e instanceof Y?this.collectFromValueComponent(e.expression):e instanceof ge&&(e.selectQuery instanceof C?this.collectFromSimpleQuery(e.selectQuery):e.selectQuery instanceof Q&&this.collectFromSimpleQuery(e.selectQuery.toSimpleQuery()))}visit(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());t&&t(e)}visitSimpleSelectQuery(e){e.withClause&&e.withClause.accept(this),e.selectClause.accept(this),e.fromClause&&e.fromClause.accept(this),e.whereClause&&e.whereClause.accept(this),e.groupByClause&&e.groupByClause.accept(this),e.havingClause&&e.havingClause.accept(this),e.orderByClause&&e.orderByClause.accept(this),e.windowClause&&e.windowClause.accept(this),e.limitClause&&e.limitClause.accept(this),e.offsetClause&&e.offsetClause.accept(this),e.fetchClause&&e.fetchClause.accept(this),e.forClause&&e.forClause.accept(this)}visitWithClause(e){for(let t of e.tables)t.accept(this)}visitCommonTable(e){e.query.accept(this)}visitSelectClause(e){for(let t of e.items)t.value.accept(this)}visitFromClause(e){if(e.source.accept(this),e.joins)for(let t of e.joins)t.accept(this)}visitWhereClause(e){e.condition.accept(this)}visitGroupByClause(e){if(e.grouping)for(let t of e.grouping)t.accept(this)}visitHavingClause(e){e.condition.accept(this)}visitOrderByClause(e){if(e.order)for(let t of e.order)typeof t=="object"&&"value"in t&&t.value?typeof t.value=="object"&&"accept"in t.value&&t.value.accept(this):typeof t=="object"&&"accept"in t&&t.accept(this)}visitWindowsClause(e){for(let t of e.windows)t.expression.accept(this)}visitLimitClause(e){e.value.accept(this)}visitOffsetClause(e){e.value.accept(this)}visitFetchClause(e){e.expression.accept(this)}visitForClause(e){}visitJoinClause(e){e.source.accept(this),e.condition&&e.condition.accept(this)}visitJoinOnClause(e){e.condition.accept(this)}visitJoinUsingClause(e){e.condition.accept(this)}visitSourceExpression(e){e.datasource.accept(this)}visitSubQuerySource(e){e.query.accept(this)}visitColumnReference(e){this.columnReferences.push(e)}visitBinaryExpression(e){e.left.accept(this),e.right.accept(this)}visitUnaryExpression(e){e.expression.accept(this)}visitFunctionCall(e){e.argument&&e.argument.accept(this)}visitCaseExpression(e){if(e.condition&&e.condition.accept(this),e.switchCase&&e.switchCase.cases)for(let t of e.switchCase.cases)t.key.accept(this),t.value.accept(this);e.switchCase&&e.switchCase.elseValue&&e.switchCase.elseValue.accept(this)}visitCastExpression(e){e.input.accept(this)}visitBetweenExpression(e){e.expression.accept(this),e.lower.accept(this),e.upper.accept(this)}visitParenExpression(e){e.expression.accept(this)}visitInlineQuery(e){e.selectQuery.accept(this)}visitArrayExpression(e){e.expression&&e.expression.accept(this)}visitArrayQueryExpression(e){e.query.accept(this)}visitValueList(e){if(e.values)for(let t of e.values)t.accept(this)}visitWindowFrameExpression(e){e.partition&&e.partition.accept(this),e.order&&e.order.accept(this)}};var Ze={nullQuery:"Query cannot be null or undefined",invalidOldName:"Old CTE name must be a non-empty string",invalidNewName:"New CTE name must be a non-empty string",sameNames:"Old and new CTE names cannot be the same",unsupportedQuery:"Unsupported query type for CTE renaming",cteNotExists:a=>`CTE '${a}' does not exist`,cteAlreadyExists:a=>`CTE '${a}' already exists`,cteNotFound:a=>`CTE '${a}' not found`},Zn=class{constructor(){this.dependencyAnalyzer=new ft,this.columnReferenceCollector=new Vt,this.tableSourceCollector=new He,this.keywordParser=new Ee(Jt)}renameCTE(e,t,n){this.validateInputs(e,t,n);let r=t.trim(),i=n.trim();if(e instanceof C)this.renameInSimpleQuery(e,r,i);else if(e instanceof Q)this.renameInBinaryQuery(e,r,i);else throw new Error(Ze.unsupportedQuery)}validateInputs(e,t,n){if(!e)throw new Error(Ze.nullQuery);if(!t||typeof t!="string"||t.trim()==="")throw new Error(Ze.invalidOldName);if(!n||typeof n!="string"||n.trim()==="")throw new Error(Ze.invalidNewName);if(t.trim()===n.trim())throw new Error(Ze.sameNames)}renameInSimpleQuery(e,t,n){let r=e.getCTENames();if(!r.includes(t))throw new Error(Ze.cteNotExists(t));if(r.includes(n))throw new Error(Ze.cteAlreadyExists(n));this.renameCTEDefinition(e,t,n),this.updateAllReferences(e,t,n)}renameInBinaryQuery(e,t,n){let r=e.toSimpleQuery(),i=[];if(r.withClause&&r.withClause.tables&&(i=r.withClause.tables.map(s=>s.aliasExpression.table.name)),!i.includes(t))throw new Error(Ze.cteNotExists(t));if(i.includes(n))throw new Error(Ze.cteAlreadyExists(n));this.renameCTEDefinition(r,t,n),r.withClause&&(e.withClause=r.withClause,e.left instanceof C&&(e.left.withClause=r.withClause)),this.renameInSelectQuery(e.left,t,n),this.renameInSelectQuery(e.right,t,n)}renameInSelectQuery(e,t,n){e instanceof C?this.updateAllReferences(e,t,n):e instanceof Q&&(this.renameInSelectQuery(e.left,t,n),this.renameInSelectQuery(e.right,t,n))}renameCTEDefinition(e,t,n){if(!e.withClause||!e.withClause.tables)throw new Error(Ze.cteNotFound(t));let r=e.withClause.tables.find(i=>i.aliasExpression.table.name===t);if(!r)throw new Error(Ze.cteNotFound(t));r.aliasExpression.table.name=n}updateAllReferences(e,t,n){let r=this.columnReferenceCollector.collect(e);for(let s of r)if(s.namespaces&&s.namespaces.length>0){for(let o of s.namespaces)if(o.name===t){o.name=n;break}}let i=this.tableSourceCollector.collect(e);for(let s of i)s.getSourceName()===t&&(s.qualifiedName.name instanceof b||("name"in s.qualifiedName.name?s.qualifiedName.name.name=n:s.qualifiedName.name.value=n));this.updateTableSourcesInCTEs(e,t,n)}updateTableSourcesInCTEs(e,t,n){if(!(!e.withClause||!e.withClause.tables))for(let r of e.withClause.tables)this.updateTableSourcesInQuery(r.query,t,n)}updateTableSourcesInQuery(e,t,n){if(e.fromClause&&e.fromClause.source.datasource&&this.updateTableSource(e.fromClause.source.datasource,t,n),e.fromClause&&e.fromClause.joins)for(let r of e.fromClause.joins)r.source.datasource&&this.updateTableSource(r.source.datasource,t,n)}updateTableSource(e,t,n){if(!e||typeof e!="object")return;let r=e;if(typeof r.getSourceName=="function")try{if(r.getSourceName()===t&&r.qualifiedName&&typeof r.qualifiedName=="object"){let s=r.qualifiedName;if(s.name&&typeof s.name=="object"){let o=s.name;"name"in o&&typeof o.name=="string"?o.name=n:"value"in o&&typeof o.value=="string"&&(o.value=n)}}}catch(i){console.warn("Warning: Failed to update table source:",i)}}renameCTEAtPosition(e,t,n){if(!e?.trim())throw new Error("SQL cannot be empty");if(!t||t.line<1||t.column<1)throw new Error("Position must be a valid line/column (1-based)");if(!n?.trim())throw new Error("New CTE name cannot be empty");let r=Le.findLexemeAtLineColumn(e,t);if(!r)throw new Error(`No CTE name found at line ${t.line}, column ${t.column}`);let i=r.value,s=A.parse(e);if(!this.isCTENameInQuery(s,i))throw new Error(`'${i}' is not a CTE name in this query`);if(!(r.type&2112))throw new Error(`Token at position is not a CTE name: '${r.value}'`);let o=this.checkNameConflicts(s,n,i);if(o.length>0)throw new Error(o.join(", "));return this.renameCTE(s,i,n),new Fe().format(s).formattedSql}checkNameConflicts(e,t,n){let r=[];return n===t||(r.push(...this.checkKeywordConflicts(t)),this.isCTENameInQuery(e,t)&&r.push(`CTE name '${t}' already exists`)),r}checkKeywordConflicts(e){let t=[];try{let n=this.keywordParser.parse(e,0);n!==null&&n.keyword.toLowerCase()===e.toLowerCase()&&t.push(`'${e}' is a reserved SQL keyword and should not be used as a CTE name`)}catch(n){console.warn(`Failed to check keyword conflicts for '${e}':`,n),this.isBasicReservedKeyword(e)&&t.push(`'${e}' is a reserved SQL keyword and should not be used as a CTE name`)}return t}isBasicReservedKeyword(e){return["select","from","where","with","as","union","join","table","null"].includes(e.toLowerCase())}isCTENameInQuery(e,t){return e instanceof C&&e.withClause?e.withClause.tables.some(n=>n.aliasExpression&&n.aliasExpression.table&&n.aliasExpression.table.name===t):e instanceof Q?this.isCTENameInQuery(e.left,t)||this.isCTENameInQuery(e.right,t):!1}};var bt={invalidSql:"Invalid SQL: unable to parse query",invalidPosition:"Invalid position: line or column out of bounds",noLexemeAtPosition:"No lexeme found at the specified position",notAnAlias:"Selected lexeme is not a valid alias",invalidNewName:"New alias name must be a non-empty string",sameNames:"Old and new alias names cannot be the same",nameConflict:a=>`Alias '${a}' already exists in this scope`,aliasNotFound:a=>`Alias '${a}' not found in current scope`},Xn=class{constructor(){this.keywordParser=new Ee(Jt)}renameAlias(e,t,n,r={}){try{this.validateInputs(e,t,n);let i=Le.findLexemeAtLineColumn(e,t);if(!i)throw new Error(bt.noLexemeAtPosition);this.validateLexemeIsAlias(i);let s=A.parse(e),o=this.detectAliasScope(e,s,i,r.scopeType),l=this.collectAliasReferences(o,i.value),u=this.checkNameConflicts(o,n,i.value);if(u.length>0)return{success:!1,originalSql:e,changes:[],conflicts:u,scope:o};let c=this.prepareChanges(l,n);if(r.dryRun)return{success:!0,originalSql:e,changes:c,conflicts:u,scope:o};let p=this.performLexemeBasedRename(e,i.value,n,o);return{success:!0,originalSql:e,newSql:p,changes:c,scope:o}}catch(i){return{success:!1,originalSql:e,changes:[],conflicts:[i instanceof Error?i.message:String(i)]}}}validateInputs(e,t,n){if(!e||typeof e!="string"||e.trim()==="")throw new Error(bt.invalidSql);if(!t||typeof t.line!="number"||typeof t.column!="number"||t.line<1||t.column<1)throw new Error(bt.invalidPosition);if(!n||typeof n!="string"||n.trim()==="")throw new Error(bt.invalidNewName)}validateLexemeIsAlias(e){if(!(e.type&64))throw new Error(bt.notAnAlias)}detectAliasScope(e,t,n,r){if(!n.position)return{type:"main",query:t,startPosition:0,endPosition:e.length};let i=n.position.startPosition;return r&&r!=="auto"?this.createScopeForType(r,e,t,i):this.autoDetectScope(e,t,i)}createScopeForType(e,t,n,r){switch(e){case"cte":return this.detectCTEScope(t,n,r);case"subquery":return this.detectSubqueryScope(t,n,r);case"main":default:return{type:"main",query:n,startPosition:0,endPosition:t.length}}}autoDetectScope(e,t,n){let r=this.detectCTEScope(e,t,n);if(r.type==="cte")return r;let i=this.detectSubqueryScope(e,t,n);return i.type==="subquery"?i:{type:"main",query:t,startPosition:0,endPosition:e.length}}detectCTEScope(e,t,n){try{let r=ht.analyzeCursorPosition(e,n);if(r.isInCTE&&r.cteRegion){let i=this.findCTEQueryByName(t,r.cteRegion.name);return{type:"cte",name:r.cteRegion.name,query:i||t,startPosition:r.cteRegion.startPosition,endPosition:r.cteRegion.endPosition}}}catch(r){console.warn("CTE scope detection failed:",r)}return{type:"main",query:t,startPosition:0,endPosition:e.length}}detectSubqueryScope(e,t,n){return{type:"main",query:t,startPosition:0,endPosition:e.length}}findCTEQueryByName(e,t){if(e instanceof C&&e.withClause?.tables){for(let n of e.withClause.tables)if(n.aliasExpression.table.name===t)return n.query}else if(e instanceof Q){let n=this.findCTEQueryByName(e.left,t);if(n)return n;let r=this.findCTEQueryByName(e.right,t);if(r)return r}return null}collectAliasReferences(e,t){let n=[];try{let r=this.collectTableAliasReferences(e,t);n.push(...r);let i=this.collectColumnAliasReferences(e,t);n.push(...i)}catch(r){console.warn(`Failed to collect alias references for '${t}':`,r)}return n}collectTableAliasReferences(e,t){let n=[];try{let i=new He(!0).collect(e.query);for(let s of i)if(s.getSourceName()===t){let l=this.createLexemeFromTableSource(s,t);l&&n.push({lexeme:l,scope:e,referenceType:"definition",context:"table"})}}catch(r){console.warn(`Failed to collect table alias references for '${t}':`,r)}return n}collectColumnAliasReferences(e,t){let n=[];try{let i=new Vt().collect(e.query);for(let s of i)if(s.namespaces&&s.namespaces.length>0){for(let o of s.namespaces)if(o.name===t){let l=this.createLexemeFromNamespace(o,t);l&&n.push({lexeme:l,scope:e,referenceType:"usage",context:"column"})}}}catch(r){console.warn(`Failed to collect column alias references for '${t}':`,r)}return n}createLexemeFromTableSource(e,t){try{return{type:64,value:t,comments:null,position:{startPosition:0,endPosition:t.length}}}catch(n){return console.warn("Failed to create lexeme from table source:",n),null}}createLexemeFromNamespace(e,t){try{return{type:64,value:t,comments:null,position:{startPosition:0,endPosition:t.length}}}catch(n){return console.warn("Failed to create lexeme from namespace:",n),null}}checkNameConflicts(e,t,n){let r=[];if(t.toLowerCase()===n.toLowerCase())return r.push(bt.sameNames),r;try{let i=this.checkTableAliasConflicts(e,t);r.push(...i);let s=this.checkKeywordConflicts(t);r.push(...s)}catch(i){console.warn(`Error during conflict detection for '${t}':`,i),r.push(`Unable to verify conflicts for name '${t}'`)}return r}checkTableAliasConflicts(e,t){let n=[];try{let i=new He(!0).collect(e.query);for(let s of i){let o=s.getSourceName();if(o&&o.toLowerCase()===t.toLowerCase()){n.push(bt.nameConflict(t));continue}let l=this.extractTableName(s);l&&l.toLowerCase()===t.toLowerCase()&&n.push(`'${t}' conflicts with table name in this scope`)}}catch(r){console.warn(`Failed to check table alias conflicts for '${t}':`,r)}return n}extractTableName(e){try{if(e.qualifiedName&&e.qualifiedName.name){let t=e.qualifiedName.name;if(typeof t=="string")return t;if(t.name&&typeof t.name=="string")return t.name;if(t.value&&typeof t.value=="string")return t.value}return e.table&&typeof e.table=="string"?e.table:null}catch(t){return console.warn("Failed to extract table name from table source:",t),null}}checkKeywordConflicts(e){let t=[];if(this.isBasicReservedKeyword(e))return t.push(`'${e}' is a reserved SQL keyword and should not be used as an alias`),t;try{let n=this.keywordParser.parse(e,0);n!==null&&n.keyword.toLowerCase()===e.toLowerCase()&&t.push(`'${e}' is a reserved SQL keyword and should not be used as an alias`)}catch(n){console.warn(`Failed to check keyword conflicts for '${e}':`,n)}return t}isBasicReservedKeyword(e){return["select","from","where","join","table","null","and","or"].includes(e.toLowerCase())}prepareChanges(e,t){return e.map(n=>({oldName:n.lexeme.value,newName:t,position:Le.charOffsetToLineColumn("",n.lexeme.position?.startPosition||0)||{line:1,column:1},context:n.context,referenceType:n.referenceType}))}performLexemeBasedRename(e,t,n,r){try{let s=Le.getAllLexemesWithPosition(e).filter(l=>l.value===t&&l.position&&l.position.startPosition>=r.startPosition&&l.position.endPosition<=r.endPosition&&l.type&64);if(s.length===0)return e;s.sort((l,u)=>u.position.startPosition-l.position.startPosition);let o=e;for(let l of s){let u=l.position;o=o.substring(0,u.startPosition)+n+o.substring(u.endPosition)}return o}catch(i){throw console.error("Failed to perform lexeme-based rename:",i),new Error(`Unable to rename alias using lexeme approach: ${i instanceof Error?i.message:String(i)}`)}}};var er=class{renameIdentifiers(e,t){if(t.size===0)return e;let n=e;for(let[r,i]of t)n=this.replaceIdentifierSafely(n,r,i);return n}renameIdentifier(e,t,n){return this.replaceIdentifierSafely(e,t,n)}renameIdentifierInScope(e,t,n,r){if(!r)return this.replaceIdentifierSafely(e,t,n);let i=e.slice(0,r.start),s=e.slice(r.start,r.end),o=e.slice(r.end),l=this.replaceIdentifierSafely(s,t,n);return i+l+o}checkRenameability(e,t){let n=this.positionToCharIndex(e,t);if(this.isInsideStringLiteral(e,n))return{canRename:!1,reason:"Cannot rename identifiers inside string literal"};let r=this.getIdentifierAtPosition(e,n);if(!r)return{canRename:!1,reason:"No identifier found at position"};let i=this.determineIdentifierType(e,n,r),s=this.calculateScopeRange(e,n,i);return{canRename:!0,currentName:r,type:i,scopeRange:s}}renameAtPosition(e,t,n){let r=this.checkRenameability(e,t);if(!r.canRename||!r.currentName)throw new Error(r.reason||"Cannot rename at this position");return this.renameIdentifierInScope(e,r.currentName,n,r.scopeRange)}positionToCharIndex(e,t){let n=e.split(`
25
- `),r=0;for(let i=0;i<t.line-1&&i<n.length;i++)r+=n[i].length+1;return r+=t.column-1,Math.min(r,e.length-1)}isInsideStringLiteral(e,t){let n=!1;for(let r=0;r<t&&r<e.length;r++)e[r]==="'"&&(n=!n);return n}getIdentifierAtPosition(e,t){if(t>=e.length)return null;let n=t;for(;n>0&&this.isIdentifierChar(e.charCodeAt(n-1));)n--;let r=t;for(;r<e.length&&this.isIdentifierChar(e.charCodeAt(r));)r++;return n===r?null:e.slice(n,r)}determineIdentifierType(e,t,n){let r=e.slice(0,t),i=e.slice(t),s=r.toUpperCase(),o=i.toUpperCase();if(s.lastIndexOf("WITH")!==-1){let y=t;for(;y>0&&this.isIdentifierChar(e.charCodeAt(y-1));)y--;let h=t;for(;h<e.length&&this.isIdentifierChar(e.charCodeAt(h));)h++;if(e.slice(h).toUpperCase().trim().startsWith("AS ("))return"cte"}let u=r.split(`
26
- `),c=u[u.length-1].toUpperCase();if(c.includes("FROM ")||c.includes("JOIN "))return"table_alias";let p=r.slice(Math.max(0,t-50)),d=i.slice(0,50),f=(p+n+d).toUpperCase();return f.includes(" AS "+n.toUpperCase())||f.includes(" "+n.toUpperCase()+" ON")||f.includes(" "+n.toUpperCase()+`
27
- `),"table_alias"}calculateScopeRange(e,t,n){if(n==="cte")return{start:0,end:e.length};let r=e.slice(0,t),i=e.slice(t),s=r.toUpperCase().lastIndexOf("SELECT"),o=s!==-1?s:0,l=i.search(/\b(SELECT|WITH|UNION)\b/i),u=l!==-1?t+l:e.length;return{start:o,end:u}}replaceIdentifierSafely(e,t,n){if(t===n||t.length===0)return e;let r=[],i=0,s=e.length,o=t.length;for(;i<s;){let l=e[i],u=l.charCodeAt(0);if(u===34||u===96||u===91){let{content:c,nextPosition:p}=this.extractAndReplaceQuotedIdentifier(e,i,l,t,n);r.push(c),i=p;continue}if(u===39){let{content:c,nextPosition:p}=this.extractQuotedString(e,i,l);r.push(c),i=p;continue}if(u===45&&i+1<s&&e.charCodeAt(i+1)===45){let{content:c,nextPosition:p}=this.extractLineComment(e,i);r.push(c),i=p;continue}if(u===47&&i+1<s&&e.charCodeAt(i+1)===42){let{content:c,nextPosition:p}=this.extractBlockComment(e,i);r.push(c),i=p;continue}if(this.isIdentifierStartChar(u)&&this.matchesIdentifierAt(e,i,t)){let c=i-1,p=i+o,d=c>=0?e[c]:null,f=p<s?e[p]:null;if(this.hasValidWordBoundaries(d,f)){r.push(n),i+=o;continue}}r.push(l),i++}return r.join("")}validateRename(e,t,n,r){if(e===t||!t.includes(r))return!1;let i=this.countWordOccurrences(e,n);return this.countWordOccurrences(t,n)<i}extractAndReplaceQuotedIdentifier(e,t,n,r,i){if(n==="[")return this.extractAndReplaceBracketedIdentifier(e,t,r,i);let s=[n],o=t+1,l=o;for(;o<e.length;){let u=e[o];if(u===n){if(o+1<e.length&&e[o+1]===n){s.push(u),s.push(e[o+1]),o+=2;continue}let c=e.slice(l,o);c.toLowerCase()===r.toLowerCase()?s.push(i):s.push(c),s.push(u);break}o++}return{content:s.join(""),nextPosition:o+1}}extractAndReplaceBracketedIdentifier(e,t,n,r){let i=["["],s=t+1,o=s;for(;s<e.length;){let l=e[s];if(l==="]"){let u=e.slice(o,s);u.toLowerCase()===n.toLowerCase()?i.push(r):i.push(u),i.push(l);break}s++}return{content:i.join(""),nextPosition:s+1}}extractQuotedString(e,t,n){let r=[n],i=t+1;for(;i<e.length;){let s=e[i];if(r.push(s),s===n){if(i+1<e.length&&e[i+1]===n){r.push(e[i+1]),i+=2;continue}break}i++}return{content:r.join(""),nextPosition:i+1}}extractLineComment(e,t){let n=[],r=t;for(;r<e.length&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)n.push(e[r]),r++;return r<e.length&&(e.charCodeAt(r)===10||e.charCodeAt(r)===13)&&(n.push(e[r]),r++),{content:n.join(""),nextPosition:r}}extractBlockComment(e,t){let n=["/","*"],r=t+2;for(;r<e.length-1;){let i=e[r];if(n.push(i),i==="*"&&e[r+1]==="/"){n.push("/"),r+=2;break}r++}return{content:n.join(""),nextPosition:r}}isIdentifierStartChar(e){return e>=65&&e<=90||e>=97&&e<=122||e===95}isIdentifierChar(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95}matchesIdentifierAt(e,t,n){if(t+n.length>e.length)return!1;for(let r=0;r<n.length;r++){let i=e.charCodeAt(t+r),s=n.charCodeAt(r),o=i>=65&&i<=90?i+32:i,l=s>=65&&s<=90?s+32:s;if(o!==l)return!1}return!0}hasValidWordBoundaries(e,t){let n=e===null||!this.isIdentifierChar(e.charCodeAt(0)),r=t===null||!this.isIdentifierChar(t.charCodeAt(0));return n&&r}countWordOccurrences(e,t){let n=0,r=0,i=e.length,s=t.length;for(;r<=i-s;){if(this.matchesIdentifierAt(e,r,t)){let o=r-1,l=r+s,u=o>=0?e[o]:null,c=l<i?e[l]:null;this.hasValidWordBoundaries(u,c)&&n++}r++}return n}};var Or=class{constructor(){this.cteRenamer=new Zn,this.aliasRenamer=new Xn,this.identifierRenamer=new er}isRenameable(e,t){try{if(!e?.trim())return{renameable:!1,renamerType:"none",reason:"Empty SQL"};if(!t||t.line<1||t.column<1)return{renameable:!1,renamerType:"none",reason:"Invalid position"};let n=Le.findLexemeAtLineColumn(e,t);if(!n)return{renameable:!1,renamerType:"none",reason:"No token found"};if(!(n.type&2112))return{renameable:!1,renamerType:"none",tokenName:n.value,reason:`Token '${n.value}' is not an identifier`};let r=n.value,i=this.detectRenamerType(e,r);return i==="unknown"?{renameable:!1,renamerType:"none",tokenName:r,reason:`Cannot determine if '${r}' is renameable`}:{renameable:!0,renamerType:i,tokenName:r}}catch(n){return{renameable:!1,renamerType:"none",reason:`Error: ${n instanceof Error?n.message:String(n)}`}}}rename(e,t,n,r){try{if(!e?.trim())return this.createErrorResult(e,n,"unknown","","SQL cannot be empty");if(!t||t.line<1||t.column<1)return this.createErrorResult(e,n,"unknown","","Position must be valid line/column (1-based)");if(!n?.trim())return this.createErrorResult(e,n,"unknown","","New name cannot be empty");let i=Le.findLexemeAtLineColumn(e,t);if(!i)return this.createErrorResult(e,n,"unknown","",`No identifier found at line ${t.line}, column ${t.column}`);if(!(i.type&64))return this.createErrorResult(e,n,"unknown",i.value,`Token '${i.value}' is not renameable`);let s=i.value,o=r?.preserveFormatting??!1,l=this.detectRenamerType(e,s);if(o)try{let u=this.attemptFormattingPreservationRename(e,t,n,s,l);if(u.success)return u}catch(u){console.warn("Formatting preservation failed, falling back to standard rename:",u)}try{let u;if(l==="cte")u=this.cteRenamer.renameCTEAtPosition(e,t,n);else if(l==="alias"){let c=this.aliasRenamer.renameAlias(e,t,n);if(!c.success)return{success:!1,originalSql:e,renamerType:"alias",originalName:s,newName:n,error:c.conflicts?.join(", ")||"Alias rename failed",formattingPreserved:!1,formattingMethod:"smart-renamer-only"};u=c.newSql}else return this.createErrorResult(e,n,"unknown",s,`Cannot determine if '${s}' is a CTE name or table alias`);return{success:!0,originalSql:e,newSql:u,renamerType:l,originalName:s,newName:n,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}catch(u){return this.createErrorResult(e,n,l,s,`${l.toUpperCase()} rename failed: ${u instanceof Error?u.message:String(u)}`)}}catch(i){return this.createErrorResult(e,n,"unknown","",`Unexpected error: ${i instanceof Error?i.message:String(i)}`)}}detectRenamerType(e,t){try{let n=A.parse(e);return this.isCTEName(n,t)?"cte":"alias"}catch{return"unknown"}}isCTEName(e,t){return e instanceof C&&e.withClause?e.withClause.tables.some(n=>n.aliasExpression&&n.aliasExpression.table&&n.aliasExpression.table.name===t):e instanceof Q?this.isCTEName(e.left,t)||this.isCTEName(e.right,t):!1}attemptFormattingPreservationRename(e,t,n,r,i){let s=this.performStandardRename(e,t,n,r,i);if(!s.success)return{...s,formattingPreserved:!1,formattingMethod:"smart-renamer-only"};let o=new Map([[r,n]]);try{let l=this.identifierRenamer.renameIdentifiers(e,o);if(this.validateRenameResult(e,l,r,n))return{success:!0,originalSql:e,newSql:l,renamerType:i,originalName:r,newName:n,formattingPreserved:!0,formattingMethod:"sql-identifier-renamer"};throw new Error("Validation failed: rename may not have been applied correctly")}catch{return{...s,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}}performStandardRename(e,t,n,r,i){try{let s;if(i==="cte")s=this.cteRenamer.renameCTEAtPosition(e,t,n);else if(i==="alias"){let o=this.aliasRenamer.renameAlias(e,t,n);if(!o.success)return{success:!1,originalSql:e,renamerType:"alias",originalName:r,newName:n,error:o.conflicts?.join(", ")||"Alias rename failed"};s=o.newSql}else return{success:!1,originalSql:e,renamerType:"unknown",originalName:r,newName:n,error:`Cannot determine if '${r}' is a CTE name or table alias`};return{success:!0,originalSql:e,newSql:s,renamerType:i,originalName:r,newName:n}}catch(s){return{success:!1,originalSql:e,renamerType:i,originalName:r,newName:n,error:`${i.toUpperCase()} rename failed: ${s instanceof Error?s.message:String(s)}`}}}validateRenameResult(e,t,n,r){if(e===t||!t.includes(r))return!1;let i=this.countWordOccurrences(e,n);return this.countWordOccurrences(t,n)<i}countWordOccurrences(e,t){let n=new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"gi"),r=e.match(n);return r?r.length:0}createErrorResult(e,t,n,r,i){return{success:!1,originalSql:e,renamerType:n,originalName:r,newName:t,error:i,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}batchRename(e,t,n){if(n?.preserveFormatting??!1)try{let i=new Map(Object.entries(t)),s=this.identifierRenamer.renameIdentifiers(e,i),o=Object.keys(t),l=Object.values(t);return{success:!0,originalSql:e,newSql:s,renamerType:"alias",originalName:o.join(", "),newName:l.join(", "),formattingPreserved:!0,formattingMethod:"sql-identifier-renamer"}}catch(i){return{success:!1,originalSql:e,renamerType:"unknown",originalName:Object.keys(t).join(", "),newName:Object.values(t).join(", "),error:`Batch rename failed: ${i instanceof Error?i.message:String(i)}`,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}else return{success:!1,originalSql:e,renamerType:"unknown",originalName:Object.keys(t).join(", "),newName:Object.values(t).join(", "),error:"Batch rename without formatting preservation not implemented. Use individual renames or enable formatting preservation.",formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}};var Fr=class{restore(e){if(e.length===0)return"";let t="";for(let n of e)t+=n.value,n.followingWhitespace&&(t+=n.followingWhitespace);return t}restoreWithComments(e,t=!0){if(e.length===0)return"";let n="";for(let r of e){if(n+=r.value,t&&r.inlineComments&&r.inlineComments.length>0)for(let i of r.inlineComments)i.trim().length>0&&(n+=` -- ${i}`);r.followingWhitespace&&(n+=r.followingWhitespace)}return n}analyzeFormatting(e){let t=0,n=0,r=0,i=0,s=0,o=0;for(let u of e){if(u.followingWhitespace){t+=u.followingWhitespace.length;let c=u.followingWhitespace.split(`
28
- `);for(let p=1;p<c.length;p++){let d=c[p],f=d.match(/^ */)?.[0].length||0,y=d.match(/^\t*/)?.[0].length||0;(f>0||y>0)&&(s++,o+=f+y*4,r+=f,i+=y)}}u.inlineComments&&(n+=u.inlineComments.length)}let l="none";return r>0&&i>0?l="mixed":r>0?l="spaces":i>0&&(l="tabs"),{totalWhitespace:t,totalComments:n,indentationStyle:l,averageIndentSize:s>0?o/s:0}}validateFormattingLexemes(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];r.position||t.push(`Lexeme ${n} missing position information`),r.followingWhitespace===void 0&&t.push(`Lexeme ${n} missing followingWhitespace property`),r.inlineComments===void 0&&t.push(`Lexeme ${n} missing inlineComments property`),r.position&&r.position.startPosition>=r.position.endPosition&&t.push(`Lexeme ${n} has invalid position range`)}return{isValid:t.length===0,issues:t}}};var tr=class a{constructor(){this.jsonColumnCounter=0;this.entityToJsonColumnMap=new Map;this.columnMappings=[]}static{this.CTE_OBJECT_PREFIX="cte_object_depth_"}static{this.WILDCARD_COLUMN="*"}buildObjectEntityCtes(e,t,n){this.jsonColumnCounter=0,this.entityToJsonColumnMap.clear(),this.columnMappings=[];let r=[e],i=e.aliasExpression.table.name,s=this.collectAndSortObjectEntities(n,t),o=this.groupEntitiesByDepth(s),l=Array.from(o.keys()).sort((u,c)=>c-u);for(let u of l){let c=o.get(u),p=`${a.CTE_OBJECT_PREFIX}${u}`,d=this.buildDepthCte(c,i,p,n,t);r.push(d),i=p}return{ctes:r,lastCteAlias:i,columnMappings:this.columnMappings}}generateUniqueJsonColumnName(e,t,n){this.jsonColumnCounter++;let r=`${e.toLowerCase()}_json_${this.jsonColumnCounter}`;return this.columnMappings.push({entityId:t,entityName:e,generatedColumnName:r,depth:n}),r}collectAndSortObjectEntities(e,t){let n=[],r=i=>{let s=t.get(i);if(!s)throw new Error(`Entity ${i} not found for depth calculation.`);if(s.isRoot)return 0;if(!s.parentId)return 1;let o=s.parentId,l=0,u=new Set;for(u.add(i);o;){if(u.has(o))throw new Error(`Circular dependency detected: ${o} already visited in path for ${i}`);u.add(o);let c=t.get(o);if(!c)throw new Error(`Parent entity ${o} not found during depth calculation for ${i}`);let p=!1;if(c.isRoot)p=!0;else{let d=e.nestedEntities.find(f=>f.id===o);if(d)d.relationshipType==="object"&&(p=!0);else throw new Error(`Parent entity ${o} (ancestor of ${i}) has no definition in mapping.nestedEntities and is not root.`)}if(p&&l++,c.isRoot)break;o=c.parentId}return l};return e.nestedEntities.forEach(i=>{if(i.relationshipType==="object"){let s=t.get(i.id);s&&!s.isRoot&&n.push({entity:s,depth:r(i.id)})}}),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let r=n.depth;t.has(r)||t.set(r,[]),t.get(r).push(n)}),t}buildDepthCte(e,t,n,r,i){let s=[new z(new b(null,new P(a.WILDCARD_COLUMN)))];for(let{entity:l}of e){let u=this.buildEntityJsonColumn(l,r,i);s.push(u)}let o=new C({selectClause:new _(s),fromClause:new J(new B(new R(null,new P(t)),null),null)});return new ne(o,new re(n,null),null)}buildEntityJsonColumn(e,t,n){let{jsonObjectArgs:r,nullChecks:i}=this.prepareEntityColumns(e);this.addChildObjectRelationships(e,r,t,n);let s=this.createJsonObject(r),o=this.buildNullCondition(i),l=this.createCaseExpression(o,s),u=this.calculateApproximateDepth(e,t),c=this.generateUniqueJsonColumnName(e.name,e.id,u);return this.entityToJsonColumnMap.set(e.id,c),new z(l,c)}calculateApproximateDepth(e,t){if(e.isRoot)return 0;if(!e.parentId)return 1;let n=1,r=e.parentId;for(;r&&r!==t.rootEntity.id;){let i=t.nestedEntities.find(s=>s.id===r);if(!i)break;n++,r=i.parentId}return n}prepareEntityColumns(e){let t=[],n=[];return Object.entries(e.columns).forEach(([r,i])=>{t.push(new Z(r,void 0,!0)),t.push(new b(null,new P(i))),n.push(new S(new b(null,new P(i)),"is",new Z(null)))}),{jsonObjectArgs:t,nullChecks:n}}addChildObjectRelationships(e,t,n,r){n.nestedEntities.filter(s=>s.parentId===e.id&&s.relationshipType==="object").forEach(s=>{let o=r.get(s.id);if(o){t.push(new Z(s.propertyName,void 0,!0));let l=this.entityToJsonColumnMap.get(o.id);if(!l)throw new Error(`JSON column name not found for child entity: ${o.id}`);t.push(new b(null,new P(l)))}})}createJsonObject(e){let t="jsonb_build_object";return new K(null,new V(t),new U(e),null)}buildNullCondition(e){return e.reduce((t,n)=>t?new S(t,"and",n):n)}createCaseExpression(e,t){return new ie(null,new Te([new ke(e,new Z(null))],t))}};var nr=class a{static{this.CTE_ARRAY_PREFIX="cte_array_depth_"}static{this.JSON_FUNCTIONS={BUILD_OBJECT:"jsonb_build_object",AGGREGATE:"jsonb_agg"}}buildArrayEntityCtes(e,t,n,r,i){let s=[...e],o=t,l=this.collectAndSortArrayEntities(r,n);if(l.length===0)return{updatedCtes:s,lastCteAlias:o};let u=this.groupEntitiesByDepth(l),c=Array.from(u.keys()).sort((p,d)=>d-p);for(let p of c){let d=u.get(p),{cte:f,newCteAlias:y}=this.buildDepthCte(d,o,s,p,r,i);s.push(f),o=y}return{updatedCtes:s,lastCteAlias:o}}collectAndSortArrayEntities(e,t){let n=[],r=i=>{let s=t.get(i);return!s||s.isRoot?0:s.parentId?1+r(s.parentId):1};return e.nestedEntities.forEach(i=>{if(i.relationshipType==="array"){let s=t.get(i.id),o=t.get(i.parentId);if(!s||!o)throw new Error(`Configuration error: Array entity '${i.id}' or its parent '${i.parentId}' not found.`);let l=Object.values(o.columns);if(l.length===0)throw new Error(`Configuration error: Parent entity '${o.name}' (ID: ${o.id}) must have at least one column defined to serve as a linking key for child array '${i.name}'.`);let u=l[0];n.push({entity:s,parentEntity:o,parentIdColumnSqlName:u,depth:r(i.id)})}}),n.sort((i,s)=>s.depth-i.depth),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let r=n.depth;t.has(r)||t.set(r,[]),t.get(r).push(n)}),t}buildDepthCte(e,t,n,r,i,s){let o=new Set;e.forEach(x=>{Object.values(x.entity.columns).forEach(I=>o.add(I));let g=I=>{i.nestedEntities.filter(T=>T.parentId===I).forEach(T=>{Object.values(T.columns).forEach(D=>{let E=typeof D=="string"?D:D.column;o.add(E)}),g(T.id)})};g(x.entity.id)});let l=n.find(x=>x.aliasExpression.table.name===t)?.query;if(!l)throw new Error(`CTE not found: ${t}`);let u=new Ke(null,n).collect(l),c=[],p=[],d=new Set;e.forEach(x=>{Object.values(x.entity.columns).forEach(g=>d.add(g))});let f=this.collectArrayEntityColumnsByDepth(i,r),y=new Set;s&&e.forEach(x=>{i.nestedEntities.filter(g=>g.parentId===x.entity.id&&g.relationshipType==="object").forEach(g=>{let I=s.find(T=>T.entityId===g.id);I&&y.add(I.generatedColumnName)})}),this.processSelectVariablesForGroupBy(u,o,f,r,p,c,y);for(let x of e){let g=this.buildAggregationDetailsForArrayEntity(x.entity,i.nestedEntities,new Map,s);p.push(new z(g.jsonAgg,x.entity.propertyName))}let h=`${a.CTE_ARRAY_PREFIX}${r}`,M=new C({selectClause:new _(p),fromClause:new J(new B(new R(null,new P(t)),null),null),groupByClause:c.length>0?new me(c):null});return{cte:new ne(M,new re(h,null),null),newCteAlias:h}}buildAggregationDetailsForArrayEntity(e,t,n,r){let i=a.JSON_FUNCTIONS.BUILD_OBJECT,s=[];Object.entries(e.columns).forEach(([d,f])=>{s.push(new Z(d,void 0,!0)),s.push(new b(null,new P(f)))}),t.filter(d=>d.parentId===e.id).forEach(d=>{let f=d.originalPropertyName||d.propertyName;if(s.push(new Z(f,void 0,!0)),d.relationshipType==="object"){if(!r)throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mappings not provided
24
+ ${e}`}addRestorationComments(e,t,n){let r=[];return r.push("-- CTE Restoration: "+t.name),t.dependencies.length>0?r.push("-- Dependencies: "+t.dependencies.join(", ")):r.push("-- Dependencies: none"),n.length>0&&r.push("-- Warnings: "+n.join(", ")),r.push("-- Generated by CTEQueryDecomposer.extractCTE()"),r.push(""),r.join(`
25
+ `)+e}getAllCTENames(e){return e.map(t=>this.getCTEName(t))}getCTEName(e){return e.aliasExpression.table.name}};var Vt=class{constructor(){this.columnReferences=[];this.visitedNodes=new Set;this.handlers=new Map,this.handlers.set(ae.kind,e=>this.visitWithClause(e)),this.handlers.set(ne.kind,e=>this.visitCommonTable(e)),this.handlers.set(_.kind,e=>this.visitSelectClause(e)),this.handlers.set(J.kind,e=>this.visitFromClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(me.kind,e=>this.visitGroupByClause(e)),this.handlers.set(de.kind,e=>this.visitHavingClause(e)),this.handlers.set(pe.kind,e=>this.visitOrderByClause(e)),this.handlers.set(nt.kind,e=>this.visitWindowsClause(e)),this.handlers.set(oe.kind,e=>this.visitLimitClause(e)),this.handlers.set(Re.kind,e=>this.visitOffsetClause(e)),this.handlers.set(Ue.kind,e=>this.visitFetchClause(e)),this.handlers.set(Ne.kind,e=>this.visitForClause(e)),this.handlers.set(fe.kind,e=>this.visitJoinClause(e)),this.handlers.set(he.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Se.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(B.kind,e=>this.visitSourceExpression(e)),this.handlers.set(j.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(b.kind,e=>this.visitColumnReference(e)),this.handlers.set(S.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(K.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ie.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ce.kind,e=>this.visitCastExpression(e)),this.handlers.set(we.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(ge.kind,e=>this.visitInlineQuery(e)),this.handlers.set(ye.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ve.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(U.kind,e=>this.visitValueList(e)),this.handlers.set(Be.kind,e=>this.visitWindowFrameExpression(e))}collect(e){return this.columnReferences=[],this.visitedNodes.clear(),e instanceof C?this.collectFromSimpleQuery(e):e instanceof Q?this.collectFromSimpleQuery(e.toSimpleQuery()):e.accept(this),[...this.columnReferences]}collectFromSimpleQuery(e){if(e.withClause&&e.withClause.tables)for(let t of e.withClause.tables)this.collectFromSimpleQuery(t.query);if(this.collectFromSelectClause(e.selectClause),e.fromClause&&this.collectFromFromClause(e.fromClause),e.whereClause&&this.collectFromValueComponent(e.whereClause.condition),e.groupByClause&&e.groupByClause.grouping)for(let t of e.groupByClause.grouping)this.collectFromValueComponent(t);if(e.havingClause&&this.collectFromValueComponent(e.havingClause.condition),e.orderByClause&&e.orderByClause.order)for(let t of e.orderByClause.order)typeof t=="object"&&"value"in t&&t.value?this.collectFromValueComponent(t.value):this.collectFromValueComponent(t)}collectFromSelectClause(e){for(let t of e.items)this.collectFromValueComponent(t.value)}collectFromFromClause(e){if(this.collectFromSourceExpression(e.source),e.joins)for(let t of e.joins)this.collectFromSourceExpression(t.source),t.condition&&this.collectFromValueComponent(t.condition.condition)}collectFromSourceExpression(e){e.datasource instanceof j&&(e.datasource.query instanceof C?this.collectFromSimpleQuery(e.datasource.query):e.datasource.query instanceof Q&&this.collectFromSimpleQuery(e.datasource.query.toSimpleQuery()))}collectFromValueComponent(e){if(e instanceof b)this.columnReferences.push(e);else if(e instanceof S)this.collectFromValueComponent(e.left),this.collectFromValueComponent(e.right);else if(e instanceof te)this.collectFromValueComponent(e.expression);else if(e instanceof K&&e.argument)this.collectFromValueComponent(e.argument);else if(e instanceof ie){if(e.condition&&this.collectFromValueComponent(e.condition),e.switchCase&&e.switchCase.cases)for(let t of e.switchCase.cases)this.collectFromValueComponent(t.key),this.collectFromValueComponent(t.value);e.switchCase&&e.switchCase.elseValue&&this.collectFromValueComponent(e.switchCase.elseValue)}else e instanceof Y?this.collectFromValueComponent(e.expression):e instanceof ge&&(e.selectQuery instanceof C?this.collectFromSimpleQuery(e.selectQuery):e.selectQuery instanceof Q&&this.collectFromSimpleQuery(e.selectQuery.toSimpleQuery()))}visit(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());t&&t(e)}visitSimpleSelectQuery(e){e.withClause&&e.withClause.accept(this),e.selectClause.accept(this),e.fromClause&&e.fromClause.accept(this),e.whereClause&&e.whereClause.accept(this),e.groupByClause&&e.groupByClause.accept(this),e.havingClause&&e.havingClause.accept(this),e.orderByClause&&e.orderByClause.accept(this),e.windowClause&&e.windowClause.accept(this),e.limitClause&&e.limitClause.accept(this),e.offsetClause&&e.offsetClause.accept(this),e.fetchClause&&e.fetchClause.accept(this),e.forClause&&e.forClause.accept(this)}visitWithClause(e){for(let t of e.tables)t.accept(this)}visitCommonTable(e){e.query.accept(this)}visitSelectClause(e){for(let t of e.items)t.value.accept(this)}visitFromClause(e){if(e.source.accept(this),e.joins)for(let t of e.joins)t.accept(this)}visitWhereClause(e){e.condition.accept(this)}visitGroupByClause(e){if(e.grouping)for(let t of e.grouping)t.accept(this)}visitHavingClause(e){e.condition.accept(this)}visitOrderByClause(e){if(e.order)for(let t of e.order)typeof t=="object"&&"value"in t&&t.value?typeof t.value=="object"&&"accept"in t.value&&t.value.accept(this):typeof t=="object"&&"accept"in t&&t.accept(this)}visitWindowsClause(e){for(let t of e.windows)t.expression.accept(this)}visitLimitClause(e){e.value.accept(this)}visitOffsetClause(e){e.value.accept(this)}visitFetchClause(e){e.expression.accept(this)}visitForClause(e){}visitJoinClause(e){e.source.accept(this),e.condition&&e.condition.accept(this)}visitJoinOnClause(e){e.condition.accept(this)}visitJoinUsingClause(e){e.condition.accept(this)}visitSourceExpression(e){e.datasource.accept(this)}visitSubQuerySource(e){e.query.accept(this)}visitColumnReference(e){this.columnReferences.push(e)}visitBinaryExpression(e){e.left.accept(this),e.right.accept(this)}visitUnaryExpression(e){e.expression.accept(this)}visitFunctionCall(e){e.argument&&e.argument.accept(this)}visitCaseExpression(e){if(e.condition&&e.condition.accept(this),e.switchCase&&e.switchCase.cases)for(let t of e.switchCase.cases)t.key.accept(this),t.value.accept(this);e.switchCase&&e.switchCase.elseValue&&e.switchCase.elseValue.accept(this)}visitCastExpression(e){e.input.accept(this)}visitBetweenExpression(e){e.expression.accept(this),e.lower.accept(this),e.upper.accept(this)}visitParenExpression(e){e.expression.accept(this)}visitInlineQuery(e){e.selectQuery.accept(this)}visitArrayExpression(e){e.expression&&e.expression.accept(this)}visitArrayQueryExpression(e){e.query.accept(this)}visitValueList(e){if(e.values)for(let t of e.values)t.accept(this)}visitWindowFrameExpression(e){e.partition&&e.partition.accept(this),e.order&&e.order.accept(this)}};var Ze={nullQuery:"Query cannot be null or undefined",invalidOldName:"Old CTE name must be a non-empty string",invalidNewName:"New CTE name must be a non-empty string",sameNames:"Old and new CTE names cannot be the same",unsupportedQuery:"Unsupported query type for CTE renaming",cteNotExists:a=>`CTE '${a}' does not exist`,cteAlreadyExists:a=>`CTE '${a}' already exists`,cteNotFound:a=>`CTE '${a}' not found`},Zn=class{constructor(){this.dependencyAnalyzer=new ft,this.columnReferenceCollector=new Vt,this.tableSourceCollector=new He,this.keywordParser=new Ee(Jt)}renameCTE(e,t,n){this.validateInputs(e,t,n);let r=t.trim(),i=n.trim();if(e instanceof C)this.renameInSimpleQuery(e,r,i);else if(e instanceof Q)this.renameInBinaryQuery(e,r,i);else throw new Error(Ze.unsupportedQuery)}validateInputs(e,t,n){if(!e)throw new Error(Ze.nullQuery);if(!t||typeof t!="string"||t.trim()==="")throw new Error(Ze.invalidOldName);if(!n||typeof n!="string"||n.trim()==="")throw new Error(Ze.invalidNewName);if(t.trim()===n.trim())throw new Error(Ze.sameNames)}renameInSimpleQuery(e,t,n){let r=e.getCTENames();if(!r.includes(t))throw new Error(Ze.cteNotExists(t));if(r.includes(n))throw new Error(Ze.cteAlreadyExists(n));this.renameCTEDefinition(e,t,n),this.updateAllReferences(e,t,n)}renameInBinaryQuery(e,t,n){let r=e.toSimpleQuery(),i=[];if(r.withClause&&r.withClause.tables&&(i=r.withClause.tables.map(s=>s.aliasExpression.table.name)),!i.includes(t))throw new Error(Ze.cteNotExists(t));if(i.includes(n))throw new Error(Ze.cteAlreadyExists(n));this.renameCTEDefinition(r,t,n),r.withClause&&(e.withClause=r.withClause,e.left instanceof C&&(e.left.withClause=r.withClause)),this.renameInSelectQuery(e.left,t,n),this.renameInSelectQuery(e.right,t,n)}renameInSelectQuery(e,t,n){e instanceof C?this.updateAllReferences(e,t,n):e instanceof Q&&(this.renameInSelectQuery(e.left,t,n),this.renameInSelectQuery(e.right,t,n))}renameCTEDefinition(e,t,n){if(!e.withClause||!e.withClause.tables)throw new Error(Ze.cteNotFound(t));let r=e.withClause.tables.find(i=>i.aliasExpression.table.name===t);if(!r)throw new Error(Ze.cteNotFound(t));r.aliasExpression.table.name=n}updateAllReferences(e,t,n){let r=this.columnReferenceCollector.collect(e);for(let s of r)if(s.namespaces&&s.namespaces.length>0){for(let o of s.namespaces)if(o.name===t){o.name=n;break}}let i=this.tableSourceCollector.collect(e);for(let s of i)s.getSourceName()===t&&(s.qualifiedName.name instanceof b||("name"in s.qualifiedName.name?s.qualifiedName.name.name=n:s.qualifiedName.name.value=n));this.updateTableSourcesInCTEs(e,t,n)}updateTableSourcesInCTEs(e,t,n){if(!(!e.withClause||!e.withClause.tables))for(let r of e.withClause.tables)this.updateTableSourcesInQuery(r.query,t,n)}updateTableSourcesInQuery(e,t,n){if(e.fromClause&&e.fromClause.source.datasource&&this.updateTableSource(e.fromClause.source.datasource,t,n),e.fromClause&&e.fromClause.joins)for(let r of e.fromClause.joins)r.source.datasource&&this.updateTableSource(r.source.datasource,t,n)}updateTableSource(e,t,n){if(!e||typeof e!="object")return;let r=e;if(typeof r.getSourceName=="function")try{if(r.getSourceName()===t&&r.qualifiedName&&typeof r.qualifiedName=="object"){let s=r.qualifiedName;if(s.name&&typeof s.name=="object"){let o=s.name;"name"in o&&typeof o.name=="string"?o.name=n:"value"in o&&typeof o.value=="string"&&(o.value=n)}}}catch(i){console.warn("Warning: Failed to update table source:",i)}}renameCTEAtPosition(e,t,n){if(!e?.trim())throw new Error("SQL cannot be empty");if(!t||t.line<1||t.column<1)throw new Error("Position must be a valid line/column (1-based)");if(!n?.trim())throw new Error("New CTE name cannot be empty");let r=Le.findLexemeAtLineColumn(e,t);if(!r)throw new Error(`No CTE name found at line ${t.line}, column ${t.column}`);let i=r.value,s=A.parse(e);if(!this.isCTENameInQuery(s,i))throw new Error(`'${i}' is not a CTE name in this query`);if(!(r.type&2112))throw new Error(`Token at position is not a CTE name: '${r.value}'`);let o=this.checkNameConflicts(s,n,i);if(o.length>0)throw new Error(o.join(", "));return this.renameCTE(s,i,n),new Fe().format(s).formattedSql}checkNameConflicts(e,t,n){let r=[];return n===t||(r.push(...this.checkKeywordConflicts(t)),this.isCTENameInQuery(e,t)&&r.push(`CTE name '${t}' already exists`)),r}checkKeywordConflicts(e){let t=[];try{let n=this.keywordParser.parse(e,0);n!==null&&n.keyword.toLowerCase()===e.toLowerCase()&&t.push(`'${e}' is a reserved SQL keyword and should not be used as a CTE name`)}catch(n){console.warn(`Failed to check keyword conflicts for '${e}':`,n),this.isBasicReservedKeyword(e)&&t.push(`'${e}' is a reserved SQL keyword and should not be used as a CTE name`)}return t}isBasicReservedKeyword(e){return["select","from","where","with","as","union","join","table","null"].includes(e.toLowerCase())}isCTENameInQuery(e,t){return e instanceof C&&e.withClause?e.withClause.tables.some(n=>n.aliasExpression&&n.aliasExpression.table&&n.aliasExpression.table.name===t):e instanceof Q?this.isCTENameInQuery(e.left,t)||this.isCTENameInQuery(e.right,t):!1}};var bt={invalidSql:"Invalid SQL: unable to parse query",invalidPosition:"Invalid position: line or column out of bounds",noLexemeAtPosition:"No lexeme found at the specified position",notAnAlias:"Selected lexeme is not a valid alias",invalidNewName:"New alias name must be a non-empty string",sameNames:"Old and new alias names cannot be the same",nameConflict:a=>`Alias '${a}' already exists in this scope`,aliasNotFound:a=>`Alias '${a}' not found in current scope`},Xn=class{constructor(){this.keywordParser=new Ee(Jt)}renameAlias(e,t,n,r={}){try{this.validateInputs(e,t,n);let i=Le.findLexemeAtLineColumn(e,t);if(!i)throw new Error(bt.noLexemeAtPosition);this.validateLexemeIsAlias(i);let s=A.parse(e),o=this.detectAliasScope(e,s,i,r.scopeType),l=this.collectAliasReferences(o,i.value),u=this.checkNameConflicts(o,n,i.value);if(u.length>0)return{success:!1,originalSql:e,changes:[],conflicts:u,scope:o};let c=this.prepareChanges(l,n);if(r.dryRun)return{success:!0,originalSql:e,changes:c,conflicts:u,scope:o};let p=this.performLexemeBasedRename(e,i.value,n,o);return{success:!0,originalSql:e,newSql:p,changes:c,scope:o}}catch(i){return{success:!1,originalSql:e,changes:[],conflicts:[i instanceof Error?i.message:String(i)]}}}validateInputs(e,t,n){if(!e||typeof e!="string"||e.trim()==="")throw new Error(bt.invalidSql);if(!t||typeof t.line!="number"||typeof t.column!="number"||t.line<1||t.column<1)throw new Error(bt.invalidPosition);if(!n||typeof n!="string"||n.trim()==="")throw new Error(bt.invalidNewName)}validateLexemeIsAlias(e){if(!(e.type&64))throw new Error(bt.notAnAlias)}detectAliasScope(e,t,n,r){if(!n.position)return{type:"main",query:t,startPosition:0,endPosition:e.length};let i=n.position.startPosition;return r&&r!=="auto"?this.createScopeForType(r,e,t,i):this.autoDetectScope(e,t,i)}createScopeForType(e,t,n,r){switch(e){case"cte":return this.detectCTEScope(t,n,r);case"subquery":return this.detectSubqueryScope(t,n,r);case"main":default:return{type:"main",query:n,startPosition:0,endPosition:t.length}}}autoDetectScope(e,t,n){let r=this.detectCTEScope(e,t,n);if(r.type==="cte")return r;let i=this.detectSubqueryScope(e,t,n);return i.type==="subquery"?i:{type:"main",query:t,startPosition:0,endPosition:e.length}}detectCTEScope(e,t,n){try{let r=ht.analyzeCursorPosition(e,n);if(r.isInCTE&&r.cteRegion){let i=this.findCTEQueryByName(t,r.cteRegion.name);return{type:"cte",name:r.cteRegion.name,query:i||t,startPosition:r.cteRegion.startPosition,endPosition:r.cteRegion.endPosition}}}catch(r){console.warn("CTE scope detection failed:",r)}return{type:"main",query:t,startPosition:0,endPosition:e.length}}detectSubqueryScope(e,t,n){return{type:"main",query:t,startPosition:0,endPosition:e.length}}findCTEQueryByName(e,t){if(e instanceof C&&e.withClause?.tables){for(let n of e.withClause.tables)if(n.aliasExpression.table.name===t)return n.query}else if(e instanceof Q){let n=this.findCTEQueryByName(e.left,t);if(n)return n;let r=this.findCTEQueryByName(e.right,t);if(r)return r}return null}collectAliasReferences(e,t){let n=[];try{let r=this.collectTableAliasReferences(e,t);n.push(...r);let i=this.collectColumnAliasReferences(e,t);n.push(...i)}catch(r){console.warn(`Failed to collect alias references for '${t}':`,r)}return n}collectTableAliasReferences(e,t){let n=[];try{let i=new He(!0).collect(e.query);for(let s of i)if(s.getSourceName()===t){let l=this.createLexemeFromTableSource(s,t);l&&n.push({lexeme:l,scope:e,referenceType:"definition",context:"table"})}}catch(r){console.warn(`Failed to collect table alias references for '${t}':`,r)}return n}collectColumnAliasReferences(e,t){let n=[];try{let i=new Vt().collect(e.query);for(let s of i)if(s.namespaces&&s.namespaces.length>0){for(let o of s.namespaces)if(o.name===t){let l=this.createLexemeFromNamespace(o,t);l&&n.push({lexeme:l,scope:e,referenceType:"usage",context:"column"})}}}catch(r){console.warn(`Failed to collect column alias references for '${t}':`,r)}return n}createLexemeFromTableSource(e,t){try{return{type:64,value:t,comments:null,position:{startPosition:0,endPosition:t.length}}}catch(n){return console.warn("Failed to create lexeme from table source:",n),null}}createLexemeFromNamespace(e,t){try{return{type:64,value:t,comments:null,position:{startPosition:0,endPosition:t.length}}}catch(n){return console.warn("Failed to create lexeme from namespace:",n),null}}checkNameConflicts(e,t,n){let r=[];if(t.toLowerCase()===n.toLowerCase())return r.push(bt.sameNames),r;try{let i=this.checkTableAliasConflicts(e,t);r.push(...i);let s=this.checkKeywordConflicts(t);r.push(...s)}catch(i){console.warn(`Error during conflict detection for '${t}':`,i),r.push(`Unable to verify conflicts for name '${t}'`)}return r}checkTableAliasConflicts(e,t){let n=[];try{let i=new He(!0).collect(e.query);for(let s of i){let o=s.getSourceName();if(o&&o.toLowerCase()===t.toLowerCase()){n.push(bt.nameConflict(t));continue}let l=this.extractTableName(s);l&&l.toLowerCase()===t.toLowerCase()&&n.push(`'${t}' conflicts with table name in this scope`)}}catch(r){console.warn(`Failed to check table alias conflicts for '${t}':`,r)}return n}extractTableName(e){try{if(e.qualifiedName&&e.qualifiedName.name){let t=e.qualifiedName.name;if(typeof t=="string")return t;if(t.name&&typeof t.name=="string")return t.name;if(t.value&&typeof t.value=="string")return t.value}return e.table&&typeof e.table=="string"?e.table:null}catch(t){return console.warn("Failed to extract table name from table source:",t),null}}checkKeywordConflicts(e){let t=[];if(this.isBasicReservedKeyword(e))return t.push(`'${e}' is a reserved SQL keyword and should not be used as an alias`),t;try{let n=this.keywordParser.parse(e,0);n!==null&&n.keyword.toLowerCase()===e.toLowerCase()&&t.push(`'${e}' is a reserved SQL keyword and should not be used as an alias`)}catch(n){console.warn(`Failed to check keyword conflicts for '${e}':`,n)}return t}isBasicReservedKeyword(e){return["select","from","where","join","table","null","and","or"].includes(e.toLowerCase())}prepareChanges(e,t){return e.map(n=>({oldName:n.lexeme.value,newName:t,position:Le.charOffsetToLineColumn("",n.lexeme.position?.startPosition||0)||{line:1,column:1},context:n.context,referenceType:n.referenceType}))}performLexemeBasedRename(e,t,n,r){try{let s=Le.getAllLexemesWithPosition(e).filter(l=>l.value===t&&l.position&&l.position.startPosition>=r.startPosition&&l.position.endPosition<=r.endPosition&&l.type&64);if(s.length===0)return e;s.sort((l,u)=>u.position.startPosition-l.position.startPosition);let o=e;for(let l of s){let u=l.position;o=o.substring(0,u.startPosition)+n+o.substring(u.endPosition)}return o}catch(i){throw console.error("Failed to perform lexeme-based rename:",i),new Error(`Unable to rename alias using lexeme approach: ${i instanceof Error?i.message:String(i)}`)}}};var er=class{renameIdentifiers(e,t){if(t.size===0)return e;let n=e;for(let[r,i]of t)n=this.replaceIdentifierSafely(n,r,i);return n}renameIdentifier(e,t,n){return this.replaceIdentifierSafely(e,t,n)}renameIdentifierInScope(e,t,n,r){if(!r)return this.replaceIdentifierSafely(e,t,n);let i=e.slice(0,r.start),s=e.slice(r.start,r.end),o=e.slice(r.end),l=this.replaceIdentifierSafely(s,t,n);return i+l+o}checkRenameability(e,t){let n=this.positionToCharIndex(e,t);if(this.isInsideStringLiteral(e,n))return{canRename:!1,reason:"Cannot rename identifiers inside string literal"};let r=this.getIdentifierAtPosition(e,n);if(!r)return{canRename:!1,reason:"No identifier found at position"};let i=this.determineIdentifierType(e,n,r),s=this.calculateScopeRange(e,n,i);return{canRename:!0,currentName:r,type:i,scopeRange:s}}renameAtPosition(e,t,n){let r=this.checkRenameability(e,t);if(!r.canRename||!r.currentName)throw new Error(r.reason||"Cannot rename at this position");return this.renameIdentifierInScope(e,r.currentName,n,r.scopeRange)}positionToCharIndex(e,t){let n=e.split(`
26
+ `),r=0;for(let i=0;i<t.line-1&&i<n.length;i++)r+=n[i].length+1;return r+=t.column-1,Math.min(r,e.length-1)}isInsideStringLiteral(e,t){let n=!1;for(let r=0;r<t&&r<e.length;r++)e[r]==="'"&&(n=!n);return n}getIdentifierAtPosition(e,t){if(t>=e.length)return null;let n=t;for(;n>0&&this.isIdentifierChar(e.charCodeAt(n-1));)n--;let r=t;for(;r<e.length&&this.isIdentifierChar(e.charCodeAt(r));)r++;return n===r?null:e.slice(n,r)}determineIdentifierType(e,t,n){let r=e.slice(0,t),i=e.slice(t),s=r.toUpperCase(),o=i.toUpperCase();if(s.lastIndexOf("WITH")!==-1){let g=t;for(;g>0&&this.isIdentifierChar(e.charCodeAt(g-1));)g--;let h=t;for(;h<e.length&&this.isIdentifierChar(e.charCodeAt(h));)h++;if(e.slice(h).toUpperCase().trim().startsWith("AS ("))return"cte"}let u=r.split(`
27
+ `),c=u[u.length-1].toUpperCase();if(c.includes("FROM ")||c.includes("JOIN "))return"table_alias";let p=r.slice(Math.max(0,t-50)),m=i.slice(0,50),f=(p+n+m).toUpperCase();return f.includes(" AS "+n.toUpperCase())||f.includes(" "+n.toUpperCase()+" ON")||f.includes(" "+n.toUpperCase()+`
28
+ `),"table_alias"}calculateScopeRange(e,t,n){if(n==="cte")return{start:0,end:e.length};let r=e.slice(0,t),i=e.slice(t),s=r.toUpperCase().lastIndexOf("SELECT"),o=s!==-1?s:0,l=i.search(/\b(SELECT|WITH|UNION)\b/i),u=l!==-1?t+l:e.length;return{start:o,end:u}}replaceIdentifierSafely(e,t,n){if(t===n||t.length===0)return e;let r=[],i=0,s=e.length,o=t.length;for(;i<s;){let l=e[i],u=l.charCodeAt(0);if(u===34||u===96||u===91){let{content:c,nextPosition:p}=this.extractAndReplaceQuotedIdentifier(e,i,l,t,n);r.push(c),i=p;continue}if(u===39){let{content:c,nextPosition:p}=this.extractQuotedString(e,i,l);r.push(c),i=p;continue}if(u===45&&i+1<s&&e.charCodeAt(i+1)===45){let{content:c,nextPosition:p}=this.extractLineComment(e,i);r.push(c),i=p;continue}if(u===47&&i+1<s&&e.charCodeAt(i+1)===42){let{content:c,nextPosition:p}=this.extractBlockComment(e,i);r.push(c),i=p;continue}if(this.isIdentifierStartChar(u)&&this.matchesIdentifierAt(e,i,t)){let c=i-1,p=i+o,m=c>=0?e[c]:null,f=p<s?e[p]:null;if(this.hasValidWordBoundaries(m,f)){r.push(n),i+=o;continue}}r.push(l),i++}return r.join("")}validateRename(e,t,n,r){if(e===t||!t.includes(r))return!1;let i=this.countWordOccurrences(e,n);return this.countWordOccurrences(t,n)<i}extractAndReplaceQuotedIdentifier(e,t,n,r,i){if(n==="[")return this.extractAndReplaceBracketedIdentifier(e,t,r,i);let s=[n],o=t+1,l=o;for(;o<e.length;){let u=e[o];if(u===n){if(o+1<e.length&&e[o+1]===n){s.push(u),s.push(e[o+1]),o+=2;continue}let c=e.slice(l,o);c.toLowerCase()===r.toLowerCase()?s.push(i):s.push(c),s.push(u);break}o++}return{content:s.join(""),nextPosition:o+1}}extractAndReplaceBracketedIdentifier(e,t,n,r){let i=["["],s=t+1,o=s;for(;s<e.length;){let l=e[s];if(l==="]"){let u=e.slice(o,s);u.toLowerCase()===n.toLowerCase()?i.push(r):i.push(u),i.push(l);break}s++}return{content:i.join(""),nextPosition:s+1}}extractQuotedString(e,t,n){let r=[n],i=t+1;for(;i<e.length;){let s=e[i];if(r.push(s),s===n){if(i+1<e.length&&e[i+1]===n){r.push(e[i+1]),i+=2;continue}break}i++}return{content:r.join(""),nextPosition:i+1}}extractLineComment(e,t){let n=[],r=t;for(;r<e.length&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)n.push(e[r]),r++;return r<e.length&&(e.charCodeAt(r)===10||e.charCodeAt(r)===13)&&(n.push(e[r]),r++),{content:n.join(""),nextPosition:r}}extractBlockComment(e,t){let n=["/","*"],r=t+2;for(;r<e.length-1;){let i=e[r];if(n.push(i),i==="*"&&e[r+1]==="/"){n.push("/"),r+=2;break}r++}return{content:n.join(""),nextPosition:r}}isIdentifierStartChar(e){return e>=65&&e<=90||e>=97&&e<=122||e===95}isIdentifierChar(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95}matchesIdentifierAt(e,t,n){if(t+n.length>e.length)return!1;for(let r=0;r<n.length;r++){let i=e.charCodeAt(t+r),s=n.charCodeAt(r),o=i>=65&&i<=90?i+32:i,l=s>=65&&s<=90?s+32:s;if(o!==l)return!1}return!0}hasValidWordBoundaries(e,t){let n=e===null||!this.isIdentifierChar(e.charCodeAt(0)),r=t===null||!this.isIdentifierChar(t.charCodeAt(0));return n&&r}countWordOccurrences(e,t){let n=0,r=0,i=e.length,s=t.length;for(;r<=i-s;){if(this.matchesIdentifierAt(e,r,t)){let o=r-1,l=r+s,u=o>=0?e[o]:null,c=l<i?e[l]:null;this.hasValidWordBoundaries(u,c)&&n++}r++}return n}};var Rr=class{constructor(){this.cteRenamer=new Zn,this.aliasRenamer=new Xn,this.identifierRenamer=new er}isRenameable(e,t){try{if(!e?.trim())return{renameable:!1,renamerType:"none",reason:"Empty SQL"};if(!t||t.line<1||t.column<1)return{renameable:!1,renamerType:"none",reason:"Invalid position"};let n=Le.findLexemeAtLineColumn(e,t);if(!n)return{renameable:!1,renamerType:"none",reason:"No token found"};if(!(n.type&2112))return{renameable:!1,renamerType:"none",tokenName:n.value,reason:`Token '${n.value}' is not an identifier`};let r=n.value,i=this.detectRenamerType(e,r);return i==="unknown"?{renameable:!1,renamerType:"none",tokenName:r,reason:`Cannot determine if '${r}' is renameable`}:{renameable:!0,renamerType:i,tokenName:r}}catch(n){return{renameable:!1,renamerType:"none",reason:`Error: ${n instanceof Error?n.message:String(n)}`}}}rename(e,t,n,r){try{if(!e?.trim())return this.createErrorResult(e,n,"unknown","","SQL cannot be empty");if(!t||t.line<1||t.column<1)return this.createErrorResult(e,n,"unknown","","Position must be valid line/column (1-based)");if(!n?.trim())return this.createErrorResult(e,n,"unknown","","New name cannot be empty");let i=Le.findLexemeAtLineColumn(e,t);if(!i)return this.createErrorResult(e,n,"unknown","",`No identifier found at line ${t.line}, column ${t.column}`);if(!(i.type&64))return this.createErrorResult(e,n,"unknown",i.value,`Token '${i.value}' is not renameable`);let s=i.value,o=r?.preserveFormatting??!1,l=this.detectRenamerType(e,s);if(o)try{let u=this.attemptFormattingPreservationRename(e,t,n,s,l);if(u.success)return u}catch(u){console.warn("Formatting preservation failed, falling back to standard rename:",u)}try{let u;if(l==="cte")u=this.cteRenamer.renameCTEAtPosition(e,t,n);else if(l==="alias"){let c=this.aliasRenamer.renameAlias(e,t,n);if(!c.success)return{success:!1,originalSql:e,renamerType:"alias",originalName:s,newName:n,error:c.conflicts?.join(", ")||"Alias rename failed",formattingPreserved:!1,formattingMethod:"smart-renamer-only"};u=c.newSql}else return this.createErrorResult(e,n,"unknown",s,`Cannot determine if '${s}' is a CTE name or table alias`);return{success:!0,originalSql:e,newSql:u,renamerType:l,originalName:s,newName:n,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}catch(u){return this.createErrorResult(e,n,l,s,`${l.toUpperCase()} rename failed: ${u instanceof Error?u.message:String(u)}`)}}catch(i){return this.createErrorResult(e,n,"unknown","",`Unexpected error: ${i instanceof Error?i.message:String(i)}`)}}detectRenamerType(e,t){try{let n=A.parse(e);return this.isCTEName(n,t)?"cte":"alias"}catch{return"unknown"}}isCTEName(e,t){return e instanceof C&&e.withClause?e.withClause.tables.some(n=>n.aliasExpression&&n.aliasExpression.table&&n.aliasExpression.table.name===t):e instanceof Q?this.isCTEName(e.left,t)||this.isCTEName(e.right,t):!1}attemptFormattingPreservationRename(e,t,n,r,i){let s=this.performStandardRename(e,t,n,r,i);if(!s.success)return{...s,formattingPreserved:!1,formattingMethod:"smart-renamer-only"};let o=new Map([[r,n]]);try{let l=this.identifierRenamer.renameIdentifiers(e,o);if(this.validateRenameResult(e,l,r,n))return{success:!0,originalSql:e,newSql:l,renamerType:i,originalName:r,newName:n,formattingPreserved:!0,formattingMethod:"sql-identifier-renamer"};throw new Error("Validation failed: rename may not have been applied correctly")}catch{return{...s,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}}performStandardRename(e,t,n,r,i){try{let s;if(i==="cte")s=this.cteRenamer.renameCTEAtPosition(e,t,n);else if(i==="alias"){let o=this.aliasRenamer.renameAlias(e,t,n);if(!o.success)return{success:!1,originalSql:e,renamerType:"alias",originalName:r,newName:n,error:o.conflicts?.join(", ")||"Alias rename failed"};s=o.newSql}else return{success:!1,originalSql:e,renamerType:"unknown",originalName:r,newName:n,error:`Cannot determine if '${r}' is a CTE name or table alias`};return{success:!0,originalSql:e,newSql:s,renamerType:i,originalName:r,newName:n}}catch(s){return{success:!1,originalSql:e,renamerType:i,originalName:r,newName:n,error:`${i.toUpperCase()} rename failed: ${s instanceof Error?s.message:String(s)}`}}}validateRenameResult(e,t,n,r){if(e===t||!t.includes(r))return!1;let i=this.countWordOccurrences(e,n);return this.countWordOccurrences(t,n)<i}countWordOccurrences(e,t){let n=new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"gi"),r=e.match(n);return r?r.length:0}createErrorResult(e,t,n,r,i){return{success:!1,originalSql:e,renamerType:n,originalName:r,newName:t,error:i,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}batchRename(e,t,n){if(n?.preserveFormatting??!1)try{let i=new Map(Object.entries(t)),s=this.identifierRenamer.renameIdentifiers(e,i),o=Object.keys(t),l=Object.values(t);return{success:!0,originalSql:e,newSql:s,renamerType:"alias",originalName:o.join(", "),newName:l.join(", "),formattingPreserved:!0,formattingMethod:"sql-identifier-renamer"}}catch(i){return{success:!1,originalSql:e,renamerType:"unknown",originalName:Object.keys(t).join(", "),newName:Object.values(t).join(", "),error:`Batch rename failed: ${i instanceof Error?i.message:String(i)}`,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}else return{success:!1,originalSql:e,renamerType:"unknown",originalName:Object.keys(t).join(", "),newName:Object.values(t).join(", "),error:"Batch rename without formatting preservation not implemented. Use individual renames or enable formatting preservation.",formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}};var Fr=class{restore(e){if(e.length===0)return"";let t="";for(let n of e)t+=n.value,n.followingWhitespace&&(t+=n.followingWhitespace);return t}restoreWithComments(e,t=!0){if(e.length===0)return"";let n="";for(let r of e){if(n+=r.value,t&&r.inlineComments&&r.inlineComments.length>0)for(let i of r.inlineComments)i.trim().length>0&&(n+=` -- ${i}`);r.followingWhitespace&&(n+=r.followingWhitespace)}return n}analyzeFormatting(e){let t=0,n=0,r=0,i=0,s=0,o=0;for(let u of e){if(u.followingWhitespace){t+=u.followingWhitespace.length;let c=u.followingWhitespace.split(`
29
+ `);for(let p=1;p<c.length;p++){let m=c[p],f=m.match(/^ */)?.[0].length||0,g=m.match(/^\t*/)?.[0].length||0;(f>0||g>0)&&(s++,o+=f+g*4,r+=f,i+=g)}}u.inlineComments&&(n+=u.inlineComments.length)}let l="none";return r>0&&i>0?l="mixed":r>0?l="spaces":i>0&&(l="tabs"),{totalWhitespace:t,totalComments:n,indentationStyle:l,averageIndentSize:s>0?o/s:0}}validateFormattingLexemes(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];r.position||t.push(`Lexeme ${n} missing position information`),r.followingWhitespace===void 0&&t.push(`Lexeme ${n} missing followingWhitespace property`),r.inlineComments===void 0&&t.push(`Lexeme ${n} missing inlineComments property`),r.position&&r.position.startPosition>=r.position.endPosition&&t.push(`Lexeme ${n} has invalid position range`)}return{isValid:t.length===0,issues:t}}};var tr=class a{constructor(){this.jsonColumnCounter=0;this.entityToJsonColumnMap=new Map;this.columnMappings=[]}static{this.CTE_OBJECT_PREFIX="cte_object_depth_"}static{this.WILDCARD_COLUMN="*"}buildObjectEntityCtes(e,t,n){this.jsonColumnCounter=0,this.entityToJsonColumnMap.clear(),this.columnMappings=[];let r=[e],i=e.aliasExpression.table.name,s=this.collectAndSortObjectEntities(n,t),o=this.groupEntitiesByDepth(s),l=Array.from(o.keys()).sort((u,c)=>c-u);for(let u of l){let c=o.get(u),p=`${a.CTE_OBJECT_PREFIX}${u}`,m=this.buildDepthCte(c,i,p,n,t);r.push(m),i=p}return{ctes:r,lastCteAlias:i,columnMappings:this.columnMappings}}generateUniqueJsonColumnName(e,t,n){this.jsonColumnCounter++;let r=`${e.toLowerCase()}_json_${this.jsonColumnCounter}`;return this.columnMappings.push({entityId:t,entityName:e,generatedColumnName:r,depth:n}),r}collectAndSortObjectEntities(e,t){let n=[],r=i=>{let s=t.get(i);if(!s)throw new Error(`Entity ${i} not found for depth calculation.`);if(s.isRoot)return 0;if(!s.parentId)return 1;let o=s.parentId,l=0,u=new Set;for(u.add(i);o;){if(u.has(o))throw new Error(`Circular dependency detected: ${o} already visited in path for ${i}`);u.add(o);let c=t.get(o);if(!c)throw new Error(`Parent entity ${o} not found during depth calculation for ${i}`);let p=!1;if(c.isRoot)p=!0;else{let m=e.nestedEntities.find(f=>f.id===o);if(m)m.relationshipType==="object"&&(p=!0);else throw new Error(`Parent entity ${o} (ancestor of ${i}) has no definition in mapping.nestedEntities and is not root.`)}if(p&&l++,c.isRoot)break;o=c.parentId}return l};return e.nestedEntities.forEach(i=>{if(i.relationshipType==="object"){let s=t.get(i.id);s&&!s.isRoot&&n.push({entity:s,depth:r(i.id)})}}),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let r=n.depth;t.has(r)||t.set(r,[]),t.get(r).push(n)}),t}buildDepthCte(e,t,n,r,i){let s=[new z(new b(null,new P(a.WILDCARD_COLUMN)))];for(let{entity:l}of e){let u=this.buildEntityJsonColumn(l,r,i);s.push(u)}let o=new C({selectClause:new _(s),fromClause:new J(new B(new O(null,new P(t)),null),null)});return new ne(o,new re(n,null),null)}buildEntityJsonColumn(e,t,n){let{jsonObjectArgs:r,nullChecks:i}=this.prepareEntityColumns(e);this.addChildObjectRelationships(e,r,t,n);let s=this.createJsonObject(r),o=this.buildNullCondition(i),l=this.createCaseExpression(o,s),u=this.calculateApproximateDepth(e,t),c=this.generateUniqueJsonColumnName(e.name,e.id,u);return this.entityToJsonColumnMap.set(e.id,c),new z(l,c)}calculateApproximateDepth(e,t){if(e.isRoot)return 0;if(!e.parentId)return 1;let n=1,r=e.parentId;for(;r&&r!==t.rootEntity.id;){let i=t.nestedEntities.find(s=>s.id===r);if(!i)break;n++,r=i.parentId}return n}prepareEntityColumns(e){let t=[],n=[];return Object.entries(e.columns).forEach(([r,i])=>{t.push(new Z(r,void 0,!0)),t.push(new b(null,new P(i))),n.push(new S(new b(null,new P(i)),"is",new Z(null)))}),{jsonObjectArgs:t,nullChecks:n}}addChildObjectRelationships(e,t,n,r){n.nestedEntities.filter(s=>s.parentId===e.id&&s.relationshipType==="object").forEach(s=>{let o=r.get(s.id);if(o){t.push(new Z(s.propertyName,void 0,!0));let l=this.entityToJsonColumnMap.get(o.id);if(!l)throw new Error(`JSON column name not found for child entity: ${o.id}`);t.push(new b(null,new P(l)))}})}createJsonObject(e){let t="jsonb_build_object";return new K(null,new $(t),new U(e),null)}buildNullCondition(e){return e.reduce((t,n)=>t?new S(t,"and",n):n)}createCaseExpression(e,t){return new ie(null,new Te([new ke(e,new Z(null))],t))}};var nr=class a{static{this.CTE_ARRAY_PREFIX="cte_array_depth_"}static{this.JSON_FUNCTIONS={BUILD_OBJECT:"jsonb_build_object",AGGREGATE:"jsonb_agg"}}buildArrayEntityCtes(e,t,n,r,i){let s=[...e],o=t,l=this.collectAndSortArrayEntities(r,n);if(l.length===0)return{updatedCtes:s,lastCteAlias:o};let u=this.groupEntitiesByDepth(l),c=Array.from(u.keys()).sort((p,m)=>m-p);for(let p of c){let m=u.get(p),{cte:f,newCteAlias:g}=this.buildDepthCte(m,o,s,p,r,i);s.push(f),o=g}return{updatedCtes:s,lastCteAlias:o}}collectAndSortArrayEntities(e,t){let n=[],r=i=>{let s=t.get(i);return!s||s.isRoot?0:s.parentId?1+r(s.parentId):1};return e.nestedEntities.forEach(i=>{if(i.relationshipType==="array"){let s=t.get(i.id),o=t.get(i.parentId);if(!s||!o)throw new Error(`Configuration error: Array entity '${i.id}' or its parent '${i.parentId}' not found.`);let l=Object.values(o.columns);if(l.length===0)throw new Error(`Configuration error: Parent entity '${o.name}' (ID: ${o.id}) must have at least one column defined to serve as a linking key for child array '${i.name}'.`);let u=l[0];n.push({entity:s,parentEntity:o,parentIdColumnSqlName:u,depth:r(i.id)})}}),n.sort((i,s)=>s.depth-i.depth),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let r=n.depth;t.has(r)||t.set(r,[]),t.get(r).push(n)}),t}buildDepthCte(e,t,n,r,i,s){let o=new Set;e.forEach(E=>{Object.values(E.entity.columns).forEach(k=>o.add(k));let y=k=>{i.nestedEntities.filter(x=>x.parentId===k).forEach(x=>{Object.values(x.columns).forEach(V=>{let T=typeof V=="string"?V:V.column;o.add(T)}),y(x.id)})};y(E.entity.id)});let l=n.find(E=>E.aliasExpression.table.name===t)?.query;if(!l)throw new Error(`CTE not found: ${t}`);let u=new Ke(null,n).collect(l),c=[],p=[],m=new Set;e.forEach(E=>{Object.values(E.entity.columns).forEach(y=>m.add(y))});let f=this.collectArrayEntityColumnsByDepth(i,r),g=new Set;s&&e.forEach(E=>{i.nestedEntities.filter(y=>y.parentId===E.entity.id&&y.relationshipType==="object").forEach(y=>{let k=s.find(x=>x.entityId===y.id);k&&g.add(k.generatedColumnName)})}),this.processSelectVariablesForGroupBy(u,o,f,r,p,c,g);for(let E of e){let y=this.buildAggregationDetailsForArrayEntity(E.entity,i.nestedEntities,new Map,s);p.push(new z(y.jsonAgg,E.entity.propertyName))}let h=`${a.CTE_ARRAY_PREFIX}${r}`,W=new C({selectClause:new _(p),fromClause:new J(new B(new O(null,new P(t)),null),null),groupByClause:c.length>0?new me(c):null});return{cte:new ne(W,new re(h,null),null),newCteAlias:h}}buildAggregationDetailsForArrayEntity(e,t,n,r){let i=a.JSON_FUNCTIONS.BUILD_OBJECT,s=[];Object.entries(e.columns).forEach(([m,f])=>{s.push(new Z(m,void 0,!0)),s.push(new b(null,new P(f)))}),t.filter(m=>m.parentId===e.id).forEach(m=>{let f=m.originalPropertyName||m.propertyName;if(s.push(new Z(f,void 0,!0)),m.relationshipType==="object"){if(!r)throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mappings not provided
29
30
 
30
31
  \u{1F50D} Details:
31
- - Entity ID: ${d.id}
32
- - Entity Name: ${d.name||"unknown"}
33
- - Property Name: ${d.propertyName}
34
- - Relationship Type: ${d.relationshipType}
32
+ - Entity ID: ${m.id}
33
+ - Entity Name: ${m.name||"unknown"}
34
+ - Property Name: ${m.propertyName}
35
+ - Relationship Type: ${m.relationshipType}
35
36
 
36
37
  \u{1F4A1} Solution:
37
38
  Column mappings are required for hybrid JSON column naming.
@@ -41,13 +42,13 @@ ${e}`}getCTEName(e){return e.aliasExpression.table.name}};var Vt=class{construct
41
42
  \u{1F527} Check:
42
43
  1. Ensure PostgresJsonQueryBuilder.buildJsonWithCteStrategy() passes columnMappings
43
44
  2. Verify PostgresObjectEntityCteBuilder.buildObjectEntityCtes() returns columnMappings
44
- 3. Check that Model-driven mapping conversion generates unique entity IDs`);let y=r.find(h=>h.entityId===d.id);if(!y){let h=r.map(M=>`${M.entityId} \u2192 ${M.generatedColumnName}`).join(", ");throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mapping not found
45
+ 3. Check that Model-driven mapping conversion generates unique entity IDs`);let g=r.find(h=>h.entityId===m.id);if(!g){let h=r.map(W=>`${W.entityId} \u2192 ${W.generatedColumnName}`).join(", ");throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mapping not found
45
46
 
46
47
  \u{1F50D} Details:
47
- - Looking for Entity ID: ${d.id}
48
- - Entity Name: ${d.name||"unknown"}
49
- - Property Name: ${d.propertyName}
50
- - Relationship Type: ${d.relationshipType}
48
+ - Looking for Entity ID: ${m.id}
49
+ - Entity Name: ${m.name||"unknown"}
50
+ - Property Name: ${m.propertyName}
51
+ - Relationship Type: ${m.relationshipType}
51
52
 
52
53
  \u{1F4CB} Available Mappings:
53
54
  ${h||"None"}
@@ -59,22 +60,22 @@ ${e}`}getCTEName(e){return e.aliasExpression.table.name}};var Vt=class{construct
59
60
  \u{1F527} Check:
60
61
  1. Model-driven mapping conversion generates consistent entity IDs
61
62
  2. PostgresObjectEntityCteBuilder processes all entities correctly
62
- 3. Entity hierarchy and parentId relationships are correct`)}s.push(new b(null,new P(y.generatedColumnName)))}else d.relationshipType==="array"&&s.push(new b(null,new P(d.propertyName)))});let l=new K(null,new V(i),new U(s),null),u=a.JSON_FUNCTIONS.AGGREGATE,c=Object.values(e.columns)[0];return{jsonAgg:new K(null,new V(u),new U([l]),null)}}collectArrayEntityColumnsByDepth(e,t){let n=new Map,r=Math.max(t+3,5);for(let i=t;i<=r;i++)n.set(i,new Set);return e.nestedEntities.filter(i=>i.relationshipType==="array").forEach(i=>{let s=this.calculateEntityDepth(i,e);n.has(s)||n.set(s,new Set),this.addEntityColumnsToDepthSet(i,s,n),this.collectDescendantColumns(i.id,s,e,n)}),n}calculateEntityDepth(e,t){let n=0,r=e;for(;r.parentId&&r.parentId!==t.rootEntity.id;)n++,r=t.nestedEntities.find(i=>i.id===r.parentId)||r;return n}addEntityColumnsToDepthSet(e,t,n){Object.values(e.columns).forEach(r=>{let i=typeof r=="string"?r:r.column;n.get(t).add(i)})}collectDescendantColumns(e,t,n,r){n.nestedEntities.filter(i=>i.parentId===e).forEach(i=>{this.addEntityColumnsToDepthSet(i,t,r),this.collectDescendantColumns(i.id,t,n,r)})}processSelectVariablesForGroupBy(e,t,n,r,i,s,o){e.forEach(l=>{if(!t.has(l.name)){if(o&&o.has(l.name))return;this.shouldIncludeColumnInGroupBy(l.name,n,r)&&(i.push(new z(new b(null,new P(l.name)),l.name)),l.name.endsWith("_json")||s.push(new b(null,new P(l.name))))}})}shouldIncludeColumnInGroupBy(e,t,n){let r=e.endsWith("_json"),i=!0;for(let[s,o]of t.entries())if(s>=n&&o.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 rr=class{constructor(){this.selectValueCollector=new Ke(null),this.objectEntityCteBuilder=new tr,this.arrayEntityCteBuilder=new nr}validateMapping(e,t){let r=new Ke().collect(e),i=new Set(r.map(u=>u.name));for(let u in t.rootEntity.columns){let c=t.rootEntity.columns[u],p=typeof c=="string"?c:c.column;if(!i.has(p))throw new Error(`Validation Error: Column "${p}" for JSON key "${u}" in root entity "${t.rootEntity.name}" not found in the query's select list.`)}let s=new Set([t.rootEntity.id]),o=new Map;t.nestedEntities.forEach(u=>{s.add(u.id),o.has(u.parentId)||o.set(u.parentId,[]),o.get(u.parentId).push(u.id)});for(let u of t.nestedEntities){if(!s.has(u.parentId))throw new Error(`Validation Error: Parent entity with ID "${u.parentId}" for nested entity "${u.name}" (ID: ${u.id}) not found.`);for(let c in u.columns){let p=u.columns[c],d=typeof p=="string"?p:p.column;if(!i.has(d))throw new Error(`Validation Error: Column "${d}" for JSON key "${c}" in nested entity "${u.name}" (ID: ${u.id}) not found in the query's select list.`)}}let l=new Set([t.rootEntity.id,...t.nestedEntities.map(u=>u.parentId)]);for(let u of l){let c=t.nestedEntities.filter(f=>f.parentId===u);if(c.filter(f=>f.relationshipType==="array").length>1){let f=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(y=>y.id===u)?.name;throw new Error(`Validation Error: Parent entity "${f}" (ID: ${u}) has multiple direct array children. This is not supported.`)}let d=new Set;for(let f of c){if(d.has(f.propertyName)){let y=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(h=>h.id===u)?.name;throw new Error(`Validation Error: Parent entity "${y}" (ID: ${u}) has duplicate property name "${f.propertyName}" for its children.`)}d.add(f.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 C?e:We.buildSimpleQuery(e);return this.buildJsonWithCteStrategy(r,t)}buildJson(e,t){return console.warn("buildJson is deprecated. Use buildJsonQuery instead."),this.buildJsonQuery(e,t)}buildJsonWithCteStrategy(e,t){this.validateMapping(e,t);let{initialCte:n,initialCteAlias:r}=this.createInitialCte(e),i=[n],s=r,o=new Map;o.set(t.rootEntity.id,{...t.rootEntity,isRoot:!0,propertyName:t.rootName}),t.nestedEntities.forEach(p=>o.set(p.id,{...p,isRoot:!1,propertyName:p.propertyName}));let l=this.objectEntityCteBuilder.buildObjectEntityCtes(n,o,t);i=l.ctes,s=l.lastCteAlias;let u=l.columnMappings,c=this.arrayEntityCteBuilder.buildArrayEntityCtes(i,s,o,t,u);return i=c.updatedCtes,s=c.lastCteAlias,this.buildFinalSelectQuery(i,s,o,t,u)}createInitialCte(e){let t="origin_query";return{initialCte:new ne(e,new re(t,null),null),initialCteAlias:t}}buildFinalSelectQuery(e,t,n,r,i){let s=[...e],o=`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 z(u,r.rootName),p=new ne(new C({selectClause:new _([c]),fromClause:new J(new B(new R(null,new P(t)),null),null)}),new re(o,null),null);s.push(p);let d="jsonb_agg",f=new K(null,new V(d),new U([new b(null,new P(r.rootName))]),null);return new C({withClause:new ae(!1,s),selectClause:new _([new z(f,`${r.rootName}_array`)]),fromClause:new J(new B(new R(null,new P(o)),null),null)})}else{let u=this.buildEntityJsonObject(l,null,r.nestedEntities,n,i),c=new z(u,r.rootName),p=new ne(new C({selectClause:new _([c]),fromClause:new J(new B(new R(null,new P(t)),null),null)}),new re(o,null),null);return s.push(p),new C({withClause:new ae(!1,s),selectClause:new _([new z(new b(null,new P(r.rootName)),r.rootName)]),fromClause:new J(new B(new R(null,new P(o)),null),null),limitClause:new oe(new Z(1))})}}buildEntityJsonObject(e,t,n,r,i){let s="jsonb_build_object",o=[];return Object.entries(e.columns).forEach(([u,c])=>{let p=typeof c=="string"?c:c.column;o.push(new Z(u,void 0,!0)),o.push(new b(null,new P(p)))}),n.filter(u=>u.parentId===e.id).forEach(u=>{let c=r.get(u.id);if(c)if(o.push(new Z(u.propertyName,void 0,!0)),u.relationshipType==="object"){let p=i.find(d=>d.entityId===c.id);if(!p)throw new Error(`Column mapping not found for entity: ${c.id}`);o.push(new b(null,new P(p.generatedColumnName)))}else u.relationshipType==="array"&&o.push(new b(null,new P(u.propertyName)))}),new K(null,new V(s),new U(o),null)}};var Ct=class{static extractParameterNames(e){return mt.collect(e).map(n=>n.name.value)}static hasParameter(e,t){return this.extractParameterNames(e).includes(t)}static separateFilters(e,t){let n=this.extractParameterNames(e),r={},i={};for(let[s,o]of Object.entries(t))n.includes(s)?r[s]=o:i[s]=o;return{hardcodedParams:r,dynamicFilters:i}}};var $t=class{constructor(e,t,n){this.name=e;this.type=t;this.tableName=n}},Br=class{constructor(e,t){this.tableColumnResolver=e,this.options={qualified:!1,upstream:!0,...t}}collect(e){let t=[],n=this.collectColumns(e);t.push(...n);let r=this.collectParameters(e);return t.push(...r),this.removeDuplicates(t)}collectColumns(e){let t=[];try{let r=new xe(this.tableColumnResolver,!1,"fullName",{upstream:this.options.upstream}).collect(e);for(let i of r){let s,o;if(i.value&&typeof i.value.getNamespace=="function"){let u=i.value.getNamespace();u&&u.trim()!==""&&(s=u,this.options.qualified&&(o=this.getRealTableName(e,u)))}s||(s=this.inferTableNameFromQuery(e),s&&this.options.qualified&&(o=s));let l=i.name;this.options.qualified&&(o||s)&&(l=`${o||s}.${i.name}`),t.push(new $t(l,"column",s))}}catch(n){console.warn("Failed to collect columns with SelectableColumnCollector, using fallback:",n);try{let i=new Bt(this.tableColumnResolver,!0).collect(e);for(let s of i)for(let o of s.columns){let l=o;this.options.qualified&&(l=`${s.name}.${o}`),t.push(new $t(l,"column",s.name))}}catch(r){console.warn("Failed to collect columns with both approaches:",n,r)}}return t}inferTableNameFromQuery(e){if(e instanceof C&&e.fromClause&&e.fromClause.source){let t=e.fromClause.source.datasource;if(t&&typeof t.table=="object"){let n=t.table;if(n&&typeof n.name=="string")return n.name}}}getRealTableName(e,t){try{let n=e.type==="WITH"?e.toSimpleQuery():e;if(n instanceof C&&n.fromClause){if(n.fromClause.source?.datasource){let i=n.fromClause.source,s=this.extractRealTableName(i,t);if(s)return s}let r=n.fromClause;if(r.joinClauses&&Array.isArray(r.joinClauses)){for(let i of r.joinClauses)if(i.source?.datasource){let s=this.extractRealTableName(i.source,t);if(s)return s}}}}catch(n){console.warn("Error resolving real table name:",n)}return t}extractRealTableName(e,t){try{let n=e.datasource;if(!n)return;let r=e.alias||e.aliasExpression?.table?.name,i=n.table?.name;if(r===t&&i||!r&&i===t)return i}catch{}}collectParameters(e){let t=[];try{let n=Ct.extractParameterNames(e);for(let r of n)t.push(new $t(r,"parameter"))}catch(n){console.warn("Failed to collect parameters:",n)}return t}removeDuplicates(e){let t=new Set,n=[];for(let r of e){let i=`${r.type}:${r.name}:${r.tableName||"none"}`;t.has(i)||(t.add(i),n.push(r))}return n.sort((r,i)=>{if(r.type!==i.type)return r.type==="column"?-1:1;if(r.type==="column"){let s=r.tableName||"",o=i.tableName||"";if(s!==o)return s.localeCompare(o)}return r.name.localeCompare(i.name)})}};var ir=class{constructor(e,t){typeof e=="function"?(this.tableColumnResolver=e,this.options=t||{}):(this.tableColumnResolver=void 0,this.options=e||{})}inject(e,t){typeof e=="string"&&(e=A.parse(e));let n=new Rt(this.tableColumnResolver,this.options),r=new xe(this.tableColumnResolver,!1,"fullName",{upstream:!0}),i=x=>this.options.ignoreCaseAndUnderscore?x.toLowerCase().replace(/_/g,""):x,s=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"],o=Object.values(t);if(o.length>0&&o.every(x=>x===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.");let c=[],p=[];for(let[x,g]of Object.entries(t))g!==void 0&&(this.isQualifiedColumnName(x)?c.push([x,g]):p.push([x,g]));for(let[x,g]of c)this.processStateParameter(x,g,e,n,r,i,s,y,f,M,H,h);let d=new Set;for(let[x,g]of c){let I=this.parseQualifiedColumnName(x);I&&d.add(`${I.table.toLowerCase()}.${I.column.toLowerCase()}`)}for(let[x,g]of p)this.processUnqualifiedParameter(x,g,e,n,r,i,s,y,f,M,H,h,d);function f(x,g,I,T,D){for(let E=0;E<I.length;E++){let w=I[E],L=w.column||g,Xe=D.find(j=>T(j.name)===T(L));if(!Xe)throw new Error(`Column '${L}' not found in query for AND condition`);let Re=Xe.value;if("="in w&&w["="]!==void 0){let j=`${g}_and_${E}_eq`,F=new N(j,w["="]);x.appendWhere(new S(Re,"=",F))}if("min"in w&&w.min!==void 0){let j=`${g}_and_${E}_min`,F=new N(j,w.min);x.appendWhere(new S(Re,">=",F))}if("max"in w&&w.max!==void 0){let j=`${g}_and_${E}_max`,F=new N(j,w.max);x.appendWhere(new S(Re,"<=",F))}if("like"in w&&w.like!==void 0){let j=`${g}_and_${E}_like`,F=new N(j,w.like);x.appendWhere(new S(Re,"like",F))}if("ilike"in w&&w.ilike!==void 0){let j=`${g}_and_${E}_ilike`,F=new N(j,w.ilike);x.appendWhere(new S(Re,"ilike",F))}if("in"in w&&w.in!==void 0){let F=w.in.map((q,G)=>new N(`${g}_and_${E}_in_${G}`,q));x.appendWhere(new S(Re,"in",new Y(new U(F))))}if("any"in w&&w.any!==void 0){let j=`${g}_and_${E}_any`,F=new N(j,w.any);x.appendWhere(new S(Re,"=",new K(null,"any",F,null)))}if("<"in w&&w["<"]!==void 0){let j=`${g}_and_${E}_lt`,F=new N(j,w["<"]);x.appendWhere(new S(Re,"<",F))}if(">"in w&&w[">"]!==void 0){let j=`${g}_and_${E}_gt`,F=new N(j,w[">"]);x.appendWhere(new S(Re,">",F))}if("!="in w&&w["!="]!==void 0){let j=`${g}_and_${E}_neq`,F=new N(j,w["!="]);x.appendWhere(new S(Re,"!=",F))}if("<>"in w&&w["<>"]!==void 0){let j=`${g}_and_${E}_ne`,F=new N(j,w["<>"]);x.appendWhere(new S(Re,"<>",F))}if("<="in w&&w["<="]!==void 0){let j=`${g}_and_${E}_le`,F=new N(j,w["<="]);x.appendWhere(new S(Re,"<=",F))}if(">="in w&&w[">="]!==void 0){let j=`${g}_and_${E}_ge`,F=new N(j,w[">="]);x.appendWhere(new S(Re,">=",F))}}}function y(x,g,I,T,D){let E=[];for(let w=0;w<I.length;w++){let L=I[w],Xe=L.column||g,Re=D.find(q=>T(q.name)===T(Xe));if(!Re)throw new Error(`Column '${Xe}' not found in query for OR condition`);let j=Re.value,F=[];if("="in L&&L["="]!==void 0){let q=`${g}_or_${w}_eq`,G=new N(q,L["="]);F.push(new S(j,"=",G))}if("min"in L&&L.min!==void 0){let q=`${g}_or_${w}_min`,G=new N(q,L.min);F.push(new S(j,">=",G))}if("max"in L&&L.max!==void 0){let q=`${g}_or_${w}_max`,G=new N(q,L.max);F.push(new S(j,"<=",G))}if("like"in L&&L.like!==void 0){let q=`${g}_or_${w}_like`,G=new N(q,L.like);F.push(new S(j,"like",G))}if("ilike"in L&&L.ilike!==void 0){let q=`${g}_or_${w}_ilike`,G=new N(q,L.ilike);F.push(new S(j,"ilike",G))}if("in"in L&&L.in!==void 0){let G=L.in.map((_r,zr)=>new N(`${g}_or_${w}_in_${zr}`,_r));F.push(new S(j,"in",new Y(new U(G))))}if("any"in L&&L.any!==void 0){let q=`${g}_or_${w}_any`,G=new N(q,L.any);F.push(new S(j,"=",new K(null,"any",G,null)))}if("<"in L&&L["<"]!==void 0){let q=`${g}_or_${w}_lt`,G=new N(q,L["<"]);F.push(new S(j,"<",G))}if(">"in L&&L[">"]!==void 0){let q=`${g}_or_${w}_gt`,G=new N(q,L[">"]);F.push(new S(j,">",G))}if("!="in L&&L["!="]!==void 0){let q=`${g}_or_${w}_neq`,G=new N(q,L["!="]);F.push(new S(j,"!=",G))}if("<>"in L&&L["<>"]!==void 0){let q=`${g}_or_${w}_ne`,G=new N(q,L["<>"]);F.push(new S(j,"<>",G))}if("<="in L&&L["<="]!==void 0){let q=`${g}_or_${w}_le`,G=new N(q,L["<="]);F.push(new S(j,"<=",G))}if(">="in L&&L[">="]!==void 0){let q=`${g}_or_${w}_ge`,G=new N(q,L[">="]);F.push(new S(j,">=",G))}if(F.length>0){let q=F[0];for(let G=1;G<F.length;G++)q=new S(q,"and",F[G]);F.length>1?E.push(new Y(q)):E.push(q)}}if(E.length>0){let w=E[0];for(let L=1;L<E.length;L++)w=new S(w,"or",E[L]);x.appendWhere(new Y(w))}}function h(x,g,I){Object.keys(x).forEach(T=>{if(!g.includes(T))throw new Error(`Unsupported operator '${T}' for state key '${I}'`)})}function M(x,g,I,T){let D=new N(I,T);x.appendWhere(new S(g,"=",D))}function H(x,g,I,T){let D=[];if("="in T){let E=new N(I,T["="]);D.push(new S(g,"=",E))}if("min"in T){let E=new N(I+"_min",T.min);D.push(new S(g,">=",E))}if("max"in T){let E=new N(I+"_max",T.max);D.push(new S(g,"<=",E))}if("like"in T){let E=new N(I+"_like",T.like);D.push(new S(g,"like",E))}if("ilike"in T){let E=new N(I+"_ilike",T.ilike);D.push(new S(g,"ilike",E))}if("in"in T){let w=T.in.map((L,Xe)=>new N(`${I}_in_${Xe}`,L));D.push(new S(g,"in",new Y(new U(w))))}if("any"in T){let E=new N(I+"_any",T.any);D.push(new S(g,"=",new K(null,"any",E,null)))}if("<"in T){let E=new N(I+"_lt",T["<"]);D.push(new S(g,"<",E))}if(">"in T){let E=new N(I+"_gt",T[">"]);D.push(new S(g,">",E))}if("!="in T){let E=new N(I+"_neq",T["!="]);D.push(new S(g,"!=",E))}if("<>"in T){let E=new N(I+"_ne",T["<>"]);D.push(new S(g,"<>",E))}if("<="in T){let E=new N(I+"_le",T["<="]);D.push(new S(g,"<=",E))}if(">="in T){let E=new N(I+"_ge",T[">="]);D.push(new S(g,">=",E))}if(D.length===1)x.appendWhere(D[0]);else if(D.length>1){let E=D[0];for(let w=1;w<D.length;w++)E=new S(E,"and",D[w]);x.appendWhere(new Y(E))}}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}parseQualifiedColumnName(e){let t=e.split(".");return t.length===2&&t[0].trim()&&t[1].trim()?{table:t[0].trim(),column:t[1].trim()}:null}isQualifiedColumnName(e){return e.includes(".")&&this.parseQualifiedColumnName(e)!==null}sanitizeParameterName(e){return e.replace(/\./g,"_")}hasColumnMapping(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"column"in e}isSimpleValue(e){return e===null||typeof e!="object"||Array.isArray(e)||e instanceof Date}processStateParameter(e,t,n,r,i,s,o,l,u,c,p,d){if(this.isOrCondition(t)){let f=t.or;if(f&&f.length>0){let y=this.findTargetQueryForLogicalCondition(r,n,e,f),h=this.getAllAvailableColumns(y,i);l(y,e,f,s,h);return}}if(this.isAndCondition(t)){let f=t.and;if(f&&f.length>0){let y=this.findTargetQueryForLogicalCondition(r,n,e,f),h=this.getAllAvailableColumns(y,i);u(y,e,f,s,h);return}}if(this.isExplicitColumnMapping(t)){let f=t.column;if(f){let y=r.find(n,f);if(y.length===0)throw new Error(`Explicit column '${f}' not found in query`);for(let h of y){let H=this.getAllAvailableColumns(h,i).find(x=>s(x.name)===s(f));if(!H)throw new Error(`Explicit column '${f}' not found in query`);this.isValidatableObject(t)&&d(t,o,e),p(h,H.value,e,t)}return}}this.processRegularColumnCondition(e,t,n,r,i,s,o,c,p,d)}processUnqualifiedParameter(e,t,n,r,i,s,o,l,u,c,p,d,f){if(this.isOrCondition(t)){let h=t.or;if(h&&h.length>0){let M=this.findTargetQueryForLogicalCondition(r,n,e,h),H=this.getAllAvailableColumns(M,i);l(M,e,h,s,H);return}}if(this.isAndCondition(t)){let h=t.and;if(h&&h.length>0){let M=this.findTargetQueryForLogicalCondition(r,n,e,h),H=this.getAllAvailableColumns(M,i);u(M,e,h,s,H);return}}if(this.isExplicitColumnMapping(t)){let h=t.column;if(h){let M=r.find(n,h);if(M.length===0)throw new Error(`Explicit column '${h}' not found in query`);for(let H of M){let g=this.getAllAvailableColumns(H,i).find(I=>s(I.name)===s(h));if(!g)throw new Error(`Explicit column '${h}' not found in query`);this.isValidatableObject(t)&&d(t,o,e),p(H,g.value,e,t)}return}}let y=r.find(n,e);if(y.length===0){if(this.options.ignoreNonExistentColumns)return;throw new Error(`Column '${e}' not found in query`)}for(let h of y){let M=this.getAllAvailableColumns(h,i),H=this.buildTableMapping(h),x=M.filter(g=>s(g.name)===s(e));for(let g of x){let I=!1;if(g.value&&typeof g.value.getNamespace=="function"){let E=g.value.getNamespace();if(E){let w=H.aliasToRealTable.get(E.toLowerCase());if(w){let L=`${w.toLowerCase()}.${e.toLowerCase()}`;f.has(L)&&(I=!0)}}}if(I)continue;let T=g.value;this.isValidatableObject(t)&&d(t,o,e);let D=T;if(this.hasColumnMapping(t)){let E=t.column;if(E){let w=M.find(L=>s(L.name)===s(E));w&&(D=w.value)}}this.isSimpleValue(t)?c(h,D,e,t):p(h,D,e,t)}}}processRegularColumnCondition(e,t,n,r,i,s,o,l,u,c){let p=e,d;if(this.isQualifiedColumnName(e)){let y=this.parseQualifiedColumnName(e);y&&(p=y.column,d=y.table)}let f=r.find(n,p);if(f.length===0){if(this.options.ignoreNonExistentColumns)return;throw new Error(`Column '${p}' not found in query`)}for(let y of f){let h=this.getAllAvailableColumns(y,i),M;if(d){let I=this.buildTableMapping(y);if(M=h.find(T=>{if(!(s(T.name)===s(p)))return!1;if(T.value&&typeof T.value.getNamespace=="function"){let E=T.value.getNamespace();if(E){let w=s(E),L=s(d),Xe=I.aliasToRealTable.get(w);if(Xe&&s(Xe)===L)return!0}}return!1}),!M){if(this.options.ignoreNonExistentColumns)continue;let T=this.buildTableMapping(y),D=Array.from(T.realTableToAlias.keys()).some(w=>s(w)===s(d)),E=Array.from(T.aliasToRealTable.keys()).some(w=>s(w)===s(d));throw!D&&!E?new Error(`Column '${e}' (qualified as ${e}) not found in query`):E&&!D?new Error(`Column '${e}' not found. Only real table names are allowed in qualified column references (e.g., 'users.name'), not aliases (e.g., 'u.name').`):new Error(`Column '${e}' (qualified as ${e}) not found in query`)}}else if(M=h.find(I=>s(I.name)===s(p)),!M)throw new Error(`Column '${p}' not found in query`);let H=M.value;this.isValidatableObject(t)&&c(t,o,e);let x=H;if(this.hasColumnMapping(t)){let I=t.column;if(I){let T=h.find(D=>s(D.name)===s(I));T&&(x=T.value)}}let g=this.sanitizeParameterName(e);this.isSimpleValue(t)?l(y,x,g,t):u(y,x,g,t)}}findTargetQueryForLogicalCondition(e,t,n,r){let i=r.map(o=>o.column||n).filter((o,l,u)=>u.indexOf(o)===l);for(let o of i){let l=e.find(t,o);if(l.length>0)return l[0]}let s=r===r.or?"OR":"AND";throw new Error(`None of the ${s} condition columns [${i.join(", ")}] found in query`)}getAllAvailableColumns(e,t){let n=t.collect(e),r=this.collectCTEColumns(e);return[...n,...r]}collectCTEColumns(e){let t=[];if(e.withClause)for(let n of e.withClause.tables)try{let r=this.collectColumnsFromSelectQuery(n.query);t.push(...r)}catch(r){console.warn(`Failed to collect columns from CTE '${n.getSourceAliasName()}':`,r)}return t}collectColumnsFromSelectQuery(e){return e instanceof C?new xe(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(e):e instanceof Q?this.collectColumnsFromSelectQuery(e.left):[]}buildTableMapping(e){let t=new Map,n=new Map;try{if(e.fromClause&&(this.processSourceForMapping(e.fromClause.source,t,n),e.fromClause.joins))for(let r of e.fromClause.joins)this.processSourceForMapping(r.source,t,n);if(e.withClause)for(let r of e.withClause.tables){let i=r.getSourceAliasName();i&&(t.set(i.toLowerCase(),i),n.set(i.toLowerCase(),i))}}catch(r){console.warn("Failed to build table mapping:",r)}return{aliasToRealTable:t,realTableToAlias:n}}processSourceForMapping(e,t,n){try{if(e.datasource instanceof R){let r=e.datasource.getSourceName(),i=e.aliasExpression?.table?.name||r;r&&i&&(t.set(i.toLowerCase(),r),n.set(r.toLowerCase(),i),i===r&&t.set(r.toLowerCase(),r))}}catch(r){console.warn("Failed to process source for mapping:",r)}}};var sr=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof C))throw new Error("Complex queries are not supported for ORDER BY removal");return new C({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:null,windowClause:e.windowClause,limitClause:e.limitClause,offsetClause:e.offsetClause,fetchClause:e.fetchClause,forClause:e.forClause})}inject(e,t){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof C))throw new Error("Complex queries are not supported for sorting");let r=new xe(this.tableColumnResolver,!1,"fullName",{upstream:!0}).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(h=>h.name===l);if(!c)continue;let p=c.value;this.validateSortCondition(l,u);let d;u.desc?d="desc":d="asc";let f=null;u.nullsFirst?f="first":u.nullsLast&&(f="last");let y=new Ae(p,d,f);i.push(y)}let s=[];e.orderByClause?s=[...e.orderByClause.order,...i]:s=i;let o=s.length>0?new pe(s):null;return new C({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:o,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 or=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=A.parse(e)),!(e instanceof C))throw new Error("Complex queries are not supported for pagination");if(e.limitClause||e.offsetClause)throw new Error("Query already contains LIMIT or OFFSET clause. Use removePagination() first if you want to override existing pagination.");let n=(t.page-1)*t.pageSize,r=new oe(new N("paging_limit",t.pageSize)),i=new Oe(new N("paging_offset",n));return new C({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,windowClause:e.windowClause,limitClause:r,offsetClause:i,fetchClause:e.fetchClause,forClause:e.forClause})}static removePagination(e){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof C))throw new Error("Complex queries are not supported for pagination removal");return new C({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 ar=class{constructor(e={}){this.options={requireAllParameters:!0,...e}}bind(e,t){let n=e,r=Ct.extractParameterNames(n);if(this.options.requireAllParameters){let i=r.filter(s=>!(s in t)||t[s]===void 0);if(i.length>0)throw new Error(`Missing values for required parameters: ${i.join(", ")}`)}for(let[i,s]of Object.entries(t))if(r.includes(i))try{st.set(n,i,s)}catch(o){throw new Error(`Failed to bind parameter '${i}': ${o instanceof Error?o.message:"Unknown error"}`)}return n}bindToSimpleQuery(e,t){return this.bind(e,t)}};var Vr=class{constructor(e){this.tableColumnResolver=e}buildQuery(e,t={}){let n;try{n=A.parse(e)}catch(i){throw new Error(`Failed to parse SQL: ${i instanceof Error?i.message:"Unknown error"}`)}let r=n;if(t.filter&&Object.keys(t.filter).length>0){let{hardcodedParams:i,dynamicFilters:s}=Ct.separateFilters(r,t.filter);if(Object.keys(i).length>0&&(r=new ar({requireAllParameters:!1}).bind(r,i)),Object.keys(s).length>0){let o=new ir(this.tableColumnResolver),l=We.buildSimpleQuery(r);r=o.inject(l,s)}}if(t.sort&&Object.keys(t.sort).length>0){let i=new sr(this.tableColumnResolver),s=We.buildSimpleQuery(r);r=i.inject(s,t.sort)}if(t.paging){let{page:i=1,pageSize:s}=t.paging;if(s!==void 0){let o=new or,l={page:i,pageSize:s},u=We.buildSimpleQuery(r);r=o.inject(u,l)}}if(t.serialize&&typeof t.serialize=="object"){let i=new rr,s=We.buildSimpleQuery(r);r=i.buildJsonQuery(s,t.serialize)}return r}buildFilteredQuery(e,t){return this.buildQuery(e,{filter:t})}buildSortedQuery(e,t){return this.buildQuery(e,{sort:t})}buildPaginatedQuery(e,t){return this.buildQuery(e,{paging:t})}buildSerializedQuery(e,t){return this.buildQuery(e,{serialize:t})}validateSql(e){try{return A.parse(e),!0}catch(t){throw new Error(`Invalid SQL: ${t instanceof Error?t.message:"Unknown error"}`)}}};function yr(a){let e=[],t=0,n={},r=()=>`entity_${++t}`,i=u=>(n[u]||(n[u]=0),n[u]++,n[u]===1?u:`${u}_${n[u]}`),s=(u,c=null)=>{let p={},d=[];for(let[f,y]of Object.entries(u))if(typeof y=="string")p[f]=y;else if("column"in y&&typeof y.column=="string"&&!("type"in y&&(y.type==="object"||y.type==="array"))){let h=y;typeof h=="object"&&"column"in h&&(p[f]=h.column,h.type==="string"&&e.push(h.column))}else if("from"in y&&typeof y.from=="string"&&!("type"in y&&(y.type==="object"||y.type==="array"))){let h=y;typeof h=="object"&&"from"in h&&(p[f]=h.from,h.type==="string"&&e.push(h.from))}else if("type"in y&&(y.type==="object"||y.type==="array")){let h=y,M=i(f),H=r(),x=s(h.structure,H);d.push({id:H,name:f.charAt(0).toUpperCase()+f.slice(1),parentId:c||"root",propertyName:M,originalPropertyName:f,relationshipType:h.type,columns:x.columns}),d.push(...x.nestedEntities.map(g=>({...g,parentId:g.parentId==="root"?H:g.parentId})))}return{columns:p,nestedEntities:d}},o=s(a.structure),l={rootName:"root",rootEntity:{id:"root",name:"Root",columns:o.columns},nestedEntities:o.nestedEntities};return l.typeInfo=a.typeInfo,{jsonMapping:l,typeProtection:{protectedStringFields:e}}}function ci(a){let e=[];return a.typeInfo?(a.typeInfo.interface||e.push("typeInfo.interface is required"),a.typeInfo.importPath||e.push("typeInfo.importPath is required")):e.push("typeInfo is required"),(!a.structure||typeof a.structure!="object")&&e.push("structure is required and must be an object"),e}function lr(a){let e={};for(let[t,n]of Object.entries(a))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 iy(a){if(!a)throw new Error("Input mapping is required");if(a.rootName&&a.rootEntity&&typeof a.rootEntity.columns=="object"&&!a.typeInfo&&!a.typeProtection&&!a.metadata&&Object.values(a.rootEntity.columns).every(t=>typeof t=="string"))return a;if(a.rootName&&a.rootEntity)return{rootName:a.rootName,rootEntity:{id:a.rootEntity.id||"root",name:a.rootEntity.name||a.rootName,columns:lr(a.rootEntity.columns||{})},nestedEntities:(a.nestedEntities||[]).map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:lr(e.columns||{})})),resultFormat:a.resultFormat,emptyResult:a.emptyResult};throw new Error("Unsupported mapping format")}function $r(a){return{rootName:a.rootName,rootEntity:{id:a.rootEntity.id,name:a.rootEntity.name,columns:lr(a.rootEntity.columns)},nestedEntities:a.nestedEntities.map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:lr(e.columns)})),resultFormat:a.resultFormat,emptyResult:a.emptyResult}}function Mr(a){let e=[],t=[],n=[];if(a.typeProtection)return{protectedStringFields:a.typeProtection.protectedStringFields||[],dateFields:a.typeProtection.dateFields,numberFields:a.typeProtection.numberFields,customTransforms:a.typeProtection.customTransforms};for(let[r,i]of Object.entries(a.rootEntity.columns))if(typeof i=="object"&&i.type){let s=i.column;switch(i.type){case"string":e.push(s);break;case"date":t.push(s);break;case"number":n.push(s);break}}for(let r of a.nestedEntities)for(let[i,s]of Object.entries(r.columns))if(typeof s=="object"&&s.type){let o=s.column;switch(s.type){case"string":e.push(o);break;case"date":t.push(o);break;case"number":n.push(o);break}}return{protectedStringFields:e,dateFields:t.length>0?t:void 0,numberFields:n.length>0?n:void 0,customTransforms:void 0}}function br(a){return a!=null&&typeof a=="object"}var vr=class{detect(e){if(!br(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:$r(e),typeProtection:Mr(e),originalInput:e,metadata:{typeInfo:e.typeInfo,version:e.metadata?.version,description:e.metadata?.description}}}},wr=class{detect(e){if(!br(e))return!1;let t=e;return t&&t.typeInfo&&t.structure&&typeof t.typeInfo.interface=="string"}convert(e){let t=yr(e);return{format:"model-driven",mapping:t.jsonMapping,typeProtection:t.typeProtection,originalInput:e,metadata:{typeInfo:e.typeInfo}}}},Sr=class{detect(e){if(!br(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}}},Zt=class{constructor(){this.strategies=[new vr,new wr,new Sr]}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 Er(a){return a.typeInfo&&a.structure?"model-driven":a.rootName&&a.rootEntity?"unified":(a.columns||a.relationships,"legacy")}function pi(a){let e={rootName:a.rootName||"root",rootEntity:{id:"root",name:a.rootName||"Root",columns:a.columns||{}},nestedEntities:[]};if(a.relationships&&typeof a.relationships=="object")for(let[t,n]of Object.entries(a.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 mi(a){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"),(a.columns||a.relationships)&&!a.rootName&&!a.rootEntity)return{format:"legacy",jsonMapping:pi(a),originalInput:a,metadata:{}};let t=new Zt().convert(a),n=t.format;return t.format==="legacy"&&a.rootName&&a.rootEntity&&(n="unified"),{format:n,jsonMapping:t.mapping,originalInput:a,metadata:{typeInfo:t.metadata?.typeInfo,typeProtection:t.typeProtection}}}function di(a){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 Zt().toLegacyMapping(a)}function hi(a){return Er(a)==="model-driven"}function fi(a){return Er(a)==="unified"}function Ci(a){return Er(a)==="legacy"}var ur=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 o=this.detectValueBasedTransformation(r);if(o){t[n]=this.applyTransformation(r,o);continue}}let s=this.config.globalTransformations&&this.getGlobalTransformationForValue(r);if(s){t[n]=this.applyTransformation(r,s);continue}if(typeof r=="object"&&!Array.isArray(r)){t[n]=this.transformSingleObject(r);continue}if(Array.isArray(r)){t[n]=r.map(o=>typeof o=="object"?this.transformSingleObject(o):o);continue}t[n]=r}return t}detectValueBasedTransformation(e){return typeof e=="string"&&this.isDateString(e)?{sourceType:"TIMESTAMP",targetType:"Date",handleNull:!0,validator:t=>typeof t=="string"&&!isNaN(Date.parse(t))}:typeof e=="number"&&!Number.isSafeInteger(e)?{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return typeof t=="string"||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?(BigInt(t),!0):!1}catch{return!1}}}:typeof e=="string"&&/^\d{16,}$/.test(e)?{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return typeof t=="string"||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?(BigInt(t),!0):!1}catch{return!1}}}:null}getGlobalTransformationForValue(e){return this.config.globalTransformations,null}detectAndGetGlobalTransformation(e){return this.detectValueBasedTransformation(e)}isDateString(e){if(this.config.strictDateDetection){if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})?$/.test(e))return!1}else if(!/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})?)?$/.test(e))return!1;let t=new Date(e);return!isNaN(t.getTime())}applyTransformation(e,t){if(e==null)return t.handleNull!==!1?e:null;if(t.validator&&!t.validator(e))return console.warn(`TypeTransformationPostProcessor: Value validation failed for ${e}`),e;try{switch(t.targetType){case"Date":return new Date(e);case"bigint":if(typeof e=="number"){let n=Math.trunc(e);return BigInt(n.toString())}return BigInt(e);case"string":return e.toString();case"number":return typeof e=="string"?parseFloat(e):Number(e);case"object":return typeof e=="string"?JSON.parse(e):e;case"custom":if(t.customTransformer&&this.config.customTransformers?.[t.customTransformer])return this.config.customTransformers[t.customTransformer](e);break;default:return e}}catch(n){return console.warn(`TypeTransformationPostProcessor: Transformation failed for ${e}:`,n),e}return e}static createDefaultConfig(){return{enableValueBasedDetection:!0,strictDateDetection:!1,globalTransformations:{DATE:{sourceType:"DATE",targetType:"Date",handleNull:!0,validator:e=>typeof e=="string"&&!isNaN(Date.parse(e))},TIMESTAMP:{sourceType:"TIMESTAMP",targetType:"Date",handleNull:!0,validator:e=>typeof e=="string"&&!isNaN(Date.parse(e))},BIGINT:{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:e=>{try{return typeof e=="string"||typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?(BigInt(e),!0):!1}catch{return!1}}}}}}static createSafeConfig(e){return{enableValueBasedDetection:!1,strictDateDetection:!0,columnTransformations:e||{},globalTransformations:{DATE:{sourceType:"DATE",targetType:"Date",handleNull:!0,validator:t=>typeof t=="string"&&!isNaN(Date.parse(t))},TIMESTAMP:{sourceType:"TIMESTAMP",targetType:"Date",handleNull:!0,validator:t=>typeof t=="string"&&!isNaN(Date.parse(t))},BIGINT:{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return typeof t=="string"||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?(BigInt(t),!0):!1}catch{return!1}}}}}}};function Cy(a,e){return new ur(e||ur.createDefaultConfig()).transformResult(a)}var gy={toDate:a=>{if(a==null)return null;let e=new Date(a);return isNaN(e.getTime())?null:e},toBigInt:a=>{if(a==null)return null;try{return BigInt(a)}catch{return null}},toObject:a=>{if(a==null)return null;try{return JSON.parse(a)}catch{return null}}};var Mt=class{constructor(e,t,n,r,i){this.id=e;this.label=t;this.type=n;this.shape=r;this.details=i}},Wt=class a extends Mt{constructor(t,n,r){super(t,n,r,r==="subquery"?"hexagon":"cylinder");this.annotations=new Set}addAnnotation(t){this.annotations.add(t)}hasAnnotation(t){return this.annotations.has(t)}getMermaidRepresentation(){return this.shape==="hexagon"?`${this.id}{{${this.label}}}`:`${this.id}[(${this.label})]`}static createTable(t){return new a(`table_${t}`,t,"table")}static createCTE(t){return new a(`cte_${t}`,`CTE:${t}`,"cte")}static createSubquery(t){return new a(`subquery_${t}`,`SubQuery:${t}`,"subquery")}},cr=class a extends Mt{constructor(e,t,n=""){let r=n?`${n}_${t.toLowerCase().replace(/\s+/g,"_")}`:t.toLowerCase().replace(/\s+/g,"_");super(r,t,"process","hexagon")}getMermaidRepresentation(){return`${this.id}{{${this.label}}}`}static createWhere(e){return new a(`${e}_where`,"WHERE",e)}static createGroupBy(e){return new a(`${e}_group_by`,"GROUP BY",e)}static createHaving(e){return new a(`${e}_having`,"HAVING",e)}static createSelect(e){return new a(`${e}_select`,"SELECT",e)}static createOrderBy(e){return new a(`${e}_order_by`,"ORDER BY",e)}static createLimit(e,t=!1){let n=t?"LIMIT/OFFSET":"LIMIT";return new a(`${e}_limit`,n,e)}},Xt=class a extends Mt{constructor(e,t,n="diamond"){super(e,t,"operation",n)}getMermaidRepresentation(){switch(this.shape){case"rounded":return`${this.id}(${this.label})`;case"rectangle":return`${this.id}[${this.label}]`;case"hexagon":return`${this.id}{{${this.label}}}`;case"stadium":return`${this.id}([${this.label}])`;case"diamond":default:return`${this.id}{${this.label}}`}}static createJoin(e,t){let n,r=t.trim().toLowerCase();return r==="join"?n="INNER JOIN":r.endsWith(" join")?n=r.toUpperCase():n=r.toUpperCase()+" JOIN",new a(`join_${e}`,n,"rectangle")}static createUnion(e,t="UNION ALL"){return new a(`${t.toLowerCase().replace(/\s+/g,"_")}_${e}`,t.toUpperCase(),"rectangle")}static createSetOperation(e,t){let n=t.toUpperCase(),r=`${n.toLowerCase().replace(/\s+/g,"_")}_${e}`;return new a(r,n,"rectangle")}},pr=class extends Mt{constructor(e="main"){let t=e==="main"?"Final Result":`${e} Result`;super(`${e}_output`,t,"output","stadium")}getMermaidRepresentation(){return`${this.id}([${this.label}])`}};var mr=class a{constructor(e,t,n){this.from=e;this.to=t;this.label=n}getMermaidRepresentation(){let e=this.label?` -->|${this.label}| `:" --> ";return`${this.from}${e}${this.to}`}static create(e,t,n){return new a(e,t,n)}static createWithNullability(e,t,n){let r=n?"NULLABLE":"NOT NULL";return new a(e,t,r)}},dr=class{constructor(){this.edges=[];this.connectionSet=new Set}add(e){let t=`${e.from}->${e.to}`;this.connectionSet.has(t)||(this.edges.push(e),this.connectionSet.add(t))}addConnection(e,t,n){this.add(mr.create(e,t,n))}addJoinConnection(e,t,n){this.add(mr.createWithNullability(e,t,n))}hasConnection(e,t){return this.connectionSet.has(`${e}->${t}`)}getAll(){return[...this.edges]}getMermaidRepresentation(){return this.edges.map(e=>e.getMermaidRepresentation()).join(`
63
+ 3. Entity hierarchy and parentId relationships are correct`)}s.push(new b(null,new P(g.generatedColumnName)))}else m.relationshipType==="array"&&s.push(new b(null,new P(m.propertyName)))});let l=new K(null,new $(i),new U(s),null),u=a.JSON_FUNCTIONS.AGGREGATE,c=Object.values(e.columns)[0];return{jsonAgg:new K(null,new $(u),new U([l]),null)}}collectArrayEntityColumnsByDepth(e,t){let n=new Map,r=Math.max(t+3,5);for(let i=t;i<=r;i++)n.set(i,new Set);return e.nestedEntities.filter(i=>i.relationshipType==="array").forEach(i=>{let s=this.calculateEntityDepth(i,e);n.has(s)||n.set(s,new Set),this.addEntityColumnsToDepthSet(i,s,n),this.collectDescendantColumns(i.id,s,e,n)}),n}calculateEntityDepth(e,t){let n=0,r=e;for(;r.parentId&&r.parentId!==t.rootEntity.id;)n++,r=t.nestedEntities.find(i=>i.id===r.parentId)||r;return n}addEntityColumnsToDepthSet(e,t,n){Object.values(e.columns).forEach(r=>{let i=typeof r=="string"?r:r.column;n.get(t).add(i)})}collectDescendantColumns(e,t,n,r){n.nestedEntities.filter(i=>i.parentId===e).forEach(i=>{this.addEntityColumnsToDepthSet(i,t,r),this.collectDescendantColumns(i.id,t,n,r)})}processSelectVariablesForGroupBy(e,t,n,r,i,s,o){e.forEach(l=>{if(!t.has(l.name)){if(o&&o.has(l.name))return;this.shouldIncludeColumnInGroupBy(l.name,n,r)&&(i.push(new z(new b(null,new P(l.name)),l.name)),l.name.endsWith("_json")||s.push(new b(null,new P(l.name))))}})}shouldIncludeColumnInGroupBy(e,t,n){let r=e.endsWith("_json"),i=!0;for(let[s,o]of t.entries())if(s>=n&&o.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 rr=class{constructor(){this.selectValueCollector=new Ke(null),this.objectEntityCteBuilder=new tr,this.arrayEntityCteBuilder=new nr}validateMapping(e,t){let r=new Ke().collect(e),i=new Set(r.map(u=>u.name));for(let u in t.rootEntity.columns){let c=t.rootEntity.columns[u],p=typeof c=="string"?c:c.column;if(!i.has(p))throw new Error(`Validation Error: Column "${p}" for JSON key "${u}" in root entity "${t.rootEntity.name}" not found in the query's select list.`)}let s=new Set([t.rootEntity.id]),o=new Map;t.nestedEntities.forEach(u=>{s.add(u.id),o.has(u.parentId)||o.set(u.parentId,[]),o.get(u.parentId).push(u.id)});for(let u of t.nestedEntities){if(!s.has(u.parentId))throw new Error(`Validation Error: Parent entity with ID "${u.parentId}" for nested entity "${u.name}" (ID: ${u.id}) not found.`);for(let c in u.columns){let p=u.columns[c],m=typeof p=="string"?p:p.column;if(!i.has(m))throw new Error(`Validation Error: Column "${m}" for JSON key "${c}" in nested entity "${u.name}" (ID: ${u.id}) not found in the query's select list.`)}}let l=new Set([t.rootEntity.id,...t.nestedEntities.map(u=>u.parentId)]);for(let u of l){let c=t.nestedEntities.filter(f=>f.parentId===u);if(c.filter(f=>f.relationshipType==="array").length>1){let f=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(g=>g.id===u)?.name;throw new Error(`Validation Error: Parent entity "${f}" (ID: ${u}) has multiple direct array children. This is not supported.`)}let m=new Set;for(let f of c){if(m.has(f.propertyName)){let g=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(h=>h.id===u)?.name;throw new Error(`Validation Error: Parent entity "${g}" (ID: ${u}) has duplicate property name "${f.propertyName}" for its children.`)}m.add(f.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 C?e:We.buildSimpleQuery(e);return this.buildJsonWithCteStrategy(r,t)}buildJson(e,t){return console.warn("buildJson is deprecated. Use buildJsonQuery instead."),this.buildJsonQuery(e,t)}buildJsonWithCteStrategy(e,t){this.validateMapping(e,t);let{initialCte:n,initialCteAlias:r}=this.createInitialCte(e),i=[n],s=r,o=new Map;o.set(t.rootEntity.id,{...t.rootEntity,isRoot:!0,propertyName:t.rootName}),t.nestedEntities.forEach(p=>o.set(p.id,{...p,isRoot:!1,propertyName:p.propertyName}));let l=this.objectEntityCteBuilder.buildObjectEntityCtes(n,o,t);i=l.ctes,s=l.lastCteAlias;let u=l.columnMappings,c=this.arrayEntityCteBuilder.buildArrayEntityCtes(i,s,o,t,u);return i=c.updatedCtes,s=c.lastCteAlias,this.buildFinalSelectQuery(i,s,o,t,u)}createInitialCte(e){let t="origin_query";return{initialCte:new ne(e,new re(t,null),null),initialCteAlias:t}}buildFinalSelectQuery(e,t,n,r,i){let s=[...e],o=`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 z(u,r.rootName),p=new ne(new C({selectClause:new _([c]),fromClause:new J(new B(new O(null,new P(t)),null),null)}),new re(o,null),null);s.push(p);let m="jsonb_agg",f=new K(null,new $(m),new U([new b(null,new P(r.rootName))]),null);return new C({withClause:new ae(!1,s),selectClause:new _([new z(f,`${r.rootName}_array`)]),fromClause:new J(new B(new O(null,new P(o)),null),null)})}else{let u=this.buildEntityJsonObject(l,null,r.nestedEntities,n,i),c=new z(u,r.rootName),p=new ne(new C({selectClause:new _([c]),fromClause:new J(new B(new O(null,new P(t)),null),null)}),new re(o,null),null);return s.push(p),new C({withClause:new ae(!1,s),selectClause:new _([new z(new b(null,new P(r.rootName)),r.rootName)]),fromClause:new J(new B(new O(null,new P(o)),null),null),limitClause:new oe(new Z(1))})}}buildEntityJsonObject(e,t,n,r,i){let s="jsonb_build_object",o=[];return Object.entries(e.columns).forEach(([u,c])=>{let p=typeof c=="string"?c:c.column;o.push(new Z(u,void 0,!0)),o.push(new b(null,new P(p)))}),n.filter(u=>u.parentId===e.id).forEach(u=>{let c=r.get(u.id);if(c)if(o.push(new Z(u.propertyName,void 0,!0)),u.relationshipType==="object"){let p=i.find(m=>m.entityId===c.id);if(!p)throw new Error(`Column mapping not found for entity: ${c.id}`);o.push(new b(null,new P(p.generatedColumnName)))}else u.relationshipType==="array"&&o.push(new b(null,new P(u.propertyName)))}),new K(null,new $(s),new U(o),null)}};var Ct=class{static extractParameterNames(e){return mt.collect(e).map(n=>n.name.value)}static hasParameter(e,t){return this.extractParameterNames(e).includes(t)}static separateFilters(e,t){let n=this.extractParameterNames(e),r={},i={};for(let[s,o]of Object.entries(t))n.includes(s)?r[s]=o:i[s]=o;return{hardcodedParams:r,dynamicFilters:i}}};var $t=class{constructor(e,t,n){this.name=e;this.type=t;this.tableName=n}},Br=class{constructor(e,t){this.tableColumnResolver=e,this.options={qualified:!1,upstream:!0,...t}}collect(e){let t=[],n=this.collectColumns(e);t.push(...n);let r=this.collectParameters(e);return t.push(...r),this.removeDuplicates(t)}collectColumns(e){let t=[];try{let r=new xe(this.tableColumnResolver,!1,"fullName",{upstream:this.options.upstream}).collect(e);for(let i of r){let s,o;if(i.value&&typeof i.value.getNamespace=="function"){let u=i.value.getNamespace();u&&u.trim()!==""&&(s=u,this.options.qualified&&(o=this.getRealTableName(e,u)))}s||(s=this.inferTableNameFromQuery(e),s&&this.options.qualified&&(o=s));let l=i.name;this.options.qualified&&(o||s)&&(l=`${o||s}.${i.name}`),t.push(new $t(l,"column",s))}}catch(n){console.warn("Failed to collect columns with SelectableColumnCollector, using fallback:",n);try{let i=new Bt(this.tableColumnResolver,!0).collect(e);for(let s of i)for(let o of s.columns){let l=o;this.options.qualified&&(l=`${s.name}.${o}`),t.push(new $t(l,"column",s.name))}}catch(r){console.warn("Failed to collect columns with both approaches:",n,r)}}return t}inferTableNameFromQuery(e){if(e instanceof C&&e.fromClause&&e.fromClause.source){let t=e.fromClause.source.datasource;if(t&&typeof t.table=="object"){let n=t.table;if(n&&typeof n.name=="string")return n.name}}}getRealTableName(e,t){try{let n=e.type==="WITH"?e.toSimpleQuery():e;if(n instanceof C&&n.fromClause){if(n.fromClause.source?.datasource){let i=n.fromClause.source,s=this.extractRealTableName(i,t);if(s)return s}let r=n.fromClause;if(r.joinClauses&&Array.isArray(r.joinClauses)){for(let i of r.joinClauses)if(i.source?.datasource){let s=this.extractRealTableName(i.source,t);if(s)return s}}}}catch(n){console.warn("Error resolving real table name:",n)}return t}extractRealTableName(e,t){try{let n=e.datasource;if(!n)return;let r=e.alias||e.aliasExpression?.table?.name,i=n.table?.name;if(r===t&&i||!r&&i===t)return i}catch{}}collectParameters(e){let t=[];try{let n=Ct.extractParameterNames(e);for(let r of n)t.push(new $t(r,"parameter"))}catch(n){console.warn("Failed to collect parameters:",n)}return t}removeDuplicates(e){let t=new Set,n=[];for(let r of e){let i=`${r.type}:${r.name}:${r.tableName||"none"}`;t.has(i)||(t.add(i),n.push(r))}return n.sort((r,i)=>{if(r.type!==i.type)return r.type==="column"?-1:1;if(r.type==="column"){let s=r.tableName||"",o=i.tableName||"";if(s!==o)return s.localeCompare(o)}return r.name.localeCompare(i.name)})}};var ir=class{constructor(e,t){typeof e=="function"?(this.tableColumnResolver=e,this.options=t||{}):(this.tableColumnResolver=void 0,this.options=e||{})}inject(e,t){typeof e=="string"&&(e=A.parse(e));let n=new Ot(this.tableColumnResolver,this.options),r=new xe(this.tableColumnResolver,!1,"fullName",{upstream:!0}),i=E=>this.options.ignoreCaseAndUnderscore?E.toLowerCase().replace(/_/g,""):E,s=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"],o=Object.values(t);if(o.length>0&&o.every(E=>E===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.");let c=[],p=[];for(let[E,y]of Object.entries(t))y!==void 0&&(this.isQualifiedColumnName(E)?c.push([E,y]):p.push([E,y]));for(let[E,y]of c)this.processStateParameter(E,y,e,n,r,i,s,g,f,W,G,h);let m=new Set;for(let[E,y]of c){let k=this.parseQualifiedColumnName(E);k&&m.add(`${k.table.toLowerCase()}.${k.column.toLowerCase()}`)}for(let[E,y]of p)this.processUnqualifiedParameter(E,y,e,n,r,i,s,g,f,W,G,h,m);function f(E,y,k,x,V){for(let T=0;T<k.length;T++){let w=k[T],L=w.column||y,Xe=V.find(D=>x(D.name)===x(L));if(!Xe)throw new Error(`Column '${L}' not found in query for AND condition`);let Oe=Xe.value;if("="in w&&w["="]!==void 0){let D=`${y}_and_${T}_eq`,F=new N(D,w["="]);E.appendWhere(new S(Oe,"=",F))}if("min"in w&&w.min!==void 0){let D=`${y}_and_${T}_min`,F=new N(D,w.min);E.appendWhere(new S(Oe,">=",F))}if("max"in w&&w.max!==void 0){let D=`${y}_and_${T}_max`,F=new N(D,w.max);E.appendWhere(new S(Oe,"<=",F))}if("like"in w&&w.like!==void 0){let D=`${y}_and_${T}_like`,F=new N(D,w.like);E.appendWhere(new S(Oe,"like",F))}if("ilike"in w&&w.ilike!==void 0){let D=`${y}_and_${T}_ilike`,F=new N(D,w.ilike);E.appendWhere(new S(Oe,"ilike",F))}if("in"in w&&w.in!==void 0){let F=w.in.map((q,H)=>new N(`${y}_and_${T}_in_${H}`,q));E.appendWhere(new S(Oe,"in",new Y(new U(F))))}if("any"in w&&w.any!==void 0){let D=`${y}_and_${T}_any`,F=new N(D,w.any);E.appendWhere(new S(Oe,"=",new K(null,"any",F,null)))}if("<"in w&&w["<"]!==void 0){let D=`${y}_and_${T}_lt`,F=new N(D,w["<"]);E.appendWhere(new S(Oe,"<",F))}if(">"in w&&w[">"]!==void 0){let D=`${y}_and_${T}_gt`,F=new N(D,w[">"]);E.appendWhere(new S(Oe,">",F))}if("!="in w&&w["!="]!==void 0){let D=`${y}_and_${T}_neq`,F=new N(D,w["!="]);E.appendWhere(new S(Oe,"!=",F))}if("<>"in w&&w["<>"]!==void 0){let D=`${y}_and_${T}_ne`,F=new N(D,w["<>"]);E.appendWhere(new S(Oe,"<>",F))}if("<="in w&&w["<="]!==void 0){let D=`${y}_and_${T}_le`,F=new N(D,w["<="]);E.appendWhere(new S(Oe,"<=",F))}if(">="in w&&w[">="]!==void 0){let D=`${y}_and_${T}_ge`,F=new N(D,w[">="]);E.appendWhere(new S(Oe,">=",F))}}}function g(E,y,k,x,V){let T=[];for(let w=0;w<k.length;w++){let L=k[w],Xe=L.column||y,Oe=V.find(q=>x(q.name)===x(Xe));if(!Oe)throw new Error(`Column '${Xe}' not found in query for OR condition`);let D=Oe.value,F=[];if("="in L&&L["="]!==void 0){let q=`${y}_or_${w}_eq`,H=new N(q,L["="]);F.push(new S(D,"=",H))}if("min"in L&&L.min!==void 0){let q=`${y}_or_${w}_min`,H=new N(q,L.min);F.push(new S(D,">=",H))}if("max"in L&&L.max!==void 0){let q=`${y}_or_${w}_max`,H=new N(q,L.max);F.push(new S(D,"<=",H))}if("like"in L&&L.like!==void 0){let q=`${y}_or_${w}_like`,H=new N(q,L.like);F.push(new S(D,"like",H))}if("ilike"in L&&L.ilike!==void 0){let q=`${y}_or_${w}_ilike`,H=new N(q,L.ilike);F.push(new S(D,"ilike",H))}if("in"in L&&L.in!==void 0){let H=L.in.map((_r,zr)=>new N(`${y}_or_${w}_in_${zr}`,_r));F.push(new S(D,"in",new Y(new U(H))))}if("any"in L&&L.any!==void 0){let q=`${y}_or_${w}_any`,H=new N(q,L.any);F.push(new S(D,"=",new K(null,"any",H,null)))}if("<"in L&&L["<"]!==void 0){let q=`${y}_or_${w}_lt`,H=new N(q,L["<"]);F.push(new S(D,"<",H))}if(">"in L&&L[">"]!==void 0){let q=`${y}_or_${w}_gt`,H=new N(q,L[">"]);F.push(new S(D,">",H))}if("!="in L&&L["!="]!==void 0){let q=`${y}_or_${w}_neq`,H=new N(q,L["!="]);F.push(new S(D,"!=",H))}if("<>"in L&&L["<>"]!==void 0){let q=`${y}_or_${w}_ne`,H=new N(q,L["<>"]);F.push(new S(D,"<>",H))}if("<="in L&&L["<="]!==void 0){let q=`${y}_or_${w}_le`,H=new N(q,L["<="]);F.push(new S(D,"<=",H))}if(">="in L&&L[">="]!==void 0){let q=`${y}_or_${w}_ge`,H=new N(q,L[">="]);F.push(new S(D,">=",H))}if(F.length>0){let q=F[0];for(let H=1;H<F.length;H++)q=new S(q,"and",F[H]);F.length>1?T.push(new Y(q)):T.push(q)}}if(T.length>0){let w=T[0];for(let L=1;L<T.length;L++)w=new S(w,"or",T[L]);E.appendWhere(new Y(w))}}function h(E,y,k){Object.keys(E).forEach(x=>{if(!y.includes(x))throw new Error(`Unsupported operator '${x}' for state key '${k}'`)})}function W(E,y,k,x){let V=new N(k,x);E.appendWhere(new S(y,"=",V))}function G(E,y,k,x){let V=[];if("="in x){let T=new N(k,x["="]);V.push(new S(y,"=",T))}if("min"in x){let T=new N(k+"_min",x.min);V.push(new S(y,">=",T))}if("max"in x){let T=new N(k+"_max",x.max);V.push(new S(y,"<=",T))}if("like"in x){let T=new N(k+"_like",x.like);V.push(new S(y,"like",T))}if("ilike"in x){let T=new N(k+"_ilike",x.ilike);V.push(new S(y,"ilike",T))}if("in"in x){let w=x.in.map((L,Xe)=>new N(`${k}_in_${Xe}`,L));V.push(new S(y,"in",new Y(new U(w))))}if("any"in x){let T=new N(k+"_any",x.any);V.push(new S(y,"=",new K(null,"any",T,null)))}if("<"in x){let T=new N(k+"_lt",x["<"]);V.push(new S(y,"<",T))}if(">"in x){let T=new N(k+"_gt",x[">"]);V.push(new S(y,">",T))}if("!="in x){let T=new N(k+"_neq",x["!="]);V.push(new S(y,"!=",T))}if("<>"in x){let T=new N(k+"_ne",x["<>"]);V.push(new S(y,"<>",T))}if("<="in x){let T=new N(k+"_le",x["<="]);V.push(new S(y,"<=",T))}if(">="in x){let T=new N(k+"_ge",x[">="]);V.push(new S(y,">=",T))}if(V.length===1)E.appendWhere(V[0]);else if(V.length>1){let T=V[0];for(let w=1;w<V.length;w++)T=new S(T,"and",V[w]);E.appendWhere(new Y(T))}}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}parseQualifiedColumnName(e){let t=e.split(".");return t.length===2&&t[0].trim()&&t[1].trim()?{table:t[0].trim(),column:t[1].trim()}:null}isQualifiedColumnName(e){return e.includes(".")&&this.parseQualifiedColumnName(e)!==null}sanitizeParameterName(e){return e.replace(/\./g,"_")}hasColumnMapping(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"column"in e}isSimpleValue(e){return e===null||typeof e!="object"||Array.isArray(e)||e instanceof Date}processStateParameter(e,t,n,r,i,s,o,l,u,c,p,m){if(this.isOrCondition(t)){let f=t.or;if(f&&f.length>0){let g=this.findTargetQueryForLogicalCondition(r,n,e,f),h=this.getAllAvailableColumns(g,i);l(g,e,f,s,h);return}}if(this.isAndCondition(t)){let f=t.and;if(f&&f.length>0){let g=this.findTargetQueryForLogicalCondition(r,n,e,f),h=this.getAllAvailableColumns(g,i);u(g,e,f,s,h);return}}if(this.isExplicitColumnMapping(t)){let f=t.column;if(f){let g=r.find(n,f);if(g.length===0)throw new Error(`Explicit column '${f}' not found in query`);for(let h of g){let G=this.getAllAvailableColumns(h,i).find(E=>s(E.name)===s(f));if(!G)throw new Error(`Explicit column '${f}' not found in query`);this.isValidatableObject(t)&&m(t,o,e),p(h,G.value,e,t)}return}}this.processRegularColumnCondition(e,t,n,r,i,s,o,c,p,m)}processUnqualifiedParameter(e,t,n,r,i,s,o,l,u,c,p,m,f){if(this.isOrCondition(t)){let h=t.or;if(h&&h.length>0){let W=this.findTargetQueryForLogicalCondition(r,n,e,h),G=this.getAllAvailableColumns(W,i);l(W,e,h,s,G);return}}if(this.isAndCondition(t)){let h=t.and;if(h&&h.length>0){let W=this.findTargetQueryForLogicalCondition(r,n,e,h),G=this.getAllAvailableColumns(W,i);u(W,e,h,s,G);return}}if(this.isExplicitColumnMapping(t)){let h=t.column;if(h){let W=r.find(n,h);if(W.length===0)throw new Error(`Explicit column '${h}' not found in query`);for(let G of W){let y=this.getAllAvailableColumns(G,i).find(k=>s(k.name)===s(h));if(!y)throw new Error(`Explicit column '${h}' not found in query`);this.isValidatableObject(t)&&m(t,o,e),p(G,y.value,e,t)}return}}let g=r.find(n,e);if(g.length===0){if(this.options.ignoreNonExistentColumns)return;throw new Error(`Column '${e}' not found in query`)}for(let h of g){let W=this.getAllAvailableColumns(h,i),G=this.buildTableMapping(h),E=W.filter(y=>s(y.name)===s(e));for(let y of E){let k=!1;if(y.value&&typeof y.value.getNamespace=="function"){let T=y.value.getNamespace();if(T){let w=G.aliasToRealTable.get(T.toLowerCase());if(w){let L=`${w.toLowerCase()}.${e.toLowerCase()}`;f.has(L)&&(k=!0)}}}if(k)continue;let x=y.value;this.isValidatableObject(t)&&m(t,o,e);let V=x;if(this.hasColumnMapping(t)){let T=t.column;if(T){let w=W.find(L=>s(L.name)===s(T));w&&(V=w.value)}}this.isSimpleValue(t)?c(h,V,e,t):p(h,V,e,t)}}}processRegularColumnCondition(e,t,n,r,i,s,o,l,u,c){let p=e,m;if(this.isQualifiedColumnName(e)){let g=this.parseQualifiedColumnName(e);g&&(p=g.column,m=g.table)}let f=r.find(n,p);if(f.length===0){if(this.options.ignoreNonExistentColumns)return;throw new Error(`Column '${p}' not found in query`)}for(let g of f){let h=this.getAllAvailableColumns(g,i),W;if(m){let k=this.buildTableMapping(g);if(W=h.find(x=>{if(!(s(x.name)===s(p)))return!1;if(x.value&&typeof x.value.getNamespace=="function"){let T=x.value.getNamespace();if(T){let w=s(T),L=s(m),Xe=k.aliasToRealTable.get(w);if(Xe&&s(Xe)===L)return!0}}return!1}),!W){if(this.options.ignoreNonExistentColumns)continue;let x=this.buildTableMapping(g),V=Array.from(x.realTableToAlias.keys()).some(w=>s(w)===s(m)),T=Array.from(x.aliasToRealTable.keys()).some(w=>s(w)===s(m));throw!V&&!T?new Error(`Column '${e}' (qualified as ${e}) not found in query`):T&&!V?new Error(`Column '${e}' not found. Only real table names are allowed in qualified column references (e.g., 'users.name'), not aliases (e.g., 'u.name').`):new Error(`Column '${e}' (qualified as ${e}) not found in query`)}}else if(W=h.find(k=>s(k.name)===s(p)),!W)throw new Error(`Column '${p}' not found in query`);let G=W.value;this.isValidatableObject(t)&&c(t,o,e);let E=G;if(this.hasColumnMapping(t)){let k=t.column;if(k){let x=h.find(V=>s(V.name)===s(k));x&&(E=x.value)}}let y=this.sanitizeParameterName(e);this.isSimpleValue(t)?l(g,E,y,t):u(g,E,y,t)}}findTargetQueryForLogicalCondition(e,t,n,r){let i=r.map(o=>o.column||n).filter((o,l,u)=>u.indexOf(o)===l);for(let o of i){let l=e.find(t,o);if(l.length>0)return l[0]}let s=r===r.or?"OR":"AND";throw new Error(`None of the ${s} condition columns [${i.join(", ")}] found in query`)}getAllAvailableColumns(e,t){let n=t.collect(e),r=this.collectCTEColumns(e);return[...n,...r]}collectCTEColumns(e){let t=[];if(e.withClause)for(let n of e.withClause.tables)try{let r=this.collectColumnsFromSelectQuery(n.query);t.push(...r)}catch(r){console.warn(`Failed to collect columns from CTE '${n.getSourceAliasName()}':`,r)}return t}collectColumnsFromSelectQuery(e){return e instanceof C?new xe(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(e):e instanceof Q?this.collectColumnsFromSelectQuery(e.left):[]}buildTableMapping(e){let t=new Map,n=new Map;try{if(e.fromClause&&(this.processSourceForMapping(e.fromClause.source,t,n),e.fromClause.joins))for(let r of e.fromClause.joins)this.processSourceForMapping(r.source,t,n);if(e.withClause)for(let r of e.withClause.tables){let i=r.getSourceAliasName();i&&(t.set(i.toLowerCase(),i),n.set(i.toLowerCase(),i))}}catch(r){console.warn("Failed to build table mapping:",r)}return{aliasToRealTable:t,realTableToAlias:n}}processSourceForMapping(e,t,n){try{if(e.datasource instanceof O){let r=e.datasource.getSourceName(),i=e.aliasExpression?.table?.name||r;r&&i&&(t.set(i.toLowerCase(),r),n.set(r.toLowerCase(),i),i===r&&t.set(r.toLowerCase(),r))}}catch(r){console.warn("Failed to process source for mapping:",r)}}};var sr=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof C))throw new Error("Complex queries are not supported for ORDER BY removal");return new C({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:null,windowClause:e.windowClause,limitClause:e.limitClause,offsetClause:e.offsetClause,fetchClause:e.fetchClause,forClause:e.forClause})}inject(e,t){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof C))throw new Error("Complex queries are not supported for sorting");let r=new xe(this.tableColumnResolver,!1,"fullName",{upstream:!0}).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(h=>h.name===l);if(!c)continue;let p=c.value;this.validateSortCondition(l,u);let m;u.desc?m="desc":m="asc";let f=null;u.nullsFirst?f="first":u.nullsLast&&(f="last");let g=new Ae(p,m,f);i.push(g)}let s=[];e.orderByClause?s=[...e.orderByClause.order,...i]:s=i;let o=s.length>0?new pe(s):null;return new C({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:o,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 or=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=A.parse(e)),!(e instanceof C))throw new Error("Complex queries are not supported for pagination");if(e.limitClause||e.offsetClause)throw new Error("Query already contains LIMIT or OFFSET clause. Use removePagination() first if you want to override existing pagination.");let n=(t.page-1)*t.pageSize,r=new oe(new N("paging_limit",t.pageSize)),i=new Re(new N("paging_offset",n));return new C({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,windowClause:e.windowClause,limitClause:r,offsetClause:i,fetchClause:e.fetchClause,forClause:e.forClause})}static removePagination(e){if(typeof e=="string"&&(e=A.parse(e)),!(e instanceof C))throw new Error("Complex queries are not supported for pagination removal");return new C({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 ar=class{constructor(e={}){this.options={requireAllParameters:!0,...e}}bind(e,t){let n=e,r=Ct.extractParameterNames(n);if(this.options.requireAllParameters){let i=r.filter(s=>!(s in t)||t[s]===void 0);if(i.length>0)throw new Error(`Missing values for required parameters: ${i.join(", ")}`)}for(let[i,s]of Object.entries(t))if(r.includes(i))try{st.set(n,i,s)}catch(o){throw new Error(`Failed to bind parameter '${i}': ${o instanceof Error?o.message:"Unknown error"}`)}return n}bindToSimpleQuery(e,t){return this.bind(e,t)}};var Vr=class{constructor(e){this.tableColumnResolver=e}buildQuery(e,t={}){let n;try{n=A.parse(e)}catch(i){throw new Error(`Failed to parse SQL: ${i instanceof Error?i.message:"Unknown error"}`)}let r=n;if(t.filter&&Object.keys(t.filter).length>0){let{hardcodedParams:i,dynamicFilters:s}=Ct.separateFilters(r,t.filter);if(Object.keys(i).length>0&&(r=new ar({requireAllParameters:!1}).bind(r,i)),Object.keys(s).length>0){let o=new ir(this.tableColumnResolver),l=We.buildSimpleQuery(r);r=o.inject(l,s)}}if(t.sort&&Object.keys(t.sort).length>0){let i=new sr(this.tableColumnResolver),s=We.buildSimpleQuery(r);r=i.inject(s,t.sort)}if(t.paging){let{page:i=1,pageSize:s}=t.paging;if(s!==void 0){let o=new or,l={page:i,pageSize:s},u=We.buildSimpleQuery(r);r=o.inject(u,l)}}if(t.serialize&&typeof t.serialize=="object"){let i=new rr,s=We.buildSimpleQuery(r);r=i.buildJsonQuery(s,t.serialize)}return r}buildFilteredQuery(e,t){return this.buildQuery(e,{filter:t})}buildSortedQuery(e,t){return this.buildQuery(e,{sort:t})}buildPaginatedQuery(e,t){return this.buildQuery(e,{paging:t})}buildSerializedQuery(e,t){return this.buildQuery(e,{serialize:t})}validateSql(e){try{return A.parse(e),!0}catch(t){throw new Error(`Invalid SQL: ${t instanceof Error?t.message:"Unknown error"}`)}}};function yr(a){let e=[],t=0,n={},r=()=>`entity_${++t}`,i=u=>(n[u]||(n[u]=0),n[u]++,n[u]===1?u:`${u}_${n[u]}`),s=(u,c=null)=>{let p={},m=[];for(let[f,g]of Object.entries(u))if(typeof g=="string")p[f]=g;else if("column"in g&&typeof g.column=="string"&&!("type"in g&&(g.type==="object"||g.type==="array"))){let h=g;typeof h=="object"&&"column"in h&&(p[f]=h.column,h.type==="string"&&e.push(h.column))}else if("from"in g&&typeof g.from=="string"&&!("type"in g&&(g.type==="object"||g.type==="array"))){let h=g;typeof h=="object"&&"from"in h&&(p[f]=h.from,h.type==="string"&&e.push(h.from))}else if("type"in g&&(g.type==="object"||g.type==="array")){let h=g,W=i(f),G=r(),E=s(h.structure,G);m.push({id:G,name:f.charAt(0).toUpperCase()+f.slice(1),parentId:c||"root",propertyName:W,originalPropertyName:f,relationshipType:h.type,columns:E.columns}),m.push(...E.nestedEntities.map(y=>({...y,parentId:y.parentId==="root"?G:y.parentId})))}return{columns:p,nestedEntities:m}},o=s(a.structure),l={rootName:"root",rootEntity:{id:"root",name:"Root",columns:o.columns},nestedEntities:o.nestedEntities};return l.typeInfo=a.typeInfo,{jsonMapping:l,typeProtection:{protectedStringFields:e}}}function ci(a){let e=[];return a.typeInfo?(a.typeInfo.interface||e.push("typeInfo.interface is required"),a.typeInfo.importPath||e.push("typeInfo.importPath is required")):e.push("typeInfo is required"),(!a.structure||typeof a.structure!="object")&&e.push("structure is required and must be an object"),e}function lr(a){let e={};for(let[t,n]of Object.entries(a))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 iy(a){if(!a)throw new Error("Input mapping is required");if(a.rootName&&a.rootEntity&&typeof a.rootEntity.columns=="object"&&!a.typeInfo&&!a.typeProtection&&!a.metadata&&Object.values(a.rootEntity.columns).every(t=>typeof t=="string"))return a;if(a.rootName&&a.rootEntity)return{rootName:a.rootName,rootEntity:{id:a.rootEntity.id||"root",name:a.rootEntity.name||a.rootName,columns:lr(a.rootEntity.columns||{})},nestedEntities:(a.nestedEntities||[]).map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:lr(e.columns||{})})),resultFormat:a.resultFormat,emptyResult:a.emptyResult};throw new Error("Unsupported mapping format")}function $r(a){return{rootName:a.rootName,rootEntity:{id:a.rootEntity.id,name:a.rootEntity.name,columns:lr(a.rootEntity.columns)},nestedEntities:a.nestedEntities.map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:lr(e.columns)})),resultFormat:a.resultFormat,emptyResult:a.emptyResult}}function Mr(a){let e=[],t=[],n=[];if(a.typeProtection)return{protectedStringFields:a.typeProtection.protectedStringFields||[],dateFields:a.typeProtection.dateFields,numberFields:a.typeProtection.numberFields,customTransforms:a.typeProtection.customTransforms};for(let[r,i]of Object.entries(a.rootEntity.columns))if(typeof i=="object"&&i.type){let s=i.column;switch(i.type){case"string":e.push(s);break;case"date":t.push(s);break;case"number":n.push(s);break}}for(let r of a.nestedEntities)for(let[i,s]of Object.entries(r.columns))if(typeof s=="object"&&s.type){let o=s.column;switch(s.type){case"string":e.push(o);break;case"date":t.push(o);break;case"number":n.push(o);break}}return{protectedStringFields:e,dateFields:t.length>0?t:void 0,numberFields:n.length>0?n:void 0,customTransforms:void 0}}function br(a){return a!=null&&typeof a=="object"}var vr=class{detect(e){if(!br(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:$r(e),typeProtection:Mr(e),originalInput:e,metadata:{typeInfo:e.typeInfo,version:e.metadata?.version,description:e.metadata?.description}}}},wr=class{detect(e){if(!br(e))return!1;let t=e;return t&&t.typeInfo&&t.structure&&typeof t.typeInfo.interface=="string"}convert(e){let t=yr(e);return{format:"model-driven",mapping:t.jsonMapping,typeProtection:t.typeProtection,originalInput:e,metadata:{typeInfo:e.typeInfo}}}},Sr=class{detect(e){if(!br(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}}},Zt=class{constructor(){this.strategies=[new vr,new wr,new Sr]}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 Er(a){return a.typeInfo&&a.structure?"model-driven":a.rootName&&a.rootEntity?"unified":(a.columns||a.relationships,"legacy")}function pi(a){let e={rootName:a.rootName||"root",rootEntity:{id:"root",name:a.rootName||"Root",columns:a.columns||{}},nestedEntities:[]};if(a.relationships&&typeof a.relationships=="object")for(let[t,n]of Object.entries(a.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 mi(a){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"),(a.columns||a.relationships)&&!a.rootName&&!a.rootEntity)return{format:"legacy",jsonMapping:pi(a),originalInput:a,metadata:{}};let t=new Zt().convert(a),n=t.format;return t.format==="legacy"&&a.rootName&&a.rootEntity&&(n="unified"),{format:n,jsonMapping:t.mapping,originalInput:a,metadata:{typeInfo:t.metadata?.typeInfo,typeProtection:t.typeProtection}}}function di(a){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 Zt().toLegacyMapping(a)}function hi(a){return Er(a)==="model-driven"}function fi(a){return Er(a)==="unified"}function Ci(a){return Er(a)==="legacy"}var ur=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 o=this.detectValueBasedTransformation(r);if(o){t[n]=this.applyTransformation(r,o);continue}}let s=this.config.globalTransformations&&this.getGlobalTransformationForValue(r);if(s){t[n]=this.applyTransformation(r,s);continue}if(typeof r=="object"&&!Array.isArray(r)){t[n]=this.transformSingleObject(r);continue}if(Array.isArray(r)){t[n]=r.map(o=>typeof o=="object"?this.transformSingleObject(o):o);continue}t[n]=r}return t}detectValueBasedTransformation(e){return typeof e=="string"&&this.isDateString(e)?{sourceType:"TIMESTAMP",targetType:"Date",handleNull:!0,validator:t=>typeof t=="string"&&!isNaN(Date.parse(t))}:typeof e=="number"&&!Number.isSafeInteger(e)?{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return typeof t=="string"||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?(BigInt(t),!0):!1}catch{return!1}}}:typeof e=="string"&&/^\d{16,}$/.test(e)?{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return typeof t=="string"||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?(BigInt(t),!0):!1}catch{return!1}}}:null}getGlobalTransformationForValue(e){return this.config.globalTransformations,null}detectAndGetGlobalTransformation(e){return this.detectValueBasedTransformation(e)}isDateString(e){if(this.config.strictDateDetection){if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})?$/.test(e))return!1}else if(!/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})?)?$/.test(e))return!1;let t=new Date(e);return!isNaN(t.getTime())}applyTransformation(e,t){if(e==null)return t.handleNull!==!1?e:null;if(t.validator&&!t.validator(e))return console.warn(`TypeTransformationPostProcessor: Value validation failed for ${e}`),e;try{switch(t.targetType){case"Date":return new Date(e);case"bigint":if(typeof e=="number"){let n=Math.trunc(e);return BigInt(n.toString())}return BigInt(e);case"string":return e.toString();case"number":return typeof e=="string"?parseFloat(e):Number(e);case"object":return typeof e=="string"?JSON.parse(e):e;case"custom":if(t.customTransformer&&this.config.customTransformers?.[t.customTransformer])return this.config.customTransformers[t.customTransformer](e);break;default:return e}}catch(n){return console.warn(`TypeTransformationPostProcessor: Transformation failed for ${e}:`,n),e}return e}static createDefaultConfig(){return{enableValueBasedDetection:!0,strictDateDetection:!1,globalTransformations:{DATE:{sourceType:"DATE",targetType:"Date",handleNull:!0,validator:e=>typeof e=="string"&&!isNaN(Date.parse(e))},TIMESTAMP:{sourceType:"TIMESTAMP",targetType:"Date",handleNull:!0,validator:e=>typeof e=="string"&&!isNaN(Date.parse(e))},BIGINT:{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:e=>{try{return typeof e=="string"||typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?(BigInt(e),!0):!1}catch{return!1}}}}}}static createSafeConfig(e){return{enableValueBasedDetection:!1,strictDateDetection:!0,columnTransformations:e||{},globalTransformations:{DATE:{sourceType:"DATE",targetType:"Date",handleNull:!0,validator:t=>typeof t=="string"&&!isNaN(Date.parse(t))},TIMESTAMP:{sourceType:"TIMESTAMP",targetType:"Date",handleNull:!0,validator:t=>typeof t=="string"&&!isNaN(Date.parse(t))},BIGINT:{sourceType:"BIGINT",targetType:"bigint",handleNull:!0,validator:t=>{try{return typeof t=="string"||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?(BigInt(t),!0):!1}catch{return!1}}}}}}};function Cy(a,e){return new ur(e||ur.createDefaultConfig()).transformResult(a)}var gy={toDate:a=>{if(a==null)return null;let e=new Date(a);return isNaN(e.getTime())?null:e},toBigInt:a=>{if(a==null)return null;try{return BigInt(a)}catch{return null}},toObject:a=>{if(a==null)return null;try{return JSON.parse(a)}catch{return null}}};var Mt=class{constructor(e,t,n,r,i){this.id=e;this.label=t;this.type=n;this.shape=r;this.details=i}},Wt=class a extends Mt{constructor(t,n,r){super(t,n,r,r==="subquery"?"hexagon":"cylinder");this.annotations=new Set}addAnnotation(t){this.annotations.add(t)}hasAnnotation(t){return this.annotations.has(t)}getMermaidRepresentation(){return this.shape==="hexagon"?`${this.id}{{${this.label}}}`:`${this.id}[(${this.label})]`}static createTable(t){return new a(`table_${t}`,t,"table")}static createCTE(t){return new a(`cte_${t}`,`CTE:${t}`,"cte")}static createSubquery(t){return new a(`subquery_${t}`,`SubQuery:${t}`,"subquery")}},cr=class a extends Mt{constructor(e,t,n=""){let r=n?`${n}_${t.toLowerCase().replace(/\s+/g,"_")}`:t.toLowerCase().replace(/\s+/g,"_");super(r,t,"process","hexagon")}getMermaidRepresentation(){return`${this.id}{{${this.label}}}`}static createWhere(e){return new a(`${e}_where`,"WHERE",e)}static createGroupBy(e){return new a(`${e}_group_by`,"GROUP BY",e)}static createHaving(e){return new a(`${e}_having`,"HAVING",e)}static createSelect(e){return new a(`${e}_select`,"SELECT",e)}static createOrderBy(e){return new a(`${e}_order_by`,"ORDER BY",e)}static createLimit(e,t=!1){let n=t?"LIMIT/OFFSET":"LIMIT";return new a(`${e}_limit`,n,e)}},Xt=class a extends Mt{constructor(e,t,n="diamond"){super(e,t,"operation",n)}getMermaidRepresentation(){switch(this.shape){case"rounded":return`${this.id}(${this.label})`;case"rectangle":return`${this.id}[${this.label}]`;case"hexagon":return`${this.id}{{${this.label}}}`;case"stadium":return`${this.id}([${this.label}])`;case"diamond":default:return`${this.id}{${this.label}}`}}static createJoin(e,t){let n,r=t.trim().toLowerCase();return r==="join"?n="INNER JOIN":r.endsWith(" join")?n=r.toUpperCase():n=r.toUpperCase()+" JOIN",new a(`join_${e}`,n,"rectangle")}static createUnion(e,t="UNION ALL"){return new a(`${t.toLowerCase().replace(/\s+/g,"_")}_${e}`,t.toUpperCase(),"rectangle")}static createSetOperation(e,t){let n=t.toUpperCase(),r=`${n.toLowerCase().replace(/\s+/g,"_")}_${e}`;return new a(r,n,"rectangle")}},pr=class extends Mt{constructor(e="main"){let t=e==="main"?"Final Result":`${e} Result`;super(`${e}_output`,t,"output","stadium")}getMermaidRepresentation(){return`${this.id}([${this.label}])`}};var mr=class a{constructor(e,t,n){this.from=e;this.to=t;this.label=n}getMermaidRepresentation(){let e=this.label?` -->|${this.label}| `:" --> ";return`${this.from}${e}${this.to}`}static create(e,t,n){return new a(e,t,n)}static createWithNullability(e,t,n){let r=n?"NULLABLE":"NOT NULL";return new a(e,t,r)}},dr=class{constructor(){this.edges=[];this.connectionSet=new Set}add(e){let t=`${e.from}->${e.to}`;this.connectionSet.has(t)||(this.edges.push(e),this.connectionSet.add(t))}addConnection(e,t,n){this.add(mr.create(e,t,n))}addJoinConnection(e,t,n){this.add(mr.createWithNullability(e,t,n))}hasConnection(e,t){return this.connectionSet.has(`${e}->${t}`)}getAll(){return[...this.edges]}getMermaidRepresentation(){return this.edges.map(e=>e.getMermaidRepresentation()).join(`
63
64
  `)}};var en=class{constructor(){this.nodes=new Map;this.edges=new dr}addNode(e){this.nodes.set(e.id,e)}addEdge(e){this.edges.add(e)}addConnection(e,t,n){this.edges.addConnection(e,t,n)}hasNode(e){return this.nodes.has(e)}hasConnection(e,t){return this.edges.hasConnection(e,t)}getNode(e){return this.nodes.get(e)}getAllNodes(){return Array.from(this.nodes.values())}getAllEdges(){return this.edges.getAll()}generateMermaid(e="TD",t){let n=`flowchart ${e}
64
65
  `;t&&(n+=` %% ${t}
65
66
  `);let r=Array.from(this.nodes.values()).map(s=>` ${s.getMermaidRepresentation()}`).join(`
66
67
  `);r&&(n+=r+`
67
68
  `),this.nodes.size>0&&this.edges.getAll().length>0&&(n+=`
68
69
  `);let i=this.edges.getMermaidRepresentation();return i&&(n+=` ${i}
69
- `),n}getOrCreateTable(e){let t=`table_${e}`,n=this.nodes.get(t);return n||(n=Wt.createTable(e),this.addNode(n)),n}getOrCreateCTE(e){let t=`cte_${e}`,n=this.nodes.get(t);return n||(n=Wt.createCTE(e),this.addNode(n)),n}getOrCreateSubquery(e){let t=`subquery_${e}`,n=this.nodes.get(t);return n||(n=Wt.createSubquery(e),this.addNode(n)),n}createProcessNode(e,t){let n=new cr(t,e);return this.addNode(n),n}createJoinNode(e,t){let n=Xt.createJoin(e,t);return this.addNode(n),n}createSetOperationNode(e,t){let n=Xt.createSetOperation(e,t);return this.addNode(n),n}createOutputNode(e="main"){let t=new pr(e);return this.addNode(t),t}};var tn=class{constructor(e){this.graph=e}processSource(e,t,n){if(e.datasource instanceof R)return this.processTableSource(e.datasource,t);if(e.datasource instanceof W)return this.processSubquerySource(e,t,n);throw new Error("Unsupported source type")}processTableSource(e,t){let n=e.getSourceName();return t.has(n)?this.graph.getOrCreateCTE(n).id:this.graph.getOrCreateTable(n).id}processSubquerySource(e,t,n){let r=e.aliasExpression?.table.name||"subquery",i=this.graph.getOrCreateSubquery(r),s=n(e.datasource.query,`subquery_${r}_internal`,t);return s&&!this.graph.hasConnection(s,i.id)&&this.graph.addConnection(s,i.id),i.id}extractTableNodeIds(e,t){let n=[],r=e.source;if(r.datasource instanceof R){let i=r.datasource.getSourceName();if(t.has(i)){let s=this.graph.getOrCreateCTE(i);n.push(s.id)}else{let s=this.graph.getOrCreateTable(i);n.push(s.id)}}if(e.joins&&e.joins.length>0)for(let i of e.joins){let s=i.source;if(s.datasource instanceof R){let o=s.datasource.getSourceName();if(t.has(o)){let l=this.graph.getOrCreateCTE(o);n.push(l.id)}else{let l=this.graph.getOrCreateTable(o);n.push(l.id)}}}return n}};var nn=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t;this.joinIdCounter=0}resetJoinCounter(){this.joinIdCounter=0}getNextJoinId(){return String(++this.joinIdCounter)}processFromClause(e,t,n){let r=this.dataSourceHandler.processSource(e.source,t,n);return e.joins&&e.joins.length>0?this.processJoins(e.joins,r,t,n):r}processJoins(e,t,n,r){let i=t;for(let s of e){let o=this.dataSourceHandler.processSource(s.source,n,r),l=this.getNextJoinId(),u=this.graph.createJoinNode(l,s.joinType.value),{leftLabel:c,rightLabel:p}=this.getJoinNullabilityLabels(s.joinType.value);i&&!this.graph.hasConnection(i,u.id)&&this.graph.addConnection(i,u.id,c),o&&!this.graph.hasConnection(o,u.id)&&this.graph.addConnection(o,u.id,p),i=u.id}return i}getJoinNullabilityLabels(e){switch(e.toLowerCase()){case"left join":return{leftLabel:"NOT NULL",rightLabel:"NULLABLE"};case"right join":return{leftLabel:"NULLABLE",rightLabel:"NOT NULL"};case"inner join":case"join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};case"full join":case"full outer join":return{leftLabel:"NULLABLE",rightLabel:"NULLABLE"};case"cross join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};default:return{leftLabel:"",rightLabel:""}}}};var rn=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t}processQueryClauses(e,t,n,r,i){return n}};var sn=class{constructor(e){this.graph=e}processCTEs(e,t,n){for(let r=0;r<e.tables.length;r++){let s=e.tables[r].getSourceAliasName(),o=this.graph.getOrCreateCTE(s);t.add(s),e.recursive&&r===0&&o.addAnnotation("recursive")}for(let r=0;r<e.tables.length;r++){let i=e.tables[r],s=i.getSourceAliasName(),o=this.graph.getOrCreateCTE(s),l=n(i.query,`cte_${s}`,t);if(l&&!this.graph.hasConnection(l,o.id)){let c=e.recursive&&r===0?"RECURSIVE":void 0;this.graph.addConnection(l,o.id,c)}}}detectRecursiveReference(e,t){return e.toString().toLowerCase().includes(t.toLowerCase())}};var Wr=class a{constructor(){this.graph=new en,this.dataSourceHandler=new tn(this.graph),this.joinHandler=new nn(this.graph,this.dataSourceHandler),this.processHandler=new rn(this.graph,this.dataSourceHandler),this.cteHandler=new sn(this.graph)}generateMermaidFlow(e,t){this.graph=new en,this.dataSourceHandler=new tn(this.graph),this.joinHandler=new nn(this.graph,this.dataSourceHandler),this.processHandler=new rn(this.graph,this.dataSourceHandler),this.cteHandler=new sn(this.graph),this.joinHandler.resetJoinCounter();let n=typeof e=="string"?A.parse(e):e,r=new Set;return this.processQuery(n,"main",r),this.graph.generateMermaid(t?.direction||"TD",t?.title)}static generate(e){return new a().generateMermaidFlow(e)}processQuery(e,t,n){if(e instanceof C)return this.processSimpleQuery(e,t,n);if(e instanceof Q)return this.processBinaryQuery(e,t,n);throw new Error("Unsupported query type")}processSimpleQuery(e,t,n){e.withClause&&this.cteHandler.processCTEs(e.withClause,n,this.processQuery.bind(this));let r="";return e.fromClause&&(e.fromClause.joins&&e.fromClause.joins.length>0?r=this.joinHandler.processFromClause(e.fromClause,n,this.processQuery.bind(this)):r=this.dataSourceHandler.processSource(e.fromClause.source,n,this.processQuery.bind(this))),r&&(r=this.processHandler.processQueryClauses(e,t,r,n,this.processQuery.bind(this))),this.handleOutputNode(r,t)}processBinaryQuery(e,t,n){let r=this.flattenBinaryChain(e,e.operator.value);return r.length>2?this.processMultiPartOperation(r,e.operator.value,t,n):this.processSimpleBinaryOperation(e,t,n)}processSimpleBinaryOperation(e,t,n){let r=this.processQuery(e.left,`${t}_left`,n),i=this.processQuery(e.right,`${t}_right`,n),s=t==="main"?"main":t.replace(/^cte_/,""),o=this.graph.createSetOperationNode(s,e.operator.value);return r&&!this.graph.hasConnection(r,o.id)&&this.graph.addConnection(r,o.id),i&&!this.graph.hasConnection(i,o.id)&&this.graph.addConnection(i,o.id),o.id}processMultiPartOperation(e,t,n,r){let i=[],s=n==="main"?"main":n.replace(/^cte_/,""),o=this.graph.createSetOperationNode(s,t);for(let l=0;l<e.length;l++){let u=`${n}_part${l+1}`,c=this.processQuery(e[l],u,r);i.push(c)}for(let l of i)l&&!this.graph.hasConnection(l,o.id)&&this.graph.addConnection(l,o.id);return o.id}handleOutputNode(e,t){if(t==="main"){let n=this.graph.createOutputNode(t);return e&&this.graph.addConnection(e,n.id),n.id}return e}flattenBinaryChain(e,t){let n=[],r=i=>{i instanceof Q&&i.operator.value===t?(r(i.left),r(i.right)):n.push(i)};return r(e),n}};var jr=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(`
70
- `);throw new Error(r)}}static extractStructureFromJsonMapping(e){let t={};return e.rootEntity&&e.rootEntity.columns&&Object.keys(e.rootEntity.columns).forEach(n=>{t[n]="primitive"}),e.nestedEntities&&e.nestedEntities.filter(n=>n.parentId===e.rootEntity.id).forEach(n=>{n.propertyName&&n.columns&&(n.relationshipType==="object"?t[n.propertyName]=this.extractNestedEntityStructure(n,e):n.relationshipType==="array"&&(t[n.propertyName]=[this.extractNestedEntityStructure(n,e)]))}),t}static extractNestedEntityStructure(e,t){let n={};return e.columns&&Object.keys(e.columns).forEach(r=>{n[r]="primitive"}),t.nestedEntities&&t.nestedEntities.filter(r=>r.parentId===e.id).forEach(r=>{r.propertyName&&r.columns&&(r.relationshipType==="object"?n[r.propertyName]=this.extractNestedEntityStructure(r,t):r.relationshipType==="array"&&(n[r.propertyName]=[this.extractNestedEntityStructure(r,t)]))}),n}static compareStructures(e,t,n=""){let r=[],i=[],s=[];if(e==="primitive"&&t==="primitive")return{isValid:!0,errors:[],missingProperties:[],extraProperties:[]};if(Array.isArray(t)&&Array.isArray(e)){if(t.length>0&&e.length>0){let u=this.compareStructures(e[0],t[0],`${n}[]`);r.push(...u.errors),i.push(...u.missingProperties),s.push(...u.extraProperties)}return{isValid:r.length===0,errors:r,missingProperties:i,extraProperties:s}}if(typeof e!="object"||typeof t!="object"||Array.isArray(e)||Array.isArray(t)||e===null||t===null)return{isValid:!0,errors:[],missingProperties:[],extraProperties:[]};let o=e,l=t;return Object.keys(l).forEach(u=>{let c=n?`${n}.${u}`:u;if(!(u in o)){i.push(c),r.push(`Missing property: ${c}`);return}let p=o[u],d=l[u],f=this.compareStructures(p,d,c);r.push(...f.errors),i.push(...f.missingProperties),s.push(...f.extraProperties)}),Object.keys(o).forEach(u=>{let c=n?`${n}.${u}`:u;u in l||s.push(c)}),{isValid:r.length===0,errors:r,missingProperties:i,extraProperties:s}}static validateAgainstSample(e,t){let n=this.extractStructureFromSample(t);return this.validate(e,n)}static validateAgainstSampleStrict(e,t){let n=this.validateAgainstSample(e,t);if(!n.isValid){let r=["JsonMapping validation against sample object failed:",...n.errors].join(`
70
+ `),n}getOrCreateTable(e){let t=`table_${e}`,n=this.nodes.get(t);return n||(n=Wt.createTable(e),this.addNode(n)),n}getOrCreateCTE(e){let t=`cte_${e}`,n=this.nodes.get(t);return n||(n=Wt.createCTE(e),this.addNode(n)),n}getOrCreateSubquery(e){let t=`subquery_${e}`,n=this.nodes.get(t);return n||(n=Wt.createSubquery(e),this.addNode(n)),n}createProcessNode(e,t){let n=new cr(t,e);return this.addNode(n),n}createJoinNode(e,t){let n=Xt.createJoin(e,t);return this.addNode(n),n}createSetOperationNode(e,t){let n=Xt.createSetOperation(e,t);return this.addNode(n),n}createOutputNode(e="main"){let t=new pr(e);return this.addNode(t),t}};var tn=class{constructor(e){this.graph=e}processSource(e,t,n){if(e.datasource instanceof O)return this.processTableSource(e.datasource,t);if(e.datasource instanceof j)return this.processSubquerySource(e,t,n);throw new Error("Unsupported source type")}processTableSource(e,t){let n=e.getSourceName();return t.has(n)?this.graph.getOrCreateCTE(n).id:this.graph.getOrCreateTable(n).id}processSubquerySource(e,t,n){let r=e.aliasExpression?.table.name||"subquery",i=this.graph.getOrCreateSubquery(r),s=n(e.datasource.query,`subquery_${r}_internal`,t);return s&&!this.graph.hasConnection(s,i.id)&&this.graph.addConnection(s,i.id),i.id}extractTableNodeIds(e,t){let n=[],r=e.source;if(r.datasource instanceof O){let i=r.datasource.getSourceName();if(t.has(i)){let s=this.graph.getOrCreateCTE(i);n.push(s.id)}else{let s=this.graph.getOrCreateTable(i);n.push(s.id)}}if(e.joins&&e.joins.length>0)for(let i of e.joins){let s=i.source;if(s.datasource instanceof O){let o=s.datasource.getSourceName();if(t.has(o)){let l=this.graph.getOrCreateCTE(o);n.push(l.id)}else{let l=this.graph.getOrCreateTable(o);n.push(l.id)}}}return n}};var nn=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t;this.joinIdCounter=0}resetJoinCounter(){this.joinIdCounter=0}getNextJoinId(){return String(++this.joinIdCounter)}processFromClause(e,t,n){let r=this.dataSourceHandler.processSource(e.source,t,n);return e.joins&&e.joins.length>0?this.processJoins(e.joins,r,t,n):r}processJoins(e,t,n,r){let i=t;for(let s of e){let o=this.dataSourceHandler.processSource(s.source,n,r),l=this.getNextJoinId(),u=this.graph.createJoinNode(l,s.joinType.value),{leftLabel:c,rightLabel:p}=this.getJoinNullabilityLabels(s.joinType.value);i&&!this.graph.hasConnection(i,u.id)&&this.graph.addConnection(i,u.id,c),o&&!this.graph.hasConnection(o,u.id)&&this.graph.addConnection(o,u.id,p),i=u.id}return i}getJoinNullabilityLabels(e){switch(e.toLowerCase()){case"left join":return{leftLabel:"NOT NULL",rightLabel:"NULLABLE"};case"right join":return{leftLabel:"NULLABLE",rightLabel:"NOT NULL"};case"inner join":case"join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};case"full join":case"full outer join":return{leftLabel:"NULLABLE",rightLabel:"NULLABLE"};case"cross join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};default:return{leftLabel:"",rightLabel:""}}}};var rn=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t}processQueryClauses(e,t,n,r,i){return n}};var sn=class{constructor(e){this.graph=e}processCTEs(e,t,n){for(let r=0;r<e.tables.length;r++){let s=e.tables[r].getSourceAliasName(),o=this.graph.getOrCreateCTE(s);t.add(s),e.recursive&&r===0&&o.addAnnotation("recursive")}for(let r=0;r<e.tables.length;r++){let i=e.tables[r],s=i.getSourceAliasName(),o=this.graph.getOrCreateCTE(s),l=n(i.query,`cte_${s}`,t);if(l&&!this.graph.hasConnection(l,o.id)){let c=e.recursive&&r===0?"RECURSIVE":void 0;this.graph.addConnection(l,o.id,c)}}}detectRecursiveReference(e,t){return e.toString().toLowerCase().includes(t.toLowerCase())}};var Wr=class a{constructor(){this.graph=new en,this.dataSourceHandler=new tn(this.graph),this.joinHandler=new nn(this.graph,this.dataSourceHandler),this.processHandler=new rn(this.graph,this.dataSourceHandler),this.cteHandler=new sn(this.graph)}generateMermaidFlow(e,t){this.graph=new en,this.dataSourceHandler=new tn(this.graph),this.joinHandler=new nn(this.graph,this.dataSourceHandler),this.processHandler=new rn(this.graph,this.dataSourceHandler),this.cteHandler=new sn(this.graph),this.joinHandler.resetJoinCounter();let n=typeof e=="string"?A.parse(e):e,r=new Set;return this.processQuery(n,"main",r),this.graph.generateMermaid(t?.direction||"TD",t?.title)}static generate(e){return new a().generateMermaidFlow(e)}processQuery(e,t,n){if(e instanceof C)return this.processSimpleQuery(e,t,n);if(e instanceof Q)return this.processBinaryQuery(e,t,n);throw new Error("Unsupported query type")}processSimpleQuery(e,t,n){e.withClause&&this.cteHandler.processCTEs(e.withClause,n,this.processQuery.bind(this));let r="";return e.fromClause&&(e.fromClause.joins&&e.fromClause.joins.length>0?r=this.joinHandler.processFromClause(e.fromClause,n,this.processQuery.bind(this)):r=this.dataSourceHandler.processSource(e.fromClause.source,n,this.processQuery.bind(this))),r&&(r=this.processHandler.processQueryClauses(e,t,r,n,this.processQuery.bind(this))),this.handleOutputNode(r,t)}processBinaryQuery(e,t,n){let r=this.flattenBinaryChain(e,e.operator.value);return r.length>2?this.processMultiPartOperation(r,e.operator.value,t,n):this.processSimpleBinaryOperation(e,t,n)}processSimpleBinaryOperation(e,t,n){let r=this.processQuery(e.left,`${t}_left`,n),i=this.processQuery(e.right,`${t}_right`,n),s=t==="main"?"main":t.replace(/^cte_/,""),o=this.graph.createSetOperationNode(s,e.operator.value);return r&&!this.graph.hasConnection(r,o.id)&&this.graph.addConnection(r,o.id),i&&!this.graph.hasConnection(i,o.id)&&this.graph.addConnection(i,o.id),o.id}processMultiPartOperation(e,t,n,r){let i=[],s=n==="main"?"main":n.replace(/^cte_/,""),o=this.graph.createSetOperationNode(s,t);for(let l=0;l<e.length;l++){let u=`${n}_part${l+1}`,c=this.processQuery(e[l],u,r);i.push(c)}for(let l of i)l&&!this.graph.hasConnection(l,o.id)&&this.graph.addConnection(l,o.id);return o.id}handleOutputNode(e,t){if(t==="main"){let n=this.graph.createOutputNode(t);return e&&this.graph.addConnection(e,n.id),n.id}return e}flattenBinaryChain(e,t){let n=[],r=i=>{i instanceof Q&&i.operator.value===t?(r(i.left),r(i.right)):n.push(i)};return r(e),n}};var jr=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(`
71
+ `);throw new Error(r)}}static extractStructureFromJsonMapping(e){let t={};return e.rootEntity&&e.rootEntity.columns&&Object.keys(e.rootEntity.columns).forEach(n=>{t[n]="primitive"}),e.nestedEntities&&e.nestedEntities.filter(n=>n.parentId===e.rootEntity.id).forEach(n=>{n.propertyName&&n.columns&&(n.relationshipType==="object"?t[n.propertyName]=this.extractNestedEntityStructure(n,e):n.relationshipType==="array"&&(t[n.propertyName]=[this.extractNestedEntityStructure(n,e)]))}),t}static extractNestedEntityStructure(e,t){let n={};return e.columns&&Object.keys(e.columns).forEach(r=>{n[r]="primitive"}),t.nestedEntities&&t.nestedEntities.filter(r=>r.parentId===e.id).forEach(r=>{r.propertyName&&r.columns&&(r.relationshipType==="object"?n[r.propertyName]=this.extractNestedEntityStructure(r,t):r.relationshipType==="array"&&(n[r.propertyName]=[this.extractNestedEntityStructure(r,t)]))}),n}static compareStructures(e,t,n=""){let r=[],i=[],s=[];if(e==="primitive"&&t==="primitive")return{isValid:!0,errors:[],missingProperties:[],extraProperties:[]};if(Array.isArray(t)&&Array.isArray(e)){if(t.length>0&&e.length>0){let u=this.compareStructures(e[0],t[0],`${n}[]`);r.push(...u.errors),i.push(...u.missingProperties),s.push(...u.extraProperties)}return{isValid:r.length===0,errors:r,missingProperties:i,extraProperties:s}}if(typeof e!="object"||typeof t!="object"||Array.isArray(e)||Array.isArray(t)||e===null||t===null)return{isValid:!0,errors:[],missingProperties:[],extraProperties:[]};let o=e,l=t;return Object.keys(l).forEach(u=>{let c=n?`${n}.${u}`:u;if(!(u in o)){i.push(c),r.push(`Missing property: ${c}`);return}let p=o[u],m=l[u],f=this.compareStructures(p,m,c);r.push(...f.errors),i.push(...f.missingProperties),s.push(...f.extraProperties)}),Object.keys(o).forEach(u=>{let c=n?`${n}.${u}`:u;u in l||s.push(c)}),{isValid:r.length===0,errors:r,missingProperties:i,extraProperties:s}}static validateAgainstSample(e,t){let n=this.extractStructureFromSample(t);return this.validate(e,n)}static validateAgainstSampleStrict(e,t){let n=this.validateAgainstSample(e,t);if(!n.isValid){let r=["JsonMapping validation against sample object failed:",...n.errors].join(`
71
72
  `);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 on=class{constructor(e){this.schemas=e,this.validateSchemas()}validateSchemas(){let e=Object.keys(this.schemas),t=[];if(Object.entries(this.schemas).forEach(([n,r])=>{Object.entries(r.columns).filter(([s,o])=>o.isPrimaryKey).map(([s,o])=>s).length===0&&t.push(`Table '${n}' has no primary key defined`),r.relationships?.forEach(s=>{e.includes(s.table)||t.push(`Table '${n}' references unknown table '${s.table}' in relationship`)})}),t.length>0)throw new Error(`Schema validation failed:\\n${t.join("\\n")}`)}getTableColumns(e){let t=this.schemas[e];return t?Object.keys(t.columns):[]}createTableColumnResolver(){return e=>this.getTableColumns(e)}createJsonMapping(e){let t=this.schemas[e];if(!t)throw new Error(`Table '${e}' not found in schema registry`);let n={};Object.entries(t.columns).forEach(([i,s])=>{n[i]=s.jsonAlias||s.name});let r=[];return t.relationships?.forEach(i=>{let s=this.schemas[i.table];if(!s)throw new Error(`Related table '${i.table}' not found in schema registry`);let o={};Object.entries(s.columns).forEach(([u,c])=>{o[u]=c.jsonAlias||c.name});let l=i.type;r.push({id:i.propertyName,name:s.displayName||i.table,parentId:e,propertyName:i.propertyName,relationshipType:l,columns:o})}),{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 jy(a){return new on(a)}function Dy(a){return new on(a).createTableColumnResolver()}function Uy(a,e){return new on(a).createJsonMapping(e)}var Qe=class{static lineColumnToCharOffset(e,t){if(t.line<1||t.column<1)return-1;let n=e.split(`
72
73
  `);if(t.line>n.length)return-1;let r=n[t.line-1];if(t.column>r.length+1)return-1;let i=0;for(let s=0;s<t.line-1;s++)i+=n[s].length+1;return i+=t.column-1,i}static charOffsetToLineColumn(e,t){if(t<0||t>e.length)return null;let n=e.split(`
73
74
  `),r=0;for(let i=0;i<n.length;i++){let s=n[i].length;if(t<r+s)return{line:i+1,column:t-r+1};if(t===r+s&&i<n.length-1)return{line:i+2,column:1};r+=s+1}if(t===e.length){let i=n[n.length-1];return{line:n.length,column:i.length+1}}return null}static isValidPosition(e,t){return this.lineColumnToCharOffset(e,t)!==-1}static getLine(e,t){if(t<1)return null;let n=e.split(`
74
75
  `);return t>n.length?null:n[t-1]}static getLineCount(e){return e.split(`
75
- `).length}};var jt=class{static{this.joinSuggestionCache=new Map}static{this.commandSuggestionCache=new Map}static{this.initialized=!1}static initialize(){if(this.initialized)return;let e=[["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"],["lateral","join"],["lateral","inner","join"],["lateral","left","join"],["lateral","left","outer","join"]],t=new Map,n=new Set;e.forEach(r=>{r.length>1&&n.add(r.slice(1).join(" ").toUpperCase())}),e.forEach(r=>{for(let i=0;i<r.length-1;i++){let s=r[i];t.has(s)||t.set(s,new Set),e.forEach(o=>{if(o.length>i+1&&o[i]===s){let l=o.slice(i+1).join(" ").toUpperCase();t.get(s).add(l)}})}}),t.forEach((r,i)=>{this.joinSuggestionCache.set(i.toLowerCase(),Array.from(r))}),this.initializeCommandKeywords(),this.initialized=!0}static getJoinSuggestions(e){return this.initialize(),this.joinSuggestionCache.get(e.toLowerCase())||[]}static isValidJoinKeyword(e){return Kt.parse(e,0)!==null}static getPartialSuggestions(e){this.initialize();let t=e.toLowerCase(),n=[];return this.joinSuggestionCache.forEach((r,i)=>{i.startsWith(t)&&(n.push(i),r.forEach(s=>{n.includes(s)||n.push(s)}))}),n}static getAllJoinKeywords(){this.initialize();let e=new Set;return this.joinSuggestionCache.forEach((t,n)=>{e.add(n),t.forEach(r=>e.add(r))}),Array.from(e)}static initializeCommandKeywords(){let e=this.extractCommandPatternsFromTrie(),t=new Map;e.forEach(n=>{for(let r=0;r<n.length-1;r++){let i=n[r],s=n[r+1];t.has(i)||t.set(i,new Set),t.get(i).add(s)}}),t.forEach((n,r)=>{this.commandSuggestionCache.set(r.toLowerCase(),Array.from(n))})}static extractCommandPatternsFromTrie(){return[["group","by"],["order","by"],["distinct","on"],["not","materialized"],["row","only"],["rows","only"],["percent","with","ties"],["key","share"],["no","key","update"],["union","all"],["intersect","all"],["except","all"],["partition","by"],["within","group"],["with","ordinality"]]}static getCommandSuggestions(e){return this.initialize(),this.commandSuggestionCache.get(e.toLowerCase())||[]}static reset(){this.joinSuggestionCache.clear(),this.commandSuggestionCache.clear(),this.initialized=!1}};var Dt=class{static{this.patternCache=null}static getKeywordPatterns(){if(this.patternCache!==null)return this.patternCache;let e=new Map,t=new Set,n=new Set;return this.extractKeywordPatterns(e,t,n),this.patternCache={requiresKeywords:e,suggestsTables:t,suggestsColumns:n},this.patternCache}static extractKeywordPatterns(e,t,n){let r=["from","join"],i=["select","where","on","having","by"];for(let s of r)this.isKeywordInDictionary(s)&&t.add(s);for(let s of i)this.isKeywordInDictionary(s)&&n.add(s);this.extractRequiresKeywordPatterns(e)}static isKeywordInDictionary(e){return jt.isValidJoinKeyword(e)?!0:["from","join","select","where","on","having","by","group","order"].includes(e)}static extractRequiresKeywordPatterns(e){let t=["inner","left","right","full","cross","natural","outer","group","order"];for(let n of t){let r=this.findPossibleFollowups(n);r.length>0&&e.set(n,r)}}static findPossibleFollowups(e){let t=new Set;return jt.getJoinSuggestions(e.toLowerCase()).forEach(i=>t.add(i.toUpperCase())),jt.getCommandSuggestions(e.toLowerCase()).forEach(i=>t.add(i.toUpperCase())),Array.from(t)}static requiresSpecificKeywords(e){let n=this.getKeywordPatterns().requiresKeywords.get(e);return n?{suggestKeywords:!0,requiredKeywords:n}:null}static analyzeIntelliSense(e,t){try{let n=Le.getAllLexemesWithPosition(e),r=-1,i;for(let c=0;c<n.length;c++){let p=n[c];if(p.position){if(t>=p.position.startPosition&&t<=p.position.endPosition){i=p,r=c;break}else if(p.position.startPosition>t){r=Math.max(0,c-1),i=r>=0?n[r]:void 0;break}}}r===-1&&n.length>0&&(r=n.length-1,i=n[r]);let s=r>0?n[r-1]:void 0;if(this.isAfterDot(e,t,s))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,tableScope:this.findPrecedingIdentifier(e,t,n),currentToken:i,previousToken:s};if(i){let c=i.value.toLowerCase(),p=this.requiresSpecificKeywords(c);if(p)return{suggestTables:!1,suggestColumns:!1,...p,currentToken:i,previousToken:s}}let l=i?.value.toLowerCase(),u=s?.value.toLowerCase();if(l){let c=this.getKeywordPatterns();if(c.suggestsTables.has(l))return{suggestTables:!0,suggestColumns:!1,suggestKeywords:!1,currentToken:i,previousToken:s};if(c.suggestsColumns.has(l))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,currentToken:i,previousToken:s}}if(u){let c=this.getKeywordPatterns(),p=this.requiresSpecificKeywords(u);if(p&&l!=="join"&&l!=="outer"&&l!=="by")return{suggestTables:!1,suggestColumns:!1,...p,currentToken:i,previousToken:s};if(c.suggestsTables.has(u))return{suggestTables:!0,suggestColumns:!1,suggestKeywords:!1,currentToken:i,previousToken:s};if(c.suggestsColumns.has(u))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,currentToken:i,previousToken:s}}return{suggestTables:!1,suggestColumns:!1,suggestKeywords:!0,currentToken:i,previousToken:s}}catch{return{suggestTables:!1,suggestColumns:!1,suggestKeywords:!1}}}static analyzeIntelliSenseAt(e,t){let n=Qe.lineColumnToCharOffset(e,t);return n===-1?{suggestTables:!1,suggestColumns:!1,suggestKeywords:!1}:this.analyzeIntelliSense(e,n)}static isAfterDot(e,t,n){if(t>0&&e[t-1]==="."||n&&n.value===".")return!0;let r=t-1;for(;r>=0&&/\s/.test(e[r]);)r--;return r>=0&&e[r]==="."}static findPrecedingIdentifier(e,t,n){if(this.isAfterDot(e,t)){let r=t-1;for(;r>=0&&/\s/.test(e[r]);)r--;if(r>=0&&e[r]==="."){let i=r;for(;r>=0&&/\s/.test(e[r]);)r--;for(;r>=0&&/[a-zA-Z0-9_]/.test(e[r]);)r--;let s=r+1;if(s<i)return e.substring(s,i)}for(let i=n.length-1;i>=0;i--)if(n[i].value==="."&&n[i].position&&n[i].position.startPosition<t){if(i>0&&this.isIdentifier(n[i-1]))return n[i-1].value;break}}}static isIdentifier(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.value)}};var an=class{static resolve(e,t){return this.createEmptyScope()}static resolveAt(e,t){let n=Qe.lineColumnToCharOffset(e,t);return n===-1?this.createEmptyScope():this.resolve(e,n)}static getColumnsForTable(e,t,n){let r=this.resolve(e,t),i=r.availableTables.find(s=>s.name===n||s.alias===n);return i?r.visibleColumns.filter(s=>s.tableName===i.name||i.alias&&s.tableAlias===i.alias):[]}static analyzeScopeFromQuery(e){let t={availableTables:[],availableCTEs:[],subqueryLevel:0,visibleColumns:[],currentQuery:e,parentQueries:[]};if(e instanceof C)t.availableCTEs=this.collectCTEs(e),t.availableTables=this.collectTablesFromQuery(e),t.visibleColumns=this.collectVisibleColumns(t.availableTables,t.availableCTEs);else if(e instanceof Q){let n=this.analyzeScopeFromQuery(e.left),r=this.analyzeScopeFromQuery(e.right);t.availableTables=[...n.availableTables,...r.availableTables],t.availableCTEs=[...n.availableCTEs,...r.availableCTEs],t.visibleColumns=[...n.visibleColumns,...r.visibleColumns]}return t}static collectCTEs(e){let t=[];if(e.withClause){let r=new X().collect(e);for(let i of r)t.push({name:i.getSourceAliasName(),query:i.query,columns:this.extractCTEColumns(i.query),materialized:i.materialized||!1})}return t}static collectTablesFromQuery(e){let t=[];if(e.fromClause){let n=this.extractTablesFromFromClause(e.fromClause);t.push(...n)}return t}static extractTablesFromFromClause(e){let t=[];if(e.source.datasource instanceof R){let n={name:this.extractTableName(e.source.datasource.qualifiedName),alias:e.source.aliasExpression?.table.name,schema:this.extractSchemaName(e.source.datasource.qualifiedName),fullName:this.getQualifiedNameString(e.source.datasource.qualifiedName),sourceType:"table"};t.push(n)}else if(e.source.datasource instanceof W){let n={name:e.source.aliasExpression?.table.name||"subquery",alias:e.source.aliasExpression?.table.name,fullName:e.source.aliasExpression?.table.name||"subquery",sourceType:"subquery",originalQuery:e.source.datasource.query};t.push(n)}if(e.joins)for(let n of e.joins){let r=this.extractTablesFromJoin(n);t.push(...r)}return t}static extractTablesFromJoin(e){let t=[];if(e.source.datasource instanceof R){let n={name:this.extractTableName(e.source.datasource.qualifiedName),alias:e.source.aliasExpression?.table.name,schema:this.extractSchemaName(e.source.datasource.qualifiedName),fullName:this.getQualifiedNameString(e.source.datasource.qualifiedName),sourceType:"table"};t.push(n)}else if(e.source.datasource instanceof W){let n={name:e.source.aliasExpression?.table.name||"subquery",alias:e.source.aliasExpression?.table.name,fullName:e.source.aliasExpression?.table.name||"subquery",sourceType:"subquery",originalQuery:e.source.datasource.query};t.push(n)}return t}static getQualifiedNameString(e){return e.toString()}static extractTableName(e){let n=this.getQualifiedNameString(e).split(".");return n[n.length-1]}static extractSchemaName(e){let n=this.getQualifiedNameString(e).split(".");return n.length>1?n[n.length-2]:void 0}static extractCTEColumns(e){try{if(e instanceof C&&e.selectClause){let t=[];for(let n of e.selectClause.items)if(n.identifier)t.push(n.identifier.name);else{let r=this.extractColumnNameFromExpression(n.value);r&&t.push(r)}return t}}catch{}}static extractColumnNameFromExpression(e){if(e&&typeof e=="object"&&"value"in e)return e.value}static collectVisibleColumns(e,t){let n=[];for(let r of t)if(r.columns)for(let i of r.columns)n.push({name:i,tableName:r.name,fullReference:`${r.name}.${i}`});for(let r of e)r.sourceType==="table"&&n.push({name:"*",tableName:r.name,tableAlias:r.alias,fullReference:`${r.alias||r.name}.*`});return n}static createEmptyScope(){return{availableTables:[],availableCTEs:[],subqueryLevel:0,visibleColumns:[],parentQueries:[]}}};var hr=class{static parseToPosition(e,t,n={}){let r=typeof t=="number"?t:Qe.lineColumnToCharOffset(e,t);if(r===-1)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};try{let i=this.tryNormalParse(e,r,n);return i.success?i:n.errorRecovery?this.tryErrorRecovery(e,r,n):i}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i),stoppedAtCursor:!1}}}static parseCurrentQuery(e,t,n={}){let r=typeof t=="number"?t:Qe.lineColumnToCharOffset(e,t);if(r===-1)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};let i=this.findQueryBoundaries(e),s=this.findQueryAtPosition(i,r);if(!s)return{success:!1,error:"No query found at cursor position",stoppedAtCursor:!1};let o=r-s.start,l=e.substring(s.start,s.end);return this.parseToPosition(l,o,n)}static tryNormalParse(e,t,n){if(t<0||t>e.length)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};let r=e.trim(),s=[".",",","SELECT","FROM","WHERE","JOIN","ON","GROUP BY","ORDER BY"].some(p=>r.toLowerCase().endsWith(p.toLowerCase())),o=A.analyze(e);if(!o.success||s)return{...o,success:!1};let l=this.getAllTokens(e),u=this.findTokenAtPosition(l,t),c=this.findTokenBeforePosition(l,t);return{...o,parsedTokens:l,tokenBeforeCursor:c,stoppedAtCursor:t<e.length,recoveryAttempts:0}}static tryErrorRecovery(e,t,n){let r=n.maxRecoveryAttempts||5,i=0,s=[()=>this.recoverWithTokenInsertion(e,t,n),()=>this.recoverWithTruncation(e,t,n),()=>this.recoverWithCompletion(e,t,n),()=>this.recoverWithMinimalSQL(e,t,n)];for(let o of s){if(i>=r)break;i++;try{let l=o();if(l.success)return l.recoveryAttempts=i,l}catch{continue}}return{success:!1,error:"All error recovery attempts failed",recoveryAttempts:i,stoppedAtCursor:!1}}static recoverWithTokenInsertion(e,t,n){if(!n.insertMissingTokens)throw new Error("Token insertion disabled");let r=[{pattern:/SELECT\s*$/i,replacement:"SELECT 1 "},{pattern:/FROM\s*$/i,replacement:"FROM dual "},{pattern:/WHERE\s*$/i,replacement:"WHERE 1=1 "},{pattern:/JOIN\s*$/i,replacement:"JOIN dual ON 1=1 "},{pattern:/ON\s*$/i,replacement:"ON 1=1 "},{pattern:/GROUP\s+BY\s*$/i,replacement:"GROUP BY 1 "},{pattern:/ORDER\s+BY\s*$/i,replacement:"ORDER BY 1 "}],i=e;for(let l of r)if(l.pattern.test(e)){i=e.replace(l.pattern,l.replacement);break}if(i===e)throw new Error("No applicable token insertion found");let s=A.analyze(i),o=this.getAllTokens(e);return{...s,parsedTokens:o,tokenBeforeCursor:this.findTokenBeforePosition(o,t),stoppedAtCursor:!0,recoveryAttempts:1}}static recoverWithTruncation(e,t,n){let r=e.substring(0,t),i=[""," 1"," FROM dual"," WHERE 1=1"];for(let s of i)try{let o=r+s,l=A.analyze(o);if(l.success){let u=this.getAllTokens(e);return{...l,parsedTokens:u.filter(c=>c.position&&c.position.startPosition<=t),tokenBeforeCursor:this.findTokenBeforePosition(u,t),stoppedAtCursor:!0,recoveryAttempts:1}}}catch{continue}throw new Error("Truncation recovery failed")}static recoverWithCompletion(e,t,n){let r=e.substring(0,t),i=e.substring(t),s=[{pattern:/\.\s*$/,completion:"id"},{pattern:/\w+\s*$/,completion:""},{pattern:/,\s*$/,completion:"1"},{pattern:/\(\s*$/,completion:"1)"}];for(let o of s)if(o.pattern.test(r)){let l=r+o.completion+i;try{let u=A.analyze(l);if(u.success){let c=this.getAllTokens(e);return{...u,parsedTokens:c,tokenBeforeCursor:this.findTokenBeforePosition(c,t),stoppedAtCursor:!0,recoveryAttempts:1}}}catch{continue}}throw new Error("Completion recovery failed")}static recoverWithMinimalSQL(e,t,n){let r="SELECT 1 FROM dual WHERE 1=1";try{let i=A.analyze(r),s=this.getAllTokens(e);return{success:!0,query:i.query,parsedTokens:s.filter(o=>o.position&&o.position.startPosition<=t),tokenBeforeCursor:this.findTokenBeforePosition(s,t),stoppedAtCursor:!0,partialAST:i.query,recoveryAttempts:1}}catch{throw new Error("Minimal SQL recovery failed")}}static getAllTokens(e){try{return Le.getAllLexemesWithPosition(e)}catch{return[]}}static findTokenAtPosition(e,t){return e.find(n=>n.position&&t>=n.position.startPosition&&t<n.position.endPosition)}static findTokenBeforePosition(e,t){let n;for(let r of e)if(r.position)if(r.position.endPosition<=t)n=r;else{if(r.position.startPosition<t)break;break}return n}static findQueryBoundaries(e){let t=[],n=0,r=!1,i="",s=!1;for(let o=0;o<e.length;o++){let l=e[o],u=o<e.length-1?e[o+1]:"";if(!s&&(l==="'"||l==='"')){r?l===i&&(r=!1,i=""):(r=!0,i=l);continue}if(!r&&l==="-"&&u==="-"){s=!0,o++;continue}if(s&&l===`
76
+ `).length}};var jt=class{static{this.joinSuggestionCache=new Map}static{this.commandSuggestionCache=new Map}static{this.initialized=!1}static initialize(){if(this.initialized)return;let e=[["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"],["lateral","join"],["lateral","inner","join"],["lateral","left","join"],["lateral","left","outer","join"]],t=new Map,n=new Set;e.forEach(r=>{r.length>1&&n.add(r.slice(1).join(" ").toUpperCase())}),e.forEach(r=>{for(let i=0;i<r.length-1;i++){let s=r[i];t.has(s)||t.set(s,new Set),e.forEach(o=>{if(o.length>i+1&&o[i]===s){let l=o.slice(i+1).join(" ").toUpperCase();t.get(s).add(l)}})}}),t.forEach((r,i)=>{this.joinSuggestionCache.set(i.toLowerCase(),Array.from(r))}),this.initializeCommandKeywords(),this.initialized=!0}static getJoinSuggestions(e){return this.initialize(),this.joinSuggestionCache.get(e.toLowerCase())||[]}static isValidJoinKeyword(e){return Kt.parse(e,0)!==null}static getPartialSuggestions(e){this.initialize();let t=e.toLowerCase(),n=[];return this.joinSuggestionCache.forEach((r,i)=>{i.startsWith(t)&&(n.push(i),r.forEach(s=>{n.includes(s)||n.push(s)}))}),n}static getAllJoinKeywords(){this.initialize();let e=new Set;return this.joinSuggestionCache.forEach((t,n)=>{e.add(n),t.forEach(r=>e.add(r))}),Array.from(e)}static initializeCommandKeywords(){let e=this.extractCommandPatternsFromTrie(),t=new Map;e.forEach(n=>{for(let r=0;r<n.length-1;r++){let i=n[r],s=n[r+1];t.has(i)||t.set(i,new Set),t.get(i).add(s)}}),t.forEach((n,r)=>{this.commandSuggestionCache.set(r.toLowerCase(),Array.from(n))})}static extractCommandPatternsFromTrie(){return[["group","by"],["order","by"],["distinct","on"],["not","materialized"],["row","only"],["rows","only"],["percent","with","ties"],["key","share"],["no","key","update"],["union","all"],["intersect","all"],["except","all"],["partition","by"],["within","group"],["with","ordinality"]]}static getCommandSuggestions(e){return this.initialize(),this.commandSuggestionCache.get(e.toLowerCase())||[]}static reset(){this.joinSuggestionCache.clear(),this.commandSuggestionCache.clear(),this.initialized=!1}};var Dt=class{static{this.patternCache=null}static getKeywordPatterns(){if(this.patternCache!==null)return this.patternCache;let e=new Map,t=new Set,n=new Set;return this.extractKeywordPatterns(e,t,n),this.patternCache={requiresKeywords:e,suggestsTables:t,suggestsColumns:n},this.patternCache}static extractKeywordPatterns(e,t,n){let r=["from","join"],i=["select","where","on","having","by"];for(let s of r)this.isKeywordInDictionary(s)&&t.add(s);for(let s of i)this.isKeywordInDictionary(s)&&n.add(s);this.extractRequiresKeywordPatterns(e)}static isKeywordInDictionary(e){return jt.isValidJoinKeyword(e)?!0:["from","join","select","where","on","having","by","group","order"].includes(e)}static extractRequiresKeywordPatterns(e){let t=["inner","left","right","full","cross","natural","outer","group","order"];for(let n of t){let r=this.findPossibleFollowups(n);r.length>0&&e.set(n,r)}}static findPossibleFollowups(e){let t=new Set;return jt.getJoinSuggestions(e.toLowerCase()).forEach(i=>t.add(i.toUpperCase())),jt.getCommandSuggestions(e.toLowerCase()).forEach(i=>t.add(i.toUpperCase())),Array.from(t)}static requiresSpecificKeywords(e){let n=this.getKeywordPatterns().requiresKeywords.get(e);return n?{suggestKeywords:!0,requiredKeywords:n}:null}static analyzeIntelliSense(e,t){try{let n=Le.getAllLexemesWithPosition(e),r=-1,i;for(let c=0;c<n.length;c++){let p=n[c];if(p.position){if(t>=p.position.startPosition&&t<=p.position.endPosition){i=p,r=c;break}else if(p.position.startPosition>t){r=Math.max(0,c-1),i=r>=0?n[r]:void 0;break}}}r===-1&&n.length>0&&(r=n.length-1,i=n[r]);let s=r>0?n[r-1]:void 0;if(this.isAfterDot(e,t,s))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,tableScope:this.findPrecedingIdentifier(e,t,n),currentToken:i,previousToken:s};if(i){let c=i.value.toLowerCase(),p=this.requiresSpecificKeywords(c);if(p)return{suggestTables:!1,suggestColumns:!1,...p,currentToken:i,previousToken:s}}let l=i?.value.toLowerCase(),u=s?.value.toLowerCase();if(l){let c=this.getKeywordPatterns();if(c.suggestsTables.has(l))return{suggestTables:!0,suggestColumns:!1,suggestKeywords:!1,currentToken:i,previousToken:s};if(c.suggestsColumns.has(l))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,currentToken:i,previousToken:s}}if(u){let c=this.getKeywordPatterns(),p=this.requiresSpecificKeywords(u);if(p&&l!=="join"&&l!=="outer"&&l!=="by")return{suggestTables:!1,suggestColumns:!1,...p,currentToken:i,previousToken:s};if(c.suggestsTables.has(u))return{suggestTables:!0,suggestColumns:!1,suggestKeywords:!1,currentToken:i,previousToken:s};if(c.suggestsColumns.has(u))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,currentToken:i,previousToken:s}}return{suggestTables:!1,suggestColumns:!1,suggestKeywords:!0,currentToken:i,previousToken:s}}catch{return{suggestTables:!1,suggestColumns:!1,suggestKeywords:!1}}}static analyzeIntelliSenseAt(e,t){let n=Qe.lineColumnToCharOffset(e,t);return n===-1?{suggestTables:!1,suggestColumns:!1,suggestKeywords:!1}:this.analyzeIntelliSense(e,n)}static isAfterDot(e,t,n){if(t>0&&e[t-1]==="."||n&&n.value===".")return!0;let r=t-1;for(;r>=0&&/\s/.test(e[r]);)r--;return r>=0&&e[r]==="."}static findPrecedingIdentifier(e,t,n){if(this.isAfterDot(e,t)){let r=t-1;for(;r>=0&&/\s/.test(e[r]);)r--;if(r>=0&&e[r]==="."){let i=r;for(;r>=0&&/\s/.test(e[r]);)r--;for(;r>=0&&/[a-zA-Z0-9_]/.test(e[r]);)r--;let s=r+1;if(s<i)return e.substring(s,i)}for(let i=n.length-1;i>=0;i--)if(n[i].value==="."&&n[i].position&&n[i].position.startPosition<t){if(i>0&&this.isIdentifier(n[i-1]))return n[i-1].value;break}}}static isIdentifier(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.value)}};var an=class{static resolve(e,t){return this.createEmptyScope()}static resolveAt(e,t){let n=Qe.lineColumnToCharOffset(e,t);return n===-1?this.createEmptyScope():this.resolve(e,n)}static getColumnsForTable(e,t,n){let r=this.resolve(e,t),i=r.availableTables.find(s=>s.name===n||s.alias===n);return i?r.visibleColumns.filter(s=>s.tableName===i.name||i.alias&&s.tableAlias===i.alias):[]}static analyzeScopeFromQuery(e){let t={availableTables:[],availableCTEs:[],subqueryLevel:0,visibleColumns:[],currentQuery:e,parentQueries:[]};if(e instanceof C)t.availableCTEs=this.collectCTEs(e),t.availableTables=this.collectTablesFromQuery(e),t.visibleColumns=this.collectVisibleColumns(t.availableTables,t.availableCTEs);else if(e instanceof Q){let n=this.analyzeScopeFromQuery(e.left),r=this.analyzeScopeFromQuery(e.right);t.availableTables=[...n.availableTables,...r.availableTables],t.availableCTEs=[...n.availableCTEs,...r.availableCTEs],t.visibleColumns=[...n.visibleColumns,...r.visibleColumns]}return t}static collectCTEs(e){let t=[];if(e.withClause){let r=new X().collect(e);for(let i of r)t.push({name:i.getSourceAliasName(),query:i.query,columns:this.extractCTEColumns(i.query),materialized:i.materialized||!1})}return t}static collectTablesFromQuery(e){let t=[];if(e.fromClause){let n=this.extractTablesFromFromClause(e.fromClause);t.push(...n)}return t}static extractTablesFromFromClause(e){let t=[];if(e.source.datasource instanceof O){let n={name:this.extractTableName(e.source.datasource.qualifiedName),alias:e.source.aliasExpression?.table.name,schema:this.extractSchemaName(e.source.datasource.qualifiedName),fullName:this.getQualifiedNameString(e.source.datasource.qualifiedName),sourceType:"table"};t.push(n)}else if(e.source.datasource instanceof j){let n={name:e.source.aliasExpression?.table.name||"subquery",alias:e.source.aliasExpression?.table.name,fullName:e.source.aliasExpression?.table.name||"subquery",sourceType:"subquery",originalQuery:e.source.datasource.query};t.push(n)}if(e.joins)for(let n of e.joins){let r=this.extractTablesFromJoin(n);t.push(...r)}return t}static extractTablesFromJoin(e){let t=[];if(e.source.datasource instanceof O){let n={name:this.extractTableName(e.source.datasource.qualifiedName),alias:e.source.aliasExpression?.table.name,schema:this.extractSchemaName(e.source.datasource.qualifiedName),fullName:this.getQualifiedNameString(e.source.datasource.qualifiedName),sourceType:"table"};t.push(n)}else if(e.source.datasource instanceof j){let n={name:e.source.aliasExpression?.table.name||"subquery",alias:e.source.aliasExpression?.table.name,fullName:e.source.aliasExpression?.table.name||"subquery",sourceType:"subquery",originalQuery:e.source.datasource.query};t.push(n)}return t}static getQualifiedNameString(e){return e.toString()}static extractTableName(e){let n=this.getQualifiedNameString(e).split(".");return n[n.length-1]}static extractSchemaName(e){let n=this.getQualifiedNameString(e).split(".");return n.length>1?n[n.length-2]:void 0}static extractCTEColumns(e){try{if(e instanceof C&&e.selectClause){let t=[];for(let n of e.selectClause.items)if(n.identifier)t.push(n.identifier.name);else{let r=this.extractColumnNameFromExpression(n.value);r&&t.push(r)}return t}}catch{}}static extractColumnNameFromExpression(e){if(e&&typeof e=="object"&&"value"in e)return e.value}static collectVisibleColumns(e,t){let n=[];for(let r of t)if(r.columns)for(let i of r.columns)n.push({name:i,tableName:r.name,fullReference:`${r.name}.${i}`});for(let r of e)r.sourceType==="table"&&n.push({name:"*",tableName:r.name,tableAlias:r.alias,fullReference:`${r.alias||r.name}.*`});return n}static createEmptyScope(){return{availableTables:[],availableCTEs:[],subqueryLevel:0,visibleColumns:[],parentQueries:[]}}};var hr=class{static parseToPosition(e,t,n={}){let r=typeof t=="number"?t:Qe.lineColumnToCharOffset(e,t);if(r===-1)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};try{let i=this.tryNormalParse(e,r,n);return i.success?i:n.errorRecovery?this.tryErrorRecovery(e,r,n):i}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i),stoppedAtCursor:!1}}}static parseCurrentQuery(e,t,n={}){let r=typeof t=="number"?t:Qe.lineColumnToCharOffset(e,t);if(r===-1)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};let i=this.findQueryBoundaries(e),s=this.findQueryAtPosition(i,r);if(!s)return{success:!1,error:"No query found at cursor position",stoppedAtCursor:!1};let o=r-s.start,l=e.substring(s.start,s.end);return this.parseToPosition(l,o,n)}static tryNormalParse(e,t,n){if(t<0||t>e.length)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};let r=e.trim(),s=[".",",","SELECT","FROM","WHERE","JOIN","ON","GROUP BY","ORDER BY"].some(p=>r.toLowerCase().endsWith(p.toLowerCase())),o=A.analyze(e);if(!o.success||s)return{...o,success:!1};let l=this.getAllTokens(e),u=this.findTokenAtPosition(l,t),c=this.findTokenBeforePosition(l,t);return{...o,parsedTokens:l,tokenBeforeCursor:c,stoppedAtCursor:t<e.length,recoveryAttempts:0}}static tryErrorRecovery(e,t,n){let r=n.maxRecoveryAttempts||5,i=0,s=[()=>this.recoverWithTokenInsertion(e,t,n),()=>this.recoverWithTruncation(e,t,n),()=>this.recoverWithCompletion(e,t,n),()=>this.recoverWithMinimalSQL(e,t,n)];for(let o of s){if(i>=r)break;i++;try{let l=o();if(l.success)return l.recoveryAttempts=i,l}catch{continue}}return{success:!1,error:"All error recovery attempts failed",recoveryAttempts:i,stoppedAtCursor:!1}}static recoverWithTokenInsertion(e,t,n){if(!n.insertMissingTokens)throw new Error("Token insertion disabled");let r=[{pattern:/SELECT\s*$/i,replacement:"SELECT 1 "},{pattern:/FROM\s*$/i,replacement:"FROM dual "},{pattern:/WHERE\s*$/i,replacement:"WHERE 1=1 "},{pattern:/JOIN\s*$/i,replacement:"JOIN dual ON 1=1 "},{pattern:/ON\s*$/i,replacement:"ON 1=1 "},{pattern:/GROUP\s+BY\s*$/i,replacement:"GROUP BY 1 "},{pattern:/ORDER\s+BY\s*$/i,replacement:"ORDER BY 1 "}],i=e;for(let l of r)if(l.pattern.test(e)){i=e.replace(l.pattern,l.replacement);break}if(i===e)throw new Error("No applicable token insertion found");let s=A.analyze(i),o=this.getAllTokens(e);return{...s,parsedTokens:o,tokenBeforeCursor:this.findTokenBeforePosition(o,t),stoppedAtCursor:!0,recoveryAttempts:1}}static recoverWithTruncation(e,t,n){let r=e.substring(0,t),i=[""," 1"," FROM dual"," WHERE 1=1"];for(let s of i)try{let o=r+s,l=A.analyze(o);if(l.success){let u=this.getAllTokens(e);return{...l,parsedTokens:u.filter(c=>c.position&&c.position.startPosition<=t),tokenBeforeCursor:this.findTokenBeforePosition(u,t),stoppedAtCursor:!0,recoveryAttempts:1}}}catch{continue}throw new Error("Truncation recovery failed")}static recoverWithCompletion(e,t,n){let r=e.substring(0,t),i=e.substring(t),s=[{pattern:/\.\s*$/,completion:"id"},{pattern:/\w+\s*$/,completion:""},{pattern:/,\s*$/,completion:"1"},{pattern:/\(\s*$/,completion:"1)"}];for(let o of s)if(o.pattern.test(r)){let l=r+o.completion+i;try{let u=A.analyze(l);if(u.success){let c=this.getAllTokens(e);return{...u,parsedTokens:c,tokenBeforeCursor:this.findTokenBeforePosition(c,t),stoppedAtCursor:!0,recoveryAttempts:1}}}catch{continue}}throw new Error("Completion recovery failed")}static recoverWithMinimalSQL(e,t,n){let r="SELECT 1 FROM dual WHERE 1=1";try{let i=A.analyze(r),s=this.getAllTokens(e);return{success:!0,query:i.query,parsedTokens:s.filter(o=>o.position&&o.position.startPosition<=t),tokenBeforeCursor:this.findTokenBeforePosition(s,t),stoppedAtCursor:!0,partialAST:i.query,recoveryAttempts:1}}catch{throw new Error("Minimal SQL recovery failed")}}static getAllTokens(e){try{return Le.getAllLexemesWithPosition(e)}catch{return[]}}static findTokenAtPosition(e,t){return e.find(n=>n.position&&t>=n.position.startPosition&&t<n.position.endPosition)}static findTokenBeforePosition(e,t){let n;for(let r of e)if(r.position)if(r.position.endPosition<=t)n=r;else{if(r.position.startPosition<t)break;break}return n}static findQueryBoundaries(e){let t=[],n=0,r=!1,i="",s=!1;for(let o=0;o<e.length;o++){let l=e[o],u=o<e.length-1?e[o+1]:"";if(!s&&(l==="'"||l==='"')){r?l===i&&(r=!1,i=""):(r=!0,i=l);continue}if(!r&&l==="-"&&u==="-"){s=!0,o++;continue}if(s&&l===`
76
77
  `){s=!1;continue}!r&&!s&&l===";"&&(t.push({start:n,end:o}),n=o+1)}return n<e.length&&t.push({start:n,end:e.length}),t}static findQueryAtPosition(e,t){return e.find(n=>t>=n.start&&t<=n.end)}};var Ut=class{static split(e){let t=[];if(!e||e.trim()==="")return{queries:[],originalText:e,getActive:()=>{},getQuery:()=>{},getNonEmpty:()=>[]};let n=this.splitRespectingQuotesAndComments(e),r=this.mergeTrailingCommentSegments(n,e),i=0;for(let s of r){let o=s.text.trim(),l=this.isEmptyQuery(o),u=o,c=Qe.charOffsetToLineColumn(e,s.start),p=Qe.charOffsetToLineColumn(e,s.end);t.push({sql:u,start:s.start,end:s.end,startLine:c?.line||1,endLine:p?.line||1,index:i++,isEmpty:l})}return{queries:t,originalText:e,getActive:s=>{let o=typeof s=="number"?s:Qe.lineColumnToCharOffset(e,s);if(o!==-1)return t.find(l=>o>=l.start&&o<=l.end)},getQuery:s=>t[s],getNonEmpty:()=>t.filter(s=>!s.isEmpty)}}static splitRespectingQuotesAndComments(e){let t=[],n=0,r=0;for(;r<=e.length;){if(r===e.length||r<e.length&&this.isValidSemicolon(e,r)){let s=e.substring(n,r);(s.length>0||r<e.length)&&t.push({text:s,start:n,end:r}),n=r+1}r++}return t}static isValidSemicolon(e,t){if(e[t]!==";")return!1;let n=!1,r=!1,i=!1,s=!1;for(let o=0;o<t;o++){let l=e[o],u=o+1<e.length?e[o+1]:"";if(!n&&!r&&!s&&l==="-"&&u==="-"){i=!0,o++;continue}if(i&&l===`
77
78
  `){i=!1;continue}if(!n&&!r&&!i&&l==="/"&&u==="*"){s=!0,o++;continue}if(s&&l==="*"&&u==="/"){s=!1,o++;continue}if(!(i||s)){if(l==="'"&&!r){n&&u==="'"?o++:n=!n;continue}if(l==='"'&&!n){r&&u==='"'?o++:r=!r;continue}}}return!n&&!r&&!i&&!s}static mergeTrailingCommentSegments(e,t){let n=[];for(let r=0;r<e.length;r++){let i=e[r],s=i.text.trim();if(this.isEmptyQuery(s)&&n.length>0){let l=n[n.length-1].text.trim(),u=s.startsWith("--"),c=!this.isEmptyQuery(l);if(u&&c){let p=n[n.length-1];n[n.length-1]={text:t.substring(p.start,i.end),start:p.start,end:i.end}}else n.push(i)}else n.push(i)}return n}static cleanSqlComments(e){if(!e)return null;let t=e;t=t.split(`
78
79
  `).map(r=>{let i=r.indexOf("--");return i>=0?r.substring(0,i):r}).join(`
79
- `),t=t.replace(/\/\*[\s\S]*?\*\//g,"");let n=t.trim();return n.length>0?n:null}static isEmptyQuery(e){return e?this.cleanSqlComments(e)===null:!0}},Dr=class{static getContextAt(e,t){let r=Ut.split(e).getActive(t);if(!r)return;let i=typeof t=="number"?t:Qe.lineColumnToCharOffset(e,t);if(i===-1)return;let s=i-r.start;return{query:r,relativePosition:s}}static extractQueries(e){return Ut.split(e).getNonEmpty().map(n=>n.sql)}};function Ur(a,e,t={}){return hr.parseToPosition(a,e,t)}function Jr(a,e){return typeof e=="number"?Dt.analyzeIntelliSense(a,e):Dt.analyzeIntelliSenseAt(a,e)}function xr(a,e){return typeof e=="number"?an.resolve(a,e):an.resolveAt(a,e)}function Kr(a){return Ut.split(a)}function gi(a,e,t={}){let n=typeof e=="number"?e:Qe.lineColumnToCharOffset(a,e);if(n===-1)return;let i=Kr(a).getActive(n);if(!i)return;let s=n-i.start,o=i.sql,l=Jr(o,s),u=xr(o,s),c=Ur(o,s,t);return{context:l,scope:u,parseResult:c,currentQuery:o,relativePosition:s}}function yi(a,e){let t=typeof e=="number"?e:Qe.lineColumnToCharOffset(a,e);if(t===-1)return[];let n=Dt.analyzeIntelliSense(a,t),r=xr(a,e),i=[];return n.suggestKeywords&&(n.requiredKeywords?n.requiredKeywords.forEach(s=>{i.push({type:"keyword",value:s,detail:`Required keyword: ${s}`})}):vi(n).forEach(o=>{i.push({type:"keyword",value:o.value,detail:o.detail})})),n.suggestTables&&(r.availableTables.forEach(s=>{i.push({type:"table",value:s.alias||s.name,detail:`Table: ${s.fullName}`,documentation:`Available table${s.alias?` (alias: ${s.alias})`:""}`})}),r.availableCTEs.forEach(s=>{i.push({type:"cte",value:s.name,detail:`CTE: ${s.name}`,documentation:`Common Table Expression${s.columns?` with columns: ${s.columns.join(", ")}`:""}`})})),n.suggestColumns&&(n.tableScope?r.visibleColumns.filter(o=>o.tableName===n.tableScope||o.tableAlias===n.tableScope).forEach(o=>{i.push({type:"column",value:o.name,detail:`Column: ${o.fullReference}`,documentation:`Column from ${o.tableName}${o.type?` (${o.type})`:""}`})}):r.visibleColumns.forEach(s=>{i.push({type:"column",value:s.name==="*"?"*":`${s.tableAlias||s.tableName}.${s.name}`,detail:`Column: ${s.fullReference}`,documentation:`Column from ${s.tableName}`})})),i}function vi(a){let e=a.previousToken?.value?.toLowerCase(),t=a.currentToken?.value?.toLowerCase();return e==="select"||t==="select"?[{value:"DISTINCT",detail:"Remove duplicate rows"},{value:"COUNT",detail:"Aggregate function"},{value:"SUM",detail:"Aggregate function"},{value:"AVG",detail:"Aggregate function"},{value:"MAX",detail:"Aggregate function"},{value:"MIN",detail:"Aggregate function"}]:e==="from"||t==="from"?[{value:"JOIN",detail:"Inner join tables"},{value:"LEFT JOIN",detail:"Left outer join"},{value:"RIGHT JOIN",detail:"Right outer join"},{value:"FULL JOIN",detail:"Full outer join"},{value:"WHERE",detail:"Filter conditions"},{value:"GROUP BY",detail:"Group results"},{value:"ORDER BY",detail:"Sort results"}]:["where","having","on"].includes(e||"")||["where","having","on"].includes(t||"")?[{value:"AND",detail:"Logical AND operator"},{value:"OR",detail:"Logical OR operator"},{value:"NOT",detail:"Logical NOT operator"},{value:"IN",detail:"Match any value in list"},{value:"LIKE",detail:"Pattern matching"},{value:"BETWEEN",detail:"Range comparison"}]:[{value:"SELECT",detail:"Query data"},{value:"FROM",detail:"Specify table"},{value:"WHERE",detail:"Filter conditions"},{value:"JOIN",detail:"Join tables"},{value:"GROUP BY",detail:"Group results"},{value:"ORDER BY",detail:"Sort results"},{value:"LIMIT",detail:"Limit results"}]}export{Xn as AliasRenamer,ye as ArrayExpression,tt as ArrayIndexExpression,ve as ArrayQueryExpression,et as ArraySliceExpression,we as BetweenExpression,S as BinaryExpression,Q as BinarySelectQuery,X as CTECollector,Yn as CTEComposer,ft as CTEDependencyAnalyzer,At as CTEDisabler,it as CTENormalizer,Ht as CTENotFoundError,Rr as CTEQueryDecomposer,ht as CTERegionDetector,Zn as CTERenamer,qn as CTETableReferenceCollector,ie as CaseExpression,ke as CaseKeyValuePair,ce as CastExpression,b as ColumnReference,Vt as ColumnReferenceCollector,Gn as CommentEditor,Dt as CursorContextAnalyzer,Gt as DuplicateCTEError,vt as DuplicateDetectionMode,Vr as DynamicQueryBuilder,$t as FilterableItem,Br as FilterableItemCollector,dt as Formatter,K as FunctionCall,P as IdentifierString,ge as InlineQuery,ot as InsertQuery,Qr as InsertQueryParser,Qt as InvalidCTENameError,Zt as JsonMappingConverter,jr as JsonSchemaValidator,Le as LexemeCursor,Z as LiteralValue,Ut as MultiQuerySplitter,Dr as MultiQueryUtils,Fr as OriginalFormatRestorer,N as ParameterExpression,Y as ParenExpression,hr as PositionAwareParser,rr as PostgresJsonQueryBuilder,_e as QualifiedName,We as QueryBuilder,Wr as QueryFlowDiagramGenerator,V as RawString,Bt as SchemaCollector,on as SchemaManager,an as ScopeResolver,A as SelectQueryParser,Ke as SelectValueCollector,xe as SelectableColumnCollector,C as SimpleSelectQuery,Or as SmartRenamer,v as SqlComponent,Tr as SqlDialectConfiguration,Fe as SqlFormatter,er as SqlIdentifierRenamer,or as SqlPaginationInjector,ir as SqlParamInjector,Hn as SqlSchemaValidator,sr as SqlSortInjector,je as StringSpecifierExpression,Te as SwitchCaseArgument,lt as TableSchema,He as TableSourceCollector,$ as TokenType,Ie as TupleExpression,ur as TypeTransformationPostProcessor,gy as TypeTransformers,Ve as TypeValue,te as UnaryExpression,Rt as UpstreamSelectQueryFinder,Hu as VALID_PRESETS,U as ValueList,Ce as ValuesQuery,Ir as WindowFrameBound,Et as WindowFrameBoundStatic,xt as WindowFrameBoundaryValue,Be as WindowFrameExpression,Ge as WindowFrameSpec,kr as WindowFrameType,Ft as WithClauseParser,lr as convertColumnsToLegacy,yr as convertModelDrivenMapping,iy as convertToLegacyJsonMapping,Uy as createJsonMappingFromSchema,jy as createSchemaManager,Dy as createTableColumnResolver,Mr as extractTypeProtection,yi as getCompletionSuggestions,Jr as getCursorContext,gi as getIntelliSenseInfo,Ci as isLegacyFormat,hi as isModelDrivenFormat,fi as isUnifiedFormat,Ur as parseToPosition,mi as processJsonMapping,xr as resolveScope,Kr as splitQueries,$r as toLegacyMapping,Cy as transformDatabaseResult,di as unifyJsonMapping,ci as validateModelDrivenMapping};
80
+ `),t=t.replace(/\/\*[\s\S]*?\*\//g,"");let n=t.trim();return n.length>0?n:null}static isEmptyQuery(e){return e?this.cleanSqlComments(e)===null:!0}},Dr=class{static getContextAt(e,t){let r=Ut.split(e).getActive(t);if(!r)return;let i=typeof t=="number"?t:Qe.lineColumnToCharOffset(e,t);if(i===-1)return;let s=i-r.start;return{query:r,relativePosition:s}}static extractQueries(e){return Ut.split(e).getNonEmpty().map(n=>n.sql)}};function Ur(a,e,t={}){return hr.parseToPosition(a,e,t)}function Jr(a,e){return typeof e=="number"?Dt.analyzeIntelliSense(a,e):Dt.analyzeIntelliSenseAt(a,e)}function xr(a,e){return typeof e=="number"?an.resolve(a,e):an.resolveAt(a,e)}function Kr(a){return Ut.split(a)}function gi(a,e,t={}){let n=typeof e=="number"?e:Qe.lineColumnToCharOffset(a,e);if(n===-1)return;let i=Kr(a).getActive(n);if(!i)return;let s=n-i.start,o=i.sql,l=Jr(o,s),u=xr(o,s),c=Ur(o,s,t);return{context:l,scope:u,parseResult:c,currentQuery:o,relativePosition:s}}function yi(a,e){let t=typeof e=="number"?e:Qe.lineColumnToCharOffset(a,e);if(t===-1)return[];let n=Dt.analyzeIntelliSense(a,t),r=xr(a,e),i=[];return n.suggestKeywords&&(n.requiredKeywords?n.requiredKeywords.forEach(s=>{i.push({type:"keyword",value:s,detail:`Required keyword: ${s}`})}):vi(n).forEach(o=>{i.push({type:"keyword",value:o.value,detail:o.detail})})),n.suggestTables&&(r.availableTables.forEach(s=>{i.push({type:"table",value:s.alias||s.name,detail:`Table: ${s.fullName}`,documentation:`Available table${s.alias?` (alias: ${s.alias})`:""}`})}),r.availableCTEs.forEach(s=>{i.push({type:"cte",value:s.name,detail:`CTE: ${s.name}`,documentation:`Common Table Expression${s.columns?` with columns: ${s.columns.join(", ")}`:""}`})})),n.suggestColumns&&(n.tableScope?r.visibleColumns.filter(o=>o.tableName===n.tableScope||o.tableAlias===n.tableScope).forEach(o=>{i.push({type:"column",value:o.name,detail:`Column: ${o.fullReference}`,documentation:`Column from ${o.tableName}${o.type?` (${o.type})`:""}`})}):r.visibleColumns.forEach(s=>{i.push({type:"column",value:s.name==="*"?"*":`${s.tableAlias||s.tableName}.${s.name}`,detail:`Column: ${s.fullReference}`,documentation:`Column from ${s.tableName}`})})),i}function vi(a){let e=a.previousToken?.value?.toLowerCase(),t=a.currentToken?.value?.toLowerCase();return e==="select"||t==="select"?[{value:"DISTINCT",detail:"Remove duplicate rows"},{value:"COUNT",detail:"Aggregate function"},{value:"SUM",detail:"Aggregate function"},{value:"AVG",detail:"Aggregate function"},{value:"MAX",detail:"Aggregate function"},{value:"MIN",detail:"Aggregate function"}]:e==="from"||t==="from"?[{value:"JOIN",detail:"Inner join tables"},{value:"LEFT JOIN",detail:"Left outer join"},{value:"RIGHT JOIN",detail:"Right outer join"},{value:"FULL JOIN",detail:"Full outer join"},{value:"WHERE",detail:"Filter conditions"},{value:"GROUP BY",detail:"Group results"},{value:"ORDER BY",detail:"Sort results"}]:["where","having","on"].includes(e||"")||["where","having","on"].includes(t||"")?[{value:"AND",detail:"Logical AND operator"},{value:"OR",detail:"Logical OR operator"},{value:"NOT",detail:"Logical NOT operator"},{value:"IN",detail:"Match any value in list"},{value:"LIKE",detail:"Pattern matching"},{value:"BETWEEN",detail:"Range comparison"}]:[{value:"SELECT",detail:"Query data"},{value:"FROM",detail:"Specify table"},{value:"WHERE",detail:"Filter conditions"},{value:"JOIN",detail:"Join tables"},{value:"GROUP BY",detail:"Group results"},{value:"ORDER BY",detail:"Sort results"},{value:"LIMIT",detail:"Limit results"}]}export{Xn as AliasRenamer,ye as ArrayExpression,tt as ArrayIndexExpression,ve as ArrayQueryExpression,et as ArraySliceExpression,we as BetweenExpression,S as BinaryExpression,Q as BinarySelectQuery,X as CTECollector,Yn as CTEComposer,ft as CTEDependencyAnalyzer,At as CTEDisabler,it as CTENormalizer,Ht as CTENotFoundError,Or as CTEQueryDecomposer,ht as CTERegionDetector,Zn as CTERenamer,qn as CTETableReferenceCollector,ie as CaseExpression,ke as CaseKeyValuePair,ce as CastExpression,b as ColumnReference,Vt as ColumnReferenceCollector,Gn as CommentEditor,Dt as CursorContextAnalyzer,Gt as DuplicateCTEError,vt as DuplicateDetectionMode,Vr as DynamicQueryBuilder,$t as FilterableItem,Br as FilterableItemCollector,dt as Formatter,K as FunctionCall,P as IdentifierString,ge as InlineQuery,ot as InsertQuery,Qr as InsertQueryParser,Qt as InvalidCTENameError,Zt as JsonMappingConverter,jr as JsonSchemaValidator,Le as LexemeCursor,Z as LiteralValue,Ut as MultiQuerySplitter,Dr as MultiQueryUtils,Fr as OriginalFormatRestorer,N as ParameterExpression,Y as ParenExpression,hr as PositionAwareParser,rr as PostgresJsonQueryBuilder,_e as QualifiedName,We as QueryBuilder,Wr as QueryFlowDiagramGenerator,$ as RawString,Bt as SchemaCollector,on as SchemaManager,an as ScopeResolver,A as SelectQueryParser,Ke as SelectValueCollector,xe as SelectableColumnCollector,C as SimpleSelectQuery,Rr as SmartRenamer,v as SqlComponent,Tr as SqlDialectConfiguration,Fe as SqlFormatter,er as SqlIdentifierRenamer,or as SqlPaginationInjector,ir as SqlParamInjector,Hn as SqlSchemaValidator,sr as SqlSortInjector,je as StringSpecifierExpression,Te as SwitchCaseArgument,lt as TableSchema,He as TableSourceCollector,M as TokenType,Ie as TupleExpression,ur as TypeTransformationPostProcessor,gy as TypeTransformers,Ve as TypeValue,te as UnaryExpression,Ot as UpstreamSelectQueryFinder,Hu as VALID_PRESETS,U as ValueList,Ce as ValuesQuery,Ir as WindowFrameBound,Et as WindowFrameBoundStatic,xt as WindowFrameBoundaryValue,Be as WindowFrameExpression,Ge as WindowFrameSpec,kr as WindowFrameType,Ft as WithClauseParser,lr as convertColumnsToLegacy,yr as convertModelDrivenMapping,iy as convertToLegacyJsonMapping,Uy as createJsonMappingFromSchema,jy as createSchemaManager,Dy as createTableColumnResolver,Mr as extractTypeProtection,yi as getCompletionSuggestions,Jr as getCursorContext,gi as getIntelliSenseInfo,Ci as isLegacyFormat,hi as isModelDrivenFormat,fi as isUnifiedFormat,Ur as parseToPosition,mi as processJsonMapping,xr as resolveScope,Kr as splitQueries,$r as toLegacyMapping,Cy as transformDatabaseResult,di as unifyJsonMapping,ci as validateModelDrivenMapping};
80
81
  //# sourceMappingURL=index.min.js.map