diff --git a/docs/guide/formatting-recipes.md b/docs/guide/formatting-recipes.md index d814b45..67fcc52 100644 --- a/docs/guide/formatting-recipes.md +++ b/docs/guide/formatting-recipes.md @@ -38,6 +38,7 @@ const { formattedSql, params } = formatter.format(query); | `parenthesesOneLine`, `betweenOneLine`, `valuesOneLine`, `joinOneLine`, `caseOneLine`, `subqueryOneLine` | `true` / `false` | `false` for each | Opt-in switches that keep the corresponding construct on a single line even if other break settings would expand it. | | `exportComment` | `true` / `false` | `false` | Emits comments collected by the parser. Turn it on when you want annotations preserved. | | `castStyle` | 'standard', 'postgres' | From preset or 'standard' | Chooses how CAST expressions are printed. 'standard' emits ANSI `CAST(expr AS type)` while 'postgres' emits `expr::type`. See "Controlling CAST style" below for usage notes and examples. | +| `constraintStyle` | `'postgres'`, `'mysql'` | From preset or `'postgres'` | Shapes constraint output in DDL: `'postgres'` prints `constraint ... primary key(...)`, while `'mysql'` emits `unique key name(...)` / `foreign key name(...)`. | Combine these settings to mirror house formatting conventions or align with existing lint rules. The following sections call out the options that trip up newcomers most often. @@ -131,6 +132,23 @@ new SqlFormatter({ castStyle: 'postgres' }).format(expr); // "price"::NUMERIC(10 - Set `castStyle: 'postgres'` when you explicitly target PostgreSQL-style `::` casts. Presets like `'postgres'`, `'redshift'`, and `'cockroachdb'` already switch this on. If you are migrating away from PostgreSQL-only syntax, enforce `castStyle: 'standard'` and phase out `::` usage gradually. + +### DDL constraint style + +`constraintStyle` controls how table- and column-level constraints appear when formatting `CREATE TABLE` statements. + +- `'postgres'` (default) prints explicit `constraint` clauses, e.g.: + ```sql + , constraint orders_pkey primary key(order_id) + , constraint orders_customer_fkey foreign key(customer_id) references customers(customer_id) + ``` +- `'mysql'` drops the leading keyword and mirrors MySQL's `UNIQUE KEY` / inline constraint syntax: + ```sql + , unique key orders_customer_unique(customer_id) + , foreign key orders_customer_fkey(customer_id) references customers(customer_id) + ``` + +Pair this option with your target engine: presets such as `'mysql'` enable it automatically, while PostgreSQL-oriented presets keep the default. ## Sample ```json diff --git a/docs/public/demo/vendor/rawsql.browser.js b/docs/public/demo/vendor/rawsql.browser.js index 1f239e9..fabb8a8 100644 --- a/docs/public/demo/vendor/rawsql.browser.js +++ b/docs/public/demo/vendor/rawsql.browser.js @@ -1,44 +1,44 @@ var F=(f=>(f[f.None=0]="None",f[f.Literal=1]="Literal",f[f.Operator=2]="Operator",f[f.OpenParen=4]="OpenParen",f[f.CloseParen=8]="CloseParen",f[f.Comma=16]="Comma",f[f.Dot=32]="Dot",f[f.Identifier=64]="Identifier",f[f.Command=128]="Command",f[f.Parameter=256]="Parameter",f[f.OpenBracket=512]="OpenBracket",f[f.CloseBracket=1024]="CloseBracket",f[f.Function=2048]="Function",f[f.StringSpecifier=4096]="StringSpecifier",f[f.Type=8192]="Type",f))(F||{});var ie=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),i=Math.min(e.length,t+5),r=e.slice(n,i),s=" ".repeat(t-n)+"^";return`${r} ${s}`}static skipWhiteSpace(e,t){let n=e.length;for(;t+4<=n&&e.slice(t,t+4)===" ";)t+=4;for(;t=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)return{newPosition:t,comments:null};if(e.charCodeAt(t)!==47||e.charCodeAt(t+1)!==42)return{newPosition:t,comments:null};if(t+20&&n[0]==="";)n.shift();for(;n.length>0&&n[n.length-1]==="";)n.pop();return n}static readWhiteSpaceAndComment(e,t){let n=null,i=e.length;for(;t=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,i,r){let s={type:e,value:e===128||e===2||e===2048?t.toLowerCase():t,comments:n};return i!==void 0&&r!==void 0&&(s.position={startPosition:i,endPosition:r}),s}createLexemeWithPosition(e,t,n,i=null){return this.createLexeme(e,t,i,n,n+t.length)}getDebugPositionInfo(e){return le.getDebugPositionInfo(this.input,e)}};var Pe=class{constructor(e){this.trie=e}isEndOfInput(e,t,n=0){return t+n>=e.length}canParse(e,t,n=0){return!this.isEndOfInput(e,t,n)}parse(e,t){if(this.isEndOfInput(e,t))return null;this.trie.reset();let n=le.tryReadRegularIdentifier(e,t);if(n===null)return null;let i=this.trie.pushLexeme(n.identifier.toLowerCase());if(i===0)return null;if(i===3)return{keyword:n.identifier,newPosition:n.newPosition};let r=n.identifier,s=le.readWhiteSpaceAndComment(e,n.newPosition);t=s.position;let o=s.lines?[...s.lines]:[];if(this.isEndOfInput(e,t))return i===2?{keyword:r,newPosition:t,comments:o.length>0?o:void 0}:null;for(;this.canParse(e,t);){let l=i,u=le.tryReadRegularIdentifier(e,t);if(u!==null){if(i=this.trie.pushLexeme(u.identifier.toLowerCase()),i===0){if(l===2)break;return null}r+=" "+u.identifier;let c=le.readWhiteSpaceAndComment(e,u.newPosition);if(t=c.position,c.lines&&c.lines.length>0&&o.push(...c.lines),i===3)break}else{if(l===2)break;return null}}return{keyword:r,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 Ur=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"]]),wn=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"],["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"],["not","matched","by","source"],["not","matched","by","target"],["update","set"],["if","not","exists"],["if","exists"],["do","nothing"],["insert","default","values"],["values"],["set"],["returning"],["create","table"],["create","temporary","table"],["alter","table"],["drop","table"],["drop","index"],["drop","constraint"],["create","index"],["create","unique","index"],["add"],["add","constraint"],["constraint"],["primary","key"],["unique"],["unique","key"],["foreign","key"],["references"],["check"],["default"],["not","null"],["null"],["generated","always"],["generated","always","as","identity"],["generated","by","default"],["generated","by","default","as","identity"],["identity"],["collate"],["deferrable"],["not","deferrable"],["initially","immediate"],["initially","deferred"],["match"],["match","full"],["match","partial"],["match","simple"],["not","valid"],["on","delete"],["on","update"],["cascade"],["restrict"],["no","action"],["set","null"],["set","default"],["include"],["only"],["concurrently"],["tablespace"],["tablesample"],["as"],["asc"],["desc"],["nulls","first"],["nulls","last"]]),Kr=new Pe(wn),vn=new Pe(Ur);var Mn=class extends me{tryRead(e){if(this.isEndOfInput())return null;let t=vn.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(128,t.keyword);let n=Kr.parse(this.input,this.position);if(n!==null){this.position=n.newPosition;let i=this.createLexeme(128,n.keyword,n.comments);return n.comments&&n.comments.length>0&&(i.positionedComments=[{position:"after",comments:n.comments}]),i}if(this.canRead(2)&&this.input[this.position]==="/"&&this.input[this.position+1]==="*"&&this.input[this.position+2]==="+"){this.position+=3;let i=this.position;for(;this.position+1=this.input.length)return!1;let i=this.input.slice(t,n).trim();return i===""?!1:/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$/.test(i)}readEscapedIdentifier(e){let t=this.position;this.position++;let n=!1;for(;this.canRead();){if(this.input[this.position]===e){n=!0;break}this.position++}if(!n)throw new Error(`Closing delimiter is not found. position: ${t}, delimiter: ${e} +${a.getDebugPositionInfo(e,t)}`);return n}static tryReadRegularIdentifier(e,t){let n=t;for(;t=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,i,r){let s={type:e,value:e===128||e===2||e===2048?t.toLowerCase():t,comments:n};return i!==void 0&&r!==void 0&&(s.position={startPosition:i,endPosition:r}),s}createLexemeWithPosition(e,t,n,i=null){return this.createLexeme(e,t,i,n,n+t.length)}getDebugPositionInfo(e){return le.getDebugPositionInfo(this.input,e)}};var Pe=class{constructor(e){this.trie=e}isEndOfInput(e,t,n=0){return t+n>=e.length}canParse(e,t,n=0){return!this.isEndOfInput(e,t,n)}parse(e,t){if(this.isEndOfInput(e,t))return null;this.trie.reset();let n=le.tryReadRegularIdentifier(e,t);if(n===null)return null;let i=this.trie.pushLexeme(n.identifier.toLowerCase());if(i===0)return null;if(i===3)return{keyword:n.identifier,newPosition:n.newPosition};let r=n.identifier,s=le.readWhiteSpaceAndComment(e,n.newPosition);t=s.position;let o=s.lines?[...s.lines]:[];if(this.isEndOfInput(e,t))return i===2?{keyword:r,newPosition:t,comments:o.length>0?o:void 0}:null;for(;this.canParse(e,t);){let u=i,l=le.tryReadRegularIdentifier(e,t);if(l!==null){if(i=this.trie.pushLexeme(l.identifier.toLowerCase()),i===0){if(u===2)break;return null}r+=" "+l.identifier;let c=le.readWhiteSpaceAndComment(e,l.newPosition);if(t=c.position,c.lines&&c.lines.length>0&&o.push(...c.lines),i===3)break}else{if(u===2)break;return null}}return{keyword:r,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=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"]]),wn=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"],["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"],["not","matched","by","source"],["not","matched","by","target"],["update","set"],["if","not","exists"],["if","exists"],["do","nothing"],["insert","default","values"],["values"],["set"],["returning"],["create","table"],["create","temporary","table"],["alter","table"],["drop","table"],["drop","index"],["drop","constraint"],["create","index"],["create","unique","index"],["add"],["add","constraint"],["constraint"],["primary","key"],["unique"],["unique","key"],["foreign","key"],["references"],["check"],["default"],["not","null"],["null"],["generated","always"],["generated","always","as","identity"],["generated","by","default"],["generated","by","default","as","identity"],["identity"],["collate"],["deferrable"],["not","deferrable"],["initially","immediate"],["initially","deferred"],["match"],["match","full"],["match","partial"],["match","simple"],["not","valid"],["on","delete"],["on","update"],["cascade"],["restrict"],["no","action"],["set","null"],["set","default"],["include"],["only"],["concurrently"],["tablespace"],["tablesample"],["as"],["asc"],["desc"],["nulls","first"],["nulls","last"]]),Jr=new Pe(wn),vn=new Pe(qr);var Mn=class extends me{tryRead(e){if(this.isEndOfInput())return null;let t=vn.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(128,t.keyword);let n=Jr.parse(this.input,this.position);if(n!==null){this.position=n.newPosition;let i=this.createLexeme(128,n.keyword,n.comments);return n.comments&&n.comments.length>0&&(i.positionedComments=[{position:"after",comments:n.comments}]),i}if(this.canRead(2)&&this.input[this.position]==="/"&&this.input[this.position+1]==="*"&&this.input[this.position+2]==="+"){this.position+=3;let i=this.position;for(;this.position+1=this.input.length)return!1;let i=this.input.slice(t,n).trim();return i===""?!1:/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$/.test(i)}readEscapedIdentifier(e){let t=this.position;this.position++;let n=!1;for(;this.canRead();){if(this.input[this.position]===e){n=!0;break}this.position++}if(!n)throw new Error(`Closing delimiter is not found. position: ${t}, delimiter: ${e} ${this.getDebugPositionInfo(t)}`);if(t===this.position)throw new Error(`Closing delimiter is not found. position: ${t}, delimiter: ${e} -${this.getDebugPositionInfo(t)}`);return this.position++,this.input.slice(t+1,this.position-1)}};var jr=new Je([["grouping","sets"],["array"]]),qr=new Pe(jr),Dn=class extends me{tryRead(e){if(this.isEndOfInput())return null;let t=qr.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 i=le.readWhiteSpaceAndComment(this.input,this.position).position-this.position;return this.canRead(i)&&this.input[this.position+i]==="("?this.createLexeme(2048,n.identifier):null}};var $n=class extends me{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 Jr=[["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"]],zr=new Je(Jr),tr=new Pe(zr),Wn=class extends me{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="'"){let i=this.readSingleQuotedString();return this.createLexeme(1,i)}let n=this.tryReadKeyword();if(n)return n;if(t==="."&&this.canRead(1)&&ie.isDigit(this.input[this.position+1]))return this.createLexeme(1,this.readDigit());if(ie.isDigit(t))return this.createLexeme(1,this.readDigit());if(t==="$"&&this.isDollarQuotedString())return this.createLexeme(1,this.readDollarQuotedString());if(t==="$"&&this.canRead(1)&&ie.isDigit(this.input[this.position+1])){let i=this.position+1,r=!1;for(;i=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}};var _r=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"]]),Hr=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"]]),Gr=new Pe(_r),Yr=new Pe(Hr);var Un=class extends me{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(ie.isOperatorSymbol(t)){let i=this.position;for(;this.canRead()&&ie.isOperatorSymbol(this.input[this.position])&&(this.position++,!!this.canRead());){let s=this.input[this.position-1],o=this.input[this.position];if(s==="-"&&o==="-"||s==="/"&&o==="*")break}this.position===i&&this.position++;let r=this.input.slice(i,this.position);return this.createLexeme(2,r)}let n=Yr.parse(this.input,this.position);return n!==null?(this.position=n.newPosition,this.createLexeme(8258,n.keyword)):(n=Gr.parse(this.input,this.position),n!==null?(this.position=n.newPosition,this.createLexeme(2,n.keyword)):null)}};var Kn=class extends me{constructor(e){super(e)}tryRead(e){if(this.isEndOfInput())return null;if(this.canRead(1)&&this.input[this.position]==="$"&&this.input[this.position+1]==="{"){this.position+=2;let n=this.position;for(;this.canRead()&&this.input[this.position]!=="}";)this.position++;if(this.isEndOfInput())throw new Error(`Unexpected end of input. Expected closing '}' for parameter at position ${n}`);let i=this.input.slice(n,this.position);if(i.length===0)throw new Error("Empty parameter name is not allowed: found ${} at position "+(n-2));return this.position++,this.createLexeme(256,"${"+i+"}")}let t=this.input[this.position];if(ie.isNamedParameterPrefix(t)){if(this.canRead(1)&&ie.isOperatorSymbol(this.input[this.position+1])||t===":"&&this.isInArraySliceContext()||t==="$"&&this.isDollarQuotedString())return null;if(t==="$"&&this.canRead(1)&&ie.isDigit(this.input[this.position+1])){let r=this.position+1,s=!1;for(;r=0;){let i=this.input[e];if(i==="]")t++;else if(i==="["){if(t--,t<0){if(e>0){let r=this.input[e-1];if(/[a-zA-Z0-9_)\]]/.test(r))return!0}if(e===0)return!1;break}}else i===")"?n++:i==="("&&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=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}};var jn=class a extends me{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 Xr=new Set(["e'","E'","x'","X'","b'","B'"]),Zr=new Set(["u&'","U&'"]),qn=class extends me{tryRead(e){let t=this.position;return this.canRead(1)&&Xr.has(this.input.slice(t,t+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(t,this.position))):this.canRead(2)&&Zr.has(this.input.slice(t,t+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(t,this.position))):null}};var Jn=class{constructor(e,t=0){this.cacheHits=0;this.cacheMisses=0;this.input=e,this.position=t,this.readers=[],this.tokenCache=new Map}register(e){return this.readers.push(e),this}registerAll(e){return e.forEach(t=>this.register(t)),this}setPosition(e){this.position=e;for(let t of this.readers)t.setPosition(e)}tryRead(e,t){if(this.tokenCache.has(e))return this.cacheHits++,this.tokenCache.get(e)||null;this.cacheMisses++,this.setPosition(e);let n=null;for(let i of this.readers)if(n=i.tryRead(t),n){this.position=i.getPosition();break}for(let i of this.readers)i.setPosition(this.position);return this.tokenCache.set(e,n),n}getMaxPosition(){let e=this.position;for(let t of this.readers){let n=t.getPosition();n>e&&(e=n)}return e}getInput(){return this.input}getCacheStats(){let e=this.cacheHits+this.cacheMisses,t=e>0?this.cacheHits/e:0;return{hits:this.cacheHits,misses:this.cacheMisses,ratio:t}}};var es=new Je([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),ts=new Pe(es),zn=class extends me{tryRead(e){if(this.isEndOfInput())return null;let t=ts.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 T=class a{constructor(e){this.input=e,this.position=0,this.readerManager=new Jn(e).register(new Vn(e)).register(new Kn(e)).register(new qn(e)).register(new Wn(e)).register(new jn(e)).register(new Mn(e)).register(new Un(e)).register(new zn(e)).register(new Dn(e)).register(new $n(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).readLexemes()}readLexmes(){return this.readLexemes()}readLexemes(){let e=this.readNextStatement(0);return e?e.lexemes:[]}tokenizeBasic(){let e=this.readNextStatement(0);return e?e.lexemes:[]}readNextStatement(e=0,t=null){let n=this.input.length;if(e>=n)return null;this.position=e;let i=e,r=t?[...t]:null,s=[],o=null;for(;this.canRead();){let p=this.readComment();if(this.position=p.position,!this.canRead()){r=this.mergeComments(r,p.lines);break}if(this.input[this.position]===";"){r=this.mergeComments(r,p.lines);break}let m=this.readerManager.tryRead(this.position,o);if(m===null)throw new Error(`Unexpected character. actual: ${this.input[this.position]}, position: ${this.position} -${this.getDebugPositionInfo(this.position)}`);let h=this.position,C=this.position=this.readerManager.getMaxPosition(),f=this.readComment();this.position=f.position;let N=this.mergeComments(r,p.lines);r=null,s.push({lexeme:m,startPos:h,endPos:C,prefixComments:N,suffixComments:f.lines}),o=m}let l=this.position,u=this.buildLexemesFromTokenData(s),c=this.skipPastTerminator(l);return{lexemes:u,statementStart:i,statementEnd:l,nextPosition:c,rawText:this.input.slice(i,l),leadingComments:r}}buildLexemesFromTokenData(e){let t=new Array(e.length);for(let n=0;n0){let s=i.suffixComments,o=n+1;for(;o0){let s=i.suffixComments,o=n+1;if(o0){let s=i.suffixComments,o=n+1;for(;o0?!e||e.length===0?[...t]:[...e,...t]:e?[...e]:null}attachCommentsToLexeme(e,t){let n=[],i=[];e.positionedComments&&e.positionedComments.length>0&&n.push(...e.positionedComments),t.prefixComments&&t.prefixComments.length>0&&(i.push(...t.prefixComments),n.push({position:"before",comments:[...t.prefixComments]})),t.suffixComments&&t.suffixComments.length>0&&(i.push(...t.suffixComments),n.push({position:"after",comments:[...t.suffixComments]})),n.length>0?(e.positionedComments=n,e.comments=null):i.length>0?(e.comments=i,e.positionedComments=void 0):(e.comments=null,e.positionedComments=void 0)}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 r of e){n=this.skipWhitespaceAndComments(n);let s=this.findLexemeAtPosition(r,n);if(s)t.push(s),n=s.endPosition;else{let o={startPosition:n,endPosition:n+r.value.length};t.push(o),n=o.endPosition}}let i=[];for(let r=0;r=this.input.length)return null;let n=[e.value,e.value.toUpperCase(),e.value.toLowerCase()];for(let i of n)if(t+i.length<=this.input.length&&this.input.substring(t,t+i.length)===i&&this.isValidLexemeMatch(i,t))return{startPosition:t,endPosition:t+i.length};return null}isValidLexemeMatch(e,t){if(t>0){let i=this.input[t-1];if(this.isAlphanumericUnderscore(i))return!1}let n=t+e.length;if(n=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(;n0&&t.push(...s),n=r.position,n===i&&n++}return t}skipWhitespaceAndComments(e){return le.readWhiteSpaceAndComment(this.input,e).position}getLineColumnInfo(e,t){let n=this.getLineColumn(e),i=this.getLineColumn(t);return{startLine:n.line,startColumn:n.column,endLine:i.line,endColumn:i.column}}getLineColumn(e){let t=1,n=1;for(let i=0;ii.position===e);n?n.comments.push(...t):this.positionedComments.push({position:e,comments:[...t]})}getPositionedComments(e){if(!this.positionedComments)return[];let t=this.positionedComments.find(n=>n.position===e);return t?t.comments:[]}getAllPositionedComments(){if(!this.positionedComments)return[];let e=[],t=this.getPositionedComments("before");e.push(...t);let n=this.getPositionedComments("after");return e.push(...n),e}},pr=class{constructor(){this.parameterSymbol=":";this.identifierEscape={start:'"',end:'"'};this.exportComment=!0}};var tt=class extends y{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null,this.returningClause=e.returning??null}};var de=class extends y{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},W=class extends y{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},E=class extends y{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof I?this.qualifiedName.name:new I(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(e,t){super();let n=typeof t=="string"?new I(t):t;this.qualifiedName=new G(hr(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},H=class extends y{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,i,r=null,s=!1,o=null){super(),this.qualifiedName=new G(e,t),this.argument=n,this.over=i,this.withinGroup=r,this.withOrdinality=s,this.internalOrderBy=o}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},mr=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(mr||{}),dr=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(dr||{}),Ut=class extends y{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},Kt=class extends y{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},it=class extends y{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Ke=class extends y{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},te=class extends y{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new R(e),this.expression=t}},b=class extends y{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new R(t),this.right=n}},Z=class extends y{static{this.kind=Symbol("LiteralExpression")}constructor(e,t,n){super(),this.value=e,this.isStringLiteral=n}},A=class extends y{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new R(e),this.value=t,this.index=null}},Le=class extends y{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},Ae=class extends y{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},R=class extends y{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},I=class extends y{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},ee=class extends y{static{this.kind=Symbol("ParenExpression")}constructor(e){super(),this.expression=e}},fe=class extends y{static{this.kind=Symbol("CastExpression")}constructor(e,t){super(),this.input=e,this.castType=t}},ue=class extends y{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},Se=class extends y{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},be=class extends y{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},Ee=class extends y{static{this.kind=Symbol("BetweenExpression")}constructor(e,t,n,i){super(),this.expression=e,this.lower=t,this.upper=n,this.negated=i}},ze=class extends y{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new R(e),this.value=new Z(t)}},De=class extends y{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new G(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof R?this.qualifiedName.name.value:this.qualifiedName.name.name;return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(t=>t.name).join(".")+"."+e:e}},xe=class extends y{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}},lt=class extends y{static{this.kind=Symbol("ArraySliceExpression")}constructor(e,t,n){super(),this.array=e,this.startIndex=t,this.endIndex=n}},ut=class extends y{static{this.kind=Symbol("ArrayIndexExpression")}constructor(e,t){super(),this.array=e,this.index=t}};function hr(a){if(a==null)return null;if(typeof a=="string")return a.trim()===""?null:[new I(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 I(t))}else{let e=a.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var G=class extends y{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=hr(e),typeof t=="string"?this.name=new R(t):this.name=t}toString(){let e=this.name instanceof R?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(t=>t.name).join(".")+"."+e:e}};var q=class extends y{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new I(t):null}},z=class extends y{static{this.kind=Symbol("SelectClause")}constructor(e,t=null,n=[]){super(),this.items=e,this.distinct=t,this.hints=n}},jt=class extends y{static{this.kind=Symbol("Distinct")}constructor(){super()}},qt=class extends y{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},re=class extends y{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},_e=class extends y{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},Oe=class extends y{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new I(e),this.expression=t}},ct=class extends y{static{this.kind=Symbol("WindowsClause")}constructor(e){super(),this.windows=e}};var Ce=class extends y{static{this.kind=Symbol("OrderByClause")}constructor(e){super(),this.order=e}},Qe=class extends y{static{this.kind=Symbol("OrderByItem")}constructor(e,t,n){super(),this.value=e,this.sortDirection=t===null?"asc":t,this.nullsPosition=n}},ge=class extends y{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},ye=class extends y{static{this.kind=Symbol("HavingClause")}constructor(e){super(),this.condition=e}},B=class extends y{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof I?this.qualifiedName.name:new I(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(e,t){super();let n=typeof t=="string"?new I(t):t;this.qualifiedName=new G(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof R?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof R?this.qualifiedName.name.value:this.qualifiedName.name.name}},nt=class extends y{static{this.kind=Symbol("FunctionSource")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"name"in e){let n=e;this.qualifiedName=new G(n.namespaces,n.name)}else this.qualifiedName=new G(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},je=class extends y{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},U=class extends y{static{this.kind=Symbol("SubQuerySource")}constructor(e){super(),this.query=e}},$=class extends y{static{this.kind=Symbol("SourceExpression")}constructor(e,t){super(),this.datasource=e,this.aliasExpression=t}getAliasName(){return this.aliasExpression?this.aliasExpression.table.name:this.datasource instanceof B?this.datasource.getSourceName():null}},we=class extends y{static{this.kind=Symbol("JoinOnClause")}constructor(e){super(),this.condition=e}},Te=class extends y{static{this.kind=Symbol("JoinUsingClause")}constructor(e){super(),this.condition=e}},ve=class extends y{static{this.kind=Symbol("JoinItem")}constructor(e,t,n,i){super(),this.joinType=new R(e),this.source=t,this.condition=n,this.lateral=i}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof B?this.source.table.name:null}},_=class extends y{static{this.kind=Symbol("FromClause")}constructor(e,t){super(),this.source=e,this.joins=t}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof B?this.source.datasource.table.name:null}getSources(){let e=[this.source];if(this.joins)for(let t of this.joins)e.push(t.source);return e}},Jt=class extends y{static{this.kind=Symbol("UsingClause")}constructor(e){super(),this.sources=e}getSources(){return[...this.sources]}},oe=class extends y{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new se(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},he=class extends y{constructor(t,n){super();this.trailingComments=null;this.globalComments=null;this.recursive=t,this.tables=n}static{this.kind=Symbol("WithClause")}},ce=class extends y{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var $e=class extends y{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},He=class extends y{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},Ft=class extends y{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var Re=class extends y{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},se=class extends y{static{this.kind=Symbol("SourceAliasExpression")}constructor(e,t){super(),this.table=new I(e),this.columns=t!==null?t.map(n=>new I(n)):null}},zt=class extends y{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new I(t):t)}},Fe=class extends y{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof Xe?t:new Xe(t.column,t.value))}},Xe=class extends y{static{this.kind=Symbol("SetClauseItem")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"column"in e){let n=e,i=typeof n.column=="string"?new I(n.column):n.column;this.qualifiedName=new G(n.namespaces,i)}else{let n=typeof e=="string"?new I(e):e;this.qualifiedName=new G(null,n)}this.value=t}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof I?this.qualifiedName.name:new I(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},bt=class extends y{static{this.kind=Symbol("UpdateClause")}constructor(e){super(),this.source=e}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof B?this.source.datasource.table.name:null}},Et=class extends y{static{this.kind=Symbol("DeleteClause")}constructor(e){super(),this.source=e}getSourceAliasName(){return this.source.getAliasName()}},xt=class extends y{constructor(e,t){super(),this.source=e,t&&t.length>0?this.columns=t.map(n=>typeof n=="string"?new I(n):n):this.columns=null}};var K=class a{static parseFromLexeme(e,t){let{identifiers:n,newIndex:i}=a.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:r,name:s}=a.extractNamespacesAndName(n),o=new I(s);if(i>t){let u=e[i-1];u.positionedComments&&u.positionedComments.length>0?o.positionedComments=u.positionedComments:u.comments&&u.comments.length>0}let l=0;return i>t&&(l=e[i-1].type),{namespaces:r,name:o,newIndex:i,lastTokenType:l}}static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length||!(e[n].type&64||e[n].type&128))throw new Error(`Expected identifier after '[' at position ${n}`);if(i.push(e[n].value),n++,n>=e.length||e[n].value!=="]")throw new Error(`Expected closing ']' after identifier at position ${n}`);n++}else if(e[n].type&64)i.push(e[n].value),n++;else if(e[n].type&2048)i.push(e[n].value),n++;else if(e[n].type&8192)i.push(e[n].value),n++;else if(e[n].value==="*"){i.push(e[n].value),n++;break}if(n({position:C.position,comments:[...C.comments]})):null,l=s.comments?[...s.comments]:null;n+=1;let u=P.parseFromLexeme(e,n);if(n=u.newIndex,n>=e.length||e[n].type!==8)throw new Error(`Expected ')' at index ${n}, but found ${e[n].value}`);let c=e[n],p=c.comments,m=c.positionedComments;n++;let h=new de(u.value);if(o&&o.length>0){let C=o.filter(f=>f.position==="after"&&f.comments.length>0).map(f=>({position:"before",comments:[...f.comments]}));C.length>0&&(h.positionedComments=h.positionedComments?[...C,...h.positionedComments]:C)}else if(l&&l.length>0){let C={position:"before",comments:[...l]};h.positionedComments=h.positionedComments?[C,...h.positionedComments]:[C]}if(m&&m.length>0){let C=m.filter(f=>f.position==="after"&&f.comments.length>0).map(f=>({position:f.position,comments:[...f.comments]}));C.length>0&&(h.positionedComments=h.positionedComments?[...h.positionedComments,...C]:C)}else p&&p.length>0&&(h.comments=p);return{value:h,newIndex:n}}let i=x.parseArgument(4,8,e,t);return n=i.newIndex,{value:new ee(i.value),newIndex:n}}};var Gn=class{static parseFromLexeme(e,t){let n=t;if(n0?o.positionedComments=i.positionedComments:i.comments&&i.comments.length>0&&(o.comments=i.comments),{value:o,newIndex:n}}throw new Error(`Invalid unary expression at index ${t}: ${e[t].value}`)}};var Yn=class{static parseFromLexeme(e,t){let n=t,i=e[n].value;i.startsWith("${")&&i.endsWith("}")?i=i.slice(2,-1):i=i.slice(1);let r=new A(i);return n++,{value:r,newIndex:n}}};var Xn=class{static parseFromLexeme(e,t){let n=t,i=e[n].value;if(n++,n>=e.length||e[n].type!==1)throw new Error(`Expected string literal after string specifier at index ${n}`);let r=e[n].value;return n++,{value:new ze(i,r),newIndex:n}}};var Zn=class a{static parseFromLexeme(e,t){let n=t,i=e[n];if(i.value==="case"){let r=i.comments,s=i.positionedComments;return n++,this.parseCaseExpression(e,n,r,s)}else if(i.value==="case when"){let r=i.comments,s=i.positionedComments;return n++,this.parseCaseWhenExpression(e,n,r,s)}return this.parseModifierUnaryExpression(e,n)}static parseModifierUnaryExpression(e,t){let n=t;if(n0?l.positionedComments=i:n&&n.length>0&&(l.positionedComments=[a.convertLegacyToPositioned(n,"before")]),{value:l,newIndex:r}}static parseCaseWhenExpression(e,t,n,i){let r=t,s=this.parseCaseConditionValuePair(e,r);r=s.newIndex;let o=[s.value],l=this.parseSwitchCaseArgument(e,r,o);r=l.newIndex;let u=new ue(null,l.value);return i&&i.length>0?u.positionedComments=i:n&&n.length>0&&(u.positionedComments=[a.convertLegacyToPositioned(n,"before")]),{value:u,newIndex:r}}static parseSwitchCaseArgument(e,t,n){let i=t,r=[...n];i=this.parseAdditionalWhenClauses(e,i,r);let{elseValue:s,elseComments:o,newIndex:l}=this.parseElseClause(e,i);i=l;let{endComments:u,newIndex:c}=this.parseEndClause(e,i);if(i=c,r.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${i})`);let p=new Le(r,s);return this.applySwitchCaseComments(p,o,u),{value:p,newIndex:i}}static parseAdditionalWhenClauses(e,t,n){let i=t;for(;i0&&i.push(...t.positioned),t?.legacy&&t.legacy.length>0&&r.push(...t.legacy),n?.positioned&&n.positioned.length>0&&i.push(...n.positioned),n?.legacy&&n.legacy.length>0&&r.push(...n.legacy),i.length>0?e.positionedComments=i:r.length>0&&(e.positionedComments=[a.convertLegacyToPositioned(r,"after")])}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,i=x.parseFromLexeme(e,n);if(n=i.newIndex,n>=e.length||!(e[n].type&128)||e[n].value!=="then")throw new Error(`Expected 'then' after WHEN condition at index ${n}`);let r=e[n].comments,s=e[n].positionedComments;n++;let o=x.parseFromLexeme(e,n);n=o.newIndex;let l=new Ae(i.value,o.value);return s&&s.length>0?l.positionedComments=s:r&&r.length>0&&(l.positionedComments=[a.convertLegacyToPositioned(r,"after")]),{value:l,newIndex:n}}static convertLegacyToPositioned(e,t="before"){return{position:t,comments:e}}};var pt=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)return{value:r,newIndex:n};let s=null,o=null;if(n0){s=[];for(let c of u.positionedComments)c.comments&&c.comments.length>0&&s.push(...c.comments)}u.comments&&u.comments.length>0&&(s||(s=[]),s.push(...u.comments))}}let l=n>=e.length?null:e[n].value==="nulls first"?(n++,"first"):e[n].value==="nulls last"?(n++,"last"):null;return s&&s.length>0&&(r.comments?r.comments.push(...s):r.comments=s),o===null&&l===null?{value:r,newIndex:n}:{value:new Qe(r,o,l),newIndex:n}}};var ei=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=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 Ke(i,r,s),newIndex:n}}static isFrameTypeKeyword(e){let t=e;return t==="rows"||t==="range"||t==="groups"}static parseFrameSpec(e,t){let n=t,i=e[n].value,r;switch(i){case"rows":r="rows";break;case"range":r="range";break;case"groups":r="groups";break;default:throw new Error(`Syntax error at position ${n}: Invalid frame type "${e[n].value}". Expected one of: ROWS, RANGE, GROUPS.`)}if(n++,n=e.length||e[n].value!=="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 it(r,o,u),newIndex:n}}else{let s=this.parseFrameBoundary(e,n),o=s.value;return n=s.newIndex,{value:new it(r,o,null),newIndex:n}}}static parseFrameBoundary(e,t){let n=t;if(n=e.length)throw new Error("Syntax error: Unexpected end of input after 'OVER' keyword. Expected either a window name or an opening parenthesis '('.");if(e[n].type&64){let i=e[n].value;return n++,{value:new I(i),newIndex:n}}if(e[n].type&4)return _t.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 ke=class a extends Error{constructor(t,n,i){super(t);this.index=n;this.context=i;this.name="ParseError"}static fromUnparsedLexemes(t,n,i){let r=Math.max(0,n-2),s=Math.min(t.length,n+3),o=t.slice(r,s).map((u,c)=>{let p=c+r===n?">":" ",m=F[u.type]||u.type;return`${p} ${c+r}:${u.value} [${m}]`}).join(` -`),l=`${i} Unparsed lexeme remains at index ${n}: ${t[n].value} +${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=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}};var Yr=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"]]),Xr=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 Pe(Yr),es=new Pe(Xr);var Un=class extends me{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(ie.isOperatorSymbol(t)){let i=this.position;for(;this.canRead()&&ie.isOperatorSymbol(this.input[this.position])&&(this.position++,!!this.canRead());){let s=this.input[this.position-1],o=this.input[this.position];if(s==="-"&&o==="-"||s==="/"&&o==="*")break}this.position===i&&this.position++;let r=this.input.slice(i,this.position);return this.createLexeme(2,r)}let n=es.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 Kn=class extends me{constructor(e){super(e)}tryRead(e){if(this.isEndOfInput())return null;if(this.canRead(1)&&this.input[this.position]==="$"&&this.input[this.position+1]==="{"){this.position+=2;let n=this.position;for(;this.canRead()&&this.input[this.position]!=="}";)this.position++;if(this.isEndOfInput())throw new Error(`Unexpected end of input. Expected closing '}' for parameter at position ${n}`);let i=this.input.slice(n,this.position);if(i.length===0)throw new Error("Empty parameter name is not allowed: found ${} at position "+(n-2));return this.position++,this.createLexeme(256,"${"+i+"}")}let t=this.input[this.position];if(ie.isNamedParameterPrefix(t)){if(this.canRead(1)&&ie.isOperatorSymbol(this.input[this.position+1])||t===":"&&this.isInArraySliceContext()||t==="$"&&this.isDollarQuotedString())return null;if(t==="$"&&this.canRead(1)&&ie.isDigit(this.input[this.position+1])){let r=this.position+1,s=!1;for(;r=0;){let i=this.input[e];if(i==="]")t++;else if(i==="["){if(t--,t<0){if(e>0){let r=this.input[e-1];if(/[a-zA-Z0-9_)\]]/.test(r))return!0}if(e===0)return!1;break}}else i===")"?n++:i==="("&&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=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}};var jn=class a extends me{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 ts=new Set(["e'","E'","x'","X'","b'","B'"]),ns=new Set(["u&'","U&'"]),qn=class extends me{tryRead(e){let t=this.position;return this.canRead(1)&&ts.has(this.input.slice(t,t+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(t,this.position))):this.canRead(2)&&ns.has(this.input.slice(t,t+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(t,this.position))):null}};var Jn=class{constructor(e,t=0){this.cacheHits=0;this.cacheMisses=0;this.input=e,this.position=t,this.readers=[],this.tokenCache=new Map}register(e){return this.readers.push(e),this}registerAll(e){return e.forEach(t=>this.register(t)),this}setPosition(e){this.position=e;for(let t of this.readers)t.setPosition(e)}tryRead(e,t){if(this.tokenCache.has(e))return this.cacheHits++,this.tokenCache.get(e)||null;this.cacheMisses++,this.setPosition(e);let n=null;for(let i of this.readers)if(n=i.tryRead(t),n){this.position=i.getPosition();break}for(let i of this.readers)i.setPosition(this.position);return this.tokenCache.set(e,n),n}getMaxPosition(){let e=this.position;for(let t of this.readers){let n=t.getPosition();n>e&&(e=n)}return e}getInput(){return this.input}getCacheStats(){let e=this.cacheHits+this.cacheMisses,t=e>0?this.cacheHits/e:0;return{hits:this.cacheHits,misses:this.cacheMisses,ratio:t}}};var is=new Je([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),rs=new Pe(is),zn=class extends me{tryRead(e){if(this.isEndOfInput())return null;let t=rs.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 T=class a{constructor(e){this.input=e,this.position=0,this.readerManager=new Jn(e).register(new Vn(e)).register(new Kn(e)).register(new qn(e)).register(new Wn(e)).register(new jn(e)).register(new Mn(e)).register(new Un(e)).register(new zn(e)).register(new Dn(e)).register(new $n(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).readLexemes()}readLexmes(){return this.readLexemes()}readLexemes(){let e=this.readNextStatement(0);return e?e.lexemes:[]}tokenizeBasic(){let e=this.readNextStatement(0);return e?e.lexemes:[]}readNextStatement(e=0,t=null){let n=this.input.length;if(e>=n)return null;this.position=e;let i=e,r=t?[...t]:null,s=[],o=null;for(;this.canRead();){let p=this.readComment();if(this.position=p.position,!this.canRead()){r=this.mergeComments(r,p.lines);break}if(this.input[this.position]===";"){r=this.mergeComments(r,p.lines);break}let m=this.readerManager.tryRead(this.position,o);if(m===null)throw new Error(`Unexpected character. actual: ${this.input[this.position]}, position: ${this.position} +${this.getDebugPositionInfo(this.position)}`);let h=this.position,C=this.position=this.readerManager.getMaxPosition(),f=this.readComment();this.position=f.position;let A=this.mergeComments(r,p.lines);r=null,s.push({lexeme:m,startPos:h,endPos:C,prefixComments:A,suffixComments:f.lines}),o=m}let u=this.position,l=this.buildLexemesFromTokenData(s),c=this.skipPastTerminator(u);return{lexemes:l,statementStart:i,statementEnd:u,nextPosition:c,rawText:this.input.slice(i,u),leadingComments:r}}buildLexemesFromTokenData(e){let t=new Array(e.length);for(let n=0;n0){let s=i.suffixComments,o=n+1;for(;o0){let s=i.suffixComments,o=n+1;if(o0){let s=i.suffixComments,o=n+1;for(;o0?!e||e.length===0?[...t]:[...e,...t]:e?[...e]:null}attachCommentsToLexeme(e,t){let n=[],i=[];e.positionedComments&&e.positionedComments.length>0&&n.push(...e.positionedComments),t.prefixComments&&t.prefixComments.length>0&&(i.push(...t.prefixComments),n.push({position:"before",comments:[...t.prefixComments]})),t.suffixComments&&t.suffixComments.length>0&&(i.push(...t.suffixComments),n.push({position:"after",comments:[...t.suffixComments]})),n.length>0?(e.positionedComments=n,e.comments=null):i.length>0?(e.comments=i,e.positionedComments=void 0):(e.comments=null,e.positionedComments=void 0)}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 r of e){n=this.skipWhitespaceAndComments(n);let s=this.findLexemeAtPosition(r,n);if(s)t.push(s),n=s.endPosition;else{let o={startPosition:n,endPosition:n+r.value.length};t.push(o),n=o.endPosition}}let i=[];for(let r=0;r=this.input.length)return null;let n=[e.value,e.value.toUpperCase(),e.value.toLowerCase()];for(let i of n)if(t+i.length<=this.input.length&&this.input.substring(t,t+i.length)===i&&this.isValidLexemeMatch(i,t))return{startPosition:t,endPosition:t+i.length};return null}isValidLexemeMatch(e,t){if(t>0){let i=this.input[t-1];if(this.isAlphanumericUnderscore(i))return!1}let n=t+e.length;if(n=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(;n0&&t.push(...s),n=r.position,n===i&&n++}return t}skipWhitespaceAndComments(e){return le.readWhiteSpaceAndComment(this.input,e).position}getLineColumnInfo(e,t){let n=this.getLineColumn(e),i=this.getLineColumn(t);return{startLine:n.line,startColumn:n.column,endLine:i.line,endColumn:i.column}}getLineColumn(e){let t=1,n=1;for(let i=0;ii.position===e);n?n.comments.push(...t):this.positionedComments.push({position:e,comments:[...t]})}getPositionedComments(e){if(!this.positionedComments)return[];let t=this.positionedComments.find(n=>n.position===e);return t?t.comments:[]}getAllPositionedComments(){if(!this.positionedComments)return[];let e=[],t=this.getPositionedComments("before");e.push(...t);let n=this.getPositionedComments("after");return e.push(...n),e}},pr=class{constructor(){this.parameterSymbol=":";this.identifierEscape={start:'"',end:'"'};this.exportComment=!0}};var tt=class extends g{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null,this.returningClause=e.returning??null}};var de=class extends g{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},W=class extends g{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},E=class extends g{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof I?this.qualifiedName.name:new I(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(e,t){super();let n=typeof t=="string"?new I(t):t;this.qualifiedName=new G(hr(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},H=class extends g{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,i,r=null,s=!1,o=null){super(),this.qualifiedName=new G(e,t),this.argument=n,this.over=i,this.withinGroup=r,this.withOrdinality=s,this.internalOrderBy=o}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},mr=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(mr||{}),dr=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(dr||{}),Ut=class extends g{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},Kt=class extends g{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},it=class extends g{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Ke=class extends g{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},te=class extends g{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new R(e),this.expression=t}},b=class extends g{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new R(t),this.right=n}},Z=class extends g{static{this.kind=Symbol("LiteralExpression")}constructor(e,t,n){super(),this.value=e,this.isStringLiteral=n}},N=class extends g{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new R(e),this.value=t,this.index=null}},Le=class extends g{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},Ne=class extends g{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},R=class extends g{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},I=class extends g{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},ee=class extends g{static{this.kind=Symbol("ParenExpression")}constructor(e){super(),this.expression=e}},fe=class extends g{static{this.kind=Symbol("CastExpression")}constructor(e,t){super(),this.input=e,this.castType=t}},ue=class extends g{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},Se=class extends g{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},be=class extends g{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},Ee=class extends g{static{this.kind=Symbol("BetweenExpression")}constructor(e,t,n,i){super(),this.expression=e,this.lower=t,this.upper=n,this.negated=i}},ze=class extends g{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new R(e),this.value=new Z(t)}},De=class extends g{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new G(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof R?this.qualifiedName.name.value:this.qualifiedName.name.name;return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(t=>t.name).join(".")+"."+e:e}},xe=class extends g{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}},lt=class extends g{static{this.kind=Symbol("ArraySliceExpression")}constructor(e,t,n){super(),this.array=e,this.startIndex=t,this.endIndex=n}},ut=class extends g{static{this.kind=Symbol("ArrayIndexExpression")}constructor(e,t){super(),this.array=e,this.index=t}};function hr(a){if(a==null)return null;if(typeof a=="string")return a.trim()===""?null:[new I(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 I(t))}else{let e=a.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var G=class extends g{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=hr(e),typeof t=="string"?this.name=new R(t):this.name=t}toString(){let e=this.name instanceof R?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(t=>t.name).join(".")+"."+e:e}};var J=class extends g{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new I(t):null}},z=class extends g{static{this.kind=Symbol("SelectClause")}constructor(e,t=null,n=[]){super(),this.items=e,this.distinct=t,this.hints=n}},jt=class extends g{static{this.kind=Symbol("Distinct")}constructor(){super()}},qt=class extends g{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},re=class extends g{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},_e=class extends g{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},Oe=class extends g{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new I(e),this.expression=t}},ct=class extends g{static{this.kind=Symbol("WindowsClause")}constructor(e){super(),this.windows=e}};var Ce=class extends g{static{this.kind=Symbol("OrderByClause")}constructor(e){super(),this.order=e}},Qe=class extends g{static{this.kind=Symbol("OrderByItem")}constructor(e,t,n){super(),this.value=e,this.sortDirection=t===null?"asc":t,this.nullsPosition=n}},ye=class extends g{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},ge=class extends g{static{this.kind=Symbol("HavingClause")}constructor(e){super(),this.condition=e}},B=class extends g{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof I?this.qualifiedName.name:new I(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(e,t){super();let n=typeof t=="string"?new I(t):t;this.qualifiedName=new G(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof R?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof R?this.qualifiedName.name.value:this.qualifiedName.name.name}},nt=class extends g{static{this.kind=Symbol("FunctionSource")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"name"in e){let n=e;this.qualifiedName=new G(n.namespaces,n.name)}else this.qualifiedName=new G(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},je=class extends g{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},K=class extends g{static{this.kind=Symbol("SubQuerySource")}constructor(e){super(),this.query=e}},$=class extends g{static{this.kind=Symbol("SourceExpression")}constructor(e,t){super(),this.datasource=e,this.aliasExpression=t}getAliasName(){return this.aliasExpression?this.aliasExpression.table.name:this.datasource instanceof B?this.datasource.getSourceName():null}},we=class extends g{static{this.kind=Symbol("JoinOnClause")}constructor(e){super(),this.condition=e}},Te=class extends g{static{this.kind=Symbol("JoinUsingClause")}constructor(e){super(),this.condition=e}},ve=class extends g{static{this.kind=Symbol("JoinItem")}constructor(e,t,n,i){super(),this.joinType=new R(e),this.source=t,this.condition=n,this.lateral=i}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof B?this.source.table.name:null}},_=class extends g{static{this.kind=Symbol("FromClause")}constructor(e,t){super(),this.source=e,this.joins=t}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof B?this.source.datasource.table.name:null}getSources(){let e=[this.source];if(this.joins)for(let t of this.joins)e.push(t.source);return e}},Jt=class extends g{static{this.kind=Symbol("UsingClause")}constructor(e){super(),this.sources=e}getSources(){return[...this.sources]}},oe=class extends g{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new se(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},he=class extends g{constructor(t,n){super();this.trailingComments=null;this.globalComments=null;this.recursive=t,this.tables=n}static{this.kind=Symbol("WithClause")}},ce=class extends g{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var $e=class extends g{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},He=class extends g{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},Ft=class extends g{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var Re=class extends g{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},se=class extends g{static{this.kind=Symbol("SourceAliasExpression")}constructor(e,t){super(),this.table=new I(e),this.columns=t!==null?t.map(n=>new I(n)):null}},zt=class extends g{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new I(t):t)}},Fe=class extends g{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof Xe?t:new Xe(t.column,t.value))}},Xe=class extends g{static{this.kind=Symbol("SetClauseItem")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"column"in e){let n=e,i=typeof n.column=="string"?new I(n.column):n.column;this.qualifiedName=new G(n.namespaces,i)}else{let n=typeof e=="string"?new I(e):e;this.qualifiedName=new G(null,n)}this.value=t}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof I?this.qualifiedName.name:new I(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},bt=class extends g{static{this.kind=Symbol("UpdateClause")}constructor(e){super(),this.source=e}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof B?this.source.datasource.table.name:null}},Et=class extends g{static{this.kind=Symbol("DeleteClause")}constructor(e){super(),this.source=e}getSourceAliasName(){return this.source.getAliasName()}},xt=class extends g{constructor(e,t){super(),this.source=e,t&&t.length>0?this.columns=t.map(n=>typeof n=="string"?new I(n):n):this.columns=null}};var j=class a{static parseFromLexeme(e,t){let{identifiers:n,newIndex:i}=a.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:r,name:s}=a.extractNamespacesAndName(n),o=new I(s);if(i>t){let l=e[i-1];l.positionedComments&&l.positionedComments.length>0?o.positionedComments=l.positionedComments:l.comments&&l.comments.length>0}let u=0;return i>t&&(u=e[i-1].type),{namespaces:r,name:o,newIndex:i,lastTokenType:u}}static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length||!(e[n].type&64||e[n].type&128))throw new Error(`Expected identifier after '[' at position ${n}`);if(i.push(e[n].value),n++,n>=e.length||e[n].value!=="]")throw new Error(`Expected closing ']' after identifier at position ${n}`);n++}else if(e[n].type&64)i.push(e[n].value),n++;else if(e[n].type&2048)i.push(e[n].value),n++;else if(e[n].type&8192)i.push(e[n].value),n++;else if(e[n].value==="*"){i.push(e[n].value),n++;break}if(n({position:C.position,comments:[...C.comments]})):null,u=s.comments?[...s.comments]:null;n+=1;let l=P.parseFromLexeme(e,n);if(n=l.newIndex,n>=e.length||e[n].type!==8)throw new Error(`Expected ')' at index ${n}, but found ${e[n].value}`);let c=e[n],p=c.comments,m=c.positionedComments;n++;let h=new de(l.value);if(o&&o.length>0){let C=o.filter(f=>f.position==="after"&&f.comments.length>0).map(f=>({position:"before",comments:[...f.comments]}));C.length>0&&(h.positionedComments=h.positionedComments?[...C,...h.positionedComments]:C)}else if(u&&u.length>0){let C={position:"before",comments:[...u]};h.positionedComments=h.positionedComments?[C,...h.positionedComments]:[C]}if(m&&m.length>0){let C=m.filter(f=>f.position==="after"&&f.comments.length>0).map(f=>({position:f.position,comments:[...f.comments]}));C.length>0&&(h.positionedComments=h.positionedComments?[...h.positionedComments,...C]:C)}else p&&p.length>0&&(h.comments=p);return{value:h,newIndex:n}}let i=x.parseArgument(4,8,e,t);return n=i.newIndex,{value:new ee(i.value),newIndex:n}}};var Gn=class{static parseFromLexeme(e,t){let n=t;if(n0?o.positionedComments=i.positionedComments:i.comments&&i.comments.length>0&&(o.comments=i.comments),{value:o,newIndex:n}}throw new Error(`Invalid unary expression at index ${t}: ${e[t].value}`)}};var Yn=class{static parseFromLexeme(e,t){let n=t,i=e[n].value;i.startsWith("${")&&i.endsWith("}")?i=i.slice(2,-1):i=i.slice(1);let r=new N(i);return n++,{value:r,newIndex:n}}};var Xn=class{static parseFromLexeme(e,t){let n=t,i=e[n].value;if(n++,n>=e.length||e[n].type!==1)throw new Error(`Expected string literal after string specifier at index ${n}`);let r=e[n].value;return n++,{value:new ze(i,r),newIndex:n}}};var Zn=class a{static parseFromLexeme(e,t){let n=t,i=e[n];if(i.value==="case"){let r=i.comments,s=i.positionedComments;return n++,this.parseCaseExpression(e,n,r,s)}else if(i.value==="case when"){let r=i.comments,s=i.positionedComments;return n++,this.parseCaseWhenExpression(e,n,r,s)}return this.parseModifierUnaryExpression(e,n)}static parseModifierUnaryExpression(e,t){let n=t;if(n0?u.positionedComments=i:n&&n.length>0&&(u.positionedComments=[a.convertLegacyToPositioned(n,"before")]),{value:u,newIndex:r}}static parseCaseWhenExpression(e,t,n,i){let r=t,s=this.parseCaseConditionValuePair(e,r);r=s.newIndex;let o=[s.value],u=this.parseSwitchCaseArgument(e,r,o);r=u.newIndex;let l=new ue(null,u.value);return i&&i.length>0?l.positionedComments=i:n&&n.length>0&&(l.positionedComments=[a.convertLegacyToPositioned(n,"before")]),{value:l,newIndex:r}}static parseSwitchCaseArgument(e,t,n){let i=t,r=[...n];i=this.parseAdditionalWhenClauses(e,i,r);let{elseValue:s,elseComments:o,newIndex:u}=this.parseElseClause(e,i);i=u;let{endComments:l,newIndex:c}=this.parseEndClause(e,i);if(i=c,r.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${i})`);let p=new Le(r,s);return this.applySwitchCaseComments(p,o,l),{value:p,newIndex:i}}static parseAdditionalWhenClauses(e,t,n){let i=t;for(;i0&&i.push(...t.positioned),t?.legacy&&t.legacy.length>0&&r.push(...t.legacy),n?.positioned&&n.positioned.length>0&&i.push(...n.positioned),n?.legacy&&n.legacy.length>0&&r.push(...n.legacy),i.length>0?e.positionedComments=i:r.length>0&&(e.positionedComments=[a.convertLegacyToPositioned(r,"after")])}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,i=x.parseFromLexeme(e,n);if(n=i.newIndex,n>=e.length||!(e[n].type&128)||e[n].value!=="then")throw new Error(`Expected 'then' after WHEN condition at index ${n}`);let r=e[n].comments,s=e[n].positionedComments;n++;let o=x.parseFromLexeme(e,n);n=o.newIndex;let u=new Ne(i.value,o.value);return s&&s.length>0?u.positionedComments=s:r&&r.length>0&&(u.positionedComments=[a.convertLegacyToPositioned(r,"after")]),{value:u,newIndex:n}}static convertLegacyToPositioned(e,t="before"){return{position:t,comments:e}}};var pt=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)return{value:r,newIndex:n};let s=null,o=null;if(n0){s=[];for(let c of l.positionedComments)c.comments&&c.comments.length>0&&s.push(...c.comments)}l.comments&&l.comments.length>0&&(s||(s=[]),s.push(...l.comments))}}let u=n>=e.length?null:e[n].value==="nulls first"?(n++,"first"):e[n].value==="nulls last"?(n++,"last"):null;return s&&s.length>0&&(r.comments?r.comments.push(...s):r.comments=s),o===null&&u===null?{value:r,newIndex:n}:{value:new Qe(r,o,u),newIndex:n}}};var ei=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=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 Ke(i,r,s),newIndex:n}}static isFrameTypeKeyword(e){let t=e;return t==="rows"||t==="range"||t==="groups"}static parseFrameSpec(e,t){let n=t,i=e[n].value,r;switch(i){case"rows":r="rows";break;case"range":r="range";break;case"groups":r="groups";break;default:throw new Error(`Syntax error at position ${n}: Invalid frame type "${e[n].value}". Expected one of: ROWS, RANGE, GROUPS.`)}if(n++,n=e.length||e[n].value!=="and")throw new Error(`Syntax error at position ${n}: Expected 'AND' keyword in BETWEEN clause.`);n++;let u=this.parseFrameBoundary(e,n),l=u.value;return n=u.newIndex,{value:new it(r,o,l),newIndex:n}}else{let s=this.parseFrameBoundary(e,n),o=s.value;return n=s.newIndex,{value:new it(r,o,null),newIndex:n}}}static parseFrameBoundary(e,t){let n=t;if(n=e.length)throw new Error("Syntax error: Unexpected end of input after 'OVER' keyword. Expected either a window name or an opening parenthesis '('.");if(e[n].type&64){let i=e[n].value;return n++,{value:new I(i),newIndex:n}}if(e[n].type&4)return _t.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 ke=class a extends Error{constructor(t,n,i){super(t);this.index=n;this.context=i;this.name="ParseError"}static fromUnparsedLexemes(t,n,i){let r=Math.max(0,n-2),s=Math.min(t.length,n+3),o=t.slice(r,s).map((l,c)=>{let p=c+r===n?">":" ",m=F[l.type]||l.type;return`${p} ${c+r}:${l.value} [${m}]`}).join(` +`),u=`${i} Unparsed lexeme remains at index ${n}: ${t[n].value} Context: -${o}`;return new a(l,n,o)}};var qe=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+10,{value:C,newIndex:n}}else{let h=new H(r,s.name,l.value,null,p,m,c);return u&&u.length>0,{value:h,newIndex:n}}}else throw ke.fromUnparsedLexemes(e,n,`Expected opening parenthesis after function name '${s.name}'.`)}static parseKeywordFunction(e,t,n){let i=t,r=K.parseFromLexeme(e,i),s=r.namespaces,o=r.name;if(i=r.newIndex,i=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 i=pt.parseFromLexeme(e,n);if(n=i.newIndex,n>=e.length||!(e[n].type&8))throw new Error(`Expected ')' after WITHIN GROUP ORDER BY clause at index ${n}`);return n++,{value:i.value,newIndex:n}}static parseAggregateArguments(e,t){let n=t,i=[],r=null;if(n>=e.length||!(e[n].type&4))throw ke.fromUnparsedLexemes(e,n,"Expected opening parenthesis.");if(n++,n=e.length||!(e[n].type&8))throw ke.fromUnparsedLexemes(e,n,"Expected closing parenthesis.");let o=e[n].comments;return n++,{arguments:i.length===1?i[0]:new W(i),orderByClause:r,closingComments:o,newIndex:n}}static parseArgumentWithComments(e,t){let n=t;if(n>=e.length||!(e[n].type&4))throw ke.fromUnparsedLexemes(e,n,"Expected opening parenthesis.");let i=e[n];n++;let r=[];if(n=e.length||!(e[n].type&8))throw ke.fromUnparsedLexemes(e,n,"Expected closing parenthesis after wildcard '*'.");let c=e[n].comments;return n++,{value:u,closingComments:c,newIndex:n}}let s=x.parseFromLexeme(e,n);if(n=s.newIndex,i.positionedComments&&i.positionedComments.length>0){let u=i.positionedComments.filter(c=>c.position==="after");if(u.length>0){let c=u.map(p=>({position:"before",comments:p.comments}));s.value.positionedComments=[...c,...s.value.positionedComments||[]],s.value,"qualifiedName"in s.value&&s.value.qualifiedName&&"name"in s.value.qualifiedName&&s.value.qualifiedName.name&&(s.value.qualifiedName.name.positionedComments=null,s.value.qualifiedName.name)}}for(r.push(s.value);n=e.length||!(e[n].type&8))throw ke.fromUnparsedLexemes(e,n,"Expected closing parenthesis.");let o=e[n].comments;return n++,{value:r.length===1?r[0]:new W(r),closingComments:o,newIndex:n}}};var Bt=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 x=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex0&&!u.value.positionedComments?u.value.positionedComments=l:u.value.comments===null&&o&&o.length>0&&(u.value.comments=o),s=u.newIndex;let c=u.value,p=this.parseArrayAccess(e,s,c);for(c=p.value,s=p.newIndex;s0&&(V.operator.comments=m.comments),m.positionedComments&&m.positionedComments.length>0&&(V.operator.positionedComments=m.positionedComments),c=V}return{value:c,newIndex:s}}static transferPositionedComments(e,t){e.positionedComments&&e.positionedComments.length>0&&!t.positionedComments?t.positionedComments=e.positionedComments:t.comments===null&&e.comments&&e.comments.length>0&&(t.comments=e.comments)}static parseItem(e,t){let n=t;if(n>=e.length)throw new Error(`Unexpected end of lexemes at index ${t}`);let i=e[n];if(i.type&64&&i.type&2&&i.type&8192){if(n+1=e.length)return this.transferPositionedComments(i,r.value),r;if(e[r.newIndex].type&1){let o=Sn.parseFromLexeme(e,r.newIndex),l=new te(e[n].value,o.value);return this.transferPositionedComments(i,l),{value:l,newIndex:o.newIndex}}return this.transferPositionedComments(i,r.value),r}else if(i.type&64){let{namespaces:r,name:s,newIndex:o}=K.parseFromLexeme(e,n);if(e[o-1].type&2048){let u=qe.parseFromLexeme(e,n);return this.transferPositionedComments(i,u.value),u}else if(e[o-1].type&8192)if(o0){let c=o.positionedComments.filter(p=>p.position==="after");c.length>0&&(u.positionedComments=c.map(p=>({position:"before",comments:p.comments})))}else o.comments&&o.comments.length>0&&(u.comments=o.comments);if(r++,r0){let u=o.positionedComments.filter(c=>c.position==="after");if(u.length>0){let c=u.map(p=>({position:"before",comments:p.comments}));l.value.positionedComments?l.value.positionedComments=[...c,...l.value.positionedComments]:l.value.positionedComments=c}}else o.comments&&o.comments.length>0&&(l.value.comments?l.value.comments=o.comments.concat(l.value.comments):l.value.comments=o.comments);for(s.push(l.value);r=e.length)throw new Error(`Expected array index or slice after '[' at index ${i-1}`);if(e[i].type&1024)throw new Error(`Empty array access brackets not supported at index ${i}`);let s=null,o=!1;if(e[i].type&2&&e[i].value===":")o=!0,i++;else{let l=Bt.getPrecedence(":"),u=this.parseExpressionWithPrecedence(e,i,l+1);s=u.value,i=u.newIndex,i=e.length||!(e[i].type&1024))throw new Error(`Expected ']' after array slice at index ${i}`);i++,r=new lt(r,s,l)}else{if(!s){let l=this.parseFromLexeme(e,i);s=l.value,i=l.newIndex}if(i>=e.length||!(e[i].type&1024))throw new Error(`Expected ']' after array index at index ${i}`);i++,r=new ut(r,s)}}return{value:r,newIndex:i}}static isSqlServerBracketIdentifier(e,t){let n=t+1;if(n>=e.length)return!1;for(;n=e.length)return!1;let i=n;if(i+1this.visitSimpleSelectQuery(e)),this.handlers.set(O.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ae.kind,e=>this.visitValuesQuery(e)),this.handlers.set(he.kind,e=>this.visitWithClause(e)),this.handlers.set(oe.kind,e=>this.visitCommonTable(e)),this.handlers.set(q.kind,e=>this.visitSelectItem(e)),this.handlers.set(I.kind,e=>this.visitIdentifierString(e)),this.handlers.set(R.kind,e=>this.visitRawString(e)),this.handlers.set(E.kind,e=>this.visitColumnReference(e)),this.handlers.set(A.kind,e=>this.visitParameterExpression(e)),this.handlers.set(Z.kind,e=>this.visitLiteralValue(e)),this.handlers.set($.kind,e=>this.visitSourceExpression(e)),this.handlers.set(B.kind,e=>this.visitTableSource(e)),this.handlers.set(nt.kind,e=>this.visitFunctionSource(e)),this.handlers.set(je.kind,e=>this.visitParenSource(e)),this.handlers.set(U.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(de.kind,e=>this.visitInlineQuery(e)),this.handlers.set(_.kind,e=>this.visitFromClause(e)),this.handlers.set(ve.kind,e=>this.visitJoinClause(e)),this.handlers.set(we.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Te.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(re.kind,e=>this.visitWhereClause(e)),this.handlers.set(ee.kind,e=>this.visitParenExpression(e)),this.handlers.set(b.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ue.kind,e=>this.visitCaseExpression(e)),this.handlers.set(Ae.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(Le.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(Ee.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(H.kind,e=>this.visitFunctionCall(e)),this.handlers.set(Se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(be.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(xe.kind,e=>this.visitTupleExpression(e)),this.handlers.set(fe.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ke.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(it.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(De.kind,e=>this.visitTypeValue(e)),this.handlers.set(W.kind,e=>this.visitValueList(e)),this.handlers.set(ze.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(z.kind,e=>this.visitSelectClause(e)),this.handlers.set(ge.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ye.kind,e=>this.visitHavingClause(e)),this.handlers.set(Ce.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Oe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(ce.kind,e=>this.visitLimitClause(e)),this.handlers.set(Re.kind,e=>this.visitForClause(e)),this.handlers.set(Qe.kind,e=>this.visitOrderByItem(e)),this.handlers.set(_e.kind,e=>this.visitPartitionByClause(e))}getCommonTables(){return this.commonTables}reset(){this.commonTables=[],this.visitedNodes.clear()}collect(e){return this.visit(e),this.getCommonTables()}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}let n=e.getKind()?.toString()||"unknown",i=e.constructor?.name||"unknown";throw new Error(`[CTECollector] No handler for ${i} with kind ${n}.`)}visitSimpleSelectQuery(e){if(e.fromClause&&e.fromClause.accept(this),e.whereClause&&e.whereClause.accept(this),e.groupByClause&&e.groupByClause.accept(this),e.havingClause&&e.havingClause.accept(this),e.orderByClause&&e.orderByClause.accept(this),e.windowClause)for(let t of e.windowClause.windows)t.accept(this);e.limitClause&&e.limitClause.accept(this),e.forClause&&e.forClause.accept(this),e.selectClause.accept(this),e.withClause&&e.withClause.accept(this)}visitBinarySelectQuery(e){e.left.accept(this),e.right.accept(this)}visitValuesQuery(e){for(let t of e.tuples)t.accept(this)}visitWithClause(e){for(let t=0;tthis.visitSimpleSelectQuery(e)),this.handlers.set(O.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ae.kind,e=>this.visitValuesQuery(e)),this.handlers.set(q.kind,e=>this.visitSelectItem(e)),this.handlers.set(I.kind,e=>this.visitIdentifierString(e)),this.handlers.set(R.kind,e=>this.visitRawString(e)),this.handlers.set(E.kind,e=>this.visitColumnReference(e)),this.handlers.set(A.kind,e=>this.visitParameterExpression(e)),this.handlers.set(Z.kind,e=>this.visitLiteralValue(e)),this.handlers.set($.kind,e=>this.visitSourceExpression(e)),this.handlers.set(B.kind,e=>this.visitTableSource(e)),this.handlers.set(je.kind,e=>this.visitParenSource(e)),this.handlers.set(U.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(de.kind,e=>this.visitInlineQuery(e)),this.handlers.set(_.kind,e=>this.visitFromClause(e)),this.handlers.set(ve.kind,e=>this.visitJoinClause(e)),this.handlers.set(we.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Te.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(re.kind,e=>this.visitWhereClause(e)),this.handlers.set(ee.kind,e=>this.visitParenExpression(e)),this.handlers.set(b.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ue.kind,e=>this.visitCaseExpression(e)),this.handlers.set(Ae.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(Le.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(Ee.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(H.kind,e=>this.visitFunctionCall(e)),this.handlers.set(Se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(be.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(xe.kind,e=>this.visitTupleExpression(e)),this.handlers.set(fe.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ke.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(it.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(De.kind,e=>this.visitTypeValue(e)),this.handlers.set(W.kind,e=>this.visitValueList(e)),this.handlers.set(lt.kind,e=>this.visitArraySliceExpression(e)),this.handlers.set(ut.kind,e=>this.visitArrayIndexExpression(e)),this.handlers.set(ze.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(z.kind,e=>this.visitSelectClause(e)),this.handlers.set(ge.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ye.kind,e=>this.visitHavingClause(e)),this.handlers.set(Ce.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Oe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(ce.kind,e=>this.visitLimitClause(e)),this.handlers.set(Re.kind,e=>this.visitForClause(e)),this.handlers.set(Qe.kind,e=>this.visitOrderByItem(e)),this.handlers.set(_e.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",i=e.constructor?.name||"unknown";throw new Error(`[CTEDisabler] No handler for ${i} with kind ${n}.`)}visitSimpleSelectQuery(e){return e.withClause&&e.withClause.tables.forEach(t=>{this.visit(t.query)}),e.withClause=null,e.selectClause=this.visit(e.selectClause),e.fromClause=e.fromClause?this.visit(e.fromClause):null,e.whereClause=e.whereClause?this.visit(e.whereClause):null,e.groupByClause=e.groupByClause?this.visit(e.groupByClause):null,e.havingClause=e.havingClause?this.visit(e.havingClause):null,e.orderByClause=e.orderByClause?this.visit(e.orderByClause):null,e.windowClause&&(e.windowClause=new ct(e.windowClause.windows.map(t=>this.visit(t)))),e.limitClause=e.limitClause?this.visit(e.limitClause):null,e.forClause=e.forClause?this.visit(e.forClause):null,e}visitBinarySelectQuery(e){return e.left=this.visit(e.left),e.right=this.visit(e.right),e}visitValuesQuery(e){let t=e.tuples.map(n=>this.visit(n));return new ae(t)}visitSelectClause(e){let t=e.items.map(n=>this.visit(n));return new z(t,e.distinct)}visitFromClause(e){let t=this.visit(e.source),n=e.joins?e.joins.map(i=>this.visit(i)):null;return new _(t,n)}visitSubQuerySource(e){let t=this.visit(e.query);return new U(t)}visitInlineQuery(e){let t=this.visit(e.selectQuery);return new de(t)}visitJoinClause(e){let t=this.visit(e.source),n=e.condition?this.visit(e.condition):null;return new ve(e.joinType.value,t,n,e.lateral)}visitJoinOnClause(e){let t=this.visit(e.condition);return new we(t)}visitJoinUsingClause(e){let t=this.visit(e.condition);return new Te(t)}visitWhereClause(e){let t=this.visit(e.condition);return new re(t)}visitGroupByClause(e){let t=e.grouping.map(n=>this.visit(n));return new ge(t)}visitHavingClause(e){let t=this.visit(e.condition);return new ye(t)}visitOrderByClause(e){let t=e.order.map(n=>this.visit(n));return new Ce(t)}visitWindowFrameClause(e){let t=this.visit(e.expression);return new Oe(e.name.name,t)}visitLimitClause(e){let t=this.visit(e.value);return new ce(t)}visitForClause(e){return new Re(e.lockMode)}visitParenExpression(e){let t=this.visit(e.expression);return new ee(t)}visitBinaryExpression(e){let t=this.visit(e.left),n=this.visit(e.right);return new b(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 ue(t,n)}visitSwitchCaseArgument(e){let t=e.cases.map(i=>this.visit(i)),n=e.elseValue?this.visit(e.elseValue):null;return new Le(t,n)}visitCaseKeyValuePair(e){let t=this.visit(e.key),n=this.visit(e.value);return new Ae(t,n)}visitBetweenExpression(e){let t=this.visit(e.expression),n=this.visit(e.lower),i=this.visit(e.upper);return new Ee(t,n,i,e.negated)}visitFunctionCall(e){let t=e.argument?this.visit(e.argument):null,n=e.over?this.visit(e.over):null;return new H(e.namespaces,e.name,t,n)}visitArrayExpression(e){let t=this.visit(e.expression);return new Se(t)}visitArrayQueryExpression(e){let t=this.visit(e.query);return new be(t)}visitTupleExpression(e){let t=e.values.map(n=>this.visit(n));return new xe(t)}visitCastExpression(e){let t=this.visit(e.input),n=this.visit(e.castType);return new fe(t,n)}visitTypeValue(e){let t=e.argument?this.visit(e.argument):null;return new De(e.namespaces,e.name,t)}visitSelectItem(e){let t=this.visit(e.value);return new q(t,e.identifier?.name)}visitIdentifierString(e){return e}visitRawString(e){return e}visitColumnReference(e){return e}visitSourceExpression(e){let t=this.visit(e.datasource),n=e.aliasExpression;return new $(t,n)}visitTableSource(e){return e}visitParenSource(e){let t=this.visit(e.source);return new je(t)}visitParameterExpression(e){return e}visitWindowFrameExpression(e){let t=e.partition?this.visit(e.partition):null,n=e.order?this.visit(e.order):null,i=e.frameSpec?this.visit(e.frameSpec):null;return new Ke(t,n,i)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new Qe(t,e.sortDirection,e.nullsPosition)}visitValueList(e){let t=e.values.map(n=>this.visit(n));return new W(t)}visitArraySliceExpression(e){return e}visitArrayIndexExpression(e){return e}visitStringSpecifierExpression(e){return e}visitPartitionByClause(e){let t=this.visit(e.value);return new _e(t)}};var rt=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(w.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(O.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ae.kind,t=>this.visitValuesQuery(t)),this.handlers.set(he.kind,t=>this.visitWithClause(t)),this.handlers.set(oe.kind,t=>this.visitCommonTable(t)),this.handlers.set(_.kind,t=>this.visitFromClause(t)),this.handlers.set(ve.kind,t=>this.visitJoinClause(t)),this.handlers.set(we.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(Te.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set($.kind,t=>this.visitSourceExpression(t)),this.handlers.set(B.kind,t=>this.visitTableSource(t)),this.handlers.set(nt.kind,t=>this.visitFunctionSource(t)),this.handlers.set(je.kind,t=>this.visitParenSource(t)),this.handlers.set(U.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(de.kind,t=>this.visitInlineQuery(t)),e||(this.handlers.set(re.kind,t=>this.visitWhereClause(t)),this.handlers.set(ge.kind,t=>this.visitGroupByClause(t)),this.handlers.set(ye.kind,t=>this.visitHavingClause(t)),this.handlers.set(Ce.kind,t=>this.visitOrderByClause(t)),this.handlers.set(Oe.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(ce.kind,t=>this.visitLimitClause(t)),this.handlers.set($e.kind,t=>this.visitOffsetClause(t)),this.handlers.set(He.kind,t=>this.visitFetchClause(t)),this.handlers.set(Re.kind,t=>this.visitForClause(t)),this.handlers.set(Qe.kind,t=>this.visitOrderByItem(t)),this.handlers.set(z.kind,t=>this.visitSelectClause(t)),this.handlers.set(q.kind,t=>this.visitSelectItem(t)),this.handlers.set(ee.kind,t=>this.visitParenExpression(t)),this.handlers.set(b.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(te.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(ue.kind,t=>this.visitCaseExpression(t)),this.handlers.set(Ae.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(Le.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(Ee.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(H.kind,t=>this.visitFunctionCall(t)),this.handlers.set(Se.kind,t=>this.visitArrayExpression(t)),this.handlers.set(be.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(xe.kind,t=>this.visitTupleExpression(t)),this.handlers.set(fe.kind,t=>this.visitCastExpression(t)),this.handlers.set(W.kind,t=>this.visitValueList(t)),this.handlers.set(ze.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 R?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof R?e.qualifiedName.name.value:e.qualifiedName.name.name}collect(e){return this.visit(e),this.getTableSources()}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.selectableOnly||this.collectCTEs(e),this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}collectCTEs(e){let t=new ne;t.visit(e);let n=t.getCommonTables();for(let i of n)this.cteNames.add(i.aliasExpression.table.name)}visitSimpleSelectQuery(e){if(e.fromClause&&e.fromClause.accept(this),!this.selectableOnly){if(e.withClause&&e.withClause.accept(this),e.whereClause&&e.whereClause.accept(this),e.groupByClause&&e.groupByClause.accept(this),e.havingClause&&e.havingClause.accept(this),e.orderByClause&&e.orderByClause.accept(this),e.windowClause)for(let t of e.windowClause.windows)t.accept(this);e.limitClause&&e.limitClause.accept(this),e.offsetClause&&e.offsetClause.accept(this),e.fetchClause&&e.fetchClause.accept(this),e.forClause&&e.forClause.accept(this),e.selectClause.accept(this)}}visitBinarySelectQuery(e){e.left.accept(this),e.right.accept(this)}visitValuesQuery(e){if(!this.selectableOnly)for(let t of e.tuples)t.accept(this)}visitWithClause(e){if(!this.selectableOnly)for(let t of e.tables)t.accept(this)}visitCommonTable(e){this.selectableOnly||e.query.accept(this)}visitFromClause(e){if(e.source.accept(this),e.joins)for(let t of e.joins)t.accept(this)}visitSourceExpression(e){e.datasource.accept(this)}visitTableSource(e){let t=this.getTableIdentifier(e);!this.tableNameMap.has(t)&&!this.isCTETable(e.table.name)&&(this.tableNameMap.set(t,!0),this.tableSources.push(e))}visitFunctionSource(e){e.argument&&this.visitValueComponent(e.argument)}visitValueComponent(e){e.accept(this)}isCTETable(e){return this.cteNames.has(e)}visitParenSource(e){e.source.accept(this)}visitSubQuerySource(e){this.selectableOnly||e.query.accept(this)}visitInlineQuery(e){this.selectableOnly||e.selectQuery.accept(this)}visitJoinClause(e){e.source.accept(this),!this.selectableOnly&&e.condition&&e.condition.accept(this)}visitJoinOnClause(e){this.selectableOnly||e.condition.accept(this)}visitJoinUsingClause(e){this.selectableOnly||e.condition.accept(this)}visitWhereClause(e){e.condition.accept(this)}visitGroupByClause(e){for(let t of e.grouping)t.accept(this)}visitHavingClause(e){e.condition.accept(this)}visitOrderByClause(e){for(let t of e.order)t.accept(this)}visitWindowFrameClause(e){e.expression.accept(this)}visitLimitClause(e){e.value.accept(this)}visitOffsetClause(e){e.value.accept(this)}visitFetchClause(e){e.expression.accept(this)}visitForClause(e){}visitOrderByItem(e){e.value.accept(this)}visitSelectClause(e){for(let t of e.items)t.accept(this)}visitSelectItem(e){e.value.accept(this)}visitParenExpression(e){e.expression.accept(this)}visitBinaryExpression(e){e.left.accept(this),e.right.accept(this)}visitUnaryExpression(e){e.expression.accept(this)}visitCaseExpression(e){e.condition&&e.condition.accept(this),e.switchCase.accept(this)}visitSwitchCaseArgument(e){for(let t of e.cases)t.accept(this);e.elseValue&&e.elseValue.accept(this)}visitCaseKeyValuePair(e){e.key.accept(this),e.value.accept(this)}visitBetweenExpression(e){e.expression.accept(this),e.lower.accept(this),e.upper.accept(this)}visitFunctionCall(e){e.argument&&e.argument.accept(this),e.over&&e.over.accept(this)}visitArrayExpression(e){e.expression.accept(this)}visitArrayQueryExpression(e){e.query.accept(this)}visitTupleExpression(e){for(let t of e.values)t.accept(this)}visitCastExpression(e){e.input.accept(this),e.castType.accept(this)}visitValueList(e){for(let t of e.values)t.accept(this)}visitStringSpecifierExpression(e){}};var Tt=class extends y{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 kt=class{static collect(e){let t=[];function n(i){if(!(!i||typeof i!="object")){i.constructor&&i.constructor.kind===A.kind&&t.push(i);for(let r of Object.keys(i)){let s=i[r];Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&s.constructor&&s.constructor.kind&&n(s)}}}return n(e),t}};var ti=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var ni=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 Ct=class extends y{static{this.kind=Symbol("UpdateQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.updateClause=e.updateClause,this.setClause=e.setClause instanceof Fe?e.setClause:new Fe(e.setClause),this.whereClause=e.whereClause??null,this.fromClause=e.fromClause??null,this.returningClause=e.returning??null}};var gt=class extends y{static{this.kind=Symbol("DeleteQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.deleteClause=e.deleteClause,this.usingClause=e.usingClause??null,this.whereClause=e.whereClause??null,this.returningClause=e.returning??null}};var Ze=class a{constructor(e=null,t=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=e??null,this.commonTableCollector=new ne,this.commonTables=[],this.initialCommonTables=t,this.handlers=new Map,this.handlers.set(w.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(z.kind,n=>this.visitSelectClause(n)),this.handlers.set($.kind,n=>this.visitSourceExpression(n)),this.handlers.set(_.kind,n=>this.visitFromClause(n))}getValues(){return this.selectValues}reset(){this.selectValues=[],this.visitedNodes.clear(),this.initialCommonTables?this.commonTables=this.initialCommonTables:this.commonTables=[]}collect(e){this.visit(e);let t=this.getValues();return this.reset(),t}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}visitSimpleSelectQuery(e){this.commonTables.length===0&&this.initialCommonTables===null&&(this.commonTables=this.commonTableCollector.collect(e)),e.selectClause&&e.selectClause.accept(this);let t=this.selectValues.filter(i=>i.name==="*");if(t.length===0)return;if(this.selectValues.some(i=>i.value instanceof E&&i.value.namespaces===null)){e.fromClause&&this.processFromClause(e.fromClause,!0),this.selectValues=this.selectValues.filter(i=>i.name!=="*");return}let n=t.filter(i=>i.value instanceof E&&i.value.namespaces).map(i=>i.value.getNamespace());if(e.fromClause){let i=e.fromClause.getSourceAliasName();if(i&&n.includes(i)&&this.processFromClause(e.fromClause,!1),e.fromClause.joins)for(let r of e.fromClause.joins){let s=r.getSourceAliasName();s&&n.includes(s)&&this.processJoinClause(r)}}this.selectValues=this.selectValues.filter(i=>i.name!=="*")}processFromClause(e,t){if(e){let n=e.getSourceAliasName();if(this.processSourceExpression(n,e.source),e.joins&&t)for(let i of e.joins)this.processJoinClause(i)}}processJoinClause(e){let t=e.getSourceAliasName();this.processSourceExpression(t,e.source)}processSourceExpression(e,t){let n=this.commonTables.find(i=>i.aliasExpression.table.name===e);if(n){let i=this.commonTables.filter(o=>o.aliasExpression.table.name!==e);new a(this.tableColumnResolver,i).collect(n.query).forEach(o=>{this.addSelectValueAsUnique(o.name,new E(e?[e]:null,o.name))})}else new a(this.tableColumnResolver,this.commonTables).collect(t).forEach(s=>{this.addSelectValueAsUnique(s.name,new E(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 E){let t=e.value.column.name;t==="*"?this.selectValues.push({name:t,value:e.value}):this.addSelectValueAsUnique(t,e.value)}}visitSourceExpression(e){if(e.aliasExpression&&e.aliasExpression.columns){let t=e.getAliasName();e.aliasExpression.columns.forEach(n=>{this.addSelectValueAsUnique(n.name,new E(t?[t]:null,n.name))});return}else if(e.datasource instanceof B){if(this.tableColumnResolver){let t=e.datasource.getSourceName();this.tableColumnResolver(t).forEach(n=>{this.addSelectValueAsUnique(n,new E([t],n))})}return}else if(e.datasource instanceof U){let t=e.getAliasName();new a(this.tableColumnResolver,this.commonTables).collect(e.datasource.query).forEach(r=>{this.addSelectValueAsUnique(r.name,new E(t?[t]:null,r.name))});return}else if(e.datasource instanceof je)return this.visit(e.datasource.source)}visitFromClause(e){e&&this.processFromClause(e,!0)}addSelectValueAsUnique(e,t){this.selectValues.some(n=>n.name===e)||this.selectValues.push({name:e,value:t})}};var It=class extends y{static{this.kind=Symbol("ReferenceDefinition")}constructor(e){super(),this.targetTable=e.targetTable,this.columns=e.columns?[...e.columns]:null,this.matchType=e.matchType??null,this.onDelete=e.onDelete??null,this.onUpdate=e.onUpdate??null,this.deferrable=e.deferrable??null,this.initially=e.initially??null}},et=class extends y{static{this.kind=Symbol("ColumnConstraintDefinition")}constructor(e){super(),this.kind=e.kind,this.constraintName=e.constraintName,this.defaultValue=e.defaultValue,this.checkExpression=e.checkExpression,this.reference=e.reference,this.rawClause=e.rawClause}},We=class extends y{static{this.kind=Symbol("TableConstraintDefinition")}constructor(e){super(),this.kind=e.kind,this.constraintName=e.constraintName,this.columns=e.columns?[...e.columns]:null,this.reference=e.reference,this.checkExpression=e.checkExpression,this.rawClause=e.rawClause,this.deferrable=e.deferrable??null,this.initially=e.initially??null}},Gt=class extends y{static{this.kind=Symbol("TableColumnDefinition")}constructor(e){super(),this.name=e.name,this.dataType=e.dataType,this.constraints=e.constraints?[...e.constraints]:[]}},Pt=class extends y{static{this.kind=Symbol("CreateTableQuery")}constructor(e){super(),this.tableName=new I(e.tableName),this.namespaces=e.namespaces?[...e.namespaces]:null,this.isTemporary=e.isTemporary??!1,this.ifNotExists=e.ifNotExists??!1,this.columns=e.columns?[...e.columns]:[],this.tableConstraints=e.tableConstraints?[...e.tableConstraints]:[],this.tableOptions=e.tableOptions??null,this.asSelectQuery=e.asSelectQuery}getSelectQuery(){let e;this.asSelectQuery?e=new Ze().collect(this.asSelectQuery).map(r=>new q(r.value,r.name)):this.columns.length>0?e=this.columns.map(n=>new q(new E(null,n.name),n.name.name)):e=[new q(new R("*"))];let t=this.namespaces&&this.namespaces.length>0?[...this.namespaces,this.tableName.name].join("."):this.tableName.name;return new w({selectClause:new z(e),fromClause:new _(new $(new B(null,t),null),null)})}getCountQuery(){let e=this.namespaces&&this.namespaces.length>0?[...this.namespaces,this.tableName.name].join("."):this.tableName.name;return new w({selectClause:new z([new q(new H(null,"count",new E(null,"*"),null))]),fromClause:new _(new $(new B(null,e),null),null)})}};var Yt=class extends y{static{this.kind=Symbol("MergeAction")}},Lt=class extends Yt{static{this.kind=Symbol("MergeUpdateAction")}constructor(e,t){super(),this.setClause=e instanceof Fe?e:new Fe(e),this.whereClause=t??null}},yt=class extends Yt{static{this.kind=Symbol("MergeDeleteAction")}constructor(e){super(),this.whereClause=e??null}},wt=class extends Yt{static{this.kind=Symbol("MergeInsertAction")}constructor(e){super(),this.columns=e.columns?e.columns.map(t=>typeof t=="string"?new I(t):t):null,this.values=e.values??null,this.defaultValues=e.defaultValues??!1}},mt=class extends Yt{static{this.kind=Symbol("MergeDoNothingAction")}},Ge=class extends y{static{this.kind=Symbol("MergeWhenClause")}constructor(e,t,n){super(),this.matchType=e,this.action=t,this.condition=n??null}},vt=class extends y{static{this.kind=Symbol("MergeQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.target=e.target,this.source=e.source,this.onCondition=e.onCondition,this.whenClauses=e.whenClauses}};var Xt=class extends y{static{this.kind=Symbol("DropTableStatement")}constructor(e){super(),this.tables=e.tables.map(t=>new G(t.namespaces,t.name)),this.ifExists=e.ifExists??!1,this.behavior=e.behavior??null}},Zt=class extends y{static{this.kind=Symbol("DropIndexStatement")}constructor(e){super(),this.indexNames=e.indexNames.map(t=>new G(t.namespaces,t.name)),this.ifExists=e.ifExists??!1,this.concurrently=e.concurrently??!1,this.behavior=e.behavior??null}},Mt=class extends y{static{this.kind=Symbol("IndexColumnDefinition")}constructor(e){super(),this.expression=e.expression,this.sortOrder=e.sortOrder??null,this.nullsOrder=e.nullsOrder??null,this.collation=e.collation??null,this.operatorClass=e.operatorClass??null}},en=class extends y{static{this.kind=Symbol("CreateIndexStatement")}constructor(e){super(),this.unique=e.unique??!1,this.concurrently=e.concurrently??!1,this.ifNotExists=e.ifNotExists??!1,this.indexName=new G(e.indexName.namespaces,e.indexName.name),this.tableName=new G(e.tableName.namespaces,e.tableName.name),this.usingMethod=e.usingMethod??null,this.columns=e.columns.map(t=>new Mt({expression:t.expression,sortOrder:t.sortOrder,nullsOrder:t.nullsOrder,collation:t.collation??null,operatorClass:t.operatorClass??null})),this.include=e.include?[...e.include]:null,this.where=e.where,this.withOptions=e.withOptions??null,this.tablespace=e.tablespace??null}},tn=class extends y{static{this.kind=Symbol("AlterTableAddConstraint")}constructor(e){super(),this.constraint=e.constraint,this.ifNotExists=e.ifNotExists??!1,this.notValid=e.notValid??!1}},nn=class extends y{static{this.kind=Symbol("AlterTableDropConstraint")}constructor(e){super(),this.constraintName=e.constraintName,this.ifExists=e.ifExists??!1,this.behavior=e.behavior??null}},rn=class extends y{static{this.kind=Symbol("AlterTableStatement")}constructor(e){super(),this.table=new G(e.table.namespaces,e.table.name),this.only=e.only??!1,this.ifExists=e.ifExists??!1,this.actions=e.actions.map(t=>t)}},sn=class extends y{static{this.kind=Symbol("DropConstraintStatement")}constructor(e){super(),this.constraintName=e.constraintName,this.ifExists=e.ifExists??!1,this.behavior=e.behavior??null}};var wr={mysql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},postgres:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed",castStyle:"postgres"},postgresWithNamedParams:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named",castStyle:"postgres"},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",castStyle:"postgres"},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",castStyle:"postgres"},flinksql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},mongodb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"}},ii=class a{constructor(e){this.handlers=new Map;this.index=1;e?.preset&&(e={...e.preset,...e}),this.parameterDecorator=new ni({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 ti({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.castStyle=e?.castStyle??"standard",this.handlers.set(W.kind,t=>this.visitValueList(t)),this.handlers.set(E.kind,t=>this.visitColumnReference(t)),this.handlers.set(G.kind,t=>this.visitQualifiedName(t)),this.handlers.set(H.kind,t=>this.visitFunctionCall(t)),this.handlers.set(te.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(b.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(Z.kind,t=>this.visitLiteralValue(t)),this.handlers.set(A.kind,t=>this.visitParameterExpression(t)),this.handlers.set(Le.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(Ae.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(R.kind,t=>this.visitRawString(t)),this.handlers.set(I.kind,t=>this.visitIdentifierString(t)),this.handlers.set(ee.kind,t=>this.visitParenExpression(t)),this.handlers.set(fe.kind,t=>this.visitCastExpression(t)),this.handlers.set(ue.kind,t=>this.visitCaseExpression(t)),this.handlers.set(Se.kind,t=>this.visitArrayExpression(t)),this.handlers.set(be.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(lt.kind,t=>this.visitArraySliceExpression(t)),this.handlers.set(ut.kind,t=>this.visitArrayIndexExpression(t)),this.handlers.set(Ee.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(ze.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(De.kind,t=>this.visitTypeValue(t)),this.handlers.set(xe.kind,t=>this.visitTupleExpression(t)),this.handlers.set(de.kind,t=>this.visitInlineQuery(t)),this.handlers.set(Ke.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(it.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(Ut.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(Kt.kind,t=>this.visitWindowFrameBoundaryValue(t)),this.handlers.set(_e.kind,t=>this.visitPartitionByClause(t)),this.handlers.set(Ce.kind,t=>this.visitOrderByClause(t)),this.handlers.set(Qe.kind,t=>this.visitOrderByItem(t)),this.handlers.set(q.kind,t=>this.visitSelectItem(t)),this.handlers.set(z.kind,t=>this.visitSelectClause(t)),this.handlers.set(jt.kind,t=>this.visitDistinct(t)),this.handlers.set(qt.kind,t=>this.visitDistinctOn(t)),this.handlers.set(Tt.kind,t=>this.visitHintClause(t)),this.handlers.set(B.kind,t=>this.visitTableSource(t)),this.handlers.set(nt.kind,t=>this.visitFunctionSource(t)),this.handlers.set($.kind,t=>this.visitSourceExpression(t)),this.handlers.set(se.kind,t=>this.visitSourceAliasExpression(t)),this.handlers.set(_.kind,t=>this.visitFromClause(t)),this.handlers.set(ve.kind,t=>this.visitJoinClause(t)),this.handlers.set(we.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(Te.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(re.kind,t=>this.visitWhereClause(t)),this.handlers.set(ge.kind,t=>this.visitGroupByClause(t)),this.handlers.set(ye.kind,t=>this.visitHavingClause(t)),this.handlers.set(ct.kind,t=>this.visitWindowClause(t)),this.handlers.set(Oe.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(ce.kind,t=>this.visitLimitClause(t)),this.handlers.set($e.kind,t=>this.visitOffsetClause(t)),this.handlers.set(He.kind,t=>this.visitFetchClause(t)),this.handlers.set(Ft.kind,t=>this.visitFetchExpression(t)),this.handlers.set(Re.kind,t=>this.visitForClause(t)),this.handlers.set(he.kind,t=>this.visitWithClause(t)),this.handlers.set(oe.kind,t=>this.visitCommonTable(t)),this.handlers.set(w.kind,t=>this.visitSimpleQuery(t)),this.handlers.set(U.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(O.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ae.kind,t=>this.visitValuesQuery(t)),this.handlers.set(xe.kind,t=>this.visitTupleExpression(t)),this.handlers.set(tt.kind,t=>this.visitInsertQuery(t)),this.handlers.set(xt.kind,t=>this.visitInsertClause(t)),this.handlers.set(Ct.kind,t=>this.visitUpdateQuery(t)),this.handlers.set(bt.kind,t=>this.visitUpdateClause(t)),this.handlers.set(gt.kind,t=>this.visitDeleteQuery(t)),this.handlers.set(Et.kind,t=>this.visitDeleteClause(t)),this.handlers.set(Jt.kind,t=>this.visitUsingClause(t)),this.handlers.set(Fe.kind,t=>this.visitSetClause(t)),this.handlers.set(Xe.kind,t=>this.visitSetClauseItem(t)),this.handlers.set(zt.kind,t=>this.visitReturningClause(t)),this.handlers.set(Pt.kind,t=>this.visitCreateTableQuery(t)),this.handlers.set(Gt.kind,t=>this.visitTableColumnDefinition(t)),this.handlers.set(et.kind,t=>this.visitColumnConstraintDefinition(t)),this.handlers.set(We.kind,t=>this.visitTableConstraintDefinition(t)),this.handlers.set(It.kind,t=>this.visitReferenceDefinition(t)),this.handlers.set(en.kind,t=>this.visitCreateIndexStatement(t)),this.handlers.set(Mt.kind,t=>this.visitIndexColumnDefinition(t)),this.handlers.set(Xt.kind,t=>this.visitDropTableStatement(t)),this.handlers.set(Zt.kind,t=>this.visitDropIndexStatement(t)),this.handlers.set(rn.kind,t=>this.visitAlterTableStatement(t)),this.handlers.set(tn.kind,t=>this.visitAlterTableAddConstraint(t)),this.handlers.set(nn.kind,t=>this.visitAlterTableDropConstraint(t)),this.handlers.set(sn.kind,t=>this.visitDropConstraintStatement(t)),this.handlers.set(vt.kind,t=>this.visitMergeQuery(t)),this.handlers.set(Ge.kind,t=>this.visitMergeWhenClause(t)),this.handlers.set(Lt.kind,t=>this.visitMergeUpdateAction(t)),this.handlers.set(yt.kind,t=>this.visitMergeDeleteAction(t)),this.handlers.set(wt.kind,t=>this.visitMergeInsertAction(t)),this.handlers.set(mt.kind,t=>this.visitMergeDoNothingAction(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,".")}static{this._selfHandlingComponentTypes=null}static getSelfHandlingComponentTypes(){return this._selfHandlingComponentTypes||(this._selfHandlingComponentTypes=new Set([w.kind,q.kind,Ae.kind,Le.kind,E.kind,Z.kind,A.kind,B.kind,se.kind,De.kind,H.kind,I.kind,G.kind])),this._selfHandlingComponentTypes}visitBinarySelectQuery(e){let t=new d(0,"");if(e.positionedComments&&e.positionedComments.length>0)this.addPositionedCommentsToToken(t,e),e.positionedComments=null;else if(e.headerComments&&e.headerComments.length>0){if(this.shouldMergeHeaderComments(e.headerComments)){let n=this.createHeaderMultiLineCommentBlock(e.headerComments);t.innerTokens.push(n)}else{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 s=0;s0&&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=kt.collect(e).sort((r,s)=>(r.index??0)-(s.index??0)),i=this.parameterDecorator.style;if(i==="named"){let r={};for(let s of n){let o=s.name.value;if(r.hasOwnProperty(o)){if(r[o]!==s.value)throw new Error(`Duplicate parameter name '${o}' with different values detected during query composition.`);continue}r[o]=s.value}return{token:t,params:r}}else if(i==="indexed"){let r=n.map(s=>s.value);return{token:t,params:r}}else if(i==="anonymous"){let r=n.map(s=>s.value);return{token:t,params:r}}return{token:t,params:[]}}componentHandlesOwnComments(e){return"handlesOwnComments"in e&&typeof e.handlesOwnComments=="function"?e.handlesOwnComments():a.getSelfHandlingComponentTypes().has(e.getKind())}visit(e){let t=this.handlers.get(e.getKind());if(t){let n=t(e);return this.componentHandlesOwnComments(e)||this.addComponentComments(n,e),n}throw new Error(`[SqlPrintTokenParser] No handler for kind: ${e.getKind().toString()}`)}hasPositionedComments(e){return(e.positionedComments?.length??0)>0}hasLegacyComments(e){return(e.comments?.length??0)>0}addComponentComments(e,t){this.hasPositionedComments(t)?this.addPositionedCommentsToToken(e,t):this.hasLegacyComments(t)&&this.addCommentsToToken(e,t.comments)}addPositionedCommentsToToken(e,t){if(!this.hasPositionedComments(t))return;let n=t.getPositionedComments("before");if(n.length>0){let s=this.createCommentBlocks(n);for(let o=s.length-1;o>=0;o--)e.innerTokens.unshift(s[o])}let i=t.getPositionedComments("after");if(i.length>0){let s=this.createCommentBlocks(i);for(let o of s)e.innerTokens.push(a.SPACE_TOKEN),e.innerTokens.push(o)}let r=["CaseExpression","SwitchCaseArgument","CaseKeyValuePair","SelectClause","LiteralValue","IdentifierString","DistinctOn","SourceAliasExpression","SimpleSelectQuery","WhereClause"];e.containerType&&r.includes(e.containerType)&&(t.positionedComments=null)}addCommentsToToken(e,t){if(!t?.length)return;let n=this.createCommentBlocks(t);this.insertCommentBlocksWithSpacing(e,n)}createInlineCommentSequence(e){let t=[];for(let n=0;n0,{value:C,newIndex:n}}else{let h=new H(r,s.name,u.value,null,p,m,c);return l&&l.length>0,{value:h,newIndex:n}}}else throw ke.fromUnparsedLexemes(e,n,`Expected opening parenthesis after function name '${s.name}'.`)}static parseKeywordFunction(e,t,n){let i=t,r=j.parseFromLexeme(e,i),s=r.namespaces,o=r.name;if(i=r.newIndex,i=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 i=pt.parseFromLexeme(e,n);if(n=i.newIndex,n>=e.length||!(e[n].type&8))throw new Error(`Expected ')' after WITHIN GROUP ORDER BY clause at index ${n}`);return n++,{value:i.value,newIndex:n}}static parseAggregateArguments(e,t){let n=t,i=[],r=null;if(n>=e.length||!(e[n].type&4))throw ke.fromUnparsedLexemes(e,n,"Expected opening parenthesis.");if(n++,n=e.length||!(e[n].type&8))throw ke.fromUnparsedLexemes(e,n,"Expected closing parenthesis.");let o=e[n].comments;return n++,{arguments:i.length===1?i[0]:new W(i),orderByClause:r,closingComments:o,newIndex:n}}static parseArgumentWithComments(e,t){let n=t;if(n>=e.length||!(e[n].type&4))throw ke.fromUnparsedLexemes(e,n,"Expected opening parenthesis.");let i=e[n];n++;let r=[];if(n=e.length||!(e[n].type&8))throw ke.fromUnparsedLexemes(e,n,"Expected closing parenthesis after wildcard '*'.");let c=e[n].comments;return n++,{value:l,closingComments:c,newIndex:n}}let s=x.parseFromLexeme(e,n);if(n=s.newIndex,i.positionedComments&&i.positionedComments.length>0){let l=i.positionedComments.filter(c=>c.position==="after");if(l.length>0){let c=l.map(p=>({position:"before",comments:p.comments}));s.value.positionedComments=[...c,...s.value.positionedComments||[]],s.value,"qualifiedName"in s.value&&s.value.qualifiedName&&"name"in s.value.qualifiedName&&s.value.qualifiedName.name&&(s.value.qualifiedName.name.positionedComments=null,s.value.qualifiedName.name)}}for(r.push(s.value);n=e.length||!(e[n].type&8))throw ke.fromUnparsedLexemes(e,n,"Expected closing parenthesis.");let o=e[n].comments;return n++,{value:r.length===1?r[0]:new W(r),closingComments:o,newIndex:n}}};var Bt=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 x=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex0&&!l.value.positionedComments?l.value.positionedComments=u:l.value.comments===null&&o&&o.length>0&&(l.value.comments=o),s=l.newIndex;let c=l.value,p=this.parseArrayAccess(e,s,c);for(c=p.value,s=p.newIndex;s0&&(V.operator.comments=m.comments),m.positionedComments&&m.positionedComments.length>0&&(V.operator.positionedComments=m.positionedComments),c=V}return{value:c,newIndex:s}}static transferPositionedComments(e,t){e.positionedComments&&e.positionedComments.length>0&&!t.positionedComments?t.positionedComments=e.positionedComments:t.comments===null&&e.comments&&e.comments.length>0&&(t.comments=e.comments)}static parseItem(e,t){let n=t;if(n>=e.length)throw new Error(`Unexpected end of lexemes at index ${t}`);let i=e[n];if(i.type&64&&i.type&2&&i.type&8192){if(n+1=e.length)return this.transferPositionedComments(i,r.value),r;if(e[r.newIndex].type&1){let o=Sn.parseFromLexeme(e,r.newIndex),u=new te(e[n].value,o.value);return this.transferPositionedComments(i,u),{value:u,newIndex:o.newIndex}}return this.transferPositionedComments(i,r.value),r}else if(i.type&64){let{namespaces:r,name:s,newIndex:o}=j.parseFromLexeme(e,n);if(e[o-1].type&2048){let l=qe.parseFromLexeme(e,n);return this.transferPositionedComments(i,l.value),l}else if(e[o-1].type&8192)if(o0){let c=o.positionedComments.filter(p=>p.position==="after");c.length>0&&(l.positionedComments=c.map(p=>({position:"before",comments:p.comments})))}else o.comments&&o.comments.length>0&&(l.comments=o.comments);if(r++,r0){let l=o.positionedComments.filter(c=>c.position==="after");if(l.length>0){let c=l.map(p=>({position:"before",comments:p.comments}));u.value.positionedComments?u.value.positionedComments=[...c,...u.value.positionedComments]:u.value.positionedComments=c}}else o.comments&&o.comments.length>0&&(u.value.comments?u.value.comments=o.comments.concat(u.value.comments):u.value.comments=o.comments);for(s.push(u.value);r=e.length)throw new Error(`Expected array index or slice after '[' at index ${i-1}`);if(e[i].type&1024)throw new Error(`Empty array access brackets not supported at index ${i}`);let s=null,o=!1;if(e[i].type&2&&e[i].value===":")o=!0,i++;else{let u=Bt.getPrecedence(":"),l=this.parseExpressionWithPrecedence(e,i,u+1);s=l.value,i=l.newIndex,i=e.length||!(e[i].type&1024))throw new Error(`Expected ']' after array slice at index ${i}`);i++,r=new lt(r,s,u)}else{if(!s){let u=this.parseFromLexeme(e,i);s=u.value,i=u.newIndex}if(i>=e.length||!(e[i].type&1024))throw new Error(`Expected ']' after array index at index ${i}`);i++,r=new ut(r,s)}}return{value:r,newIndex:i}}static isSqlServerBracketIdentifier(e,t){let n=t+1;if(n>=e.length)return!1;for(;n=e.length)return!1;let i=n;if(i+1this.visitSimpleSelectQuery(e)),this.handlers.set(O.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ae.kind,e=>this.visitValuesQuery(e)),this.handlers.set(he.kind,e=>this.visitWithClause(e)),this.handlers.set(oe.kind,e=>this.visitCommonTable(e)),this.handlers.set(J.kind,e=>this.visitSelectItem(e)),this.handlers.set(I.kind,e=>this.visitIdentifierString(e)),this.handlers.set(R.kind,e=>this.visitRawString(e)),this.handlers.set(E.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($.kind,e=>this.visitSourceExpression(e)),this.handlers.set(B.kind,e=>this.visitTableSource(e)),this.handlers.set(nt.kind,e=>this.visitFunctionSource(e)),this.handlers.set(je.kind,e=>this.visitParenSource(e)),this.handlers.set(K.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(de.kind,e=>this.visitInlineQuery(e)),this.handlers.set(_.kind,e=>this.visitFromClause(e)),this.handlers.set(ve.kind,e=>this.visitJoinClause(e)),this.handlers.set(we.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Te.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(re.kind,e=>this.visitWhereClause(e)),this.handlers.set(ee.kind,e=>this.visitParenExpression(e)),this.handlers.set(b.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ue.kind,e=>this.visitCaseExpression(e)),this.handlers.set(Ne.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(Le.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(Ee.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(H.kind,e=>this.visitFunctionCall(e)),this.handlers.set(Se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(be.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(xe.kind,e=>this.visitTupleExpression(e)),this.handlers.set(fe.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ke.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(it.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(De.kind,e=>this.visitTypeValue(e)),this.handlers.set(W.kind,e=>this.visitValueList(e)),this.handlers.set(ze.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(z.kind,e=>this.visitSelectClause(e)),this.handlers.set(ye.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ge.kind,e=>this.visitHavingClause(e)),this.handlers.set(Ce.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Oe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(ce.kind,e=>this.visitLimitClause(e)),this.handlers.set(Re.kind,e=>this.visitForClause(e)),this.handlers.set(Qe.kind,e=>this.visitOrderByItem(e)),this.handlers.set(_e.kind,e=>this.visitPartitionByClause(e))}getCommonTables(){return this.commonTables}reset(){this.commonTables=[],this.visitedNodes.clear()}collect(e){return this.visit(e),this.getCommonTables()}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}let n=e.getKind()?.toString()||"unknown",i=e.constructor?.name||"unknown";throw new Error(`[CTECollector] No handler for ${i} with kind ${n}.`)}visitSimpleSelectQuery(e){if(e.fromClause&&e.fromClause.accept(this),e.whereClause&&e.whereClause.accept(this),e.groupByClause&&e.groupByClause.accept(this),e.havingClause&&e.havingClause.accept(this),e.orderByClause&&e.orderByClause.accept(this),e.windowClause)for(let t of e.windowClause.windows)t.accept(this);e.limitClause&&e.limitClause.accept(this),e.forClause&&e.forClause.accept(this),e.selectClause.accept(this),e.withClause&&e.withClause.accept(this)}visitBinarySelectQuery(e){e.left.accept(this),e.right.accept(this)}visitValuesQuery(e){for(let t of e.tuples)t.accept(this)}visitWithClause(e){for(let t=0;tthis.visitSimpleSelectQuery(e)),this.handlers.set(O.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ae.kind,e=>this.visitValuesQuery(e)),this.handlers.set(J.kind,e=>this.visitSelectItem(e)),this.handlers.set(I.kind,e=>this.visitIdentifierString(e)),this.handlers.set(R.kind,e=>this.visitRawString(e)),this.handlers.set(E.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($.kind,e=>this.visitSourceExpression(e)),this.handlers.set(B.kind,e=>this.visitTableSource(e)),this.handlers.set(je.kind,e=>this.visitParenSource(e)),this.handlers.set(K.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(de.kind,e=>this.visitInlineQuery(e)),this.handlers.set(_.kind,e=>this.visitFromClause(e)),this.handlers.set(ve.kind,e=>this.visitJoinClause(e)),this.handlers.set(we.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Te.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(re.kind,e=>this.visitWhereClause(e)),this.handlers.set(ee.kind,e=>this.visitParenExpression(e)),this.handlers.set(b.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ue.kind,e=>this.visitCaseExpression(e)),this.handlers.set(Ne.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(Le.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(Ee.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(H.kind,e=>this.visitFunctionCall(e)),this.handlers.set(Se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(be.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(xe.kind,e=>this.visitTupleExpression(e)),this.handlers.set(fe.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ke.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(it.kind,e=>this.visitWindowFrameSpec(e)),this.handlers.set(De.kind,e=>this.visitTypeValue(e)),this.handlers.set(W.kind,e=>this.visitValueList(e)),this.handlers.set(lt.kind,e=>this.visitArraySliceExpression(e)),this.handlers.set(ut.kind,e=>this.visitArrayIndexExpression(e)),this.handlers.set(ze.kind,e=>this.visitStringSpecifierExpression(e)),this.handlers.set(z.kind,e=>this.visitSelectClause(e)),this.handlers.set(ye.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ge.kind,e=>this.visitHavingClause(e)),this.handlers.set(Ce.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Oe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(ce.kind,e=>this.visitLimitClause(e)),this.handlers.set(Re.kind,e=>this.visitForClause(e)),this.handlers.set(Qe.kind,e=>this.visitOrderByItem(e)),this.handlers.set(_e.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",i=e.constructor?.name||"unknown";throw new Error(`[CTEDisabler] No handler for ${i} with kind ${n}.`)}visitSimpleSelectQuery(e){return e.withClause&&e.withClause.tables.forEach(t=>{this.visit(t.query)}),e.withClause=null,e.selectClause=this.visit(e.selectClause),e.fromClause=e.fromClause?this.visit(e.fromClause):null,e.whereClause=e.whereClause?this.visit(e.whereClause):null,e.groupByClause=e.groupByClause?this.visit(e.groupByClause):null,e.havingClause=e.havingClause?this.visit(e.havingClause):null,e.orderByClause=e.orderByClause?this.visit(e.orderByClause):null,e.windowClause&&(e.windowClause=new ct(e.windowClause.windows.map(t=>this.visit(t)))),e.limitClause=e.limitClause?this.visit(e.limitClause):null,e.forClause=e.forClause?this.visit(e.forClause):null,e}visitBinarySelectQuery(e){return e.left=this.visit(e.left),e.right=this.visit(e.right),e}visitValuesQuery(e){let t=e.tuples.map(n=>this.visit(n));return new ae(t)}visitSelectClause(e){let t=e.items.map(n=>this.visit(n));return new z(t,e.distinct)}visitFromClause(e){let t=this.visit(e.source),n=e.joins?e.joins.map(i=>this.visit(i)):null;return new _(t,n)}visitSubQuerySource(e){let t=this.visit(e.query);return new K(t)}visitInlineQuery(e){let t=this.visit(e.selectQuery);return new de(t)}visitJoinClause(e){let t=this.visit(e.source),n=e.condition?this.visit(e.condition):null;return new ve(e.joinType.value,t,n,e.lateral)}visitJoinOnClause(e){let t=this.visit(e.condition);return new we(t)}visitJoinUsingClause(e){let t=this.visit(e.condition);return new Te(t)}visitWhereClause(e){let t=this.visit(e.condition);return new re(t)}visitGroupByClause(e){let t=e.grouping.map(n=>this.visit(n));return new ye(t)}visitHavingClause(e){let t=this.visit(e.condition);return new ge(t)}visitOrderByClause(e){let t=e.order.map(n=>this.visit(n));return new Ce(t)}visitWindowFrameClause(e){let t=this.visit(e.expression);return new Oe(e.name.name,t)}visitLimitClause(e){let t=this.visit(e.value);return new ce(t)}visitForClause(e){return new Re(e.lockMode)}visitParenExpression(e){let t=this.visit(e.expression);return new ee(t)}visitBinaryExpression(e){let t=this.visit(e.left),n=this.visit(e.right);return new b(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 ue(t,n)}visitSwitchCaseArgument(e){let t=e.cases.map(i=>this.visit(i)),n=e.elseValue?this.visit(e.elseValue):null;return new Le(t,n)}visitCaseKeyValuePair(e){let t=this.visit(e.key),n=this.visit(e.value);return new Ne(t,n)}visitBetweenExpression(e){let t=this.visit(e.expression),n=this.visit(e.lower),i=this.visit(e.upper);return new Ee(t,n,i,e.negated)}visitFunctionCall(e){let t=e.argument?this.visit(e.argument):null,n=e.over?this.visit(e.over):null;return new H(e.namespaces,e.name,t,n)}visitArrayExpression(e){let t=this.visit(e.expression);return new Se(t)}visitArrayQueryExpression(e){let t=this.visit(e.query);return new be(t)}visitTupleExpression(e){let t=e.values.map(n=>this.visit(n));return new xe(t)}visitCastExpression(e){let t=this.visit(e.input),n=this.visit(e.castType);return new fe(t,n)}visitTypeValue(e){let t=e.argument?this.visit(e.argument):null;return new De(e.namespaces,e.name,t)}visitSelectItem(e){let t=this.visit(e.value);return new J(t,e.identifier?.name)}visitIdentifierString(e){return e}visitRawString(e){return e}visitColumnReference(e){return e}visitSourceExpression(e){let t=this.visit(e.datasource),n=e.aliasExpression;return new $(t,n)}visitTableSource(e){return e}visitParenSource(e){let t=this.visit(e.source);return new je(t)}visitParameterExpression(e){return e}visitWindowFrameExpression(e){let t=e.partition?this.visit(e.partition):null,n=e.order?this.visit(e.order):null,i=e.frameSpec?this.visit(e.frameSpec):null;return new Ke(t,n,i)}visitWindowFrameSpec(e){return e}visitLiteralValue(e){return e}visitOrderByItem(e){let t=this.visit(e.value);return new Qe(t,e.sortDirection,e.nullsPosition)}visitValueList(e){let t=e.values.map(n=>this.visit(n));return new W(t)}visitArraySliceExpression(e){return e}visitArrayIndexExpression(e){return e}visitStringSpecifierExpression(e){return e}visitPartitionByClause(e){let t=this.visit(e.value);return new _e(t)}};var rt=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(w.kind,t=>this.visitSimpleSelectQuery(t)),this.handlers.set(O.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ae.kind,t=>this.visitValuesQuery(t)),this.handlers.set(he.kind,t=>this.visitWithClause(t)),this.handlers.set(oe.kind,t=>this.visitCommonTable(t)),this.handlers.set(_.kind,t=>this.visitFromClause(t)),this.handlers.set(ve.kind,t=>this.visitJoinClause(t)),this.handlers.set(we.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(Te.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set($.kind,t=>this.visitSourceExpression(t)),this.handlers.set(B.kind,t=>this.visitTableSource(t)),this.handlers.set(nt.kind,t=>this.visitFunctionSource(t)),this.handlers.set(je.kind,t=>this.visitParenSource(t)),this.handlers.set(K.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(de.kind,t=>this.visitInlineQuery(t)),e||(this.handlers.set(re.kind,t=>this.visitWhereClause(t)),this.handlers.set(ye.kind,t=>this.visitGroupByClause(t)),this.handlers.set(ge.kind,t=>this.visitHavingClause(t)),this.handlers.set(Ce.kind,t=>this.visitOrderByClause(t)),this.handlers.set(Oe.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(ce.kind,t=>this.visitLimitClause(t)),this.handlers.set($e.kind,t=>this.visitOffsetClause(t)),this.handlers.set(He.kind,t=>this.visitFetchClause(t)),this.handlers.set(Re.kind,t=>this.visitForClause(t)),this.handlers.set(Qe.kind,t=>this.visitOrderByItem(t)),this.handlers.set(z.kind,t=>this.visitSelectClause(t)),this.handlers.set(J.kind,t=>this.visitSelectItem(t)),this.handlers.set(ee.kind,t=>this.visitParenExpression(t)),this.handlers.set(b.kind,t=>this.visitBinaryExpression(t)),this.handlers.set(te.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(ue.kind,t=>this.visitCaseExpression(t)),this.handlers.set(Ne.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(Le.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(Ee.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(H.kind,t=>this.visitFunctionCall(t)),this.handlers.set(Se.kind,t=>this.visitArrayExpression(t)),this.handlers.set(be.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(xe.kind,t=>this.visitTupleExpression(t)),this.handlers.set(fe.kind,t=>this.visitCastExpression(t)),this.handlers.set(W.kind,t=>this.visitValueList(t)),this.handlers.set(ze.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 R?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof R?e.qualifiedName.name.value:e.qualifiedName.name.name}collect(e){return this.visit(e),this.getTableSources()}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.selectableOnly||this.collectCTEs(e),this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}collectCTEs(e){let t=new ne;t.visit(e);let n=t.getCommonTables();for(let i of n)this.cteNames.add(i.aliasExpression.table.name)}visitSimpleSelectQuery(e){if(e.fromClause&&e.fromClause.accept(this),!this.selectableOnly){if(e.withClause&&e.withClause.accept(this),e.whereClause&&e.whereClause.accept(this),e.groupByClause&&e.groupByClause.accept(this),e.havingClause&&e.havingClause.accept(this),e.orderByClause&&e.orderByClause.accept(this),e.windowClause)for(let t of e.windowClause.windows)t.accept(this);e.limitClause&&e.limitClause.accept(this),e.offsetClause&&e.offsetClause.accept(this),e.fetchClause&&e.fetchClause.accept(this),e.forClause&&e.forClause.accept(this),e.selectClause.accept(this)}}visitBinarySelectQuery(e){e.left.accept(this),e.right.accept(this)}visitValuesQuery(e){if(!this.selectableOnly)for(let t of e.tuples)t.accept(this)}visitWithClause(e){if(!this.selectableOnly)for(let t of e.tables)t.accept(this)}visitCommonTable(e){this.selectableOnly||e.query.accept(this)}visitFromClause(e){if(e.source.accept(this),e.joins)for(let t of e.joins)t.accept(this)}visitSourceExpression(e){e.datasource.accept(this)}visitTableSource(e){let t=this.getTableIdentifier(e);!this.tableNameMap.has(t)&&!this.isCTETable(e.table.name)&&(this.tableNameMap.set(t,!0),this.tableSources.push(e))}visitFunctionSource(e){e.argument&&this.visitValueComponent(e.argument)}visitValueComponent(e){e.accept(this)}isCTETable(e){return this.cteNames.has(e)}visitParenSource(e){e.source.accept(this)}visitSubQuerySource(e){this.selectableOnly||e.query.accept(this)}visitInlineQuery(e){this.selectableOnly||e.selectQuery.accept(this)}visitJoinClause(e){e.source.accept(this),!this.selectableOnly&&e.condition&&e.condition.accept(this)}visitJoinOnClause(e){this.selectableOnly||e.condition.accept(this)}visitJoinUsingClause(e){this.selectableOnly||e.condition.accept(this)}visitWhereClause(e){e.condition.accept(this)}visitGroupByClause(e){for(let t of e.grouping)t.accept(this)}visitHavingClause(e){e.condition.accept(this)}visitOrderByClause(e){for(let t of e.order)t.accept(this)}visitWindowFrameClause(e){e.expression.accept(this)}visitLimitClause(e){e.value.accept(this)}visitOffsetClause(e){e.value.accept(this)}visitFetchClause(e){e.expression.accept(this)}visitForClause(e){}visitOrderByItem(e){e.value.accept(this)}visitSelectClause(e){for(let t of e.items)t.accept(this)}visitSelectItem(e){e.value.accept(this)}visitParenExpression(e){e.expression.accept(this)}visitBinaryExpression(e){e.left.accept(this),e.right.accept(this)}visitUnaryExpression(e){e.expression.accept(this)}visitCaseExpression(e){e.condition&&e.condition.accept(this),e.switchCase.accept(this)}visitSwitchCaseArgument(e){for(let t of e.cases)t.accept(this);e.elseValue&&e.elseValue.accept(this)}visitCaseKeyValuePair(e){e.key.accept(this),e.value.accept(this)}visitBetweenExpression(e){e.expression.accept(this),e.lower.accept(this),e.upper.accept(this)}visitFunctionCall(e){e.argument&&e.argument.accept(this),e.over&&e.over.accept(this)}visitArrayExpression(e){e.expression.accept(this)}visitArrayQueryExpression(e){e.query.accept(this)}visitTupleExpression(e){for(let t of e.values)t.accept(this)}visitCastExpression(e){e.input.accept(this),e.castType.accept(this)}visitValueList(e){for(let t of e.values)t.accept(this)}visitStringSpecifierExpression(e){}};var Tt=class extends g{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 kt=class{static collect(e){let t=[];function n(i){if(!(!i||typeof i!="object")){i.constructor&&i.constructor.kind===N.kind&&t.push(i);for(let r of Object.keys(i)){let s=i[r];Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&s.constructor&&s.constructor.kind&&n(s)}}}return n(e),t}};var ti=class{constructor(e){this.start=e?.start??'"',this.end=e?.end??'"'}decorate(e){return e=this.start+e+this.end,e}};var ni=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 Ct=class extends g{static{this.kind=Symbol("UpdateQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.updateClause=e.updateClause,this.setClause=e.setClause instanceof Fe?e.setClause:new Fe(e.setClause),this.whereClause=e.whereClause??null,this.fromClause=e.fromClause??null,this.returningClause=e.returning??null}};var yt=class extends g{static{this.kind=Symbol("DeleteQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.deleteClause=e.deleteClause,this.usingClause=e.usingClause??null,this.whereClause=e.whereClause??null,this.returningClause=e.returning??null}};var Ze=class a{constructor(e=null,t=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=e??null,this.commonTableCollector=new ne,this.commonTables=[],this.initialCommonTables=t,this.handlers=new Map,this.handlers.set(w.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(z.kind,n=>this.visitSelectClause(n)),this.handlers.set($.kind,n=>this.visitSourceExpression(n)),this.handlers.set(_.kind,n=>this.visitFromClause(n))}getValues(){return this.selectValues}reset(){this.selectValues=[],this.visitedNodes.clear(),this.initialCommonTables?this.commonTables=this.initialCommonTables:this.commonTables=[]}collect(e){this.visit(e);let t=this.getValues();return this.reset(),t}visit(e){if(!this.isRootVisit){this.visitNode(e);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(e)}finally{this.isRootVisit=!0}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}visitSimpleSelectQuery(e){this.commonTables.length===0&&this.initialCommonTables===null&&(this.commonTables=this.commonTableCollector.collect(e)),e.selectClause&&e.selectClause.accept(this);let t=this.selectValues.filter(i=>i.name==="*");if(t.length===0)return;if(this.selectValues.some(i=>i.value instanceof E&&i.value.namespaces===null)){e.fromClause&&this.processFromClause(e.fromClause,!0),this.selectValues=this.selectValues.filter(i=>i.name!=="*");return}let n=t.filter(i=>i.value instanceof E&&i.value.namespaces).map(i=>i.value.getNamespace());if(e.fromClause){let i=e.fromClause.getSourceAliasName();if(i&&n.includes(i)&&this.processFromClause(e.fromClause,!1),e.fromClause.joins)for(let r of e.fromClause.joins){let s=r.getSourceAliasName();s&&n.includes(s)&&this.processJoinClause(r)}}this.selectValues=this.selectValues.filter(i=>i.name!=="*")}processFromClause(e,t){if(e){let n=e.getSourceAliasName();if(this.processSourceExpression(n,e.source),e.joins&&t)for(let i of e.joins)this.processJoinClause(i)}}processJoinClause(e){let t=e.getSourceAliasName();this.processSourceExpression(t,e.source)}processSourceExpression(e,t){let n=this.commonTables.find(i=>i.aliasExpression.table.name===e);if(n){let i=this.commonTables.filter(o=>o.aliasExpression.table.name!==e);new a(this.tableColumnResolver,i).collect(n.query).forEach(o=>{this.addSelectValueAsUnique(o.name,new E(e?[e]:null,o.name))})}else new a(this.tableColumnResolver,this.commonTables).collect(t).forEach(s=>{this.addSelectValueAsUnique(s.name,new E(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 E){let t=e.value.column.name;t==="*"?this.selectValues.push({name:t,value:e.value}):this.addSelectValueAsUnique(t,e.value)}}visitSourceExpression(e){if(e.aliasExpression&&e.aliasExpression.columns){let t=e.getAliasName();e.aliasExpression.columns.forEach(n=>{this.addSelectValueAsUnique(n.name,new E(t?[t]:null,n.name))});return}else if(e.datasource instanceof B){if(this.tableColumnResolver){let t=e.datasource.getSourceName();this.tableColumnResolver(t).forEach(n=>{this.addSelectValueAsUnique(n,new E([t],n))})}return}else if(e.datasource instanceof K){let t=e.getAliasName();new a(this.tableColumnResolver,this.commonTables).collect(e.datasource.query).forEach(r=>{this.addSelectValueAsUnique(r.name,new E(t?[t]:null,r.name))});return}else if(e.datasource instanceof je)return this.visit(e.datasource.source)}visitFromClause(e){e&&this.processFromClause(e,!0)}addSelectValueAsUnique(e,t){this.selectValues.some(n=>n.name===e)||this.selectValues.push({name:e,value:t})}};var It=class extends g{static{this.kind=Symbol("ReferenceDefinition")}constructor(e){super(),this.targetTable=e.targetTable,this.columns=e.columns?[...e.columns]:null,this.matchType=e.matchType??null,this.onDelete=e.onDelete??null,this.onUpdate=e.onUpdate??null,this.deferrable=e.deferrable??null,this.initially=e.initially??null}},et=class extends g{static{this.kind=Symbol("ColumnConstraintDefinition")}constructor(e){super(),this.kind=e.kind,this.constraintName=e.constraintName,this.defaultValue=e.defaultValue,this.checkExpression=e.checkExpression,this.reference=e.reference,this.rawClause=e.rawClause}},We=class extends g{static{this.kind=Symbol("TableConstraintDefinition")}constructor(e){super(),this.kind=e.kind,this.constraintName=e.constraintName,this.columns=e.columns?[...e.columns]:null,this.reference=e.reference,this.checkExpression=e.checkExpression,this.rawClause=e.rawClause,this.deferrable=e.deferrable??null,this.initially=e.initially??null}},Gt=class extends g{static{this.kind=Symbol("TableColumnDefinition")}constructor(e){super(),this.name=e.name,this.dataType=e.dataType,this.constraints=e.constraints?[...e.constraints]:[]}},Pt=class extends g{static{this.kind=Symbol("CreateTableQuery")}constructor(e){super(),this.tableName=new I(e.tableName),this.namespaces=e.namespaces?[...e.namespaces]:null,this.isTemporary=e.isTemporary??!1,this.ifNotExists=e.ifNotExists??!1,this.columns=e.columns?[...e.columns]:[],this.tableConstraints=e.tableConstraints?[...e.tableConstraints]:[],this.tableOptions=e.tableOptions??null,this.asSelectQuery=e.asSelectQuery}getSelectQuery(){let e;this.asSelectQuery?e=new Ze().collect(this.asSelectQuery).map(r=>new J(r.value,r.name)):this.columns.length>0?e=this.columns.map(n=>new J(new E(null,n.name),n.name.name)):e=[new J(new R("*"))];let t=this.namespaces&&this.namespaces.length>0?[...this.namespaces,this.tableName.name].join("."):this.tableName.name;return new w({selectClause:new z(e),fromClause:new _(new $(new B(null,t),null),null)})}getCountQuery(){let e=this.namespaces&&this.namespaces.length>0?[...this.namespaces,this.tableName.name].join("."):this.tableName.name;return new w({selectClause:new z([new J(new H(null,"count",new E(null,"*"),null))]),fromClause:new _(new $(new B(null,e),null),null)})}};var Yt=class extends g{static{this.kind=Symbol("MergeAction")}},Lt=class extends Yt{static{this.kind=Symbol("MergeUpdateAction")}constructor(e,t){super(),this.setClause=e instanceof Fe?e:new Fe(e),this.whereClause=t??null}},gt=class extends Yt{static{this.kind=Symbol("MergeDeleteAction")}constructor(e){super(),this.whereClause=e??null}},wt=class extends Yt{static{this.kind=Symbol("MergeInsertAction")}constructor(e){super(),this.columns=e.columns?e.columns.map(t=>typeof t=="string"?new I(t):t):null,this.values=e.values??null,this.defaultValues=e.defaultValues??!1}},mt=class extends Yt{static{this.kind=Symbol("MergeDoNothingAction")}},Ge=class extends g{static{this.kind=Symbol("MergeWhenClause")}constructor(e,t,n){super(),this.matchType=e,this.action=t,this.condition=n??null}},vt=class extends g{static{this.kind=Symbol("MergeQuery")}constructor(e){super(),this.withClause=e.withClause??null,this.target=e.target,this.source=e.source,this.onCondition=e.onCondition,this.whenClauses=e.whenClauses}};var Xt=class extends g{static{this.kind=Symbol("DropTableStatement")}constructor(e){super(),this.tables=e.tables.map(t=>new G(t.namespaces,t.name)),this.ifExists=e.ifExists??!1,this.behavior=e.behavior??null}},Zt=class extends g{static{this.kind=Symbol("DropIndexStatement")}constructor(e){super(),this.indexNames=e.indexNames.map(t=>new G(t.namespaces,t.name)),this.ifExists=e.ifExists??!1,this.concurrently=e.concurrently??!1,this.behavior=e.behavior??null}},Mt=class extends g{static{this.kind=Symbol("IndexColumnDefinition")}constructor(e){super(),this.expression=e.expression,this.sortOrder=e.sortOrder??null,this.nullsOrder=e.nullsOrder??null,this.collation=e.collation??null,this.operatorClass=e.operatorClass??null}},en=class extends g{static{this.kind=Symbol("CreateIndexStatement")}constructor(e){super(),this.unique=e.unique??!1,this.concurrently=e.concurrently??!1,this.ifNotExists=e.ifNotExists??!1,this.indexName=new G(e.indexName.namespaces,e.indexName.name),this.tableName=new G(e.tableName.namespaces,e.tableName.name),this.usingMethod=e.usingMethod??null,this.columns=e.columns.map(t=>new Mt({expression:t.expression,sortOrder:t.sortOrder,nullsOrder:t.nullsOrder,collation:t.collation??null,operatorClass:t.operatorClass??null})),this.include=e.include?[...e.include]:null,this.where=e.where,this.withOptions=e.withOptions??null,this.tablespace=e.tablespace??null}},tn=class extends g{static{this.kind=Symbol("AlterTableAddConstraint")}constructor(e){super(),this.constraint=e.constraint,this.ifNotExists=e.ifNotExists??!1,this.notValid=e.notValid??!1}},nn=class extends g{static{this.kind=Symbol("AlterTableDropConstraint")}constructor(e){super(),this.constraintName=e.constraintName,this.ifExists=e.ifExists??!1,this.behavior=e.behavior??null}},rn=class extends g{static{this.kind=Symbol("AlterTableStatement")}constructor(e){super(),this.table=new G(e.table.namespaces,e.table.name),this.only=e.only??!1,this.ifExists=e.ifExists??!1,this.actions=e.actions.map(t=>t)}},sn=class extends g{static{this.kind=Symbol("DropConstraintStatement")}constructor(e){super(),this.constraintName=e.constraintName,this.ifExists=e.ifExists??!1,this.behavior=e.behavior??null}};var wr={mysql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous",constraintStyle:"mysql"},postgres:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed",castStyle:"postgres",constraintStyle:"postgres"},postgresWithNamedParams:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named",castStyle:"postgres",constraintStyle:"postgres"},sqlserver:{identifierEscape:{start:"[",end:"]"},parameterSymbol:"@",parameterStyle:"named",constraintStyle:"postgres"},sqlite:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named",constraintStyle:"postgres"},oracle:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named",constraintStyle:"postgres"},clickhouse:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous",constraintStyle:"postgres"},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",castStyle:"postgres"},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",castStyle:"postgres"},flinksql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},mongodb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"}},ii=class a{constructor(e){this.handlers=new Map;this.index=1;e?.preset&&(e={...e.preset,...e}),this.parameterDecorator=new ni({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 ti({start:e?.identifierEscape?.start??'"',end:e?.identifierEscape?.end??'"'}),this.castStyle=e?.castStyle??"standard",this.constraintStyle=e?.constraintStyle??"postgres",this.handlers.set(W.kind,t=>this.visitValueList(t)),this.handlers.set(E.kind,t=>this.visitColumnReference(t)),this.handlers.set(G.kind,t=>this.visitQualifiedName(t)),this.handlers.set(H.kind,t=>this.visitFunctionCall(t)),this.handlers.set(te.kind,t=>this.visitUnaryExpression(t)),this.handlers.set(b.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(Le.kind,t=>this.visitSwitchCaseArgument(t)),this.handlers.set(Ne.kind,t=>this.visitCaseKeyValuePair(t)),this.handlers.set(R.kind,t=>this.visitRawString(t)),this.handlers.set(I.kind,t=>this.visitIdentifierString(t)),this.handlers.set(ee.kind,t=>this.visitParenExpression(t)),this.handlers.set(fe.kind,t=>this.visitCastExpression(t)),this.handlers.set(ue.kind,t=>this.visitCaseExpression(t)),this.handlers.set(Se.kind,t=>this.visitArrayExpression(t)),this.handlers.set(be.kind,t=>this.visitArrayQueryExpression(t)),this.handlers.set(lt.kind,t=>this.visitArraySliceExpression(t)),this.handlers.set(ut.kind,t=>this.visitArrayIndexExpression(t)),this.handlers.set(Ee.kind,t=>this.visitBetweenExpression(t)),this.handlers.set(ze.kind,t=>this.visitStringSpecifierExpression(t)),this.handlers.set(De.kind,t=>this.visitTypeValue(t)),this.handlers.set(xe.kind,t=>this.visitTupleExpression(t)),this.handlers.set(de.kind,t=>this.visitInlineQuery(t)),this.handlers.set(Ke.kind,t=>this.visitWindowFrameExpression(t)),this.handlers.set(it.kind,t=>this.visitWindowFrameSpec(t)),this.handlers.set(Ut.kind,t=>this.visitWindowFrameBoundStatic(t)),this.handlers.set(Kt.kind,t=>this.visitWindowFrameBoundaryValue(t)),this.handlers.set(_e.kind,t=>this.visitPartitionByClause(t)),this.handlers.set(Ce.kind,t=>this.visitOrderByClause(t)),this.handlers.set(Qe.kind,t=>this.visitOrderByItem(t)),this.handlers.set(J.kind,t=>this.visitSelectItem(t)),this.handlers.set(z.kind,t=>this.visitSelectClause(t)),this.handlers.set(jt.kind,t=>this.visitDistinct(t)),this.handlers.set(qt.kind,t=>this.visitDistinctOn(t)),this.handlers.set(Tt.kind,t=>this.visitHintClause(t)),this.handlers.set(B.kind,t=>this.visitTableSource(t)),this.handlers.set(nt.kind,t=>this.visitFunctionSource(t)),this.handlers.set($.kind,t=>this.visitSourceExpression(t)),this.handlers.set(se.kind,t=>this.visitSourceAliasExpression(t)),this.handlers.set(_.kind,t=>this.visitFromClause(t)),this.handlers.set(ve.kind,t=>this.visitJoinClause(t)),this.handlers.set(we.kind,t=>this.visitJoinOnClause(t)),this.handlers.set(Te.kind,t=>this.visitJoinUsingClause(t)),this.handlers.set(re.kind,t=>this.visitWhereClause(t)),this.handlers.set(ye.kind,t=>this.visitGroupByClause(t)),this.handlers.set(ge.kind,t=>this.visitHavingClause(t)),this.handlers.set(ct.kind,t=>this.visitWindowClause(t)),this.handlers.set(Oe.kind,t=>this.visitWindowFrameClause(t)),this.handlers.set(ce.kind,t=>this.visitLimitClause(t)),this.handlers.set($e.kind,t=>this.visitOffsetClause(t)),this.handlers.set(He.kind,t=>this.visitFetchClause(t)),this.handlers.set(Ft.kind,t=>this.visitFetchExpression(t)),this.handlers.set(Re.kind,t=>this.visitForClause(t)),this.handlers.set(he.kind,t=>this.visitWithClause(t)),this.handlers.set(oe.kind,t=>this.visitCommonTable(t)),this.handlers.set(w.kind,t=>this.visitSimpleQuery(t)),this.handlers.set(K.kind,t=>this.visitSubQuerySource(t)),this.handlers.set(O.kind,t=>this.visitBinarySelectQuery(t)),this.handlers.set(ae.kind,t=>this.visitValuesQuery(t)),this.handlers.set(xe.kind,t=>this.visitTupleExpression(t)),this.handlers.set(tt.kind,t=>this.visitInsertQuery(t)),this.handlers.set(xt.kind,t=>this.visitInsertClause(t)),this.handlers.set(Ct.kind,t=>this.visitUpdateQuery(t)),this.handlers.set(bt.kind,t=>this.visitUpdateClause(t)),this.handlers.set(yt.kind,t=>this.visitDeleteQuery(t)),this.handlers.set(Et.kind,t=>this.visitDeleteClause(t)),this.handlers.set(Jt.kind,t=>this.visitUsingClause(t)),this.handlers.set(Fe.kind,t=>this.visitSetClause(t)),this.handlers.set(Xe.kind,t=>this.visitSetClauseItem(t)),this.handlers.set(zt.kind,t=>this.visitReturningClause(t)),this.handlers.set(Pt.kind,t=>this.visitCreateTableQuery(t)),this.handlers.set(Gt.kind,t=>this.visitTableColumnDefinition(t)),this.handlers.set(et.kind,t=>this.visitColumnConstraintDefinition(t)),this.handlers.set(We.kind,t=>this.visitTableConstraintDefinition(t)),this.handlers.set(It.kind,t=>this.visitReferenceDefinition(t)),this.handlers.set(en.kind,t=>this.visitCreateIndexStatement(t)),this.handlers.set(Mt.kind,t=>this.visitIndexColumnDefinition(t)),this.handlers.set(Xt.kind,t=>this.visitDropTableStatement(t)),this.handlers.set(Zt.kind,t=>this.visitDropIndexStatement(t)),this.handlers.set(rn.kind,t=>this.visitAlterTableStatement(t)),this.handlers.set(tn.kind,t=>this.visitAlterTableAddConstraint(t)),this.handlers.set(nn.kind,t=>this.visitAlterTableDropConstraint(t)),this.handlers.set(sn.kind,t=>this.visitDropConstraintStatement(t)),this.handlers.set(vt.kind,t=>this.visitMergeQuery(t)),this.handlers.set(Ge.kind,t=>this.visitMergeWhenClause(t)),this.handlers.set(Lt.kind,t=>this.visitMergeUpdateAction(t)),this.handlers.set(gt.kind,t=>this.visitMergeDeleteAction(t)),this.handlers.set(wt.kind,t=>this.visitMergeInsertAction(t)),this.handlers.set(mt.kind,t=>this.visitMergeDoNothingAction(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,".")}static{this._selfHandlingComponentTypes=null}static getSelfHandlingComponentTypes(){return this._selfHandlingComponentTypes||(this._selfHandlingComponentTypes=new Set([w.kind,J.kind,Ne.kind,Le.kind,E.kind,Z.kind,N.kind,B.kind,se.kind,De.kind,H.kind,I.kind,G.kind])),this._selfHandlingComponentTypes}visitBinarySelectQuery(e){let t=new d(0,"");if(e.positionedComments&&e.positionedComments.length>0)this.addPositionedCommentsToToken(t,e),e.positionedComments=null;else if(e.headerComments&&e.headerComments.length>0){if(this.shouldMergeHeaderComments(e.headerComments)){let n=this.createHeaderMultiLineCommentBlock(e.headerComments);t.innerTokens.push(n)}else{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 s=0;s0&&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=kt.collect(e).sort((r,s)=>(r.index??0)-(s.index??0)),i=this.parameterDecorator.style;if(i==="named"){let r={};for(let s of n){let o=s.name.value;if(r.hasOwnProperty(o)){if(r[o]!==s.value)throw new Error(`Duplicate parameter name '${o}' with different values detected during query composition.`);continue}r[o]=s.value}return{token:t,params:r}}else if(i==="indexed"){let r=n.map(s=>s.value);return{token:t,params:r}}else if(i==="anonymous"){let r=n.map(s=>s.value);return{token:t,params:r}}return{token:t,params:[]}}componentHandlesOwnComments(e){return"handlesOwnComments"in e&&typeof e.handlesOwnComments=="function"?e.handlesOwnComments():a.getSelfHandlingComponentTypes().has(e.getKind())}visit(e){let t=this.handlers.get(e.getKind());if(t){let n=t(e);return this.componentHandlesOwnComments(e)||this.addComponentComments(n,e),n}throw new Error(`[SqlPrintTokenParser] No handler for kind: ${e.getKind().toString()}`)}hasPositionedComments(e){return(e.positionedComments?.length??0)>0}hasLegacyComments(e){return(e.comments?.length??0)>0}addComponentComments(e,t){this.hasPositionedComments(t)?this.addPositionedCommentsToToken(e,t):this.hasLegacyComments(t)&&this.addCommentsToToken(e,t.comments)}addPositionedCommentsToToken(e,t){if(!this.hasPositionedComments(t))return;let n=t.getPositionedComments("before");if(n.length>0){let s=this.createCommentBlocks(n);for(let o=s.length-1;o>=0;o--)e.innerTokens.unshift(s[o])}let i=t.getPositionedComments("after");if(i.length>0){let s=this.createCommentBlocks(i);for(let o of s)e.innerTokens.push(a.SPACE_TOKEN),e.innerTokens.push(o)}let r=["CaseExpression","SwitchCaseArgument","CaseKeyValuePair","SelectClause","LiteralValue","IdentifierString","DistinctOn","SourceAliasExpression","SimpleSelectQuery","WhereClause"];e.containerType&&r.includes(e.containerType)&&(t.positionedComments=null)}addCommentsToToken(e,t){if(!t?.length)return;let n=this.createCommentBlocks(t);this.insertCommentBlocksWithSpacing(e,n)}createInlineCommentSequence(e){let t=[];for(let n=0;n0&&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.containerType==="IdentifierString"){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.innerTokens.unshift(...t),this.shouldAddSeparatorSpace(e.containerType)){let i=new d(10," ");e.innerTokens.splice(t.length,0,i),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)}addPositionedCommentsToParenExpression(e,t){if(!t.positionedComments)return;let n=t.getPositionedComments("before");if(n.length>0){let r=this.createCommentBlocks(n),s=1;for(let o of r)e.innerTokens.splice(s,0,o),s++}let i=t.getPositionedComments("after");if(i.length>0){let r=this.createCommentBlocks(i),s=e.innerTokens.length;for(let o of r)e.innerTokens.splice(s-1,0,o)}}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.startsWith("/*")&&e.endsWith("*/"),n=t?e.slice(2,-2):e,s=this.escapeCommentDelimiters(n).replace(/\r?\n/g,` `).split(` -`).map(u=>u.replace(/\s+/g," ").trim()).filter(u=>u.length>0);if(s.length===0)return"/* */";let o=s.length===1&&/^[-=_+*#]+$/.test(s[0]);return t?o||s.length===1?`/* ${s[0]} */`:`/* -${s.map(u=>` ${u}`).join(` +`).map(l=>l.replace(/\s+/g," ").trim()).filter(l=>l.length>0);if(s.length===0)return"/* */";let o=s.length===1&&/^[-=_+*#]+$/.test(s[0]);return t?o||s.length===1?`/* ${s[0]} */`:`/* +${s.map(l=>` ${l}`).join(` `)} -*/`:o?`/* ${s[0]} */`:`/* ${s.join(" ")} */`}shouldMergeHeaderComments(e){return e.length<=1?!1:e.some(t=>{let n=t.trim();return/^[-=_+*#]{3,}$/.test(n)||n.startsWith("- ")||n.startsWith("* ")})}createHeaderMultiLineCommentBlock(e){let t=new d(0,"","CommentBlock");if(e.length===0){let n=new d(6,"/* */");t.innerTokens.push(n)}else{let n=new d(6,"/*");t.innerTokens.push(n),t.innerTokens.push(new d(12,""));for(let r of e){let s=this.escapeCommentDelimiters(r),o=new d(6,` ${s}`);t.innerTokens.push(o),t.innerTokens.push(new d(12,""))}let i=new d(6,"*/");t.innerTokens.push(i)}return t.innerTokens.push(new d(12,"")),t.innerTokens.push(new d(10," ")),t}formatLineComment(e){let t=this.sanitizeLineCommentContent(e);return t?`-- ${t}`:"--"}sanitizeLineCommentContent(e){let t=this.escapeCommentDelimiters(e).replace(/\r?\n/g," ").replace(/\u2028|\u2029/g," ").replace(/\s+/g," ").trim();return t.startsWith("--")&&(t=t.slice(2).trimStart()),t}escapeCommentDelimiters(e){return e.replace(/\/\*/g,"\\/\\*").replace(/\*\//g,"*\\/")}visitValueList(e){let t=new d(0,"","ValueList");for(let n=0;n0&&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)),this.addComponentComments(t,e),t}visitFunctionCall(e){let t=new d(0,"","FunctionCall");if(this.addComponentComments(t,e),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 I?(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");t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(a.SPACE_TOKEN);let n=this.visit(e.operator),i=n.text.toLowerCase();return(i==="and"||i==="or")&&(n.type=5),t.innerTokens.push(n),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}visitLiteralValue(e){let t;e.value===null?t="null":e.isStringLiteral?t=`'${e.value.replace(/'/g,"''")}'`:typeof e.value=="string"?t=e.value:t=e.value.toString();let n=new d(2,t,"LiteralValue");return e.positionedComments&&e.positionedComments.length>0?(this.addPositionedCommentsToToken(n,e),e.positionedComments=null):e.comments&&e.comments.length>0&&this.addCommentsToToken(n,e.comments),n}visitParameterExpression(e){e.index=this.index;let t=this.parameterDecorator.decorate(e.name.value,e.index),n=new d(7,t);return this.addComponentComments(n,e),this.index++,n}visitSwitchCaseArgument(e){let t=new d(0,"","SwitchCaseArgument");this.addComponentComments(t,e);for(let n of e.cases)t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(n.accept(this));if(e.elseValue)t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.createElseToken(e.elseValue,e.comments));else if(e.comments&&e.comments.length>0){t.innerTokens.push(a.SPACE_TOKEN);let n=this.createInlineCommentSequence(e.comments);t.innerTokens.push(...n)}return t}createElseToken(e,t){let n=new d(0,"","ElseClause");if(n.innerTokens.push(new d(1,"else")),t&&t.length>0){n.innerTokens.push(a.SPACE_TOKEN);let r=this.createInlineCommentSequence(t);n.innerTokens.push(...r)}n.innerTokens.push(a.SPACE_TOKEN);let i=new d(0,"","CaseElseValue");return i.innerTokens.push(this.visit(e)),n.innerTokens.push(i),n}visitCaseKeyValuePair(e){let t=new d(0,"","CaseKeyValuePair");if(e.positionedComments&&e.positionedComments.length>0&&(this.addPositionedCommentsToToken(t,e),e.positionedComments=null),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")),e.comments&&e.comments.length>0){t.innerTokens.push(a.SPACE_TOKEN);let i=this.createInlineCommentSequence(e.comments);t.innerTokens.push(...i)}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);if(e.positionedComments&&e.positionedComments.length>0){let i=new d(0,"","IdentifierString");this.addPositionedCommentsToToken(i,e),e.positionedComments=null;let r=new d(2,t);return i.innerTokens.push(r),i}if(e.comments&&e.comments.length>0){let i=new d(0,"","IdentifierString"),r=new d(2,t);return i.innerTokens.push(r),this.addComponentComments(i,e),i}return new d(2,t,"IdentifierString")}visitParenExpression(e){let t=new d(0,"","ParenExpression"),n=e.positionedComments&&e.positionedComments.length>0,i=e.expression.positionedComments&&e.expression.positionedComments.length>0,r=[],s=[];if(i&&(r=e.expression.getPositionedComments("before"),s=e.expression.getPositionedComments("after"),e.expression.positionedComments=null),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),r.length>0){let o=this.createCommentBlocks(r),l=1;for(let u of o)t.innerTokens.splice(l,0,u),l++}if(s.length>0){let o=this.createCommentBlocks(s),l=t.innerTokens.length;for(let u of o)t.innerTokens.splice(l-1,0,u)}return n&&(this.addPositionedCommentsToParenExpression(t,e),e.positionedComments=null),t}visitCastExpression(e){let t=new d(0,"","CastExpression");return this.castStyle==="postgres"?(t.innerTokens.push(this.visit(e.input)),t.innerTokens.push(new d(5,"::")),t.innerTokens.push(this.visit(e.castType)),t):(t.innerTokens.push(new d(1,"cast")),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.input)),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.castType)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t)}visitCaseExpression(e){let t=new d(0,"","CaseExpression");return e.positionedComments&&e.positionedComments.length>0&&(this.addPositionedCommentsToToken(t,e),e.positionedComments=null),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 this.addComponentComments(t,e),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;n0&&t.innerTokens.push(...a.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t.innerTokens.push(a.PAREN_CLOSE_TOKEN),this.addComponentComments(t,e),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"),n=e.positionedComments,i=e.value.positionedComments;e.value.positionedComments=null;let r=e.getPositionedComments("before"),s=e.getPositionedComments("after"),o=e.value.constructor.name==="ParenExpression";if(r.length>0){let h=this.createInlineCommentSequence(r);t.innerTokens.push(...h),t.innerTokens.push(a.SPACE_TOKEN)}if(t.innerTokens.push(this.visit(e.value)),s.length>0&&!o){t.innerTokens.push(a.SPACE_TOKEN);let h=this.createInlineCommentSequence(s);t.innerTokens.push(...h)}if(e.positionedComments=n,e.value.positionedComments=i,!e.identifier)return t;if(e.value instanceof E){let h=e.value.column.name;if(e.identifier.name===h)return t}t.innerTokens.push(a.SPACE_TOKEN);let l="asKeywordPositionedComments"in e?e.asKeywordPositionedComments:null;if(l){let h=l.filter(C=>C.position==="before");if(h.length>0)for(let C of h){let f=this.createInlineCommentSequence(C.comments);t.innerTokens.push(...f),t.innerTokens.push(a.SPACE_TOKEN)}}if(t.innerTokens.push(new d(1,"as")),l){let h=l.filter(C=>C.position==="after");if(h.length>0){t.innerTokens.push(a.SPACE_TOKEN);for(let C of h){let f=this.createInlineCommentSequence(C.comments);t.innerTokens.push(...f)}}}let u="asKeywordComments"in e?e.asKeywordComments:null;if(u&&u.length>0){t.innerTokens.push(a.SPACE_TOKEN);let h=this.createInlineCommentSequence(u);t.innerTokens.push(...h)}t.innerTokens.push(a.SPACE_TOKEN);let c=this.visit(e.identifier);t.innerTokens.push(c);let p="aliasPositionedComments"in e?e.aliasPositionedComments:null;if(p){let h=p.filter(C=>C.position==="after");if(h.length>0){t.innerTokens.push(a.SPACE_TOKEN);for(let C of h){let f=this.createInlineCommentSequence(C.comments);t.innerTokens.push(...f)}}}let m=e.aliasComments;if(m&&m.length>0){t.innerTokens.push(a.SPACE_TOKEN);let h=this.createInlineCommentSequence(m);t.innerTokens.push(...h)}return t}visitSelectClause(e){let t=new d(1,"select","SelectClause");e.positionedComments&&e.positionedComments.length>0&&(this.addPositionedCommentsToToken(t,e),e.positionedComments=null);let n="select";for(let i of e.hints)n+=" "+this.visit(i).text;if(e.distinct){let i=e.distinct.accept(this);if(i.innerTokens&&i.innerTokens.length>0){let r=i.text;for(let s of i.innerTokens)r+=this.flattenTokenText(s);n+=" "+r}else n+=" "+i.text}t.text=n,t.innerTokens.push(a.SPACE_TOKEN);for(let i=0;i0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[i]));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){let t=new d(1,"distinct");return e.positionedComments&&e.positionedComments.length>0&&(this.addPositionedCommentsToToken(t,e),e.positionedComments=null),t}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(i=>i.accept(this).text).join(".")+"."),t+=e.table.accept(this).text;let n=new d(2,t);return this.addComponentComments(n,e),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 B){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;ns.position==="before");if(r.length>0)for(let s of r){let o=this.createInlineCommentSequence(s.comments);t.innerTokens.push(...o),t.innerTokens.push(a.SPACE_TOKEN)}}if(t.innerTokens.push(new d(1,e.joinType.value)),n){let r=n.filter(s=>s.position==="after");if(r.length>0){t.innerTokens.push(a.SPACE_TOKEN);for(let s of r){let o=this.createInlineCommentSequence(s.comments);t.innerTokens.push(...o)}}}let i=e.joinKeywordComments;if(i&&i.length>0){t.innerTokens.push(a.SPACE_TOKEN);let r=this.createInlineCommentSequence(i);t.innerTokens.push(...r)}return 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;n0&&t.innerTokens.push(...a.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));t.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return e.positionedComments&&e.positionedComments.length>0?(this.addPositionedCommentsToToken(t,e),e.positionedComments=null):e.comments&&e.comments.length>0&&this.addCommentsToToken(t,e.comments),t}visitWhereClause(e){let t=new d(1,"where","WhereClause");return this.addComponentComments(t,e),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;n0&&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;n0&&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;n0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(e.tables[n].accept(this));return t.innerTokens.push(a.SPACE_TOKEN),this.addComponentComments(t,e),t}visitCommonTable(e){let t=new d(0,"","CommonTable");e.positionedComments&&e.positionedComments.length>0?(this.addPositionedCommentsToToken(t,e),e.positionedComments=null):e.comments&&e.comments.length>0&&this.addCommentsToToken(t,e.comments),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){if(this.shouldMergeHeaderComments(e.headerComments)){let n=this.createHeaderMultiLineCommentBlock(e.headerComments);t.innerTokens.push(n)}else{let n=this.createCommentBlocks(e.headerComments);t.innerTokens.push(...n)}e.withClause&&t.innerTokens.push(a.SPACE_TOKEN)}if(e.positionedComments&&e.positionedComments.length>0&&(this.addPositionedCommentsToToken(t,e),e.positionedComments=null),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)if(this.shouldMergeHeaderComments(e.headerComments)){let i=this.createHeaderMultiLineCommentBlock(e.headerComments);t.innerTokens.push(i),t.innerTokens.push(a.SPACE_TOKEN)}else{let i=this.createCommentBlocks(e.headerComments);for(let r of i)t.innerTokens.push(r),t.innerTokens.push(a.SPACE_TOKEN)}t.innerTokens.push(a.SPACE_TOKEN);let n=new d(0,"","Values");for(let i=0;i0&&n.innerTokens.push(...a.commaSpaceTokens()),n.innerTokens.push(e.tuples[i].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 i=new d(4,")");this.addCommentsToToken(i,e.comments),t.innerTokens.push(i),e.comments=null}else t.innerTokens.push(a.PAREN_CLOSE_TOKEN);return t}visitInsertQuery(e){let t=new d(0,"","InsertQuery");return e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(this.visit(e.insertClause)),e.selectQuery&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.selectQuery))),e.returningClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.returningClause.accept(this))),t}visitInsertClause(e){let t=new d(0,"","InsertClause");if(t.innerTokens.push(new d(1,"insert into")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),e.columns&&e.columns.length>0){t.innerTokens.push(a.PAREN_OPEN_TOKEN);for(let n=0;n0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(e.columns[n].accept(this));t.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return t}visitDeleteQuery(e){let t=new d(0,"","DeleteQuery");return e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(e.deleteClause.accept(this)),e.usingClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.usingClause.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}visitDeleteClause(e){let t=new d(1,"delete from","DeleteClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t}visitUsingClause(e){let t=new d(1,"using","UsingClause");if(e.sources.length>0){t.innerTokens.push(a.SPACE_TOKEN);for(let n=0;n0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.sources[n]))}return t}visitMergeQuery(e){let t=new d(0,"","MergeQuery");e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(new d(1,"merge into")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.target.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"using")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"on")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.onCondition.accept(this));for(let n of e.whenClauses)t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(n.accept(this));return t}visitMergeWhenClause(e){let t=new d(0,"","MergeWhenClause");return t.innerTokens.push(new d(1,this.mergeMatchTypeToKeyword(e.matchType))),e.condition&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"and")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.condition.accept(this))),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"then")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.action.accept(this)),t}visitMergeUpdateAction(e){let t=new d(0,"","MergeUpdateAction");return t.innerTokens.push(new d(1,"update")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.setClause.accept(this)),e.whereClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),t}visitMergeDeleteAction(e){let t=new d(0,"","MergeDeleteAction");return t.innerTokens.push(new d(1,"delete")),e.whereClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),t}visitMergeInsertAction(e){let t=new d(0,"","MergeInsertAction");if(t.innerTokens.push(new d(1,"insert")),e.columns&&e.columns.length>0){t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(a.PAREN_OPEN_TOKEN);for(let n=0;n0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(e.columns[n].accept(this));t.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return e.defaultValues?(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"default values")),t):(e.values&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"values")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(e.values.accept(this)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN)),t)}visitMergeDoNothingAction(e){return new d(1,"do nothing","MergeDoNothingAction")}mergeMatchTypeToKeyword(e){switch(e){case"matched":return"when matched";case"not_matched":return"when not matched";case"not_matched_by_source":return"when not matched by source";case"not_matched_by_target":return"when not matched by target";default:return"when"}}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;n0&&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;n0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));return t}visitCreateTableQuery(e){let t=e.isTemporary?"create temporary table":"create table",n=e.ifNotExists?`${t} if not exists`:t,i=new d(1,n,"CreateTableQuery");i.innerTokens.push(a.SPACE_TOKEN);let r=new G(e.namespaces??null,e.tableName);i.innerTokens.push(r.accept(this));let s=[...e.columns,...e.tableConstraints];if(s.length>0){i.innerTokens.push(a.SPACE_TOKEN),i.innerTokens.push(a.PAREN_OPEN_TOKEN);let o=new d(0,"","CreateTableDefinition");for(let l=0;l0&&o.innerTokens.push(...a.commaSpaceTokens()),o.innerTokens.push(s[l].accept(this));i.innerTokens.push(o),i.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return e.tableOptions&&(i.innerTokens.push(a.SPACE_TOKEN),i.innerTokens.push(e.tableOptions.accept(this))),e.asSelectQuery&&(i.innerTokens.push(a.SPACE_TOKEN),i.innerTokens.push(new d(1,"as")),i.innerTokens.push(a.SPACE_TOKEN),i.innerTokens.push(e.asSelectQuery.accept(this))),i}visitTableColumnDefinition(e){let t=new d(0,"","TableColumnDefinition");t.innerTokens.push(e.name.accept(this)),e.dataType&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.dataType.accept(this)));for(let n of e.constraints)t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(n.accept(this));return t}visitColumnConstraintDefinition(e){let t=new d(0,"","ColumnConstraintDefinition");e.constraintName&&(t.innerTokens.push(new d(1,"constraint")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.constraintName.accept(this)));let n=r=>{t.innerTokens.length>0&&t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,r))},i=r=>{t.innerTokens.length>0&&t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(r.accept(this))};switch(e.kind){case"not-null":n("not null");break;case"null":n("null");break;case"default":n("default"),e.defaultValue&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.defaultValue.accept(this)));break;case"primary-key":n("primary key");break;case"unique":n("unique");break;case"references":e.reference&&i(e.reference);break;case"check":e.checkExpression&&(n("check"),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.checkExpression)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN));break;case"generated-always-identity":case"generated-by-default-identity":case"raw":e.rawClause&&i(e.rawClause);break}return t}visitTableConstraintDefinition(e){let t=new d(0,"","TableConstraintDefinition"),n=s=>{t.innerTokens.length>0&&t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,s))},i=s=>{t.innerTokens.length>0&&t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(s.accept(this))},r=s=>{if(!s||s.length===0)return;t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(a.PAREN_OPEN_TOKEN);let o=new d(0,"","ValueList");for(let l=0;l0&&o.innerTokens.push(...a.commaSpaceTokens()),o.innerTokens.push(s[l].accept(this));t.innerTokens.push(o),t.innerTokens.push(a.PAREN_CLOSE_TOKEN)};switch(e.constraintName&&(n("constraint"),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.constraintName.accept(this))),e.kind){case"primary-key":n("primary key"),r(e.columns??[]);break;case"unique":n("unique"),r(e.columns??[]);break;case"foreign-key":n("foreign key"),r(e.columns??[]),e.reference&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.reference.accept(this)));break;case"check":e.checkExpression&&(n("check"),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.checkExpression)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN));break;case"raw":e.rawClause&&i(e.rawClause);break}return t}visitReferenceDefinition(e){let t=new d(0,"","ReferenceDefinition");if(t.innerTokens.push(new d(1,"references")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.targetTable.accept(this)),e.columns&&e.columns.length>0){t.innerTokens.push(a.PAREN_OPEN_TOKEN);let n=new d(0,"","ValueList");for(let i=0;i0&&n.innerTokens.push(...a.commaSpaceTokens()),n.innerTokens.push(e.columns[i].accept(this));t.innerTokens.push(n),t.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return e.matchType&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,`match ${e.matchType}`))),e.onDelete&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"on delete")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,e.onDelete))),e.onUpdate&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"on update")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,e.onUpdate))),e.deferrable==="deferrable"?(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"deferrable"))):e.deferrable==="not deferrable"&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"not deferrable"))),e.initially==="immediate"?(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"initially immediate"))):e.initially==="deferred"&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"initially deferred"))),t}visitCreateIndexStatement(e){let t=["create"];e.unique&&t.push("unique"),t.push("index"),e.concurrently&&t.push("concurrently"),e.ifNotExists&&t.push("if not exists");let n=new d(1,t.join(" "),"CreateIndexStatement");n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(e.indexName.accept(this)),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,"on")),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(e.tableName.accept(this)),e.usingMethod&&(n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,"using")),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(e.usingMethod.accept(this))),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(a.PAREN_OPEN_TOKEN);let i=new d(0,"","IndexColumnList");for(let r=0;r0&&i.innerTokens.push(...a.commaSpaceTokens()),i.innerTokens.push(e.columns[r].accept(this));if(n.innerTokens.push(i),n.innerTokens.push(a.PAREN_CLOSE_TOKEN),e.include&&e.include.length>0){n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,"include")),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(a.PAREN_OPEN_TOKEN);let r=new d(0,"","ValueList");for(let s=0;s0&&r.innerTokens.push(...a.commaSpaceTokens()),r.innerTokens.push(e.include[s].accept(this));n.innerTokens.push(r),n.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return e.withOptions&&(n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(e.withOptions.accept(this))),e.tablespace&&(n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,"tablespace")),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(e.tablespace.accept(this))),e.where&&(n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,"where")),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(this.visit(e.where))),n}visitIndexColumnDefinition(e){let t=new d(0,"","IndexColumnDefinition");return t.innerTokens.push(this.visit(e.expression)),e.collation&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"collate")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.collation.accept(this))),e.operatorClass&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.operatorClass.accept(this))),e.sortOrder&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,e.sortOrder))),e.nullsOrder&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,`nulls ${e.nullsOrder}`))),t}visitDropTableStatement(e){let t=e.ifExists?"drop table if exists":"drop table",n=new d(1,t,"DropTableStatement");n.innerTokens.push(a.SPACE_TOKEN);let i=new d(0,"","ValueList");for(let r=0;r0&&i.innerTokens.push(...a.commaSpaceTokens()),i.innerTokens.push(e.tables[r].accept(this));return n.innerTokens.push(i),e.behavior&&(n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,e.behavior))),n}visitDropIndexStatement(e){let t=["drop","index"];e.concurrently&&t.push("concurrently"),e.ifExists&&t.push("if exists");let n=new d(1,t.join(" "),"DropIndexStatement");n.innerTokens.push(a.SPACE_TOKEN);let i=new d(0,"","ValueList");for(let r=0;r0&&i.innerTokens.push(...a.commaSpaceTokens()),i.innerTokens.push(e.indexNames[r].accept(this));return n.innerTokens.push(i),e.behavior&&(n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,e.behavior))),n}visitAlterTableStatement(e){let t=["alter","table"];e.ifExists&&t.push("if exists"),e.only&&t.push("only");let n=new d(1,t.join(" "),"AlterTableStatement");n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(e.table.accept(this));for(let i=0;i{let n=t.trim();return/^[-=_+*#]{3,}$/.test(n)||n.startsWith("- ")||n.startsWith("* ")})}createHeaderMultiLineCommentBlock(e){let t=new d(0,"","CommentBlock");if(e.length===0){let n=new d(6,"/* */");t.innerTokens.push(n)}else{let n=new d(6,"/*");t.innerTokens.push(n),t.innerTokens.push(new d(12,""));for(let r of e){let s=this.escapeCommentDelimiters(r),o=new d(6,` ${s}`);t.innerTokens.push(o),t.innerTokens.push(new d(12,""))}let i=new d(6,"*/");t.innerTokens.push(i)}return t.innerTokens.push(new d(12,"")),t.innerTokens.push(new d(10," ")),t}formatLineComment(e){let t=this.sanitizeLineCommentContent(e);return t?`-- ${t}`:"--"}sanitizeLineCommentContent(e){let t=this.escapeCommentDelimiters(e).replace(/\r?\n/g," ").replace(/\u2028|\u2029/g," ").replace(/\s+/g," ").trim();return t.startsWith("--")&&(t=t.slice(2).trimStart()),t}escapeCommentDelimiters(e){return e.replace(/\/\*/g,"\\/\\*").replace(/\*\//g,"*\\/")}visitValueList(e){let t=new d(0,"","ValueList");for(let n=0;n0&&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)),this.addComponentComments(t,e),t}visitFunctionCall(e){let t=new d(0,"","FunctionCall");if(this.addComponentComments(t,e),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 I?(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");t.innerTokens.push(this.visit(e.left)),t.innerTokens.push(a.SPACE_TOKEN);let n=this.visit(e.operator),i=n.text.toLowerCase();return(i==="and"||i==="or")&&(n.type=5),t.innerTokens.push(n),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.right)),t}visitLiteralValue(e){let t;e.value===null?t="null":e.isStringLiteral?t=`'${e.value.replace(/'/g,"''")}'`:typeof e.value=="string"?t=e.value:t=e.value.toString();let n=new d(2,t,"LiteralValue");return e.positionedComments&&e.positionedComments.length>0?(this.addPositionedCommentsToToken(n,e),e.positionedComments=null):e.comments&&e.comments.length>0&&this.addCommentsToToken(n,e.comments),n}visitParameterExpression(e){e.index=this.index;let t=this.parameterDecorator.decorate(e.name.value,e.index),n=new d(7,t);return this.addComponentComments(n,e),this.index++,n}visitSwitchCaseArgument(e){let t=new d(0,"","SwitchCaseArgument");this.addComponentComments(t,e);for(let n of e.cases)t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(n.accept(this));if(e.elseValue)t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.createElseToken(e.elseValue,e.comments));else if(e.comments&&e.comments.length>0){t.innerTokens.push(a.SPACE_TOKEN);let n=this.createInlineCommentSequence(e.comments);t.innerTokens.push(...n)}return t}createElseToken(e,t){let n=new d(0,"","ElseClause");if(n.innerTokens.push(new d(1,"else")),t&&t.length>0){n.innerTokens.push(a.SPACE_TOKEN);let r=this.createInlineCommentSequence(t);n.innerTokens.push(...r)}n.innerTokens.push(a.SPACE_TOKEN);let i=new d(0,"","CaseElseValue");return i.innerTokens.push(this.visit(e)),n.innerTokens.push(i),n}visitCaseKeyValuePair(e){let t=new d(0,"","CaseKeyValuePair");if(e.positionedComments&&e.positionedComments.length>0&&(this.addPositionedCommentsToToken(t,e),e.positionedComments=null),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")),e.comments&&e.comments.length>0){t.innerTokens.push(a.SPACE_TOKEN);let i=this.createInlineCommentSequence(e.comments);t.innerTokens.push(...i)}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);if(e.positionedComments&&e.positionedComments.length>0){let i=new d(0,"","IdentifierString");this.addPositionedCommentsToToken(i,e),e.positionedComments=null;let r=new d(2,t);return i.innerTokens.push(r),i}if(e.comments&&e.comments.length>0){let i=new d(0,"","IdentifierString"),r=new d(2,t);return i.innerTokens.push(r),this.addComponentComments(i,e),i}return new d(2,t,"IdentifierString")}visitParenExpression(e){let t=new d(0,"","ParenExpression"),n=e.positionedComments&&e.positionedComments.length>0,i=e.expression.positionedComments&&e.expression.positionedComments.length>0,r=[],s=[];if(i&&(r=e.expression.getPositionedComments("before"),s=e.expression.getPositionedComments("after"),e.expression.positionedComments=null),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.expression)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),r.length>0){let o=this.createCommentBlocks(r),u=1;for(let l of o)t.innerTokens.splice(u,0,l),u++}if(s.length>0){let o=this.createCommentBlocks(s),u=t.innerTokens.length;for(let l of o)t.innerTokens.splice(u-1,0,l)}return n&&(this.addPositionedCommentsToParenExpression(t,e),e.positionedComments=null),t}visitCastExpression(e){let t=new d(0,"","CastExpression");return this.castStyle==="postgres"?(t.innerTokens.push(this.visit(e.input)),t.innerTokens.push(new d(5,"::")),t.innerTokens.push(this.visit(e.castType)),t):(t.innerTokens.push(new d(1,"cast")),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.input)),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.castType)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN),t)}visitCaseExpression(e){let t=new d(0,"","CaseExpression");return e.positionedComments&&e.positionedComments.length>0&&(this.addPositionedCommentsToToken(t,e),e.positionedComments=null),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 this.addComponentComments(t,e),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;n0&&t.innerTokens.push(...a.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.values[n]));return t.innerTokens.push(a.PAREN_CLOSE_TOKEN),this.addComponentComments(t,e),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"),n=e.positionedComments,i=e.value.positionedComments;e.value.positionedComments=null;let r=e.getPositionedComments("before"),s=e.getPositionedComments("after"),o=e.value.constructor.name==="ParenExpression";if(r.length>0){let h=this.createInlineCommentSequence(r);t.innerTokens.push(...h),t.innerTokens.push(a.SPACE_TOKEN)}if(t.innerTokens.push(this.visit(e.value)),s.length>0&&!o){t.innerTokens.push(a.SPACE_TOKEN);let h=this.createInlineCommentSequence(s);t.innerTokens.push(...h)}if(e.positionedComments=n,e.value.positionedComments=i,!e.identifier)return t;if(e.value instanceof E){let h=e.value.column.name;if(e.identifier.name===h)return t}t.innerTokens.push(a.SPACE_TOKEN);let u="asKeywordPositionedComments"in e?e.asKeywordPositionedComments:null;if(u){let h=u.filter(C=>C.position==="before");if(h.length>0)for(let C of h){let f=this.createInlineCommentSequence(C.comments);t.innerTokens.push(...f),t.innerTokens.push(a.SPACE_TOKEN)}}if(t.innerTokens.push(new d(1,"as")),u){let h=u.filter(C=>C.position==="after");if(h.length>0){t.innerTokens.push(a.SPACE_TOKEN);for(let C of h){let f=this.createInlineCommentSequence(C.comments);t.innerTokens.push(...f)}}}let l="asKeywordComments"in e?e.asKeywordComments:null;if(l&&l.length>0){t.innerTokens.push(a.SPACE_TOKEN);let h=this.createInlineCommentSequence(l);t.innerTokens.push(...h)}t.innerTokens.push(a.SPACE_TOKEN);let c=this.visit(e.identifier);t.innerTokens.push(c);let p="aliasPositionedComments"in e?e.aliasPositionedComments:null;if(p){let h=p.filter(C=>C.position==="after");if(h.length>0){t.innerTokens.push(a.SPACE_TOKEN);for(let C of h){let f=this.createInlineCommentSequence(C.comments);t.innerTokens.push(...f)}}}let m=e.aliasComments;if(m&&m.length>0){t.innerTokens.push(a.SPACE_TOKEN);let h=this.createInlineCommentSequence(m);t.innerTokens.push(...h)}return t}visitSelectClause(e){let t=new d(1,"select","SelectClause");e.positionedComments&&e.positionedComments.length>0&&(this.addPositionedCommentsToToken(t,e),e.positionedComments=null);let n="select";for(let i of e.hints)n+=" "+this.visit(i).text;if(e.distinct){let i=e.distinct.accept(this);if(i.innerTokens&&i.innerTokens.length>0){let r=i.text;for(let s of i.innerTokens)r+=this.flattenTokenText(s);n+=" "+r}else n+=" "+i.text}t.text=n,t.innerTokens.push(a.SPACE_TOKEN);for(let i=0;i0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.items[i]));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){let t=new d(1,"distinct");return e.positionedComments&&e.positionedComments.length>0&&(this.addPositionedCommentsToToken(t,e),e.positionedComments=null),t}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(i=>i.accept(this).text).join(".")+"."),t+=e.table.accept(this).text;let n=new d(2,t);return this.addComponentComments(n,e),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 B){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;ns.position==="before");if(r.length>0)for(let s of r){let o=this.createInlineCommentSequence(s.comments);t.innerTokens.push(...o),t.innerTokens.push(a.SPACE_TOKEN)}}if(t.innerTokens.push(new d(1,e.joinType.value)),n){let r=n.filter(s=>s.position==="after");if(r.length>0){t.innerTokens.push(a.SPACE_TOKEN);for(let s of r){let o=this.createInlineCommentSequence(s.comments);t.innerTokens.push(...o)}}}let i=e.joinKeywordComments;if(i&&i.length>0){t.innerTokens.push(a.SPACE_TOKEN);let r=this.createInlineCommentSequence(i);t.innerTokens.push(...r)}return 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;n0&&t.innerTokens.push(...a.argumentCommaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));t.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return e.positionedComments&&e.positionedComments.length>0?(this.addPositionedCommentsToToken(t,e),e.positionedComments=null):e.comments&&e.comments.length>0&&this.addCommentsToToken(t,e.comments),t}visitWhereClause(e){let t=new d(1,"where","WhereClause");return this.addComponentComments(t,e),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;n0&&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;n0&&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;n0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(e.tables[n].accept(this));return t.innerTokens.push(a.SPACE_TOKEN),this.addComponentComments(t,e),t}visitCommonTable(e){let t=new d(0,"","CommonTable");e.positionedComments&&e.positionedComments.length>0?(this.addPositionedCommentsToToken(t,e),e.positionedComments=null):e.comments&&e.comments.length>0&&this.addCommentsToToken(t,e.comments),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){if(this.shouldMergeHeaderComments(e.headerComments)){let n=this.createHeaderMultiLineCommentBlock(e.headerComments);t.innerTokens.push(n)}else{let n=this.createCommentBlocks(e.headerComments);t.innerTokens.push(...n)}e.withClause&&t.innerTokens.push(a.SPACE_TOKEN)}if(e.positionedComments&&e.positionedComments.length>0&&(this.addPositionedCommentsToToken(t,e),e.positionedComments=null),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)if(this.shouldMergeHeaderComments(e.headerComments)){let i=this.createHeaderMultiLineCommentBlock(e.headerComments);t.innerTokens.push(i),t.innerTokens.push(a.SPACE_TOKEN)}else{let i=this.createCommentBlocks(e.headerComments);for(let r of i)t.innerTokens.push(r),t.innerTokens.push(a.SPACE_TOKEN)}t.innerTokens.push(a.SPACE_TOKEN);let n=new d(0,"","Values");for(let i=0;i0&&n.innerTokens.push(...a.commaSpaceTokens()),n.innerTokens.push(e.tuples[i].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 i=new d(4,")");this.addCommentsToToken(i,e.comments),t.innerTokens.push(i),e.comments=null}else t.innerTokens.push(a.PAREN_CLOSE_TOKEN);return t}visitInsertQuery(e){let t=new d(0,"","InsertQuery");return e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(this.visit(e.insertClause)),e.selectQuery&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(this.visit(e.selectQuery))),e.returningClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.returningClause.accept(this))),t}visitInsertClause(e){let t=new d(0,"","InsertClause");if(t.innerTokens.push(new d(1,"insert into")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),e.columns&&e.columns.length>0){t.innerTokens.push(a.PAREN_OPEN_TOKEN);for(let n=0;n0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(e.columns[n].accept(this));t.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return t}visitDeleteQuery(e){let t=new d(0,"","DeleteQuery");return e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(e.deleteClause.accept(this)),e.usingClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.usingClause.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}visitDeleteClause(e){let t=new d(1,"delete from","DeleteClause");return t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t}visitUsingClause(e){let t=new d(1,"using","UsingClause");if(e.sources.length>0){t.innerTokens.push(a.SPACE_TOKEN);for(let n=0;n0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.sources[n]))}return t}visitMergeQuery(e){let t=new d(0,"","MergeQuery");e.withClause&&t.innerTokens.push(e.withClause.accept(this)),t.innerTokens.push(new d(1,"merge into")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.target.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"using")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.source.accept(this)),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"on")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.onCondition.accept(this));for(let n of e.whenClauses)t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(n.accept(this));return t}visitMergeWhenClause(e){let t=new d(0,"","MergeWhenClause");return t.innerTokens.push(new d(1,this.mergeMatchTypeToKeyword(e.matchType))),e.condition&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"and")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.condition.accept(this))),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"then")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.action.accept(this)),t}visitMergeUpdateAction(e){let t=new d(0,"","MergeUpdateAction");return t.innerTokens.push(new d(1,"update")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.setClause.accept(this)),e.whereClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),t}visitMergeDeleteAction(e){let t=new d(0,"","MergeDeleteAction");return t.innerTokens.push(new d(1,"delete")),e.whereClause&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.whereClause.accept(this))),t}visitMergeInsertAction(e){let t=new d(0,"","MergeInsertAction");if(t.innerTokens.push(new d(1,"insert")),e.columns&&e.columns.length>0){t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(a.PAREN_OPEN_TOKEN);for(let n=0;n0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(e.columns[n].accept(this));t.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return e.defaultValues?(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"default values")),t):(e.values&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"values")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(e.values.accept(this)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN)),t)}visitMergeDoNothingAction(e){return new d(1,"do nothing","MergeDoNothingAction")}mergeMatchTypeToKeyword(e){switch(e){case"matched":return"when matched";case"not_matched":return"when not matched";case"not_matched_by_source":return"when not matched by source";case"not_matched_by_target":return"when not matched by target";default:return"when"}}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;n0&&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;n0&&t.innerTokens.push(...a.commaSpaceTokens()),t.innerTokens.push(this.visit(e.columns[n]));return t}visitCreateTableQuery(e){let t=e.isTemporary?"create temporary table":"create table",n=e.ifNotExists?`${t} if not exists`:t,i=new d(1,n,"CreateTableQuery");i.innerTokens.push(a.SPACE_TOKEN);let r=new G(e.namespaces??null,e.tableName);i.innerTokens.push(r.accept(this));let s=[...e.columns,...e.tableConstraints];if(s.length>0){i.innerTokens.push(a.SPACE_TOKEN),i.innerTokens.push(a.PAREN_OPEN_TOKEN);let o=new d(0,"","CreateTableDefinition");for(let u=0;u0&&o.innerTokens.push(...a.commaSpaceTokens()),o.innerTokens.push(s[u].accept(this));i.innerTokens.push(o),i.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return e.tableOptions&&(i.innerTokens.push(a.SPACE_TOKEN),i.innerTokens.push(e.tableOptions.accept(this))),e.asSelectQuery&&(i.innerTokens.push(a.SPACE_TOKEN),i.innerTokens.push(new d(1,"as")),i.innerTokens.push(a.SPACE_TOKEN),i.innerTokens.push(e.asSelectQuery.accept(this))),i}visitTableColumnDefinition(e){let t=new d(0,"","TableColumnDefinition");t.innerTokens.push(e.name.accept(this)),e.dataType&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.dataType.accept(this)));for(let n of e.constraints)t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(n.accept(this));return t}visitColumnConstraintDefinition(e){let t=new d(0,"","ColumnConstraintDefinition");e.constraintName&&(t.innerTokens.push(new d(1,"constraint")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.constraintName.accept(this)));let n=r=>{t.innerTokens.length>0&&t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,r))},i=r=>{t.innerTokens.length>0&&t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(r.accept(this))};switch(e.kind){case"not-null":n("not null");break;case"null":n("null");break;case"default":n("default"),e.defaultValue&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.defaultValue.accept(this)));break;case"primary-key":n("primary key");break;case"unique":n("unique");break;case"references":e.reference&&i(e.reference);break;case"check":e.checkExpression&&(n("check"),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.checkExpression)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN));break;case"generated-always-identity":case"generated-by-default-identity":case"raw":e.rawClause&&i(e.rawClause);break}return t}visitTableConstraintDefinition(e){let t=new d(0,"","TableConstraintDefinition"),n=l=>{t.innerTokens.length>0&&t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,l))},i=l=>{t.innerTokens.length>0&&t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(l.accept(this))},r=l=>{if(!l||l.length===0)return;t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(a.PAREN_OPEN_TOKEN);let c=new d(0,"","ValueList");for(let p=0;p0&&c.innerTokens.push(...a.commaSpaceTokens()),c.innerTokens.push(l[p].accept(this));t.innerTokens.push(c),t.innerTokens.push(a.PAREN_CLOSE_TOKEN)},s=this.constraintStyle==="mysql",o=new Set(["primary-key","unique","foreign-key"]),u=s&&!!e.constraintName&&o.has(e.kind);switch(e.constraintName&&!u&&(n("constraint"),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.constraintName.accept(this))),e.kind){case"primary-key":n("primary key"),u&&e.constraintName&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.constraintName.accept(this))),r(e.columns??[]);break;case"unique":s?(n("unique key"),u&&e.constraintName&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.constraintName.accept(this)))):n("unique"),r(e.columns??[]);break;case"foreign-key":n("foreign key"),u&&e.constraintName&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.constraintName.accept(this))),r(e.columns??[]),e.reference&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.reference.accept(this)));break;case"check":e.checkExpression&&(n("check"),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(a.PAREN_OPEN_TOKEN),t.innerTokens.push(this.visit(e.checkExpression)),t.innerTokens.push(a.PAREN_CLOSE_TOKEN));break;case"raw":e.rawClause&&i(e.rawClause);break}return t}visitReferenceDefinition(e){let t=new d(0,"","ReferenceDefinition");if(t.innerTokens.push(new d(1,"references")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.targetTable.accept(this)),e.columns&&e.columns.length>0){t.innerTokens.push(a.PAREN_OPEN_TOKEN);let n=new d(0,"","ValueList");for(let i=0;i0&&n.innerTokens.push(...a.commaSpaceTokens()),n.innerTokens.push(e.columns[i].accept(this));t.innerTokens.push(n),t.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return e.matchType&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,`match ${e.matchType}`))),e.onDelete&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"on delete")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,e.onDelete))),e.onUpdate&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"on update")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,e.onUpdate))),e.deferrable==="deferrable"?(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"deferrable"))):e.deferrable==="not deferrable"&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"not deferrable"))),e.initially==="immediate"?(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"initially immediate"))):e.initially==="deferred"&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"initially deferred"))),t}visitCreateIndexStatement(e){let t=["create"];e.unique&&t.push("unique"),t.push("index"),e.concurrently&&t.push("concurrently"),e.ifNotExists&&t.push("if not exists");let n=new d(1,t.join(" "),"CreateIndexStatement");n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(e.indexName.accept(this)),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,"on")),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(e.tableName.accept(this)),e.usingMethod&&(n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,"using")),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(e.usingMethod.accept(this))),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(a.PAREN_OPEN_TOKEN);let i=new d(0,"","IndexColumnList");for(let r=0;r0&&i.innerTokens.push(...a.commaSpaceTokens()),i.innerTokens.push(e.columns[r].accept(this));if(n.innerTokens.push(i),n.innerTokens.push(a.PAREN_CLOSE_TOKEN),e.include&&e.include.length>0){n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,"include")),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(a.PAREN_OPEN_TOKEN);let r=new d(0,"","ValueList");for(let s=0;s0&&r.innerTokens.push(...a.commaSpaceTokens()),r.innerTokens.push(e.include[s].accept(this));n.innerTokens.push(r),n.innerTokens.push(a.PAREN_CLOSE_TOKEN)}return e.withOptions&&(n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(e.withOptions.accept(this))),e.tablespace&&(n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,"tablespace")),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(e.tablespace.accept(this))),e.where&&(n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,"where")),n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(this.visit(e.where))),n}visitIndexColumnDefinition(e){let t=new d(0,"","IndexColumnDefinition");return t.innerTokens.push(this.visit(e.expression)),e.collation&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,"collate")),t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.collation.accept(this))),e.operatorClass&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(e.operatorClass.accept(this))),e.sortOrder&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,e.sortOrder))),e.nullsOrder&&(t.innerTokens.push(a.SPACE_TOKEN),t.innerTokens.push(new d(1,`nulls ${e.nullsOrder}`))),t}visitDropTableStatement(e){let t=e.ifExists?"drop table if exists":"drop table",n=new d(1,t,"DropTableStatement");n.innerTokens.push(a.SPACE_TOKEN);let i=new d(0,"","ValueList");for(let r=0;r0&&i.innerTokens.push(...a.commaSpaceTokens()),i.innerTokens.push(e.tables[r].accept(this));return n.innerTokens.push(i),e.behavior&&(n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,e.behavior))),n}visitDropIndexStatement(e){let t=["drop","index"];e.concurrently&&t.push("concurrently"),e.ifExists&&t.push("if exists");let n=new d(1,t.join(" "),"DropIndexStatement");n.innerTokens.push(a.SPACE_TOKEN);let i=new d(0,"","ValueList");for(let r=0;r0&&i.innerTokens.push(...a.commaSpaceTokens()),i.innerTokens.push(e.indexNames[r].accept(this));return n.innerTokens.push(i),e.behavior&&(n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(new d(1,e.behavior))),n}visitAlterTableStatement(e){let t=["alter","table"];e.ifExists&&t.push("if exists"),e.only&&t.push("only");let n=new d(1,t.join(" "),"AlterTableStatement");n.innerTokens.push(a.SPACE_TOKEN),n.innerTokens.push(e.table.accept(this));for(let i=0;i0){let t=this.lines[this.lines.length-1];t.text!==""&&(t.text=t.text.trimEnd()+this.newline)}this.lines.push(new nr(e,""))}appendText(e){if(this.cleanupLine(e)){let n=this.lines[this.lines.length-1];n.text=n.text.trimEnd()+e;return}let t=this.getCurrentLine();e===" "&&t.text===""||(t.text+=e)}cleanupLine(e){let t=this.getCurrentLine();if(e===","&&t.text.trim()===""&&this.lines.length>1&&(this.commaBreak==="after"||this.commaBreak==="none")){let n=this.lines.length-2;for(;n>=0&&this.lines[n].text.trim()==="";)this.lines.splice(n,1),n--;if(n<0)return!1;let i=this.lines[n];return this.lineHasTrailingComment(i.text)?!1:(this.lines.pop(),!0)}return!1}lineHasTrailingComment(e){return e.replace(/'([^']|'')*'/g,"").replace(/"([^"]|"")*"/g,"").trim().includes("--")}getCurrentLine(){if(this.lines.length>0)return this.lines[this.lines.length-1];throw new Error("No tokens to get current line from.")}isCurrentLineEmpty(){return this.lines.length>0?this.lines[this.lines.length-1].text.trim()==="":!0}},nr=class{constructor(e,t){this.level=e,this.text=t}};var vr={space:" ",tab:" "},Sr={lf:` `,crlf:`\r -`,cr:"\r"},br={quote:{start:'"',end:'"'},backtick:{start:"`",end:"`"},bracket:{start:"[",end:"]"},none:{start:"",end:""}};function Er(a){if(a===void 0)return;let e=typeof a=="string"?a.toLowerCase():a;return typeof e=="string"&&Object.prototype.hasOwnProperty.call(vr,e)?vr[e]:a}function xr(a){if(a===void 0)return;let e=typeof a=="string"?a.toLowerCase():a;return typeof e=="string"&&Object.prototype.hasOwnProperty.call(Sr,e)?Sr[e]:a}function Tr(a){if(a===void 0)return;if(typeof a=="string"){let n=a.toLowerCase();if(!Object.prototype.hasOwnProperty.call(br,n))throw new Error(`Unknown identifierEscape option: ${a}`);let i=br[n];return{start:i.start,end:i.end}}let e=a.start??"",t=a.end??"";return{start:e,end:t}}var ri=class{constructor(e){this.options=e}shouldFormatContainer(e,t){switch(e.containerType){case"ParenExpression":return this.options.parenthesesOneLine&&!t;case"BetweenExpression":return this.options.betweenOneLine;case"Values":return this.options.valuesOneLine;case"JoinOnClause":return this.options.joinOneLine;case"CaseExpression":return this.options.caseOneLine;case"InlineQuery":return this.options.subqueryOneLine;default:return!1}}isInsertClauseOneline(e){return this.options.insertColumnsOneLine&&e==="InsertClause"}shouldInsertJoinNewline(e){return!(e&&this.options.withClauseStyle==="full-oneline")}resolveCommaBreak(e,t,n,i){return e==="WithClause"?n:e==="Values"?i:this.isInsertClauseOneline(e)?"none":t}shouldSkipInsertClauseSpace(e,t,n){if(e!=="InsertClause")return!1;if(t&&t.type===4&&t.text==="(")return!0;if(!this.options.insertColumnsOneLine)return!1;let i=n.slice(-1);return i==="("||i===" "||i===""}shouldSkipCommentBlockSpace(e,t){return e==="CommentBlock"&&t&&this.options.withClauseStyle==="full-oneline"}formatInsertClauseToken(e,t,n,i){if(!this.isInsertClauseOneline(t))return{handled:!1};if(e==="")return{handled:!0};let r=e.match(/^\s+/)?.[0]??"",s=r?e.slice(r.length):e;if(s==="")return{handled:!0};if(r){let o=n.slice(-1);o!=="("&&o!==" "&&o!==""&&i()}return{handled:!0,text:s}}};var si=class a{constructor(e){this.insideWithClause=!1;this.pendingLineCommentBreak=null;this.smartCommentBlockBuilder=null;let t=Er(e?.indentChar),n=xr(e?.newline);this.indentChar=t??"",this.indentSize=e?.indentSize??0,this.newline=n??" ",this.commaBreak=e?.commaBreak??"none",this.cteCommaBreak=e?.cteCommaBreak??this.commaBreak,this.valuesCommaBreak=e?.valuesCommaBreak??this.commaBreak,this.andBreak=e?.andBreak??"none",this.orBreak=e?.orBreak??"none",this.keywordCase=e?.keywordCase??"none",this.exportComment=e?.exportComment??!1,this.withClauseStyle=e?.withClauseStyle??"standard",this.commentStyle=e?.commentStyle??"block",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.indentNestedParentheses=e?.indentNestedParentheses??!1,this.insertColumnsOneLine=e?.insertColumnsOneLine??!1;let i={parenthesesOneLine:this.parenthesesOneLine,betweenOneLine:this.betweenOneLine,valuesOneLine:this.valuesOneLine,joinOneLine:this.joinOneLine,caseOneLine:this.caseOneLine,subqueryOneLine:this.subqueryOneLine,insertColumnsOneLine:this.insertColumnsOneLine,withClauseStyle:this.withClauseStyle};this.onelineHelper=new ri(i),this.linePrinter=new En(this.indentChar,this.indentSize,this.newline,this.commaBreak),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","CreateTableDefinition","AlterTableStatement","IndexColumnList"])}print(e,t=0){return this.linePrinter=new En(this.indentChar,this.indentSize,this.newline,this.commaBreak),this.insideWithClause=!1,this.pendingLineCommentBreak=null,this.smartCommentBlockBuilder=null,this.linePrinter.lines.length>0&&t!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=t),this.appendToken(e,t,void 0,0,!1),this.linePrinter.print()}appendToken(e,t,n,i=0,r=!1){let s=this.insideWithClause;if(e.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"&&(this.insideWithClause=!0),this.shouldSkipToken(e))return;if(this.smartCommentBlockBuilder&&e.containerType!=="CommentBlock"&&e.type!==12&&this.flushSmartCommentBlockBuilder(),this.pendingLineCommentBreak!==null){this.isOnelineMode()||this.linePrinter.appendNewline(this.pendingLineCommentBreak);let f=e.type===12;if(this.pendingLineCommentBreak=null,f)return}if(e.containerType==="CommentBlock"){this.handleCommentBlockContainer(e,t);return}let o=this.linePrinter.getCurrentLine(),u=this.isCaseContext(e.containerType)?i+1:i,c=this.shouldIndentNestedParentheses(e);if(e.type===1)this.handleKeywordToken(e,t,n,i);else if(e.type===3)this.handleCommaToken(e,t,n);else if(e.type===4)this.handleParenthesisToken(e,t,r,n);else if(e.type===5&&e.text.toLowerCase()==="and")this.handleAndOperatorToken(e,t,n,i);else if(e.type===5&&e.text.toLowerCase()==="or")this.handleOrOperatorToken(e,t,n,i);else if(e.containerType==="JoinClause")this.handleJoinClauseToken(e,t);else if(e.type===6)this.exportComment&&this.printCommentToken(e.text,t,n);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(this.shouldFormatContainerAsOneline(e,c)){this.handleOnelineToken(e,t);return}else this.tryAppendInsertClauseTokenText(e.text,n)||this.linePrinter.appendText(e.text);if(e.keywordTokens&&e.keywordTokens.length>0)for(let f=0;f0){this.linePrinter.appendText(s);return}this.ensureSpaceBeforeKeyword(),this.linePrinter.appendText(s)}ensureSpaceBeforeKeyword(){let e=this.linePrinter.getCurrentLine();e.text===""||e.text[e.text.length-1]==="("||this.ensureTrailingSpace()}ensureTrailingSpace(){let e=this.linePrinter.getCurrentLine();e.text!==""&&(e.text.endsWith(" ")||(e.text+=" "),e.text=e.text.replace(/\s+$/," "))}tryAppendInsertClauseTokenText(e,t){let n=this.linePrinter.getCurrentLine().text,i=this.onelineHelper.formatInsertClauseToken(e,t,n,()=>this.ensureTrailingSpace());return i.handled?(i.text&&this.linePrinter.appendText(i.text),!0):!1}handleCommaToken(e,t,n){let i=e.text,r=n==="WithClause",s=this.onelineHelper.resolveCommaBreak(n,this.commaBreak,this.cteCommaBreak,this.valuesCommaBreak);if(this.insideWithClause&&this.withClauseStyle==="full-oneline")this.linePrinter.appendText(i);else if(this.withClauseStyle==="cte-oneline"&&r)this.linePrinter.appendText(i),this.linePrinter.appendNewline(t);else if(s==="before"){let o=this.linePrinter.commaBreak;o!=="before"&&(this.linePrinter.commaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||(this.linePrinter.appendNewline(t),n==="InsertClause"&&(this.linePrinter.getCurrentLine().level=t+1)),this.linePrinter.appendText(i),o!=="before"&&(this.linePrinter.commaBreak=o)}else if(s==="after"){let o=this.linePrinter.commaBreak;o!=="after"&&(this.linePrinter.commaBreak="after"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(i),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),o!=="after"&&(this.linePrinter.commaBreak=o)}else if(s==="none"){let o=this.linePrinter.commaBreak;o!=="none"&&(this.linePrinter.commaBreak="none"),this.linePrinter.appendText(i),this.onelineHelper.isInsertClauseOneline(n)&&this.ensureTrailingSpace(),o!=="none"&&(this.linePrinter.commaBreak=o)}else this.linePrinter.appendText(i)}handleAndOperatorToken(e,t,n,i=0){let r=this.applyKeywordCase(e.text);if(i>0){this.linePrinter.appendText(r);return}this.andBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)):this.andBreak==="after"?(this.linePrinter.appendText(r),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t)):this.linePrinter.appendText(r)}handleParenthesisToken(e,t,n,i){if(e.text==="("){if(this.linePrinter.appendText(e.text),i==="InsertClause"&&this.insertColumnsOneLine)return;this.isOnelineMode()||(this.shouldBreakAfterOpeningParen(i)?this.linePrinter.appendNewline(t+1):n&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&this.linePrinter.appendNewline(t));return}if(e.text===")"&&!this.isOnelineMode()){if(this.shouldBreakBeforeClosingParen(i)){this.linePrinter.appendNewline(Math.max(t,0)),this.linePrinter.appendText(e.text);return}if(n&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")){let r=Math.max(t-1,0);this.linePrinter.appendNewline(r)}}this.linePrinter.appendText(e.text)}handleOrOperatorToken(e,t,n,i=0){let r=this.applyKeywordCase(e.text);if(i>0){this.linePrinter.appendText(r);return}this.orBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)):this.orBreak==="after"?(this.linePrinter.appendText(r),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t)):this.linePrinter.appendText(r)}shouldIndentNestedParentheses(e){return!this.indentNestedParentheses||e.containerType!=="ParenExpression"?!1:e.innerTokens.some(t=>this.containsParenExpression(t))}containsParenExpression(e){if(e.containerType==="ParenExpression")return!0;for(let t of e.innerTokens)if(this.containsParenExpression(t))return!0;return!1}handleJoinClauseToken(e,t){let n=this.applyKeywordCase(e.text);this.onelineHelper.shouldInsertJoinNewline(this.insideWithClause)&&this.linePrinter.appendNewline(t),this.linePrinter.appendText(n)}shouldFormatContainerAsOneline(e,t){return this.onelineHelper.shouldFormatContainer(e,t)}isInsertClauseOneline(e){return this.onelineHelper.isInsertClauseOneline(e)}handleSpaceToken(e,t,n){this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder();let i=this.linePrinter.getCurrentLine().text;if(!this.onelineHelper.shouldSkipInsertClauseSpace(t,n,i)){if(this.onelineHelper.shouldSkipCommentBlockSpace(t,this.insideWithClause)){let r=this.linePrinter.getCurrentLine();r.text!==""&&!r.text.endsWith(" ")&&this.linePrinter.appendText(" ");return}this.linePrinter.appendText(e.text)}}printCommentToken(e,t,n){let i=e.trim();if(i&&!(this.commentStyle==="smart"&&n==="CommentBlock"&&this.handleSmartCommentBlockToken(e,i,t)))if(this.commentStyle==="smart"){let r=this.normalizeCommentForSmart(i);if(r.lines.length>1||r.forceBlock){let s=this.buildBlockComment(r.lines,t);this.linePrinter.appendText(s)}else{let s=r.lines[0],o=s?`-- ${s}`:"--";n==="CommentBlock"?(this.linePrinter.appendText(o),this.pendingLineCommentBreak=t):(this.linePrinter.appendText(o),this.linePrinter.appendNewline(t))}}else{if(i.startsWith("/*")&&i.endsWith("*/"))if(/\r?\n/.test(i)){let r=this.isOnelineMode()?" ":typeof this.newline=="string"?this.newline:` +`,cr:"\r"},br={quote:{start:'"',end:'"'},backtick:{start:"`",end:"`"},bracket:{start:"[",end:"]"},none:{start:"",end:""}};function Er(a){if(a===void 0)return;let e=typeof a=="string"?a.toLowerCase():a;return typeof e=="string"&&Object.prototype.hasOwnProperty.call(vr,e)?vr[e]:a}function xr(a){if(a===void 0)return;let e=typeof a=="string"?a.toLowerCase():a;return typeof e=="string"&&Object.prototype.hasOwnProperty.call(Sr,e)?Sr[e]:a}function Tr(a){if(a===void 0)return;if(typeof a=="string"){let n=a.toLowerCase();if(!Object.prototype.hasOwnProperty.call(br,n))throw new Error(`Unknown identifierEscape option: ${a}`);let i=br[n];return{start:i.start,end:i.end}}let e=a.start??"",t=a.end??"";return{start:e,end:t}}var ri=class{constructor(e){this.options=e}shouldFormatContainer(e,t){switch(e.containerType){case"ParenExpression":return this.options.parenthesesOneLine&&!t;case"BetweenExpression":return this.options.betweenOneLine;case"Values":return this.options.valuesOneLine;case"JoinOnClause":return this.options.joinOneLine;case"CaseExpression":return this.options.caseOneLine;case"InlineQuery":return this.options.subqueryOneLine;default:return!1}}isInsertClauseOneline(e){return this.options.insertColumnsOneLine&&e==="InsertClause"}shouldInsertJoinNewline(e){return!(e&&this.options.withClauseStyle==="full-oneline")}resolveCommaBreak(e,t,n,i){return e==="WithClause"?n:e==="Values"?i:this.isInsertClauseOneline(e)?"none":t}shouldSkipInsertClauseSpace(e,t,n){if(e!=="InsertClause")return!1;if(t&&t.type===4&&t.text==="(")return!0;if(!this.options.insertColumnsOneLine)return!1;let i=n.slice(-1);return i==="("||i===" "||i===""}shouldSkipCommentBlockSpace(e,t){return e==="CommentBlock"&&t&&this.options.withClauseStyle==="full-oneline"}formatInsertClauseToken(e,t,n,i){if(!this.isInsertClauseOneline(t))return{handled:!1};if(e==="")return{handled:!0};let r=e.match(/^\s+/)?.[0]??"",s=r?e.slice(r.length):e;if(s==="")return{handled:!0};if(r){let o=n.slice(-1);o!=="("&&o!==" "&&o!==""&&i()}return{handled:!0,text:s}}};var kr=new Set(["unique","check","key","index"]),Ir=new Set(["primary key","foreign key","unique key"]),Pr=new Set(["references"]),si=class a{constructor(e){this.insideWithClause=!1;this.pendingLineCommentBreak=null;this.smartCommentBlockBuilder=null;let t=Er(e?.indentChar),n=xr(e?.newline);this.indentChar=t??"",this.indentSize=e?.indentSize??0,this.newline=n??" ",this.commaBreak=e?.commaBreak??"none",this.cteCommaBreak=e?.cteCommaBreak??this.commaBreak,this.valuesCommaBreak=e?.valuesCommaBreak??this.commaBreak,this.andBreak=e?.andBreak??"none",this.orBreak=e?.orBreak??"none",this.keywordCase=e?.keywordCase??"none",this.exportComment=e?.exportComment??!1,this.withClauseStyle=e?.withClauseStyle??"standard",this.commentStyle=e?.commentStyle??"block",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.indentNestedParentheses=e?.indentNestedParentheses??!1,this.insertColumnsOneLine=e?.insertColumnsOneLine??!1;let i={parenthesesOneLine:this.parenthesesOneLine,betweenOneLine:this.betweenOneLine,valuesOneLine:this.valuesOneLine,joinOneLine:this.joinOneLine,caseOneLine:this.caseOneLine,subqueryOneLine:this.subqueryOneLine,insertColumnsOneLine:this.insertColumnsOneLine,withClauseStyle:this.withClauseStyle};this.onelineHelper=new ri(i),this.linePrinter=new En(this.indentChar,this.indentSize,this.newline,this.commaBreak),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","CreateTableDefinition","AlterTableStatement","IndexColumnList"])}print(e,t=0){return this.linePrinter=new En(this.indentChar,this.indentSize,this.newline,this.commaBreak),this.insideWithClause=!1,this.pendingLineCommentBreak=null,this.smartCommentBlockBuilder=null,this.linePrinter.lines.length>0&&t!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=t),this.appendToken(e,t,void 0,0,!1),this.linePrinter.print()}appendToken(e,t,n,i=0,r=!1){let s=this.insideWithClause;if(e.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"&&(this.insideWithClause=!0),this.shouldSkipToken(e))return;if(this.smartCommentBlockBuilder&&e.containerType!=="CommentBlock"&&e.type!==12&&this.flushSmartCommentBlockBuilder(),this.pendingLineCommentBreak!==null){this.isOnelineMode()||this.linePrinter.appendNewline(this.pendingLineCommentBreak);let f=e.type===12;if(this.pendingLineCommentBreak=null,f)return}if(e.containerType==="CommentBlock"){this.handleCommentBlockContainer(e,t);return}let o=this.linePrinter.getCurrentLine(),l=this.isCaseContext(e.containerType)?i+1:i,c=this.shouldIndentNestedParentheses(e);if(e.type===1)this.handleKeywordToken(e,t,n,i);else if(e.type===3)this.handleCommaToken(e,t,n);else if(e.type===4)this.handleParenthesisToken(e,t,r,n);else if(e.type===5&&e.text.toLowerCase()==="and")this.handleAndOperatorToken(e,t,n,i);else if(e.type===5&&e.text.toLowerCase()==="or")this.handleOrOperatorToken(e,t,n,i);else if(e.containerType==="JoinClause")this.handleJoinClauseToken(e,t);else if(e.type===6)this.exportComment&&this.printCommentToken(e.text,t,n);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(this.shouldFormatContainerAsOneline(e,c)){this.handleOnelineToken(e,t);return}else this.tryAppendInsertClauseTokenText(e.text,n)||this.linePrinter.appendText(e.text);if(e.keywordTokens&&e.keywordTokens.length>0)for(let f=0;f0){this.linePrinter.appendText(s);return}this.ensureSpaceBeforeKeyword(),this.linePrinter.appendText(s)}ensureSpaceBeforeKeyword(){let e=this.linePrinter.getCurrentLine();e.text===""||e.text[e.text.length-1]==="("||this.ensureTrailingSpace()}ensureTrailingSpace(){let e=this.linePrinter.getCurrentLine();e.text!==""&&(e.text.endsWith(" ")||(e.text+=" "),e.text=e.text.replace(/\s+$/," "))}tryAppendInsertClauseTokenText(e,t){let n=this.linePrinter.getCurrentLine().text,i=this.onelineHelper.formatInsertClauseToken(e,t,n,()=>this.ensureTrailingSpace());return i.handled?(i.text&&this.linePrinter.appendText(i.text),!0):!1}handleCommaToken(e,t,n){let i=e.text,r=n==="WithClause",s=this.onelineHelper.resolveCommaBreak(n,this.commaBreak,this.cteCommaBreak,this.valuesCommaBreak);if(this.insideWithClause&&this.withClauseStyle==="full-oneline")this.linePrinter.appendText(i);else if(this.withClauseStyle==="cte-oneline"&&r)this.linePrinter.appendText(i),this.linePrinter.appendNewline(t);else if(s==="before"){let o=this.linePrinter.commaBreak;o!=="before"&&(this.linePrinter.commaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||(this.linePrinter.appendNewline(t),n==="InsertClause"&&(this.linePrinter.getCurrentLine().level=t+1)),this.linePrinter.appendText(i),o!=="before"&&(this.linePrinter.commaBreak=o)}else if(s==="after"){let o=this.linePrinter.commaBreak;o!=="after"&&(this.linePrinter.commaBreak="after"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(i),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),o!=="after"&&(this.linePrinter.commaBreak=o)}else if(s==="none"){let o=this.linePrinter.commaBreak;o!=="none"&&(this.linePrinter.commaBreak="none"),this.linePrinter.appendText(i),this.onelineHelper.isInsertClauseOneline(n)&&this.ensureTrailingSpace(),o!=="none"&&(this.linePrinter.commaBreak=o)}else this.linePrinter.appendText(i)}handleAndOperatorToken(e,t,n,i=0){let r=this.applyKeywordCase(e.text);if(i>0){this.linePrinter.appendText(r);return}this.andBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)):this.andBreak==="after"?(this.linePrinter.appendText(r),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t)):this.linePrinter.appendText(r)}handleParenthesisToken(e,t,n,i){if(e.text==="("){if(this.linePrinter.appendText(e.text),i==="InsertClause"&&this.insertColumnsOneLine)return;this.isOnelineMode()||(this.shouldBreakAfterOpeningParen(i)?this.linePrinter.appendNewline(t+1):n&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&this.linePrinter.appendNewline(t));return}if(e.text===")"&&!this.isOnelineMode()){if(this.shouldBreakBeforeClosingParen(i)){this.linePrinter.appendNewline(Math.max(t,0)),this.linePrinter.appendText(e.text);return}if(n&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")){let r=Math.max(t-1,0);this.linePrinter.appendNewline(r)}}this.linePrinter.appendText(e.text)}handleOrOperatorToken(e,t,n,i=0){let r=this.applyKeywordCase(e.text);if(i>0){this.linePrinter.appendText(r);return}this.orBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t),this.linePrinter.appendText(r)):this.orBreak==="after"?(this.linePrinter.appendText(r),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(t)):this.linePrinter.appendText(r)}shouldIndentNestedParentheses(e){return!this.indentNestedParentheses||e.containerType!=="ParenExpression"?!1:e.innerTokens.some(t=>this.containsParenExpression(t))}containsParenExpression(e){if(e.containerType==="ParenExpression")return!0;for(let t of e.innerTokens)if(this.containsParenExpression(t))return!0;return!1}handleJoinClauseToken(e,t){let n=this.applyKeywordCase(e.text);this.onelineHelper.shouldInsertJoinNewline(this.insideWithClause)&&this.linePrinter.appendNewline(t),this.linePrinter.appendText(n)}shouldFormatContainerAsOneline(e,t){return this.onelineHelper.shouldFormatContainer(e,t)}isInsertClauseOneline(e){return this.onelineHelper.isInsertClauseOneline(e)}handleSpaceToken(e,t,n,i,r){this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder();let s=this.linePrinter.getCurrentLine().text;if(!this.onelineHelper.shouldSkipInsertClauseSpace(t,n,s)){if(this.onelineHelper.shouldSkipCommentBlockSpace(t,this.insideWithClause)){let o=this.linePrinter.getCurrentLine();o.text!==""&&!o.text.endsWith(" ")&&this.linePrinter.appendText(" ");return}this.shouldSkipSpaceBeforeParenthesis(t,n,i,r)||this.linePrinter.appendText(e.text)}}findPreviousSignificantToken(e,t){for(let n=t-1;n>=0;n--){let i=e[n];if(!(i.type===10||i.type===12)&&!(i.type===6&&!this.exportComment))return{token:i,index:n}}}shouldSkipSpaceBeforeParenthesis(e,t,n,i){return!t||t.type!==4||t.text!=="("||!e||!this.isCreateTableSpacingContext(e)||!n?!1:!!(this.isCreateTableNameToken(n,e)||this.isCreateTableConstraintKeyword(n,e)||i&&this.isCreateTableConstraintKeyword(i,e)&&this.isIdentifierAttachedToConstraint(n,i,e))}isCreateTableSpacingContext(e){switch(e){case"CreateTableQuery":case"CreateTableDefinition":case"TableConstraintDefinition":case"ColumnConstraintDefinition":case"ReferenceDefinition":return!0;default:return!1}}isCreateTableNameToken(e,t){return t!=="CreateTableQuery"?!1:e.containerType==="QualifiedName"}isCreateTableConstraintKeyword(e,t){if(e.type!==1)return!1;let n=e.text.toLowerCase();return t==="ReferenceDefinition"?Pr.has(n):!!(kr.has(n)||Ir.has(n))}isIdentifierAttachedToConstraint(e,t,n){if(!e)return!1;if(n==="ReferenceDefinition")return e.containerType==="QualifiedName"&&Pr.has(t.text.toLowerCase());if(n==="TableConstraintDefinition"||n==="ColumnConstraintDefinition"){let i=t.text.toLowerCase();if(kr.has(i)||Ir.has(i))return e.containerType==="IdentifierString"}return!1}printCommentToken(e,t,n){let i=e.trim();if(i&&!(this.commentStyle==="smart"&&n==="CommentBlock"&&this.handleSmartCommentBlockToken(e,i,t)))if(this.commentStyle==="smart"){let r=this.normalizeCommentForSmart(i);if(r.lines.length>1||r.forceBlock){let s=this.buildBlockComment(r.lines,t);this.linePrinter.appendText(s)}else{let s=r.lines[0],o=s?`-- ${s}`:"--";n==="CommentBlock"?(this.linePrinter.appendText(o),this.pendingLineCommentBreak=t):(this.linePrinter.appendText(o),this.linePrinter.appendNewline(t))}}else{if(i.startsWith("/*")&&i.endsWith("*/"))if(/\r?\n/.test(i)){let r=this.isOnelineMode()?" ":typeof this.newline=="string"?this.newline:` `,s=i.replace(/\r?\n/g,r);this.linePrinter.appendText(s)}else this.linePrinter.appendText(i);else this.linePrinter.appendText(i);i.startsWith("--")&&(n==="CommentBlock"?this.pendingLineCommentBreak=t:this.linePrinter.appendNewline(t))}}handleSmartCommentBlockToken(e,t,n){if(!this.smartCommentBlockBuilder){if(t==="/*")return this.smartCommentBlockBuilder={lines:[],level:n,mode:"block"},!0;let r=this.extractLineCommentContent(t);return r!==null?(this.smartCommentBlockBuilder={lines:[r],level:n,mode:"line"},!0):!1}if(this.smartCommentBlockBuilder.mode==="block"){if(t==="*/"){let{lines:r,level:s}=this.smartCommentBlockBuilder,o=this.buildBlockComment(r,s);return this.linePrinter.appendText(o),this.pendingLineCommentBreak=s,this.smartCommentBlockBuilder=null,!0}return this.smartCommentBlockBuilder.lines.push(this.normalizeSmartBlockLine(e)),!0}let i=this.extractLineCommentContent(t);return i!==null?(this.smartCommentBlockBuilder.lines.push(i),!0):(this.flushSmartCommentBlockBuilder(),!1)}handleCommentBlockContainer(e,t){if(!this.exportComment)return;if(this.commentStyle!=="smart"){let i=this.extractRawCommentBlockLines(e);if(i.length>0){let r=i.map(o=>`/* ${o} */`).join(" "),s=e.innerTokens?.some(o=>o.type===10&&o.text.includes(" "));this.linePrinter.appendText(s?`${r} `:r);return}for(let r of e.innerTokens)this.appendToken(r,t,e.containerType,0,!1);return}let n=this.collectCommentBlockLines(e);if(n.length===0&&!this.smartCommentBlockBuilder){this.smartCommentBlockBuilder={lines:[""],level:t,mode:"line"};return}!this.smartCommentBlockBuilder||this.smartCommentBlockBuilder.mode!=="line"?this.smartCommentBlockBuilder={lines:[...n],level:t,mode:"line"}:this.smartCommentBlockBuilder.lines.push(...n)}normalizeSmartBlockLine(e){let t=e.replace(/\s+$/g,"");return t?(t.startsWith(" ")&&(t=t.slice(2)),t.startsWith("* ")?t.slice(2):t==="*"?"":t.startsWith("*")?t.slice(1):t):""}extractLineCommentContent(e){return e.startsWith("--")?e.slice(2).trimStart():e.startsWith("/*")&&e.endsWith("*/")?e.slice(2,-2).trim():null}flushSmartCommentBlockBuilder(){if(!this.smartCommentBlockBuilder)return;let{lines:e,level:t,mode:n}=this.smartCommentBlockBuilder;if(n==="line"){if(e.length>1){let i=this.buildBlockComment(e,t);this.linePrinter.appendText(i)}else{let i=e[0]??"",r=i?`-- ${i}`:"--";this.linePrinter.appendText(r)}this.isOnelineMode()||this.linePrinter.appendNewline(t),this.pendingLineCommentBreak=null}this.smartCommentBlockBuilder=null}collectCommentBlockLines(e){let t=[],n=!1;for(let i of e.innerTokens??[])if(i.type===6){let r=i.text.trim();if(r==="/*"){n=!0;continue}if(r==="*/"){n=!1;continue}if(n){t.push(this.normalizeSmartBlockLine(i.text));continue}let s=this.extractLineCommentContent(r);s!==null&&t.push(s)}return t}extractRawCommentBlockLines(e){let t=[],n=!1;for(let i of e.innerTokens??[])if(i.type===6){let s=i.text.trim();if(s==="/*"){n=!0;continue}if(s==="*/"){n=!1;continue}if(n){s.length>0&&t.push(s);continue}}return t}normalizeCommentForSmart(e){let t=e.trim(),n=t,i=!1;if(t.startsWith("--"))n=t.slice(2);else if(t.startsWith("/*")&&t.endsWith("*/")){let p=t.slice(2,-2);p.replace(/\r?\n/g,` `).includes(` `)?(i=!0,n=p):(n=p,n.trim()||(n=t))}let o=this.escapeCommentDelimiters(n).replace(/\r?\n/g,` `).split(` -`),l=[],u=[];for(let p of o){let m=p.trim(),h=this.sanitizeCommentLine(p);h.length>0&&(l.push(h),u.push(m))}let c=l;if(c.length===0&&(c=[""]),!i&&c.length===1&&!c[0]&&t.startsWith("/*")&&t.endsWith("*/")){let p=this.escapeCommentDelimiters(t);c=[this.sanitizeCommentLine(p)]}return!i&&c.length>1&&(i=!0),c=c.map((p,m)=>{if(/^[-=_+*#]+$/.test(p)){let C=(u[m]??p).replace(/\s+/g,"");if(C.length>=p.length)return C}return p}),{lines:c,forceBlock:i}}buildBlockComment(e,t){if(e.length<=1){let c=e[0]??"";return c?`/* ${c} */`:"/* */"}let n=this.newline===" "?` -`:this.newline,i=this.linePrinter.getCurrentLine()?.level??t,r=this.getIndentString(i),o=r+" ",l=e.map(c=>`${o}${c}`).join(n),u=`${r}*/`;return`/*${n}${l}${n}${u}`}getIndentString(e){return e<=0?"":this.indentSize<=0?" ".repeat(e):(typeof this.indentChar=="string"?this.indentChar:"").repeat(this.indentSize*e)}sanitizeCommentLine(e){let t=e;return t=t.replace(/\u2028|\u2029/g," "),t=t.replace(/\s+/g," ").trim(),t}escapeCommentDelimiters(e){return e.replace(/\/\*/g,"\\/\\*").replace(/\*\//g,"*\\/")}handleCommentNewlineToken(e,t){if(!this.smartCommentBlockBuilder){if(this.pendingLineCommentBreak!==null){this.linePrinter.appendNewline(this.pendingLineCommentBreak),this.pendingLineCommentBreak=null;return}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 i=this.createCteOnelinePrinter().print(e,t),r=this.cleanDuplicateSpaces(i);r=r.replace(/\(\s+/g,"(").replace(/\s+\)/g," )"),this.linePrinter.appendText(r.trim())}createCteOnelinePrinter(){return new a({indentChar:"",indentSize:0,newline:" ",commaBreak:this.commaBreak,cteCommaBreak:this.cteCommaBreak,valuesCommaBreak:this.valuesCommaBreak,andBreak:this.andBreak,orBreak:this.orBreak,keywordCase:this.keywordCase,exportComment:!1,withClauseStyle:"standard",indentNestedParentheses:!1,insertColumnsOneLine:this.insertColumnsOneLine})}handleOnelineToken(e,t){let i=this.createOnelinePrinter().print(e,t),r=this.cleanDuplicateSpaces(i);this.linePrinter.appendText(r)}getClauseBreakIndentLevel(e,t){return t}shouldBreakAfterOpeningParen(e){return e==="InsertClause"?!this.isInsertClauseOneline(e):!1}shouldBreakBeforeClosingParen(e){return e==="InsertClause"?!this.isInsertClauseOneline(e):!1}shouldConvertSpaceToClauseBreak(e,t){if(!e||!t)return!1;let n=t.type===1?t.text.toLowerCase():null,i=t.containerType;return!!(e==="UpdateQuery"&&(n==="set"||n==="from"||n==="where"||n==="returning")||e==="InsertQuery"&&(n==="returning"||n&&(n.startsWith("select")||n.startsWith("values"))||i==="ValuesQuery"||i==="SimpleSelectQuery"||i==="InsertClause")||e==="DeleteQuery"&&(n==="using"||n==="where"||n==="returning")||(e==="MergeUpdateAction"||e==="MergeDeleteAction")&&n==="where"||e==="MergeInsertAction"&&n&&(n.startsWith("values")||n==="default values"))}createOnelinePrinter(){return new a({indentChar:"",indentSize:0,newline:" ",commaBreak:"none",cteCommaBreak:this.cteCommaBreak,valuesCommaBreak:"none",andBreak:"none",orBreak:"none",keywordCase:this.keywordCase,exportComment:this.exportComment,withClauseStyle:"standard",parenthesesOneLine:!1,betweenOneLine:!1,valuesOneLine:!1,joinOneLine:!1,caseOneLine:!1,subqueryOneLine:!1,indentNestedParentheses:!1,insertColumnsOneLine:this.insertColumnsOneLine})}cleanDuplicateSpaces(e){return e.replace(/\s{2,}/g," ")}};var Ip=["mysql","postgres","sqlserver","sqlite"],Ue=class{constructor(e={}){let t=e.preset?wr[e.preset]:void 0;if(e.preset&&!t)throw new Error(`Invalid preset: ${e.preset}`);let n=Tr(e.identifierEscape??t?.identifierEscape),i={...t,identifierEscape:n??t?.identifierEscape,parameterSymbol:e.parameterSymbol??t?.parameterSymbol,parameterStyle:e.parameterStyle??t?.parameterStyle,castStyle:e.castStyle??t?.castStyle};this.parser=new ii({...i}),this.printer=new si({...e,parenthesesOneLine:e.parenthesesOneLine,betweenOneLine:e.betweenOneLine,valuesOneLine:e.valuesOneLine,joinOneLine:e.joinOneLine,caseOneLine:e.caseOneLine,subqueryOneLine:e.subqueryOneLine,indentNestedParentheses:e.indentNestedParentheses})}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var At=class{constructor(){this.sqlFormatter=new Ue({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(e,t=null){return t&&(this.sqlFormatter=new Ue(t)),this.sqlFormatter.format(e).formattedSql}formatWithParameters(e,t=null){t&&(this.sqlFormatter=new Ue(t));let n=this.sqlFormatter.format(e);return{sql:n.formattedSql,params:n.params}}visit(e){return this.format(e)}};var oi=class{constructor(){this.sourceCollector=new rt(!0),this.cteCollector=new ne,this.formatter=new At}build(e){if(e.length===0)return new he(!1,e);let t=this.resolveDuplicateNames(e),{tableMap:n,recursiveCTEs:i,dependencies:r}=this.buildDependencyGraph(t),s=this.sortCommonTables(t,n,i,r);return new he(i.size>0,s)}resolveDuplicateNames(e){let t=new Map;for(let i of e){let r=i.aliasExpression.table.name;t.has(r)||t.set(r,[]),t.get(r).push(i)}let n=[];for(let[i,r]of Array.from(t.entries())){if(r.length===1){n.push(r[0]);continue}let s=r.map(l=>this.formatter.format(l.query));if(new Set(s).size===1)n.push(r[0]);else throw new Error(`CTE name conflict detected: '${i}' has multiple different definitions`)}return n}buildDependencyGraph(e){let t=new Map;for(let s of e)t.set(s.aliasExpression.table.name,s);let n=new Set,i=new Map,r=new Map;for(let s of e){let 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}i.has(o)||i.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)&&(i.get(o).add(p),r.has(p)||r.set(p,new Set),r.get(p).add(o))}}return{tableMap:t,recursiveCTEs:n,dependencies:i}}sortCommonTables(e,t,n,i){let r=[],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=i.get(c)||new Set;for(let m of Array.from(p))u(m);l.delete(c),o.add(c),n.has(c)?r.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[...r,...s]}};var ai=class{constructor(){this.nameConflictResolver=new oi,this.cteCollector=new ne}inject(e,t){if(t.length===0)return e;t.push(...this.cteCollector.collect(e));let n=this.nameConflictResolver.build(t);if(e instanceof w)return this.injectIntoSimpleQuery(e,n);if(e instanceof O)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 w)return this.injectIntoSimpleQuery(e.left,t),e;if(e.left instanceof O)return this.injectIntoBinaryQuery(e.left,t),e;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var dt=class{constructor(){}static normalize(e){let n=new ne().collect(e);return n.length===0?e:(new Ht().execute(e),new ai().inject(e,n))}};var Vt=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))(Vt||{}),Ne=class a{constructor(e,t=!1,n="columnNameOnly",i){this.selectValues=[];this.visitedNodes=new Set;this.uniqueKeys=new Set;this.isRootVisit=!0;this.tableColumnResolver=null;this.commonTables=[];this.initializeProperties(e,t,n,i),this.initializeHandlers()}initializeProperties(e,t,n,i){this.tableColumnResolver=e??null,this.includeWildCard=t,this.commonTableCollector=new ne,this.commonTables=[],this.duplicateDetection=n,this.options=i||{}}initializeHandlers(){this.handlers=new Map,this.handlers.set(w.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(O.kind,e=>this.visitBinarySelectQuery(e)),this.initializeClauseHandlers(),this.initializeValueComponentHandlers()}initializeClauseHandlers(){this.handlers.set(z.kind,e=>this.visitSelectClause(e)),this.handlers.set(_.kind,e=>this.visitFromClause(e)),this.handlers.set(re.kind,e=>this.visitWhereClause(e)),this.handlers.set(ge.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ye.kind,e=>this.visitHavingClause(e)),this.handlers.set(Ce.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Oe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(ce.kind,e=>this.visitLimitClause(e)),this.handlers.set($e.kind,e=>this.offsetClause(e)),this.handlers.set(He.kind,e=>this.visitFetchClause(e)),this.handlers.set(we.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Te.kind,e=>this.visitJoinUsingClause(e))}initializeValueComponentHandlers(){this.handlers.set(E.kind,e=>this.visitColumnReference(e)),this.handlers.set(b.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(H.kind,e=>this.visitFunctionCall(e)),this.handlers.set(de.kind,e=>this.visitInlineQuery(e)),this.handlers.set(ee.kind,e=>this.visitParenExpression(e)),this.handlers.set(ue.kind,e=>this.visitCaseExpression(e)),this.handlers.set(fe.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ee.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(Se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(be.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(lt.kind,e=>this.visitArraySliceExpression(e)),this.handlers.set(ut.kind,e=>this.visitArrayIndexExpression(e)),this.handlers.set(W.kind,e=>this.visitValueList(e)),this.handlers.set(Ke.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(_e.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 i=n?n+"."+e:e;return this.normalizeColumnName(i)}}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 w||e instanceof O))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 w?this.visitSimpleSelectQuery(e.left):e.left instanceof O&&this.visitBinarySelectQuery(e.left),e.right instanceof w?this.visitSimpleSelectQuery(e.right):e.right instanceof O&&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 E){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 Ze(this.tableColumnResolver,this.commonTables).collect(e);for(let i of n)this.addSelectValueAsUnique(i.name,i.value);if(this.options.upstream&&this.collectUpstreamColumns(e),e.joins)for(let i of e.joins)i.condition&&i.condition.accept(this)}visitWhereClause(e){e.condition&&e.condition.accept(this)}visitGroupByClause(e){if(e.grouping)for(let t of e.grouping)t.accept(this)}visitHavingClause(e){e.condition&&e.condition.accept(this)}visitOrderByClause(e){if(e.order)for(let t of e.order)t.accept(this)}visitWindowFrameClause(e){e.expression.accept(this)}visitWindowFrameExpression(e){e.partition&&e.partition.accept(this),e.order&&e.order.accept(this),e.frameSpec&&e.frameSpec.accept(this)}visitLimitClause(e){e.value&&e.value.accept(this)}offsetClause(e){e.value&&e.value.accept(this)}visitFetchClause(e){e.expression&&e.expression.accept(this)}visitJoinOnClause(e){e.condition&&e.condition.accept(this)}visitJoinUsingClause(e){e.condition&&e.condition.accept(this)}visitColumnReference(e){if(e.column.name!=="*")this.addSelectValueAsUnique(e.column.name,e);else if(this.includeWildCard)this.addSelectValueAsUnique(e.column.name,e);else return}visitBinaryExpression(e){e.left&&e.left.accept(this),e.right&&e.right.accept(this)}visitUnaryExpression(e){e.expression&&e.expression.accept(this)}visitFunctionCall(e){e.argument&&e.argument.accept(this),e.over&&e.over.accept(this),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 B){let t=this.findCTEByName(e.datasource.table.name);t?this.collectUpstreamColumnsFromCTE(t):this.collectUpstreamColumnsFromTable(e.datasource)}else e.datasource instanceof U?this.collectUpstreamColumnsFromSubquery(e.datasource):e.datasource instanceof je&&this.collectUpstreamColumnsFromSource(new $(e.datasource.source,null))}collectUpstreamColumnsFromTable(e){if(this.tableColumnResolver){let t=e.table.name,n=this.tableColumnResolver(t);for(let i of n){let r=new E(e.table.name,i);this.addSelectValueAsUnique(i,r)}}}collectUpstreamColumnsFromSubquery(e){if(e.query instanceof w){let n=new a(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!0}).collect(e.query);for(let i of n)this.addSelectValueAsUnique(i.name,i.value)}}collectUpstreamColumnsFromCTE(e){if(e.query instanceof w){let n=new a(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!1}).collect(e.query);for(let i of n)i.name!=="*"&&this.addSelectValueAsUnique(i.name,i.value)}}collectAllAvailableCTEColumns(){for(let e of this.commonTables)this.collectUpstreamColumnsFromCTE(e)}findCTEByName(e){return this.commonTables.find(t=>t.getSourceAliasName()===e)||null}};var Dt=class a{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex0?r.positionedComments=n.positionedComments:n.comments&&n.comments.length>0&&(r.comments=n.comments),{value:r,newIndex:i}}static parseFunctionSource(e,t){let n=t.newIndex,{namespaces:i,name:r}=t,s=x.parseArgument(4,8,e,n);n=s.newIndex;let o=r.name;return{value:new nt({namespaces:i,name:o},s.value),newIndex:n}}static parseParenSource(e,t){let n=t,i=e[n];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 s=this.parseSubQuerySource(e,n,i);if(n=s.newIndex,n0){let l=n.positionedComments.filter(u=>u.position==="after");if(l.length>0){let u=l.map(c=>({position:"before",comments:c.comments}));r.positionedComments?r.positionedComments=[...u,...r.positionedComments]:r.positionedComments=u,r.comments&&(r.comments=null)}}return{value:new U(r),newIndex:i}}};var xn=class extends Error{constructor(t){super(`CTE '${t}' already exists in the query`);this.cteName=t;this.name="DuplicateCTEError"}},on=class extends Error{constructor(t,n){super(`Invalid CTE name '${t}': ${n}`);this.cteName=t;this.name="InvalidCTENameError"}},Tn=class extends Error{constructor(t){super(`CTE '${t}' not found in the query`);this.cteName=t;this.name="CTENotFoundError"}};var an=class{constructor(e,t){this.options=t||{},this.tableColumnResolver=e,this.columnCollector=new Ne(this.tableColumnResolver,!1,"fullName",{upstream:!0})}find(e,t){let n=typeof t=="string"?[t]:t,r=new ne().collect(e),s=new Map;for(let o of r)s.set(o.getSourceAliasName(),o);return this.findUpstream(e,n,s)}handleTableSource(e,t,n){let i=n.get(e.table.name);if(i){let r=new Map(n);r.delete(e.table.name);let s=this.findUpstream(i.query,t,r);return s.length===0?null:s}return null}handleSubQuerySource(e,t,n){let i=this.findUpstream(e.query,t,n);return i.length===0?null:i}processFromClauseBranches(e,t,n){let i=e.getSources();if(i.length===0)return null;let r=[],s=!0,o=0;for(let l of i){let u=l.datasource,c=null;if(u instanceof B)c=this.handleTableSource(u,t,n),o++;else if(u instanceof U)c=this.handleSubQuerySource(u,t,n),o++;else{if(u instanceof ae)continue;s=!1;break}if(c===null){s=!1;break}r.push(c)}return s&&r.length===o?r.flat():null}findUpstream(e,t,n){if(e instanceof w){let i=e.fromClause;if(i){let c=this.processFromClauseBranches(i,t,n);if(c&&c.length>0)return c}let r=this.columnCollector.collect(e).map(c=>c.name),s=this.collectCTEColumns(e,n),o=[...r,...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 O){let i=this.findUpstream(e.left,t,n),r=this.findUpstream(e.right,t,n);return[...i,...r]}return[]}collectCTEColumns(e,t){let n=[];if(e.withClause)for(let i of e.withClause.tables){let r=this.collectColumnsFromSelectQuery(i.query);n.push(...r)}return n}collectColumnsFromSelectQuery(e){if(e instanceof w)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 O)return this.collectColumnsFromSelectQuery(e.left);return[]}};var $t=class{static parseFromLexeme(e,t){let n=t;if(n0&&(l.positionedComments=i.positionedComments),{value:l,newIndex:n}}let s=new se(r,null);return i.positionedComments&&i.positionedComments.length>0&&(s.positionedComments=i.positionedComments),{value:s,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 pe=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndexo.name),r=t.tuples.map(o=>{if(o.values.length!==i.length)throw new Error("Tuple value count does not match column count.");let l=i.map((c,p)=>new q(o.values[p],c)),u=new z(l);return new w({selectClause:u})}),s=r[0];for(let o=1;oo.name),i=this.flattenSelectQueries(e.selectQuery);if(!i.length)throw new Error("No SELECT components found to convert.");let r=i.map(o=>{if(o.fromClause||o.whereClause&&o.whereClause.condition)throw new Error("SELECT queries with FROM or WHERE clauses cannot be converted to VALUES.");let l=new Map;for(let c of o.selectClause.items){let p=c.identifier?.name??null;if(!p)throw new Error("Each SELECT item must have an alias matching target columns.");l.has(p)||l.set(p,c.value)}let u=n.map(c=>{let p=l.get(c);if(!p)throw new Error(`Column '${c}' is not provided by the SELECT query.`);return p});return new xe(u)}),s=new ae(r,n);return new tt({withClause:e.withClause,insertClause:e.insertClause,selectQuery:s,returning:e.returningClause})}static flattenSelectQueries(e){if(e instanceof w)return[e];if(e instanceof O)return[...this.flattenSelectQueries(e.left),...this.flattenSelectQueries(e.right)];throw new Error("Unsupported SelectQuery subtype for conversion.")}};var Ie=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=r=>r instanceof ae?a.buildSimpleQuery(r):r,i=new O(n(e[0]),t,n(e[1]));dt.normalize(i);for(let r=2;r0?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 U(e),i=new $(n,new se("vq",e.columnAliases)),r=new _(i,null),s=e.columnAliases.map(l=>new q(new E("vq",l),l)),o=new z(s,null);return new w({selectClause:o,fromClause:r})}static createSelectAllClause(){let e=new E(null,"*"),t=new q(e,"*");return new z([t],null)}static buildCreateTableQuery(e,t,n=!1,i=!1){return new Pt({tableName:t,isTemporary:n,ifNotExists:i,asSelectQuery:e})}static buildInsertQuery(e,t,n){let i=a.normalizeInsertOptions(t,n),r=a.prepareInsertColumns(e,i.columns??null),s=a.extractWithClause(e),o=pe.parse(i.target);return new tt({withClause:s??void 0,insertClause:new xt(o,r),selectQuery:e})}static convertInsertValuesToSelect(e){return kn.toSelectUnion(e)}static convertInsertSelectToValues(e){return kn.toValues(e)}static buildUpdateQuery(e,t,n,i){let r=a.normalizeUpdateOptions(t,n,i),s=a.prepareUpdateColumns(e,r.primaryKeys,r.columns??null),o=new bt(pe.parse(r.target)),l=o.getSourceAliasName();if(!l)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let u=a.extractWithClause(e),c=s.map(C=>new Xe(C,a.toColumnReference(r.sourceAlias,C)));if(c.length===0)throw new Error("No updatable columns found. Ensure the select list contains at least one column other than the specified primary keys.");let p=new Fe(c),m=new _(e.toSource(r.sourceAlias),null),h=new re(a.buildEqualityPredicate(l,r.sourceAlias,r.primaryKeys));return new Ct({updateClause:o,setClause:p,fromClause:m,whereClause:h,withClause:u??void 0})}static buildDeleteQuery(e,t){let n=a.normalizeDeleteOptions(t),i=a.prepareDeleteColumns(e,n.primaryKeys,n.columns??null),r=new Et(pe.parse(n.target)),s=r.getSourceAliasName();if(!s)throw new Error("Source expression does not have an alias. Please provide an alias for the delete target.");let o=a.extractWithClause(e),l=a.buildEqualityPredicate(s,n.sourceAlias,i),u=e.toSource(n.sourceAlias),c=new z([new q(new Z(1))]),p=new w({selectClause:c,fromClause:new _(u,null),whereClause:new re(l)}),m=new re(new te("exists",new de(p)));return new gt({deleteClause:r,whereClause:m,withClause:o??void 0})}static buildMergeQuery(e,t){let n=a.normalizeMergeOptions(t),i=a.prepareMergeColumns(e,n.primaryKeys,n.updateColumns??null,n.insertColumns??null,n.matchedAction??"update",n.notMatchedAction??"insert"),r=pe.parse(n.target),s=r.getAliasName();if(!s)throw new Error("Source expression does not have an alias. Please provide an alias for the merge target.");let o=a.extractWithClause(e),l=a.buildEqualityPredicate(s,n.sourceAlias,n.primaryKeys),u=e.toSource(n.sourceAlias),c=[],p=n.matchedAction??"update";if(p==="update"){if(i.updateColumns.length===0)throw new Error("No columns available for MERGE update action. Provide updateColumns or ensure the select list includes non-key columns.");let C=i.updateColumns.map(f=>new Xe(f,a.toColumnReference(n.sourceAlias,f)));c.push(new Ge("matched",new Lt(new Fe(C))))}else p==="delete"?c.push(new Ge("matched",new yt)):p==="doNothing"&&c.push(new Ge("matched",new mt));let m=n.notMatchedAction??"insert";if(m==="insert"){if(i.insertColumns.length===0)throw new Error("Unable to infer MERGE insert columns. Provide insertColumns explicitly.");let C=new W(i.insertColumns.map(f=>a.toColumnReference(n.sourceAlias,f)));c.push(new Ge("not_matched",new wt({columns:i.insertColumns,values:C})))}else m==="doNothing"&&c.push(new Ge("not_matched",new mt));let h=n.notMatchedBySourceAction??"doNothing";if(h==="delete"?c.push(new Ge("not_matched_by_source",new yt)):h==="doNothing"&&c.push(new Ge("not_matched_by_source",new mt)),c.length===0)throw new Error("At least one MERGE action must be generated. Adjust the merge conversion options.");return new vt({withClause:o??void 0,target:r,source:u,onCondition:l,whenClauses:c})}static normalizeInsertOptions(e,t){return typeof e=="string"?{target:e,columns:t}:t&&t.length>0?{...e,columns:t}:{...e}}static normalizeUpdateOptions(e,t,n){if(typeof e=="string"){if(!t)throw new Error("updateTableExprRaw is required when using the legacy buildUpdateQuery signature.");if(n===void 0)throw new Error("primaryKeys are required when using the legacy buildUpdateQuery signature.");return{target:t,primaryKeys:a.normalizeColumnArray(n),sourceAlias:e}}return{target:e.target,primaryKeys:a.normalizeColumnArray(e.primaryKeys),sourceAlias:e.sourceAlias??"src",columns:e.columns}}static normalizeDeleteOptions(e){return{...e,primaryKeys:a.normalizeColumnArray(e.primaryKeys),sourceAlias:e.sourceAlias??"src"}}static normalizeMergeOptions(e){return{...e,primaryKeys:a.normalizeColumnArray(e.primaryKeys),sourceAlias:e.sourceAlias??"src"}}static normalizeColumnArray(e){let n=(Array.isArray(e)?e:[e]).map(i=>i.trim()).filter(i=>i.length>0);if(!n.length)throw new Error("At least one column must be specified.");return n}static collectSelectItems(e){return new Ze().collect(e)}static collectSelectColumnNames(e){let t=a.collectSelectItems(e),n=[];for(let i of t){if(!i.name||i.name==="*")throw new Error("Columns cannot be inferred from the selectQuery. Make sure you are not using wildcards or unnamed columns.");n.includes(i.name)||n.push(i.name)}if(!n.length)throw new Error("Unable to determine any column names from selectQuery.");return n}static ensurePrimaryKeys(e,t){let n=new Set(e);for(let i of t)if(!n.has(i))throw new Error(`Primary key column '${i}' is not present in selectQuery select list.`)}static prepareInsertColumns(e,t){let n=a.collectSelectColumnNames(e);if(t&&t.length>0){let i=a.normalizeColumnArray(t),r=i.filter((o,l)=>i.indexOf(o)===l),s=r.filter(o=>!n.includes(o));if(s.length>0)throw new Error(`Columns specified in conversion options were not found in selectQuery select list: [${s.join(", ")}].`);return a.rebuildSelectClause(e,r),a.ensureSelectClauseSize(e,r.length),r}return a.ensureSelectClauseSize(e,n.length),n}static prepareUpdateColumns(e,t,n){let i=a.collectSelectColumnNames(e);a.ensurePrimaryKeys(i,t);let r=new Set(t),s=i.filter(u=>!r.has(u)),o;if(n&&n.length>0){let u=a.normalizeColumnArray(n),c=u.filter((m,h)=>u.indexOf(m)===h),p=c.filter(m=>r.has(m)||!s.includes(m));if(p.length>0)throw new Error(`Provided update columns were not found in selectQuery output or are primary keys: [${p.join(", ")}].`);o=c}else o=Array.from(new Set(s));let l=Array.from(new Set([...t,...o]));return a.rebuildSelectClause(e,l),a.ensureSelectClauseSize(e,l.length),o}static prepareDeleteColumns(e,t,n){let i=a.collectSelectColumnNames(e);a.ensurePrimaryKeys(i,t);let r=new Set(t),s=[];if(n&&n.length>0){let u=a.normalizeColumnArray(n),c=new Set(u);s=i.filter(p=>c.has(p)&&!r.has(p))}let o=new Set;t.forEach(u=>o.add(u)),s.forEach(u=>o.add(u));let l=i.filter(u=>o.has(u));return a.rebuildSelectClause(e,l),a.ensureSelectClauseSize(e,l.length),l}static prepareMergeColumns(e,t,n,i,r,s){let o=a.collectSelectColumnNames(e);a.ensurePrimaryKeys(o,t);let l=new Set(t),u=[];if(r==="update"){let C=o.filter(f=>!l.has(f));if(n&&n.length>0){let f=a.normalizeColumnArray(n),N=f.filter((v,g)=>f.indexOf(v)===g),V=N.filter(v=>l.has(v)||!C.includes(v));if(V.length>0)throw new Error(`Provided update columns were not found in selectQuery output or are primary keys: [${V.join(", ")}].`);u=N}else u=Array.from(new Set(C))}let c=[];if(s==="insert")if(i&&i.length>0){let C=a.normalizeColumnArray(i),f=C.filter((V,v)=>C.indexOf(V)===v),N=f.filter(V=>!o.includes(V));if(N.length>0)throw new Error(`Provided insert columns were not found in selectQuery output: [${N.join(", ")}].`);c=f}else c=Array.from(new Set(o));let p=Array.from(new Set([...t,...u,...c,...o])).filter(C=>o.includes(C));return a.rebuildSelectClause(e,p),a.ensureSelectClauseSize(e,p.length),{updateColumns:r==="update"?u:[],insertColumns:s==="insert"?c:[]}}static rebuildSelectClause(e,t){let n=new Map;for(let s of e.selectClause.items){let o=a.getSelectItemName(s);o&&(n.has(o)||n.set(o,s))}let i=[],r=new Set;for(let s of t){if(r.has(s))continue;let o=n.get(s);if(!o)throw new Error(`Column '${s}' not found in select clause.`);i.push(o),r.add(s)}if(!i.length)throw new Error("Unable to rebuild select clause with the requested columns.");e.selectClause.items=i}static getSelectItemName(e){return e.identifier?e.identifier.name:e.value instanceof E?e.value.column.name:null}static ensureSelectClauseSize(e,t){if(e.selectClause.items.length!==t)throw new Error(`Select clause column count (${e.selectClause.items.length}) does not match expected count (${t}).`)}static extractWithClause(e){let n=new ne().collect(e);return n.length===0?null:(new Ht().execute(e),new he(!1,n))}static buildEqualityPredicate(e,t,n){let i=a.mergeUniqueColumns(n);if(!i.length)throw new Error("At least one column is required to build a comparison predicate.");let r=null;for(let s of i){let o=new b(a.toColumnReference(e,s),"=",a.toColumnReference(t,s));r=r?new b(r,"and",o):o}return r}static toColumnReference(e,t){return new E(e,t)}static mergeUniqueColumns(e){let t=new Set,n=[];for(let i of e)t.has(i)||(t.add(i),n.push(i));return n}};var w=class extends y{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)}toInsertQuery(t){return Ie.buildInsertQuery(this,t)}toUpdateQuery(t){return Ie.buildUpdateQuery(this,t)}toDeleteQuery(t){return Ie.buildDeleteQuery(this,t)}toMergeQuery(t){return Ie.buildMergeQuery(this,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 Ie.buildBinaryQuery([this,n],t)}appendWhereRaw(t){let n=x.parse(t);this.appendWhere(n)}appendWhere(t){this.whereClause?this.whereClause.condition=new b(this.whereClause.condition,"and",t):this.whereClause=new re(t)}appendHavingRaw(t){let n=x.parse(t);this.appendHaving(n)}appendHaving(t){this.havingClause?this.havingClause.condition=new b(this.havingClause.condition,"and",t):this.havingClause=new ye(t)}innerJoinRaw(t,n,i,r=null){this.joinSourceRaw("inner join",t,n,i,r)}leftJoinRaw(t,n,i,r=null){this.joinSourceRaw("left join",t,n,i,r)}rightJoinRaw(t,n,i,r=null){this.joinSourceRaw("right join",t,n,i,r)}innerJoin(t,n,i=null){this.joinSource("inner join",t,n,i)}leftJoin(t,n,i=null){this.joinSource("left join",t,n,i)}rightJoin(t,n,i=null){this.joinSource("right join",t,n,i)}joinSourceRaw(t,n,i,r,s=null){let o=Dt.parse(n),l=new $(o,new se(i,null));this.joinSource(t,l,r,s)}joinSource(t,n,i,r=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let s=Array.isArray(i)?i:[i],l=new Ne(r).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 C of l)if(s.some(f=>f==C.name)){let f=new b(C.value,"=",new E([p],C.name));u?u=new b(u,"and",f):u=f,c++}if(!u||c!==s.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${s.join(", ")}`);let m=new we(u),h=new ve(t,n,m,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(h):this.fromClause.joins=[h]),dt.normalize(this)}toSource(t){if(!t||t.trim()==="")throw new Error("Alias is required for toSource(). Please specify a non-empty alias name.");return new $(new U(this),new se(t,null))}appendWith(t){let n=Array.isArray(t)?t:[t];this.withClause?this.withClause.tables.push(...n):this.withClause=new he(!1,n),dt.normalize(this)}appendWithRaw(t,n){let i=P.parse(t),r=new oe(i,n,null);this.appendWith(r)}overrideSelectItemExpr(t,n){let i=this.selectClause.items.filter(u=>u.identifier?.name===t);if(i.length===0)throw new Error(`Column ${t} not found in the query`);if(i.length>1)throw new Error(`Duplicate column name ${t} found in the query`);let r=i[0],o=new At().visit(r.value),l=n(o);r.value=x.parse(l)}appendWhereExpr(t,n,i){if(i&&i.upstream){let s=new an().find(this,[t]),o=new Ne,l=new At;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 r=new Ne,s=new At,o=r.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 ht.set(this,t,n),this}toSimpleQuery(){return this}addCTE(t,n,i){if(!t||t.trim()==="")throw new on(t,"name cannot be empty or whitespace-only");if(this.hasCTE(t))throw new xn(t);let r=i?.materialized??null,s=new oe(n,t,r);return this.appendWith(s),this.cteNameCache.add(t),this}removeCTE(t){if(!this.hasCTE(t))throw new Tn(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,i){if(!t||t.trim()==="")throw new on(t,"name cannot be empty or whitespace-only");this.hasCTE(t)&&this.removeCTE(t);let r=i?.materialized??null,s=new oe(n,t,r);return this.appendWith(s),this.cteNameCache.add(t),this}};var li=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex{this.clearPositionedCommentsRecursively(t)}),e.value&&this.clearPositionedCommentsRecursively(e.value))}static extractValueTokenComments(e,t){if(t>=e.length)return{positioned:null,legacy:null};let n=e[t];return{positioned:n.positionedComments&&n.positionedComments.length>0?n.positionedComments:null,legacy:null}}static parseAsKeyword(e,t){if(t>=e.length||e[t].value!=="as")return{asComments:{positioned:null,legacy:null},newIndex:t};let n=e[t];return{asComments:{positioned:n.positionedComments&&n.positionedComments.length>0?n.positionedComments:null,legacy:n.comments&&n.comments.length>0?n.comments:null},newIndex:t+1}}static applyValueTokenComments(e,t){if(t.positioned){for(let n of t.positioned)e.addPositionedComments(n.position,n.comments);this.clearValueTokenComments(e)}}static applyAsKeywordComments(e,t){t.positioned?e.asKeywordPositionedComments=t.positioned:t.legacy&&(e.asKeywordComments=t.legacy)}static applyAliasComments(e,t,n){n&&n.length>0?e.aliasPositionedComments=n:t&&t.length>0&&(e.aliasComments=t)}static clearValueTokenComments(e){if("positionedComments"in e.value&&(e.value.positionedComments=null),e.value.constructor.name==="ColumnReference"){let t=e.value;t.qualifiedName&&t.qualifiedName.name&&(t.qualifiedName.name.positionedComments=null)}e.value.constructor.name==="BinaryExpression"&&this.clearPositionedCommentsRecursively(e.value)}};var ci=class{static tryParse(e,t){let n=t;if(n0?{value:i,newIndex:n}:null}static isJoinKeyword(e){return!!vn.parse(e,0)}static parseLateral(e,t){let n=t;return n=e.length?!1:!!(e[t].type&16||this.isJoinKeyword(e[t].value)===!0)}static parseJoinClause(e,t){let n=t,{joinType:i,joinComments:r,newIndex:s}=this.parseJoinKeyword(e,n);n=s;let o=this.parseLateral(e,n),l=o.value;n=o.newIndex;let u=pe.parseFromLexeme(e,n);n=u.newIndex;let c=this.parseJoinCondition(e,n,i,u.value,l,r);if(c)return c;let p=new ve(i,u.value,null,l);return this.applyJoinComments(p,r),{value:p,newIndex:n}}static parseJoinKeyword(e,t){let n=e[t].value===","?"cross join":e[t].value,i=this.extractJoinKeywordComments(e[t]);return{joinType:n,joinComments:i,newIndex:t+1}}static extractJoinKeywordComments(e){return{positioned:e.positionedComments&&e.positionedComments.length>0?e.positionedComments:null,legacy:e.comments&&e.comments.length>0?e.comments:null}}static parseJoinCondition(e,t,n,i,r,s){if(t>=e.length)return null;let o=ci.tryParse(e,t);if(o){let u=new ve(n,i,o.value,r);return this.applyJoinComments(u,s),{value:u,newIndex:o.newIndex}}let l=pi.tryParse(e,t);if(l){let u=new ve(n,i,l.value,r);return this.applyJoinComments(u,s),{value:u,newIndex:l.newIndex}}return null}static applyJoinComments(e,t){t.positioned?e.joinKeywordPositionedComments=t.positioned:t.legacy&&(e.joinKeywordComments=t.legacy)}};var ln=class{static collectClauseComments(e,t,n){if(t>=e.length||e[t].value.toLowerCase()!==n.toLowerCase())return null;let i=[];e[t].comments&&i.push(...e[t].comments);let r=t-1;for(;r>=0;){let s=e[r];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&&(i.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;r--}return i.length>0?i:null}static isSignificantSqlKeyword(e){return new Set(["select","from","where","group by","having","order by","limit","offset"]).has(e.toLowerCase())}};var un=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error("Syntax error: Unexpected end of input after 'FROM' keyword. The FROM clause requires a table reference.");let r=pe.parseFromLexeme(e,n);n=r.newIndex;let s=mi.tryParse(e,n);if(n=s?.newIndex||n,s!==null){let o=new _(r.value,s.value);return{value:o,newIndex:n}}else{let o=new _(r.value,null);return{value:o,newIndex:n}}}};var st=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error("Syntax error: Unexpected end of input after 'WHERE' keyword. The WHERE clause requires a condition expression.");let o=x.parseFromLexeme(e,n),l=new re(o.value);return l.comments=r,s&&s.length>0&&(l.positionedComments=s.map(u=>({position:u.position,comments:[...u.comments]}))),{value:l,newIndex:o.newIndex}}};var di=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error("Syntax error: Unexpected end of input after 'GROUP BY' keyword. The GROUP BY clause requires at least one expression to group by.");let i=[],r=this.parseItem(e,n);for(i.push(r.value),n=r.newIndex;n=e.length)throw new Error("Syntax error: Unexpected end of input after 'HAVING' keyword. The HAVING clause requires a condition expression.");let i=x.parseFromLexeme(e,n);return{value:new ye(i.value),newIndex:i.newIndex}}};var fi=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error("Syntax error: Unexpected end of input after 'WINDOW' keyword. The WINDOW clause requires at least one window definition.");let i=[];for(;n=e.length||e[n].type!==64)throw new Error("Syntax error: Expected window name after 'WINDOW' keyword.");let r=e[n].value;if(n++,n>=e.length||e[n].value!=="as")throw new Error(`Syntax error at position ${n}: Expected 'AS' keyword after window name.`);n++;let s=_t.parseFromLexeme(e,n);if(n=s.newIndex,i.push(new Oe(r,s.value)),n=e.length)throw new Error("Syntax error: Unexpected end of input after 'LIMIT' keyword. The LIMIT clause requires a numeric expression.");let i=x.parseFromLexeme(e,n);return n=i.newIndex,{value:new ce(i.value),newIndex:n}}};var gi=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error("Syntax error: Unexpected end of input after 'FOR' keyword. The FOR clause requires a lock mode specification.");let i=e[n].value,r;switch(i){case"update":r="update",n++;break;case"share":r="share",n++;break;case"key share":r="key share",n++;break;case"no key update":r="no key update",n++;break;default:throw new Error(`Syntax error at position ${n}: Invalid lock mode "${i}". Valid lock modes are: UPDATE, SHARE, KEY SHARE, NO KEY UPDATE.`)}return{value:new Re(r),newIndex:n}}};var In=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=0;r--){let s=e[r];if(s.value.toLowerCase()==="with"){this.collectWithTokenComments(s,i);break}if(s.type&16||s.value.toLowerCase()==="recursive")break;this.collectTokenComments(s,i)}}static collectWithTokenComments(e,t){let n=!1;if(e.positionedComments&&e.positionedComments.length>0)for(let i of e.positionedComments)i.position==="after"&&i.comments&&(this.addPositionedComment(t,"before",i.comments),n=!0);!n&&e.comments&&e.comments.length>0&&this.addPositionedComment(t,"before",e.comments)}static collectTokenComments(e,t){e.comments&&e.comments.length>0&&this.addPositionedComment(t,"before",e.comments),e.positionedComments&&e.positionedComments.length>0&&(t.positionedComments||(t.positionedComments=[]),t.positionedComments.unshift(...e.positionedComments))}static addPositionedComment(e,t,n){e.positionedComments||(e.positionedComments=[]),e.positionedComments.unshift({position:t,comments:[...n]})}static parseAsKeyword(e,t){if(t=e.length)return{materialized:null,newIndex:t};let n=e[t].value;return n==="materialized"?{materialized:!0,newIndex:t+1}:n==="not materialized"?{materialized:!1,newIndex:t+1}:{materialized:null,newIndex:t}}static parseInnerSelectQuery(e,t){let n=t;if(n0&&(r.value.headerComments?r.value.headerComments=[...i,...r.value.headerComments]:r.value.headerComments=i),n0?s:null,newIndex:n}}static extractComments(e){let t=[];if(e.positionedComments)for(let n of e.positionedComments)n.comments&&t.push(...n.comments);return e.comments&&e.comments.length>0&&t.push(...e.comments),t}};var Ye=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex0&&(c.trailingComments=l),{value:c,newIndex:n,headerComments:i}}static extractWithTokenHeaderComments(e,t){if(t>=e.length)return null;let n=e[t],i=null;if(n.positionedComments&&n.positionedComments.length>0)for(let r of n.positionedComments)r.position==="before"&&r.comments&&(i||(i=[]),i.push(...r.comments));return!i&&n.comments&&n.comments.length>0&&(i=[...n.comments]),i}static parseWithKeyword(e,t){if(t=e.length)throw new Error(`Syntax error at position ${n}: Expected 'VALUES' keyword but input ended early.`);let i=e[n];if(i.value.toLowerCase()!=="values")throw new Error(`Syntax error at position ${n}: Expected 'VALUES' keyword but found "${i.value}". VALUES clauses must start with the VALUES keyword.`);let r=this.extractLexemeComments(i);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 s=[],o=this.parseTuple(e,n);for(s.push(o.value),n=o.newIndex,r.after.length>0&&o.value.addPositionedComments("before",r.after);n0&&(l.headerComments=r.before),{value:l,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)throw new Error("Syntax error: Unexpected end of input after opening parenthesis in tuple expression.");if(e[n].type&8){let u=new xe([]),c=this.extractLexemeComments(e[n]);return n++,i.before.length>0&&u.addPositionedComments("before",i.before),c.after.length>0&&u.addPositionedComments("after",c.after),{value:u,newIndex:n}}let s=x.parseFromLexeme(e,n);for(r.push(s.value),n=s.newIndex;n=e.length)throw new Error("Syntax error: Unexpected end of input after comma in tuple expression.");let u=x.parseFromLexeme(e,n);r.push(u.value),n=u.newIndex}if(n>=e.length||e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected closing parenthesis but found "${n0&&l.addPositionedComments("before",i.before),i.after.length>0&&r.length>0&&r[0].addPositionedComments("before",i.after),o.before.length>0&&r.length>0&&r[r.length-1].addPositionedComments("after",o.before),o.after.length>0&&l.addPositionedComments("after",o.after),{value:l,newIndex:n}}static extractLexemeComments(e){let t=[],n=[];if(!e)return{before:t,after:n};if(e.positionedComments&&e.positionedComments.length>0)for(let i of e.positionedComments)!i.comments||i.comments.length===0||(i.position==="before"?t.push(...i.comments):i.position==="after"&&n.push(...i.comments));else e.comments&&e.comments.length>0&&t.push(...e.comments);return{before:this.dedupeComments(t),after:this.dedupeComments(n)}}static dedupeComments(e){if(e.length<=1)return e;let t=new Set,n=[];for(let i of e)t.has(i)||(t.add(i),n.push(i));return n}};var yi=class{static parseFromLexeme(e,t){let n=t;if(e[n].value!=="fetch")throw new Error(`Syntax error at position ${n}: Expected 'FETCH' keyword but found "${e[n].value}".`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH' keyword.");let i=ir.parseFromLexeme(e,n),r=i.value;return n=i.newIndex,{value:new He(r),newIndex:n}}},ir=class{static parseFromLexeme(e,t){let n=t,i,r=e[n].value;if(r==="first")i="first";else if(r==="next")i="next";else throw new Error(`Syntax error at position ${n}: Expected 'FIRST' or 'NEXT' after 'FETCH' but found "${e[n].value}".`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT'.");let s=null,o=null;if(e[n].value==="row only"||e[n].value==="rows only")return s=new Z(1),o="rows only",n++,{value:new Ft(i,s,o),newIndex:n};let l=x.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 '.");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 '.");return{value:new Ft(i,s,o),newIndex:n}}};var wi=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error("Syntax error: Unexpected end of input after 'OFFSET' keyword. The OFFSET clause requires a numeric expression.");let i=x.parseFromLexeme(e,n);return n=i.newIndex,n=e.length)return null;let n=this.getAllLexemesWithPosition(e);for(let i of n)if(i.position&&t>=i.position.startPosition&&t=e.length));){let i=this.parseNextToken(e,n);i?(t.push(i),n=i.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],i=t+1,r=n;for(;i!]/.test(e[i])&&/[=<>!]/.test(n)&&(n+=e[i++]);let r=this.getOperatorTokenType(n);return this.createLexeme(r,n,t,i)}static parseWordToken(e,t){let n=t,i="";for(;n0&&(u.push(h),l.push(m))}let c=u;if(c.length===0&&(c=[""]),!i&&c.length===1&&!c[0]&&t.startsWith("/*")&&t.endsWith("*/")){let p=this.escapeCommentDelimiters(t);c=[this.sanitizeCommentLine(p)]}return!i&&c.length>1&&(i=!0),c=c.map((p,m)=>{if(/^[-=_+*#]+$/.test(p)){let C=(l[m]??p).replace(/\s+/g,"");if(C.length>=p.length)return C}return p}),{lines:c,forceBlock:i}}buildBlockComment(e,t){if(e.length<=1){let c=e[0]??"";return c?`/* ${c} */`:"/* */"}let n=this.newline===" "?` +`:this.newline,i=this.linePrinter.getCurrentLine()?.level??t,r=this.getIndentString(i),o=r+" ",u=e.map(c=>`${o}${c}`).join(n),l=`${r}*/`;return`/*${n}${u}${n}${l}`}getIndentString(e){return e<=0?"":this.indentSize<=0?" ".repeat(e):(typeof this.indentChar=="string"?this.indentChar:"").repeat(this.indentSize*e)}sanitizeCommentLine(e){let t=e;return t=t.replace(/\u2028|\u2029/g," "),t=t.replace(/\s+/g," ").trim(),t}escapeCommentDelimiters(e){return e.replace(/\/\*/g,"\\/\\*").replace(/\*\//g,"*\\/")}handleCommentNewlineToken(e,t){if(!this.smartCommentBlockBuilder){if(this.pendingLineCommentBreak!==null){this.linePrinter.appendNewline(this.pendingLineCommentBreak),this.pendingLineCommentBreak=null;return}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 i=this.createCteOnelinePrinter().print(e,t),r=this.cleanDuplicateSpaces(i);r=r.replace(/\(\s+/g,"(").replace(/\s+\)/g," )"),this.linePrinter.appendText(r.trim())}createCteOnelinePrinter(){return new a({indentChar:"",indentSize:0,newline:" ",commaBreak:this.commaBreak,cteCommaBreak:this.cteCommaBreak,valuesCommaBreak:this.valuesCommaBreak,andBreak:this.andBreak,orBreak:this.orBreak,keywordCase:this.keywordCase,exportComment:!1,withClauseStyle:"standard",indentNestedParentheses:!1,insertColumnsOneLine:this.insertColumnsOneLine})}handleOnelineToken(e,t){let i=this.createOnelinePrinter().print(e,t),r=this.cleanDuplicateSpaces(i);this.linePrinter.appendText(r)}getClauseBreakIndentLevel(e,t){return t}shouldBreakAfterOpeningParen(e){return e==="InsertClause"?!this.isInsertClauseOneline(e):!1}shouldBreakBeforeClosingParen(e){return e==="InsertClause"?!this.isInsertClauseOneline(e):!1}shouldConvertSpaceToClauseBreak(e,t){if(!e||!t)return!1;let n=t.type===1?t.text.toLowerCase():null,i=t.containerType;return!!(e==="UpdateQuery"&&(n==="set"||n==="from"||n==="where"||n==="returning")||e==="InsertQuery"&&(n==="returning"||n&&(n.startsWith("select")||n.startsWith("values"))||i==="ValuesQuery"||i==="SimpleSelectQuery"||i==="InsertClause")||e==="DeleteQuery"&&(n==="using"||n==="where"||n==="returning")||(e==="MergeUpdateAction"||e==="MergeDeleteAction")&&n==="where"||e==="MergeInsertAction"&&n&&(n.startsWith("values")||n==="default values"))}createOnelinePrinter(){return new a({indentChar:"",indentSize:0,newline:" ",commaBreak:"none",cteCommaBreak:this.cteCommaBreak,valuesCommaBreak:"none",andBreak:"none",orBreak:"none",keywordCase:this.keywordCase,exportComment:this.exportComment,withClauseStyle:"standard",parenthesesOneLine:!1,betweenOneLine:!1,valuesOneLine:!1,joinOneLine:!1,caseOneLine:!1,subqueryOneLine:!1,indentNestedParentheses:!1,insertColumnsOneLine:this.insertColumnsOneLine})}cleanDuplicateSpaces(e){return e.replace(/\s{2,}/g," ")}};var Ap=["mysql","postgres","sqlserver","sqlite"],Ue=class{constructor(e={}){let t=e.preset?wr[e.preset]:void 0;if(e.preset&&!t)throw new Error(`Invalid preset: ${e.preset}`);let n=Tr(e.identifierEscape??t?.identifierEscape),i={...t,identifierEscape:n??t?.identifierEscape,parameterSymbol:e.parameterSymbol??t?.parameterSymbol,parameterStyle:e.parameterStyle??t?.parameterStyle,castStyle:e.castStyle??t?.castStyle},r=e.constraintStyle??t?.constraintStyle??"postgres",s={...i,constraintStyle:r};this.parser=new ii({...s}),this.printer=new si({...e,parenthesesOneLine:e.parenthesesOneLine,betweenOneLine:e.betweenOneLine,valuesOneLine:e.valuesOneLine,joinOneLine:e.joinOneLine,caseOneLine:e.caseOneLine,subqueryOneLine:e.subqueryOneLine,indentNestedParentheses:e.indentNestedParentheses})}format(e){let{token:t,params:n}=this.parser.parse(e);return{formattedSql:this.printer.print(t),params:n}}};var Nt=class{constructor(){this.sqlFormatter=new Ue({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(e,t=null){return t&&(this.sqlFormatter=new Ue(t)),this.sqlFormatter.format(e).formattedSql}formatWithParameters(e,t=null){t&&(this.sqlFormatter=new Ue(t));let n=this.sqlFormatter.format(e);return{sql:n.formattedSql,params:n.params}}visit(e){return this.format(e)}};var oi=class{constructor(){this.sourceCollector=new rt(!0),this.cteCollector=new ne,this.formatter=new Nt}build(e){if(e.length===0)return new he(!1,e);let t=this.resolveDuplicateNames(e),{tableMap:n,recursiveCTEs:i,dependencies:r}=this.buildDependencyGraph(t),s=this.sortCommonTables(t,n,i,r);return new he(i.size>0,s)}resolveDuplicateNames(e){let t=new Map;for(let i of e){let r=i.aliasExpression.table.name;t.has(r)||t.set(r,[]),t.get(r).push(i)}let n=[];for(let[i,r]of Array.from(t.entries())){if(r.length===1){n.push(r[0]);continue}let s=r.map(u=>this.formatter.format(u.query));if(new Set(s).size===1)n.push(r[0]);else throw new Error(`CTE name conflict detected: '${i}' has multiple different definitions`)}return n}buildDependencyGraph(e){let t=new Map;for(let s of e)t.set(s.aliasExpression.table.name,s);let n=new Set,i=new Map,r=new Map;for(let s of e){let o=s.aliasExpression.table.name,u=this.sourceCollector.collect(s.query);for(let c of u)if(c.table.name===o){n.add(o);break}i.has(o)||i.set(o,new Set);let l=this.cteCollector.collect(s.query);for(let c of l){let p=c.aliasExpression.table.name;t.has(p)&&(i.get(o).add(p),r.has(p)||r.set(p,new Set),r.get(p).add(o))}}return{tableMap:t,recursiveCTEs:n,dependencies:i}}sortCommonTables(e,t,n,i){let r=[],s=[],o=new Set,u=new Set,l=c=>{if(o.has(c))return;if(u.has(c))throw new Error(`Circular reference detected in CTE: ${c}`);u.add(c);let p=i.get(c)||new Set;for(let m of Array.from(p))l(m);u.delete(c),o.add(c),n.has(c)?r.push(t.get(c)):s.push(t.get(c))};for(let c of e){let p=c.aliasExpression.table.name;o.has(p)||l(p)}return[...r,...s]}};var ai=class{constructor(){this.nameConflictResolver=new oi,this.cteCollector=new ne}inject(e,t){if(t.length===0)return e;t.push(...this.cteCollector.collect(e));let n=this.nameConflictResolver.build(t);if(e instanceof w)return this.injectIntoSimpleQuery(e,n);if(e instanceof O)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 w)return this.injectIntoSimpleQuery(e.left,t),e;if(e.left instanceof O)return this.injectIntoBinaryQuery(e.left,t),e;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var dt=class{constructor(){}static normalize(e){let n=new ne().collect(e);return n.length===0?e:(new Ht().execute(e),new ai().inject(e,n))}};var Vt=(t=>(t.ColumnNameOnly="columnNameOnly",t.FullName="fullName",t))(Vt||{}),Ae=class a{constructor(e,t=!1,n="columnNameOnly",i){this.selectValues=[];this.visitedNodes=new Set;this.uniqueKeys=new Set;this.isRootVisit=!0;this.tableColumnResolver=null;this.commonTables=[];this.initializeProperties(e,t,n,i),this.initializeHandlers()}initializeProperties(e,t,n,i){this.tableColumnResolver=e??null,this.includeWildCard=t,this.commonTableCollector=new ne,this.commonTables=[],this.duplicateDetection=n,this.options=i||{}}initializeHandlers(){this.handlers=new Map,this.handlers.set(w.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(O.kind,e=>this.visitBinarySelectQuery(e)),this.initializeClauseHandlers(),this.initializeValueComponentHandlers()}initializeClauseHandlers(){this.handlers.set(z.kind,e=>this.visitSelectClause(e)),this.handlers.set(_.kind,e=>this.visitFromClause(e)),this.handlers.set(re.kind,e=>this.visitWhereClause(e)),this.handlers.set(ye.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ge.kind,e=>this.visitHavingClause(e)),this.handlers.set(Ce.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Oe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(ce.kind,e=>this.visitLimitClause(e)),this.handlers.set($e.kind,e=>this.offsetClause(e)),this.handlers.set(He.kind,e=>this.visitFetchClause(e)),this.handlers.set(we.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Te.kind,e=>this.visitJoinUsingClause(e))}initializeValueComponentHandlers(){this.handlers.set(E.kind,e=>this.visitColumnReference(e)),this.handlers.set(b.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(H.kind,e=>this.visitFunctionCall(e)),this.handlers.set(de.kind,e=>this.visitInlineQuery(e)),this.handlers.set(ee.kind,e=>this.visitParenExpression(e)),this.handlers.set(ue.kind,e=>this.visitCaseExpression(e)),this.handlers.set(fe.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ee.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(Se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(be.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(lt.kind,e=>this.visitArraySliceExpression(e)),this.handlers.set(ut.kind,e=>this.visitArrayIndexExpression(e)),this.handlers.set(W.kind,e=>this.visitValueList(e)),this.handlers.set(Ke.kind,e=>this.visitWindowFrameExpression(e)),this.handlers.set(_e.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 i=n?n+"."+e:e;return this.normalizeColumnName(i)}}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 w||e instanceof O))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 w?this.visitSimpleSelectQuery(e.left):e.left instanceof O&&this.visitBinarySelectQuery(e.left),e.right instanceof w?this.visitSimpleSelectQuery(e.right):e.right instanceof O&&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 E){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 Ze(this.tableColumnResolver,this.commonTables).collect(e);for(let i of n)this.addSelectValueAsUnique(i.name,i.value);if(this.options.upstream&&this.collectUpstreamColumns(e),e.joins)for(let i of e.joins)i.condition&&i.condition.accept(this)}visitWhereClause(e){e.condition&&e.condition.accept(this)}visitGroupByClause(e){if(e.grouping)for(let t of e.grouping)t.accept(this)}visitHavingClause(e){e.condition&&e.condition.accept(this)}visitOrderByClause(e){if(e.order)for(let t of e.order)t.accept(this)}visitWindowFrameClause(e){e.expression.accept(this)}visitWindowFrameExpression(e){e.partition&&e.partition.accept(this),e.order&&e.order.accept(this),e.frameSpec&&e.frameSpec.accept(this)}visitLimitClause(e){e.value&&e.value.accept(this)}offsetClause(e){e.value&&e.value.accept(this)}visitFetchClause(e){e.expression&&e.expression.accept(this)}visitJoinOnClause(e){e.condition&&e.condition.accept(this)}visitJoinUsingClause(e){e.condition&&e.condition.accept(this)}visitColumnReference(e){if(e.column.name!=="*")this.addSelectValueAsUnique(e.column.name,e);else if(this.includeWildCard)this.addSelectValueAsUnique(e.column.name,e);else return}visitBinaryExpression(e){e.left&&e.left.accept(this),e.right&&e.right.accept(this)}visitUnaryExpression(e){e.expression&&e.expression.accept(this)}visitFunctionCall(e){e.argument&&e.argument.accept(this),e.over&&e.over.accept(this),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 B){let t=this.findCTEByName(e.datasource.table.name);t?this.collectUpstreamColumnsFromCTE(t):this.collectUpstreamColumnsFromTable(e.datasource)}else e.datasource instanceof K?this.collectUpstreamColumnsFromSubquery(e.datasource):e.datasource instanceof je&&this.collectUpstreamColumnsFromSource(new $(e.datasource.source,null))}collectUpstreamColumnsFromTable(e){if(this.tableColumnResolver){let t=e.table.name,n=this.tableColumnResolver(t);for(let i of n){let r=new E(e.table.name,i);this.addSelectValueAsUnique(i,r)}}}collectUpstreamColumnsFromSubquery(e){if(e.query instanceof w){let n=new a(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!0}).collect(e.query);for(let i of n)this.addSelectValueAsUnique(i.name,i.value)}}collectUpstreamColumnsFromCTE(e){if(e.query instanceof w){let n=new a(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!1}).collect(e.query);for(let i of n)i.name!=="*"&&this.addSelectValueAsUnique(i.name,i.value)}}collectAllAvailableCTEColumns(){for(let e of this.commonTables)this.collectUpstreamColumnsFromCTE(e)}findCTEByName(e){return this.commonTables.find(t=>t.getSourceAliasName()===e)||null}};var Dt=class a{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex0?r.positionedComments=n.positionedComments:n.comments&&n.comments.length>0&&(r.comments=n.comments),{value:r,newIndex:i}}static parseFunctionSource(e,t){let n=t.newIndex,{namespaces:i,name:r}=t,s=x.parseArgument(4,8,e,n);n=s.newIndex;let o=r.name;return{value:new nt({namespaces:i,name:o},s.value),newIndex:n}}static parseParenSource(e,t){let n=t,i=e[n];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 s=this.parseSubQuerySource(e,n,i);if(n=s.newIndex,n0){let u=n.positionedComments.filter(l=>l.position==="after");if(u.length>0){let l=u.map(c=>({position:"before",comments:c.comments}));r.positionedComments?r.positionedComments=[...l,...r.positionedComments]:r.positionedComments=l,r.comments&&(r.comments=null)}}return{value:new K(r),newIndex:i}}};var xn=class extends Error{constructor(t){super(`CTE '${t}' already exists in the query`);this.cteName=t;this.name="DuplicateCTEError"}},on=class extends Error{constructor(t,n){super(`Invalid CTE name '${t}': ${n}`);this.cteName=t;this.name="InvalidCTENameError"}},Tn=class extends Error{constructor(t){super(`CTE '${t}' not found in the query`);this.cteName=t;this.name="CTENotFoundError"}};var an=class{constructor(e,t){this.options=t||{},this.tableColumnResolver=e,this.columnCollector=new Ae(this.tableColumnResolver,!1,"fullName",{upstream:!0})}find(e,t){let n=typeof t=="string"?[t]:t,r=new ne().collect(e),s=new Map;for(let o of r)s.set(o.getSourceAliasName(),o);return this.findUpstream(e,n,s)}handleTableSource(e,t,n){let i=n.get(e.table.name);if(i){let r=new Map(n);r.delete(e.table.name);let s=this.findUpstream(i.query,t,r);return s.length===0?null:s}return null}handleSubQuerySource(e,t,n){let i=this.findUpstream(e.query,t,n);return i.length===0?null:i}processFromClauseBranches(e,t,n){let i=e.getSources();if(i.length===0)return null;let r=[],s=!0,o=0;for(let u of i){let l=u.datasource,c=null;if(l instanceof B)c=this.handleTableSource(l,t,n),o++;else if(l instanceof K)c=this.handleSubQuerySource(l,t,n),o++;else{if(l instanceof ae)continue;s=!1;break}if(c===null){s=!1;break}r.push(c)}return s&&r.length===o?r.flat():null}findUpstream(e,t,n){if(e instanceof w){let i=e.fromClause;if(i){let c=this.processFromClauseBranches(i,t,n);if(c&&c.length>0)return c}let r=this.columnCollector.collect(e).map(c=>c.name),s=this.collectCTEColumns(e,n),o=[...r,...s],u=c=>this.options.ignoreCaseAndUnderscore?c.toLowerCase().replace(/_/g,""):c;return t.every(c=>o.some(p=>u(p)===u(c)))?[e]:[]}else if(e instanceof O){let i=this.findUpstream(e.left,t,n),r=this.findUpstream(e.right,t,n);return[...i,...r]}return[]}collectCTEColumns(e,t){let n=[];if(e.withClause)for(let i of e.withClause.tables){let r=this.collectColumnsFromSelectQuery(i.query);n.push(...r)}return n}collectColumnsFromSelectQuery(e){if(e instanceof w)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 O)return this.collectColumnsFromSelectQuery(e.left);return[]}};var $t=class{static parseFromLexeme(e,t){let n=t;if(n0&&(u.positionedComments=i.positionedComments),{value:u,newIndex:n}}let s=new se(r,null);return i.positionedComments&&i.positionedComments.length>0&&(s.positionedComments=i.positionedComments),{value:s,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 pe=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndexo.name),r=t.tuples.map(o=>{if(o.values.length!==i.length)throw new Error("Tuple value count does not match column count.");let u=i.map((c,p)=>new J(o.values[p],c)),l=new z(u);return new w({selectClause:l})}),s=r[0];for(let o=1;oo.name),i=this.flattenSelectQueries(e.selectQuery);if(!i.length)throw new Error("No SELECT components found to convert.");let r=i.map(o=>{if(o.fromClause||o.whereClause&&o.whereClause.condition)throw new Error("SELECT queries with FROM or WHERE clauses cannot be converted to VALUES.");let u=new Map;for(let c of o.selectClause.items){let p=c.identifier?.name??null;if(!p)throw new Error("Each SELECT item must have an alias matching target columns.");u.has(p)||u.set(p,c.value)}let l=n.map(c=>{let p=u.get(c);if(!p)throw new Error(`Column '${c}' is not provided by the SELECT query.`);return p});return new xe(l)}),s=new ae(r,n);return new tt({withClause:e.withClause,insertClause:e.insertClause,selectQuery:s,returning:e.returningClause})}static flattenSelectQueries(e){if(e instanceof w)return[e];if(e instanceof O)return[...this.flattenSelectQueries(e.left),...this.flattenSelectQueries(e.right)];throw new Error("Unsupported SelectQuery subtype for conversion.")}};var Ie=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=r=>r instanceof ae?a.buildSimpleQuery(r):r,i=new O(n(e[0]),t,n(e[1]));dt.normalize(i);for(let r=2;r0?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 K(e),i=new $(n,new se("vq",e.columnAliases)),r=new _(i,null),s=e.columnAliases.map(u=>new J(new E("vq",u),u)),o=new z(s,null);return new w({selectClause:o,fromClause:r})}static createSelectAllClause(){let e=new E(null,"*"),t=new J(e,"*");return new z([t],null)}static buildCreateTableQuery(e,t,n=!1,i=!1){return new Pt({tableName:t,isTemporary:n,ifNotExists:i,asSelectQuery:e})}static buildInsertQuery(e,t,n){let i=a.normalizeInsertOptions(t,n),r=a.prepareInsertColumns(e,i.columns??null),s=a.extractWithClause(e),o=pe.parse(i.target);return new tt({withClause:s??void 0,insertClause:new xt(o,r),selectQuery:e})}static convertInsertValuesToSelect(e){return kn.toSelectUnion(e)}static convertInsertSelectToValues(e){return kn.toValues(e)}static buildUpdateQuery(e,t,n,i){let r=a.normalizeUpdateOptions(t,n,i),s=a.prepareUpdateColumns(e,r.primaryKeys,r.columns??null),o=new bt(pe.parse(r.target)),u=o.getSourceAliasName();if(!u)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let l=a.extractWithClause(e),c=s.map(C=>new Xe(C,a.toColumnReference(r.sourceAlias,C)));if(c.length===0)throw new Error("No updatable columns found. Ensure the select list contains at least one column other than the specified primary keys.");let p=new Fe(c),m=new _(e.toSource(r.sourceAlias),null),h=new re(a.buildEqualityPredicate(u,r.sourceAlias,r.primaryKeys));return new Ct({updateClause:o,setClause:p,fromClause:m,whereClause:h,withClause:l??void 0})}static buildDeleteQuery(e,t){let n=a.normalizeDeleteOptions(t),i=a.prepareDeleteColumns(e,n.primaryKeys,n.columns??null),r=new Et(pe.parse(n.target)),s=r.getSourceAliasName();if(!s)throw new Error("Source expression does not have an alias. Please provide an alias for the delete target.");let o=a.extractWithClause(e),u=a.buildEqualityPredicate(s,n.sourceAlias,i),l=e.toSource(n.sourceAlias),c=new z([new J(new Z(1))]),p=new w({selectClause:c,fromClause:new _(l,null),whereClause:new re(u)}),m=new re(new te("exists",new de(p)));return new yt({deleteClause:r,whereClause:m,withClause:o??void 0})}static buildMergeQuery(e,t){let n=a.normalizeMergeOptions(t),i=a.prepareMergeColumns(e,n.primaryKeys,n.updateColumns??null,n.insertColumns??null,n.matchedAction??"update",n.notMatchedAction??"insert"),r=pe.parse(n.target),s=r.getAliasName();if(!s)throw new Error("Source expression does not have an alias. Please provide an alias for the merge target.");let o=a.extractWithClause(e),u=a.buildEqualityPredicate(s,n.sourceAlias,n.primaryKeys),l=e.toSource(n.sourceAlias),c=[],p=n.matchedAction??"update";if(p==="update"){if(i.updateColumns.length===0)throw new Error("No columns available for MERGE update action. Provide updateColumns or ensure the select list includes non-key columns.");let C=i.updateColumns.map(f=>new Xe(f,a.toColumnReference(n.sourceAlias,f)));c.push(new Ge("matched",new Lt(new Fe(C))))}else p==="delete"?c.push(new Ge("matched",new gt)):p==="doNothing"&&c.push(new Ge("matched",new mt));let m=n.notMatchedAction??"insert";if(m==="insert"){if(i.insertColumns.length===0)throw new Error("Unable to infer MERGE insert columns. Provide insertColumns explicitly.");let C=new W(i.insertColumns.map(f=>a.toColumnReference(n.sourceAlias,f)));c.push(new Ge("not_matched",new wt({columns:i.insertColumns,values:C})))}else m==="doNothing"&&c.push(new Ge("not_matched",new mt));let h=n.notMatchedBySourceAction??"doNothing";if(h==="delete"?c.push(new Ge("not_matched_by_source",new gt)):h==="doNothing"&&c.push(new Ge("not_matched_by_source",new mt)),c.length===0)throw new Error("At least one MERGE action must be generated. Adjust the merge conversion options.");return new vt({withClause:o??void 0,target:r,source:l,onCondition:u,whenClauses:c})}static normalizeInsertOptions(e,t){return typeof e=="string"?{target:e,columns:t}:t&&t.length>0?{...e,columns:t}:{...e}}static normalizeUpdateOptions(e,t,n){if(typeof e=="string"){if(!t)throw new Error("updateTableExprRaw is required when using the legacy buildUpdateQuery signature.");if(n===void 0)throw new Error("primaryKeys are required when using the legacy buildUpdateQuery signature.");return{target:t,primaryKeys:a.normalizeColumnArray(n),sourceAlias:e}}return{target:e.target,primaryKeys:a.normalizeColumnArray(e.primaryKeys),sourceAlias:e.sourceAlias??"src",columns:e.columns}}static normalizeDeleteOptions(e){return{...e,primaryKeys:a.normalizeColumnArray(e.primaryKeys),sourceAlias:e.sourceAlias??"src"}}static normalizeMergeOptions(e){return{...e,primaryKeys:a.normalizeColumnArray(e.primaryKeys),sourceAlias:e.sourceAlias??"src"}}static normalizeColumnArray(e){let n=(Array.isArray(e)?e:[e]).map(i=>i.trim()).filter(i=>i.length>0);if(!n.length)throw new Error("At least one column must be specified.");return n}static collectSelectItems(e){return new Ze().collect(e)}static collectSelectColumnNames(e){let t=a.collectSelectItems(e),n=[];for(let i of t){if(!i.name||i.name==="*")throw new Error("Columns cannot be inferred from the selectQuery. Make sure you are not using wildcards or unnamed columns.");n.includes(i.name)||n.push(i.name)}if(!n.length)throw new Error("Unable to determine any column names from selectQuery.");return n}static ensurePrimaryKeys(e,t){let n=new Set(e);for(let i of t)if(!n.has(i))throw new Error(`Primary key column '${i}' is not present in selectQuery select list.`)}static prepareInsertColumns(e,t){let n=a.collectSelectColumnNames(e);if(t&&t.length>0){let i=a.normalizeColumnArray(t),r=i.filter((o,u)=>i.indexOf(o)===u),s=r.filter(o=>!n.includes(o));if(s.length>0)throw new Error(`Columns specified in conversion options were not found in selectQuery select list: [${s.join(", ")}].`);return a.rebuildSelectClause(e,r),a.ensureSelectClauseSize(e,r.length),r}return a.ensureSelectClauseSize(e,n.length),n}static prepareUpdateColumns(e,t,n){let i=a.collectSelectColumnNames(e);a.ensurePrimaryKeys(i,t);let r=new Set(t),s=i.filter(l=>!r.has(l)),o;if(n&&n.length>0){let l=a.normalizeColumnArray(n),c=l.filter((m,h)=>l.indexOf(m)===h),p=c.filter(m=>r.has(m)||!s.includes(m));if(p.length>0)throw new Error(`Provided update columns were not found in selectQuery output or are primary keys: [${p.join(", ")}].`);o=c}else o=Array.from(new Set(s));let u=Array.from(new Set([...t,...o]));return a.rebuildSelectClause(e,u),a.ensureSelectClauseSize(e,u.length),o}static prepareDeleteColumns(e,t,n){let i=a.collectSelectColumnNames(e);a.ensurePrimaryKeys(i,t);let r=new Set(t),s=[];if(n&&n.length>0){let l=a.normalizeColumnArray(n),c=new Set(l);s=i.filter(p=>c.has(p)&&!r.has(p))}let o=new Set;t.forEach(l=>o.add(l)),s.forEach(l=>o.add(l));let u=i.filter(l=>o.has(l));return a.rebuildSelectClause(e,u),a.ensureSelectClauseSize(e,u.length),u}static prepareMergeColumns(e,t,n,i,r,s){let o=a.collectSelectColumnNames(e);a.ensurePrimaryKeys(o,t);let u=new Set(t),l=[];if(r==="update"){let C=o.filter(f=>!u.has(f));if(n&&n.length>0){let f=a.normalizeColumnArray(n),A=f.filter((v,y)=>f.indexOf(v)===y),V=A.filter(v=>u.has(v)||!C.includes(v));if(V.length>0)throw new Error(`Provided update columns were not found in selectQuery output or are primary keys: [${V.join(", ")}].`);l=A}else l=Array.from(new Set(C))}let c=[];if(s==="insert")if(i&&i.length>0){let C=a.normalizeColumnArray(i),f=C.filter((V,v)=>C.indexOf(V)===v),A=f.filter(V=>!o.includes(V));if(A.length>0)throw new Error(`Provided insert columns were not found in selectQuery output: [${A.join(", ")}].`);c=f}else c=Array.from(new Set(o));let p=Array.from(new Set([...t,...l,...c,...o])).filter(C=>o.includes(C));return a.rebuildSelectClause(e,p),a.ensureSelectClauseSize(e,p.length),{updateColumns:r==="update"?l:[],insertColumns:s==="insert"?c:[]}}static rebuildSelectClause(e,t){let n=new Map;for(let s of e.selectClause.items){let o=a.getSelectItemName(s);o&&(n.has(o)||n.set(o,s))}let i=[],r=new Set;for(let s of t){if(r.has(s))continue;let o=n.get(s);if(!o)throw new Error(`Column '${s}' not found in select clause.`);i.push(o),r.add(s)}if(!i.length)throw new Error("Unable to rebuild select clause with the requested columns.");e.selectClause.items=i}static getSelectItemName(e){return e.identifier?e.identifier.name:e.value instanceof E?e.value.column.name:null}static ensureSelectClauseSize(e,t){if(e.selectClause.items.length!==t)throw new Error(`Select clause column count (${e.selectClause.items.length}) does not match expected count (${t}).`)}static extractWithClause(e){let n=new ne().collect(e);return n.length===0?null:(new Ht().execute(e),new he(!1,n))}static buildEqualityPredicate(e,t,n){let i=a.mergeUniqueColumns(n);if(!i.length)throw new Error("At least one column is required to build a comparison predicate.");let r=null;for(let s of i){let o=new b(a.toColumnReference(e,s),"=",a.toColumnReference(t,s));r=r?new b(r,"and",o):o}return r}static toColumnReference(e,t){return new E(e,t)}static mergeUniqueColumns(e){let t=new Set,n=[];for(let i of e)t.has(i)||(t.add(i),n.push(i));return n}};var w=class extends g{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)}toInsertQuery(t){return Ie.buildInsertQuery(this,t)}toUpdateQuery(t){return Ie.buildUpdateQuery(this,t)}toDeleteQuery(t){return Ie.buildDeleteQuery(this,t)}toMergeQuery(t){return Ie.buildMergeQuery(this,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 Ie.buildBinaryQuery([this,n],t)}appendWhereRaw(t){let n=x.parse(t);this.appendWhere(n)}appendWhere(t){this.whereClause?this.whereClause.condition=new b(this.whereClause.condition,"and",t):this.whereClause=new re(t)}appendHavingRaw(t){let n=x.parse(t);this.appendHaving(n)}appendHaving(t){this.havingClause?this.havingClause.condition=new b(this.havingClause.condition,"and",t):this.havingClause=new ge(t)}innerJoinRaw(t,n,i,r=null){this.joinSourceRaw("inner join",t,n,i,r)}leftJoinRaw(t,n,i,r=null){this.joinSourceRaw("left join",t,n,i,r)}rightJoinRaw(t,n,i,r=null){this.joinSourceRaw("right join",t,n,i,r)}innerJoin(t,n,i=null){this.joinSource("inner join",t,n,i)}leftJoin(t,n,i=null){this.joinSource("left join",t,n,i)}rightJoin(t,n,i=null){this.joinSource("right join",t,n,i)}joinSourceRaw(t,n,i,r,s=null){let o=Dt.parse(n),u=new $(o,new se(i,null));this.joinSource(t,u,r,s)}joinSource(t,n,i,r=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let s=Array.isArray(i)?i:[i],u=new Ae(r).collect(this),l=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 C of u)if(s.some(f=>f==C.name)){let f=new b(C.value,"=",new E([p],C.name));l?l=new b(l,"and",f):l=f,c++}if(!l||c!==s.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${s.join(", ")}`);let m=new we(l),h=new ve(t,n,m,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(h):this.fromClause.joins=[h]),dt.normalize(this)}toSource(t){if(!t||t.trim()==="")throw new Error("Alias is required for toSource(). Please specify a non-empty alias name.");return new $(new K(this),new se(t,null))}appendWith(t){let n=Array.isArray(t)?t:[t];this.withClause?this.withClause.tables.push(...n):this.withClause=new he(!1,n),dt.normalize(this)}appendWithRaw(t,n){let i=P.parse(t),r=new oe(i,n,null);this.appendWith(r)}overrideSelectItemExpr(t,n){let i=this.selectClause.items.filter(l=>l.identifier?.name===t);if(i.length===0)throw new Error(`Column ${t} not found in the query`);if(i.length>1)throw new Error(`Duplicate column name ${t} found in the query`);let r=i[0],o=new Nt().visit(r.value),u=n(o);r.value=x.parse(u)}appendWhereExpr(t,n,i){if(i&&i.upstream){let s=new an().find(this,[t]),o=new Ae,u=new Nt;for(let l of s){let c=o.collect(l).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=u.format(c[0]);l.appendWhereRaw(n(p))}}else{let r=new Ae,s=new Nt,o=r.collect(this).filter(l=>l.name===t).map(l=>l.value);if(o.length!==1)throw new Error(`Expected exactly one expression for column '${t}'`);let u=s.format(o[0]);this.appendWhereRaw(n(u))}}setParameter(t,n){return ht.set(this,t,n),this}toSimpleQuery(){return this}addCTE(t,n,i){if(!t||t.trim()==="")throw new on(t,"name cannot be empty or whitespace-only");if(this.hasCTE(t))throw new xn(t);let r=i?.materialized??null,s=new oe(n,t,r);return this.appendWith(s),this.cteNameCache.add(t),this}removeCTE(t){if(!this.hasCTE(t))throw new Tn(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,i){if(!t||t.trim()==="")throw new on(t,"name cannot be empty or whitespace-only");this.hasCTE(t)&&this.removeCTE(t);let r=i?.materialized??null,s=new oe(n,t,r);return this.appendWith(s),this.cteNameCache.add(t),this}};var li=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex{this.clearPositionedCommentsRecursively(t)}),e.value&&this.clearPositionedCommentsRecursively(e.value))}static extractValueTokenComments(e,t){if(t>=e.length)return{positioned:null,legacy:null};let n=e[t];return{positioned:n.positionedComments&&n.positionedComments.length>0?n.positionedComments:null,legacy:null}}static parseAsKeyword(e,t){if(t>=e.length||e[t].value!=="as")return{asComments:{positioned:null,legacy:null},newIndex:t};let n=e[t];return{asComments:{positioned:n.positionedComments&&n.positionedComments.length>0?n.positionedComments:null,legacy:n.comments&&n.comments.length>0?n.comments:null},newIndex:t+1}}static applyValueTokenComments(e,t){if(t.positioned){for(let n of t.positioned)e.addPositionedComments(n.position,n.comments);this.clearValueTokenComments(e)}}static applyAsKeywordComments(e,t){t.positioned?e.asKeywordPositionedComments=t.positioned:t.legacy&&(e.asKeywordComments=t.legacy)}static applyAliasComments(e,t,n){n&&n.length>0?e.aliasPositionedComments=n:t&&t.length>0&&(e.aliasComments=t)}static clearValueTokenComments(e){if("positionedComments"in e.value&&(e.value.positionedComments=null),e.value.constructor.name==="ColumnReference"){let t=e.value;t.qualifiedName&&t.qualifiedName.name&&(t.qualifiedName.name.positionedComments=null)}e.value.constructor.name==="BinaryExpression"&&this.clearPositionedCommentsRecursively(e.value)}};var ci=class{static tryParse(e,t){let n=t;if(n0?{value:i,newIndex:n}:null}static isJoinKeyword(e){return!!vn.parse(e,0)}static parseLateral(e,t){let n=t;return n=e.length?!1:!!(e[t].type&16||this.isJoinKeyword(e[t].value)===!0)}static parseJoinClause(e,t){let n=t,{joinType:i,joinComments:r,newIndex:s}=this.parseJoinKeyword(e,n);n=s;let o=this.parseLateral(e,n),u=o.value;n=o.newIndex;let l=pe.parseFromLexeme(e,n);n=l.newIndex;let c=this.parseJoinCondition(e,n,i,l.value,u,r);if(c)return c;let p=new ve(i,l.value,null,u);return this.applyJoinComments(p,r),{value:p,newIndex:n}}static parseJoinKeyword(e,t){let n=e[t].value===","?"cross join":e[t].value,i=this.extractJoinKeywordComments(e[t]);return{joinType:n,joinComments:i,newIndex:t+1}}static extractJoinKeywordComments(e){return{positioned:e.positionedComments&&e.positionedComments.length>0?e.positionedComments:null,legacy:e.comments&&e.comments.length>0?e.comments:null}}static parseJoinCondition(e,t,n,i,r,s){if(t>=e.length)return null;let o=ci.tryParse(e,t);if(o){let l=new ve(n,i,o.value,r);return this.applyJoinComments(l,s),{value:l,newIndex:o.newIndex}}let u=pi.tryParse(e,t);if(u){let l=new ve(n,i,u.value,r);return this.applyJoinComments(l,s),{value:l,newIndex:u.newIndex}}return null}static applyJoinComments(e,t){t.positioned?e.joinKeywordPositionedComments=t.positioned:t.legacy&&(e.joinKeywordComments=t.legacy)}};var ln=class{static collectClauseComments(e,t,n){if(t>=e.length||e[t].value.toLowerCase()!==n.toLowerCase())return null;let i=[];e[t].comments&&i.push(...e[t].comments);let r=t-1;for(;r>=0;){let s=e[r];if(s.comments&&s.comments.length>0){let o=s.comments.filter(u=>{let l=u.toLowerCase();return l.includes(n.toLowerCase())||l.includes("\u306E")||l.includes("\u30B3\u30E1\u30F3\u30C8")});o.length>0&&(i.unshift(...o),s.comments=s.comments.filter(u=>!o.includes(u)),s.comments.length===0&&(s.comments=null));break}if(this.isSignificantSqlKeyword(s.value))break;r--}return i.length>0?i:null}static isSignificantSqlKeyword(e){return new Set(["select","from","where","group by","having","order by","limit","offset"]).has(e.toLowerCase())}};var un=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error("Syntax error: Unexpected end of input after 'FROM' keyword. The FROM clause requires a table reference.");let r=pe.parseFromLexeme(e,n);n=r.newIndex;let s=mi.tryParse(e,n);if(n=s?.newIndex||n,s!==null){let o=new _(r.value,s.value);return{value:o,newIndex:n}}else{let o=new _(r.value,null);return{value:o,newIndex:n}}}};var st=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error("Syntax error: Unexpected end of input after 'WHERE' keyword. The WHERE clause requires a condition expression.");let o=x.parseFromLexeme(e,n),u=new re(o.value);return u.comments=r,s&&s.length>0&&(u.positionedComments=s.map(l=>({position:l.position,comments:[...l.comments]}))),{value:u,newIndex:o.newIndex}}};var di=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error("Syntax error: Unexpected end of input after 'GROUP BY' keyword. The GROUP BY clause requires at least one expression to group by.");let i=[],r=this.parseItem(e,n);for(i.push(r.value),n=r.newIndex;n=e.length)throw new Error("Syntax error: Unexpected end of input after 'HAVING' keyword. The HAVING clause requires a condition expression.");let i=x.parseFromLexeme(e,n);return{value:new ge(i.value),newIndex:i.newIndex}}};var fi=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error("Syntax error: Unexpected end of input after 'WINDOW' keyword. The WINDOW clause requires at least one window definition.");let i=[];for(;n=e.length||e[n].type!==64)throw new Error("Syntax error: Expected window name after 'WINDOW' keyword.");let r=e[n].value;if(n++,n>=e.length||e[n].value!=="as")throw new Error(`Syntax error at position ${n}: Expected 'AS' keyword after window name.`);n++;let s=_t.parseFromLexeme(e,n);if(n=s.newIndex,i.push(new Oe(r,s.value)),n=e.length)throw new Error("Syntax error: Unexpected end of input after 'LIMIT' keyword. The LIMIT clause requires a numeric expression.");let i=x.parseFromLexeme(e,n);return n=i.newIndex,{value:new ce(i.value),newIndex:n}}};var yi=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error("Syntax error: Unexpected end of input after 'FOR' keyword. The FOR clause requires a lock mode specification.");let i=e[n].value,r;switch(i){case"update":r="update",n++;break;case"share":r="share",n++;break;case"key share":r="key share",n++;break;case"no key update":r="no key update",n++;break;default:throw new Error(`Syntax error at position ${n}: Invalid lock mode "${i}". Valid lock modes are: UPDATE, SHARE, KEY SHARE, NO KEY UPDATE.`)}return{value:new Re(r),newIndex:n}}};var In=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=0;r--){let s=e[r];if(s.value.toLowerCase()==="with"){this.collectWithTokenComments(s,i);break}if(s.type&16||s.value.toLowerCase()==="recursive")break;this.collectTokenComments(s,i)}}static collectWithTokenComments(e,t){let n=!1;if(e.positionedComments&&e.positionedComments.length>0)for(let i of e.positionedComments)i.position==="after"&&i.comments&&(this.addPositionedComment(t,"before",i.comments),n=!0);!n&&e.comments&&e.comments.length>0&&this.addPositionedComment(t,"before",e.comments)}static collectTokenComments(e,t){e.comments&&e.comments.length>0&&this.addPositionedComment(t,"before",e.comments),e.positionedComments&&e.positionedComments.length>0&&(t.positionedComments||(t.positionedComments=[]),t.positionedComments.unshift(...e.positionedComments))}static addPositionedComment(e,t,n){e.positionedComments||(e.positionedComments=[]),e.positionedComments.unshift({position:t,comments:[...n]})}static parseAsKeyword(e,t){if(t=e.length)return{materialized:null,newIndex:t};let n=e[t].value;return n==="materialized"?{materialized:!0,newIndex:t+1}:n==="not materialized"?{materialized:!1,newIndex:t+1}:{materialized:null,newIndex:t}}static parseInnerSelectQuery(e,t){let n=t;if(n0&&(r.value.headerComments?r.value.headerComments=[...i,...r.value.headerComments]:r.value.headerComments=i),n0?s:null,newIndex:n}}static extractComments(e){let t=[];if(e.positionedComments)for(let n of e.positionedComments)n.comments&&t.push(...n.comments);return e.comments&&e.comments.length>0&&t.push(...e.comments),t}};var Ye=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex0&&(c.trailingComments=u),{value:c,newIndex:n,headerComments:i}}static extractWithTokenHeaderComments(e,t){if(t>=e.length)return null;let n=e[t],i=null;if(n.positionedComments&&n.positionedComments.length>0)for(let r of n.positionedComments)r.position==="before"&&r.comments&&(i||(i=[]),i.push(...r.comments));return!i&&n.comments&&n.comments.length>0&&(i=[...n.comments]),i}static parseWithKeyword(e,t){if(t=e.length)throw new Error(`Syntax error at position ${n}: Expected 'VALUES' keyword but input ended early.`);let i=e[n];if(i.value.toLowerCase()!=="values")throw new Error(`Syntax error at position ${n}: Expected 'VALUES' keyword but found "${i.value}". VALUES clauses must start with the VALUES keyword.`);let r=this.extractLexemeComments(i);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 s=[],o=this.parseTuple(e,n);for(s.push(o.value),n=o.newIndex,r.after.length>0&&o.value.addPositionedComments("before",r.after);n0&&(u.headerComments=r.before),{value:u,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)throw new Error("Syntax error: Unexpected end of input after opening parenthesis in tuple expression.");if(e[n].type&8){let l=new xe([]),c=this.extractLexemeComments(e[n]);return n++,i.before.length>0&&l.addPositionedComments("before",i.before),c.after.length>0&&l.addPositionedComments("after",c.after),{value:l,newIndex:n}}let s=x.parseFromLexeme(e,n);for(r.push(s.value),n=s.newIndex;n=e.length)throw new Error("Syntax error: Unexpected end of input after comma in tuple expression.");let l=x.parseFromLexeme(e,n);r.push(l.value),n=l.newIndex}if(n>=e.length||e[n].type!==8)throw new Error(`Syntax error at position ${n}: Expected closing parenthesis but found "${n0&&u.addPositionedComments("before",i.before),i.after.length>0&&r.length>0&&r[0].addPositionedComments("before",i.after),o.before.length>0&&r.length>0&&r[r.length-1].addPositionedComments("after",o.before),o.after.length>0&&u.addPositionedComments("after",o.after),{value:u,newIndex:n}}static extractLexemeComments(e){let t=[],n=[];if(!e)return{before:t,after:n};if(e.positionedComments&&e.positionedComments.length>0)for(let i of e.positionedComments)!i.comments||i.comments.length===0||(i.position==="before"?t.push(...i.comments):i.position==="after"&&n.push(...i.comments));else e.comments&&e.comments.length>0&&t.push(...e.comments);return{before:this.dedupeComments(t),after:this.dedupeComments(n)}}static dedupeComments(e){if(e.length<=1)return e;let t=new Set,n=[];for(let i of e)t.has(i)||(t.add(i),n.push(i));return n}};var gi=class{static parseFromLexeme(e,t){let n=t;if(e[n].value!=="fetch")throw new Error(`Syntax error at position ${n}: Expected 'FETCH' keyword but found "${e[n].value}".`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH' keyword.");let i=ir.parseFromLexeme(e,n),r=i.value;return n=i.newIndex,{value:new He(r),newIndex:n}}},ir=class{static parseFromLexeme(e,t){let n=t,i,r=e[n].value;if(r==="first")i="first";else if(r==="next")i="next";else throw new Error(`Syntax error at position ${n}: Expected 'FIRST' or 'NEXT' after 'FETCH' but found "${e[n].value}".`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT'.");let s=null,o=null;if(e[n].value==="row only"||e[n].value==="rows only")return s=new Z(1),o="rows only",n++,{value:new Ft(i,s,o),newIndex:n};let u=x.parseFromLexeme(e,n);if(s=u.value,n=u.newIndex,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT '.");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 '.");return{value:new Ft(i,s,o),newIndex:n}}};var wi=class{static parse(e){let n=new T(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error("Syntax error: Unexpected end of input after 'OFFSET' keyword. The OFFSET clause requires a numeric expression.");let i=x.parseFromLexeme(e,n);return n=i.newIndex,n=e.length)return null;let n=this.getAllLexemesWithPosition(e);for(let i of n)if(i.position&&t>=i.position.startPosition&&t=e.length));){let i=this.parseNextToken(e,n);i?(t.push(i),n=i.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],i=t+1,r=n;for(;i!]/.test(e[i])&&/[=<>!]/.test(n)&&(n+=e[i++]);let r=this.getOperatorTokenType(n);return this.createLexeme(r,n,t,i)}static parseWordToken(e,t){let n=t,i="";for(;nn.length)return-1;let i=n[t.line-1];if(t.column>i.length+1)return-1;let r=0;for(let s=0;se.length)return null;let n=e.split(` -`),i=0;for(let r=0;rt>=s.startPosition&&tt>=s.startPosition&&ti.length)return-1;let r=i[t-1];if(n>r.length+1)return-1;let s=0;for(let o=0;oe.length)return null;let i=e.substring(0,t).split(` -`);return{line:i.length,column:i[i.length-1].length+1}}static extractCTERegions(e){let t=Be.getAllLexemesWithPosition(e),n=[],i=0,r=!1;for(;i0;){if(e[i].value==="("?n++:e[i].value===")"&&n--,n===0)return{index:i,endPosition:e[i].position.endPosition};i++}return null}static extractCTESQL(e,t,n,i){let r=t[n+1].position.startPosition,s=t[i-1].position.endPosition;return e.substring(r,s).trim()}static isMainQuerySelect(e,t){let n=0;for(let i=t-1;i>=0;i--)e[i].value===")"?n++:e[i].value==="("&&n--;return n===0}static calculateExtendedCTEBoundaries(e,t){return t.length===0?[]:t.map((n,i)=>{let r;return i{n.push({name:i.name,startPosition:i.startPosition,type:"CTE"})}),t.length>0){let r=t[t.length-1].endPosition;for(;r=t.length)return e.length;let i=t[n];if(i.position?.startPosition!==void 0)return i.position.startPosition;let r=0;for(let l=0;ll.value),s=t[i.newIndex],o=this.calculateCharacterPosition(e,t,i.newIndex);return{success:!1,query:i.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:r}}return{success:!0,query:i.value}}catch(n){let i,r=n instanceof Error?n.message:String(n),s=r.match(/position (\d+)/);if(s){let o=parseInt(s[1],10);i=this.calculateCharacterPosition(e,t,o)}return{success:!1,error:r,errorPosition:i}}}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 extractUnionTokenComments(e){let t=[];if(e.positionedComments&&e.positionedComments.length>0){for(let n of e.positionedComments)n.comments&&n.comments.length>0&&t.push(...n.comments);e.positionedComments=void 0}return e.comments&&e.comments.length>0&&(t.push(...e.comments),e.comments=null),t.length>0?t: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 i=e[n].value;if(!this.selectCommandSet.has(i)&&i!=="values")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' or 'VALUES' keyword but found "${e[n].value}".`);let r=this.selectCommandSet.has(i)?this.parseSimpleSelectQuery(e,n):this.parseValuesQuery(e,n),s=r.value;for(n=r.newIndex;n=e.length)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 O(s,l,p.value);this.transferHeaderComments(s,m),u&&u.length>0&&(p.value.headerComments?p.value.headerComments=[...u,...p.value.headerComments]:p.value.headerComments=u),s=m,n=p.newIndex}else if(c==="values"){let p=this.parseValuesQuery(e,n),m=new O(s,l,p.value);this.transferHeaderComments(s,m),u&&u.length>0&&(p.value.headerComments?p.value.headerComments=[...u,...p.value.headerComments]:p.value.headerComments=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,{withClauseResult:i,newIndex:r,selectQuery:s}=this.parseWithClauseAndComments(e,n);n=r;let{clauses:o,newIndex:l,selectTokenComments:u}=this.parseAllClauses(e,n,i);if(n=l,u&&u.length>0)if(i){let m=[...s.betweenClauseComments??[]];for(let h of u)m.includes(h)||m.push(h);s.betweenClauseComments=m,s.mainSelectPrefixComments=void 0}else{let p=s.headerComments??[];s.headerComments=[...p,...u]}let c=new w({withClause:i?i.value:null,...o});return this.applyCommentsToQuery(c,s,i),{value:c,newIndex:n}}static parseWithClauseAndComments(e,t){let n=t,i=null,r={};for(r.headerComments=this.collectHeaderComments(e,n);n0&&n.push(...r.comments),i++}return n}static collectWithTokenHeaderComments(e,t){if(!e.positionedComments)return;t.headerComments||(t.headerComments=[]);let n=[];for(let i of e.positionedComments)i.position==="before"&&i.comments?t.headerComments.push(...i.comments):n.push(i);e.positionedComments=n.length>0?n:void 0}static collectMainSelectPrefixComments(e,t,n){let i=[];t?.value.trailingComments&&i.push(...t.value.trailingComments);let r=this.findMainSelectIndex(e,t,n);if(t&&r>t.newIndex)for(let s=t.newIndex;s0&&i.push(...o.comments)}return i}static collectBetweenClauseComments(e,t,n){if(!t)return[];let i=[],r=t.newIndex,s=Math.max(0,r-1);for(let o=s;o0){for(let u of l.positionedComments)u.comments&&i.push(...u.comments);l.positionedComments=void 0}l.comments&&l.comments.length>0&&(i.push(...l.comments),l.comments=null)}return i}static findMainSelectIndex(e,t,n){if(t){for(let i=t.newIndex;i=e.length||e[i].value!=="select")throw new Error(`Syntax error at position ${i}: Expected 'SELECT' keyword but found "${i0&&(i.push(...n.comments),n.comments=null),n.positionedComments&&n.positionedComments.length>0){for(let r of n.positionedComments)r.position==="before"&&r.comments&&i.push(...r.comments);n.positionedComments=void 0}return i}static applyCommentsToQuery(e,t,n){t.headerComments?.length>0&&(e.headerComments=t.headerComments);let i=r=>{if(!r||r.length===0)return;let s=e.comments??[],o=[];for(let l of r)o.includes(l)||o.push(l);for(let l of s)o.includes(l)||o.push(l);e.comments=o};i(t.mainSelectPrefixComments),i(t.betweenClauseComments)}static parseValuesQuery(e,t){let n=cn.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}static getCursorCte(e,t){return Nt.getCursorCte(e,t)}static getCursorCteAt(e,t,n){return Nt.getCursorCteAt(e,t,n)}static positionToLineColumn(e,t){return Nt.positionToLineColumn(e,t)}};var Ot=class{static parseFromLexeme(e,t){let n=t;if(e[n]?.value!=="returning")throw new Error(`Syntax error at position ${n}: Expected 'RETURNING' but found '${e[n]?.value}'.`);n++;let i=[];for(;n=e.length)throw new Error("Syntax error: Unexpected end of input while parsing INSERT statement. VALUES or SELECT clause expected.");let o=e[n].value.toLowerCase(),l;if(o==="values"){let c=cn.parseFromLexeme(e,n);l=c.value,n=c.newIndex}else{let c=P.parseFromLexeme(e,n);l=c.value,n=c.newIndex}let u=null;if(e[n]?.value==="returning"){let c=Ot.parseFromLexeme(e,n);u=c.value,n=c.newIndex}return{value:new tt({withClause:i,insertClause:new xt(r.value,s??null),selectQuery:l,returning:u}),newIndex:n}}};var Si=class{static parseFromLexeme(e,t){let n=pe.parseFromLexeme(e,t);return{value:new bt(n.value),newIndex:n.newIndex}}};var bi=class{static parseFromLexeme(e,t){if(e[t].value!=="set")throw new Error(`Syntax error at position ${t}: Expected 'SET' but found '${e[t].value}'.`);t++;let n=[];for(;t=e.length)throw new Error(`[DeleteClauseParser] Unexpected end of input at position ${t}: expected 'DELETE FROM'.`);if(e[t]?.value?.toLowerCase()!=="delete from"){let r=e[t]?.position?.startPosition??t;throw new Error(`[DeleteClauseParser] Syntax error at position ${r}: expected 'DELETE FROM' but found '${e[t]?.value}'.`)}let i=pe.parseFromLexeme(e,t+1);return{value:new Et(i.value),newIndex:i.newIndex}}};var Ti=class{static parseFromLexeme(e,t){if(e[t].value!=="using")throw new Error(`Syntax error at position ${t}: Expected 'USING' but found '${e[t].value}'.`);let n=t+1,i=[],r=pe.parseFromLexeme(e,n);for(i.push(r.value),n=r.newIndex;e[n]?.type===16;){n++;let s=pe.parseFromLexeme(e,n);i.push(s.value),n=s.newIndex}return{value:new Jt(i),newIndex:n}}};var ki=class{static parse(e){let n=new T(e).readLexemes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error(`[CreateTableParser] Unexpected end of input at position ${n}.`);let i=e[n].value.toLowerCase(),r=i==="create temporary table";if(i!=="create table"&&!r)throw new Error(`[CreateTableParser] Syntax error at position ${n}: expected 'CREATE TABLE' but found '${e[n].value}'.`);n++;let s=g=>e[n+g]?.value.toLowerCase(),o=!1;s(0)==="if not exists"&&(n++,o=!0);let l=this.parseQualifiedName(e,n);n=l.newIndex;let u=l.name,c=l.namespaces,p=u.positionedComments?[...u.positionedComments]:null,m=u.comments?[...u.comments]:null,h=[],C=[],f=null,N;if(e[n]?.type===4&&({columns:h,tableConstraints:C,newIndex:n}=this.parseDefinitionList(e,n)),nn&&(f=new R(ft(e,n,M)),n=M)}}let V=s(0);if(V==="as"){n++;let g=P.parseFromLexeme(e,n);N=g.value,n=g.newIndex}else if(V==="select"||V==="with"||V==="values"){let g=P.parseFromLexeme(e,n);N=g.value,n=g.newIndex}let v=new Pt({tableName:u.name,namespaces:c,isTemporary:r,ifNotExists:o,columns:h,tableConstraints:C,tableOptions:f,asSelectQuery:N});return p&&(v.tableName.positionedComments=p.map(g=>({position:g.position,comments:[...g.comments]}))),m&&(v.tableName.comments=[...m]),{value:v,newIndex:n}}static parseQualifiedName(e,t){let{namespaces:n,name:i,newIndex:r}=K.parseFromLexeme(e,t);return{namespaces:n?[...n]:null,name:i,newIndex:r}}static parseDefinitionList(e,t){let n=t,i=[],r=[];for(n++;n0){let u=[...i.namespaces,i.name.name].join(".");throw new Error(`[CreateTableParser] Column name '${u}' must not include a schema or namespace qualifier.`)}let r=i.name,s;if(n0&&(o=u.leadingComments),n||u.rawText.trim().length===0))&&(l++,r.push(this.dispatchParse(u,l)))}return r}static dispatchParse(e,t){if(e.lexemes.length===0)throw new Error(`[SqlParser] Statement ${t} does not contain any tokens.`);let n=e.lexemes[0].value.toLowerCase();if(n==="with"){let i=this.getCommandAfterWith(e.lexemes);return i==="insert into"?this.parseInsertStatement(e,t):i==="update"?this.parseUpdateStatement(e,t):i==="delete from"?this.parseDeleteStatement(e,t):i==="merge into"?this.parseMergeStatement(e,t):this.parseSelectStatement(e,t)}if(n==="select"||n==="values")return this.parseSelectStatement(e,t);if(n==="insert into")return this.parseInsertStatement(e,t);if(n==="update")return this.parseUpdateStatement(e,t);if(n==="delete from")return this.parseDeleteStatement(e,t);if(n==="create table"||n==="create temporary table")return this.parseCreateTableStatement(e,t);if(n==="merge into")return this.parseMergeStatement(e,t);if(n==="create index"||n==="create unique index")return this.parseCreateIndexStatement(e,t);if(n==="drop table")return this.parseDropTableStatement(e,t);if(n==="drop index")return this.parseDropIndexStatement(e,t);if(n==="alter table")return this.parseAlterTableStatement(e,t);if(n==="drop constraint")return this.parseDropConstraintStatement(e,t);throw new Error(`[SqlParser] Statement ${t} starts with unsupported token "${e.lexemes[0].value}". Support for additional statement types will be introduced soon.`)}static parseSelectStatement(e,t){try{let n=P.parseFromLexeme(e.lexemes,0);if(n.newIndex({...t,comments:t.comments?[...t.comments]:null,positionedComments:t.positionedComments?t.positionedComments.map(n=>({position:n.position,comments:[...n.comments]})):void 0,position:t.position?{...t.position}:void 0}))}static consumeNextStatement(e,t,n){let i=t,r=null;for(;;){let s=e.readNextStatement(i,r);if(r=null,!s)return null;if(i=s.nextPosition,!(s.lexemes.length===0&&(s.leadingComments&&s.leadingComments.length>0&&(r=s.leadingComments),n||s.rawText.trim().length===0)))return{segment:s,nextCursor:i}}}};var Ri=class{constructor(){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(w.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(O.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ae.kind,e=>this.visitValuesQuery(e)),this.handlers.set(_.kind,e=>this.visitFromClause(e)),this.handlers.set(ve.kind,e=>this.visitJoinClause(e)),this.handlers.set(we.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Te.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set($.kind,e=>this.visitSourceExpression(e)),this.handlers.set(B.kind,e=>this.visitTableSource(e)),this.handlers.set(nt.kind,e=>this.visitFunctionSource(e)),this.handlers.set(je.kind,e=>this.visitParenSource(e)),this.handlers.set(U.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(de.kind,e=>this.visitInlineQuery(e)),this.handlers.set(re.kind,e=>this.visitWhereClause(e)),this.handlers.set(ge.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ye.kind,e=>this.visitHavingClause(e)),this.handlers.set(Ce.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Oe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(ce.kind,e=>this.visitLimitClause(e)),this.handlers.set($e.kind,e=>this.visitOffsetClause(e)),this.handlers.set(He.kind,e=>this.visitFetchClause(e)),this.handlers.set(Re.kind,e=>this.visitForClause(e)),this.handlers.set(Qe.kind,e=>this.visitOrderByItem(e)),this.handlers.set(z.kind,e=>this.visitSelectClause(e)),this.handlers.set(q.kind,e=>this.visitSelectItem(e)),this.handlers.set(ee.kind,e=>this.visitParenExpression(e)),this.handlers.set(b.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ue.kind,e=>this.visitCaseExpression(e)),this.handlers.set(Ae.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(Le.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(Ee.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(H.kind,e=>this.visitFunctionCall(e)),this.handlers.set(Se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(be.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(xe.kind,e=>this.visitTupleExpression(e)),this.handlers.set(fe.kind,e=>this.visitCastExpression(e)),this.handlers.set(W.kind,e=>this.visitValueList(e)),this.handlers.set(ze.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 R?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof R?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 Qt=class a{constructor(){this.dependencyGraph=null;this.cteMap=new Map;this.sourceCollector=new rt(!1),this.cteReferenceCollector=new Ri,this.cteCollector=new ne}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=[],i=new Map;for(let s of this.dependencyGraph.nodes)i.set(s.name,new Set(s.dependencies));let r=s=>{if(e.has(s))return;if(t.has(s))throw new Error(`${a.ERROR_MESSAGES.CIRCULAR_REFERENCE}: ${s}`);t.add(s);let o=i.get(s)||new Set;for(let l of o)r(l);t.delete(s),e.add(s),n.push(s)};for(let s of this.dependencyGraph.nodes)e.has(s.name)||r(s.name);return n}buildDependencyGraph(e,t){let n=[],i=[],r=new Map,s=new Map;for(let l of e){let u=a.getCTEName(l);r.set(u,new Set),s.set(u,new Set)}r.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&&(r.get(u).add(m),s.get(m).add(u),i.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)&&(r.get(a.MAIN_QUERY_NAME).add(c),s.get(c).add(a.MAIN_QUERY_NAME),i.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(r.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(r.get(a.MAIN_QUERY_NAME)||new Set),dependents:Array.from(s.get(a.MAIN_QUERY_NAME)||new Set)}),{nodes:n,edges:i}}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 w({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 Fi=class{static addComment(e,t,n="before"){if(this.isSelectQuery(e)){let i=e;i.headerComments||(i.headerComments=[]),i.headerComments.push(t)}else e.addPositionedComments(n,[t])}static isSelectQuery(e){return"__selectQueryType"in e&&e.__selectQueryType==="SelectQuery"}static editComment(e,t,n,i="before"){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{let r=e.getPositionedComments(i);if(!r||t<0||t>=r.length)throw new Error(`Invalid comment index: ${t}. Component has ${r?.length||0} ${i} positioned comments.`);let s=e.positionedComments?.find(o=>o.position===i);s&&(s.comments[t]=n)}}static deleteComment(e,t,n="before"){if(this.isSelectQuery(e)){let i=e;if(!i.headerComments||t<0||t>=i.headerComments.length)throw new Error(`Invalid comment index: ${t}. Component has ${i.headerComments?.length||0} comments.`);i.headerComments.splice(t,1),i.headerComments.length===0&&(i.headerComments=null)}else{let i=e.getPositionedComments(n);if(!i||t<0||t>=i.length)throw new Error(`Invalid comment index: ${t}. Component has ${i?.length||0} ${n} positioned comments.`);let r=e.positionedComments?.find(s=>s.position===n);r&&(r.comments.splice(t,1),r.comments.length===0&&(e.positionedComments=e.positionedComments?.filter(s=>s.position!==n)||null,e.positionedComments?.length===0&&(e.positionedComments=null)))}}static deleteAllComments(e){if(this.isSelectQuery(e)){let t=e;t.headerComments=null}else e.positionedComments=null}static getComments(e){return this.isSelectQuery(e)?e.headerComments||[]:e.getAllPositionedComments()}static findComponentsWithComment(e,t,n=!1){let i=[],r=n?t:t.toLowerCase(),s=o=>{if(o&&o instanceof y){let l=!1,u=o.getAllPositionedComments();if(u&&u.some(c=>(n?c:c.toLowerCase()).includes(r))&&(l=!0),this.isSelectQuery(o)){let c=o;c.headerComments&&c.headerComments.some(p=>(n?p:p.toLowerCase()).includes(r))&&(l=!0)}l&&i.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),i}static replaceInComments(e,t,n,i=!1){let r=0,s=o=>{if(o&&o instanceof y){if(o.comments)for(let l=0;l{if(i&&i instanceof y){let r=i.getAllPositionedComments();if(r&&(t+=r.length),this.isSelectQuery(i)){let s=i;s.headerComments&&(t+=s.headerComments.length)}}for(let r in i)i[r]&&typeof i[r]=="object"&&(Array.isArray(i[r])?i[r].forEach(n):n(i[r]))};return n(e),t}static getAllComments(e){let t=[],n=i=>{if(i&&i instanceof y){let r=i.getAllPositionedComments();if(r&&r.forEach((s,o)=>{t.push({comment:s,component:i,index:o})}),this.isSelectQuery(i)){let s=i;s.headerComments&&s.headerComments.forEach((o,l)=>{t.push({comment:o,component:i,index:l})})}}for(let r in i)i[r]&&typeof i[r]=="object"&&(Array.isArray(i[r])?i[r].forEach(n):n(i[r]))};return n(e),t}};var St=class{constructor(e,t){this.name=e,this.columns=t}},pn=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(w.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(O.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 w||e instanceof O))throw new Error(`Unsupported SQL component type for schema collection. Received: ${e.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let t=new ne;this.commonTables=t.collect(e),this.visitNode(e),this.consolidateTableSchemas()}finally{this.running=!1}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}reset(){this.tableSchemas=[],this.visitedNodes=new Set,this.commonTables=[],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(i=>n?.add(i))}this.tableSchemas=Array.from(e.entries()).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>new St(t,Array.from(n).sort()))}handleSourceExpression(e,t,n){if(e.datasource instanceof B){let i=e.datasource.getSourceName(),r=this.commonTables.filter(s=>s.getSourceAliasName()===i);if(r.length>0){r[0].query.accept(this);let s=e.getAliasName()??i;this.processCTETableSchema(r[0],s,t,n)}else{let s=e.getAliasName()??i;this.processCollectTableSchema(i,s,t,n)}}else e.datasource instanceof U&&this.visitNode(e.datasource.query)}visitSimpleSelectQuery(e){if(e.fromClause===null)return;let n=new Ne(this.tableColumnResolver,!0,"fullName").collect(e),i;if(this.allowWildcardWithoutResolver){let r=this.getSelectClauseColumns(e);i=n.filter(s=>s.value instanceof E).map(s=>s.value).filter(s=>{let o=s.getNamespace(),l=s.column.name;return r.some(u=>{if(u.value instanceof E){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 i=n.filter(r=>r.value instanceof E).map(r=>r.value).map(r=>({table:r.getNamespace(),column:r.column.name}));if(e.fromClause.joins!==null&&e.fromClause.joins.length>0){let r=i.filter(s=>s.table==="").map(s=>s.column);if(r.length>0)if(this.isAnalyzeMode)this.unresolvedColumns.push(...r),this.analysisError=`Column reference(s) without table name found in query: ${r.join(", ")}`;else throw new Error(`Column reference(s) without table name found in query: ${r.join(", ")}`)}if(e.fromClause.source.datasource instanceof B?this.handleSourceExpression(e.fromClause.source,i,!0):e.fromClause.source.datasource instanceof U&&e.fromClause.source.datasource.query.accept(this),e.fromClause?.joins)for(let r of e.fromClause.joins)r.source.datasource instanceof B?this.handleSourceExpression(r.source,i,!1):r.source.datasource instanceof U&&r.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 E){let i=n.value.column.name;t.push({name:i,value:n.value})}return t}processCollectTableSchema(e,t,n,i=!1){if(this.tableColumnResolver===null&&n.filter(l=>l.table===t||i&&l.table==="").filter(l=>l.column==="*").length>0&&!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||i&&c.table==="").filter(c=>c.column==="*").map(c=>c.table?`${c.table}.*`:"*");this.unresolvedColumns.push(...u)}else throw new Error(l)}let r=n.filter(o=>o.column!=="*").filter(o=>o.table===t||i&&o.table==="").map(o=>o.column),s=new St(e,r);this.tableSchemas.push(s)}processCTETableSchema(e,t,n,i=!1){let r=e.getSourceAliasName(),s=this.getCTEColumns(e),o=n.filter(c=>c.table===t||i&&c.table==="").map(c=>c.column);if(o.includes("*")){if(this.tableColumnResolver!==null){let c=this.tableColumnResolver(r);if(c.length>0){let p=new St(r,c);this.tableSchemas.push(p);return}}if(s.length>0){let c=new St(r,s);this.tableSchemas.push(c);return}else if(this.allowWildcardWithoutResolver){let c=new St(r,[]);this.tableSchemas.push(c);return}else{let c=`Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards. Target table: ${r}`;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(r);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 "${r}": ${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 "${r}": ${p.join(", ")}`))}}let u=new St(r,l);this.tableSchemas.push(u)}getCTEColumns(e){try{return e.query instanceof w&&e.query.selectClause?this.extractColumnsFromSelectItems(e.query.selectClause.items,e):this.extractColumnsUsingCollector(e.query)}catch{return[]}}extractColumnsFromSelectItems(e,t){let n=[];for(let i of e)if(i.value instanceof E){let r=i.identifier?.name||i.value.column.name;if(i.value.column.name==="*"){let s=this.resolveWildcardInCTE(i.value,t);if(s===null)return[];n.push(...s)}else n.push(r)}else i.identifier&&n.push(i.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 w)||!e.query.fromClause)return null;let t=e.query.fromClause.source;return t.datasource instanceof B?this.resolveTableWildcard(t.datasource.table.name):(t.datasource instanceof U,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 Ne(null,!0,"fullName").collect(e).filter(i=>i.value instanceof E).map(i=>i.value).map(i=>i.column.name).filter((i,r,s)=>s.indexOf(i)===r)}removeDuplicates(e){return e.filter((t,n,i)=>i.indexOf(t)===n)}};var Bi=class{static validate(e,t){let n=typeof e=="string"?P.parse(e):e,i=Array.isArray(t)?l=>{let u=t.find(c=>c.name===l);return u?u.columns:[]}:t,s=new pn(i).collect(n),o=[];for(let l of s){let u=i(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(` -`))}};var Mi=class{constructor(e={}){this.knownCTENames=[];this.options=e,this.formatter=new Ue(e),this.dependencyAnalyzer=new Qt}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)})),i=this.buildTempQueryForAnalysis(n,t),r=this.dependencyAnalyzer.analyzeDependencies(i),s=this.sortCTEsByDependencies(n,r),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 r=P.parse(e);if(r.withClause&&r.withClause.tables){let s=this.getKnownCTENames();if(r.withClause.tables.map(u=>this.getCTEName(u)).every(u=>s.includes(u))){let u=new w({selectClause:r.selectClause,fromClause:r.fromClause,whereClause:r.whereClause,groupByClause:r.groupByClause,havingClause:r.havingClause,orderByClause:r.orderByClause,windowClause:r.windowClause,limitClause:r.limitClause,offsetClause:r.offsetClause,fetchClause:r.fetchClause,forClause:r.forClause,withClause:void 0});return new Ue({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"),i=e.match(n);if(!i)return e;let r=i.index+i[0].length,s=1,o=r;for(;o0;){let l=e[o];l==="("?s++:l===")"&&s--,o++}return s===0?e.substring(r,o-1).trim():e}buildTempQueryForAnalysis(e,t){let i=`with ${e.map(r=>`${r.name} as (${r.query})`).join(", ")} ${t}`;try{return P.parse(i)}catch(r){throw new Error(`Failed to parse temporary query for dependency analysis: ${r}`)}}sortCTEsByDependencies(e,t){let n=new Map;return e.forEach(i=>n.set(i.name,i.query)),t.nodes.map(i=>({name:i.name,query:n.get(i.name)||""})).filter(i=>i.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=P.parse(e),n=Object.entries(this.options.schema).map(([i,r])=>({name:i,columns:r}));Bi.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=P.parse(e);return this.formatter.format(t).formattedSql}catch{return e}return e}};var Ir=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 Qt,this.cteCollector=new ne,this.formatter=new Ue(e)}decompose(e){let t=this.cteCollector.collect(e);if(t.length===0)return[];let n=this.findRecursiveCTEs(e,t),i=this.dependencyAnalyzer.analyzeDependencies(e);return this.validateCircularDependencies(n.length>0),this.processCTENodes(e,i.nodes,n)}synchronize(e,t){if(e.length===0)return[];let n=this.flattenNestedWithClauses(e),i={...this.options,addComments:void 0},s=new Mi(i).compose(n,t),o=P.parse(s);return this.decompose(o)}extractCTE(e,t){let n=[],i=this.cteCollector.collect(e);if(i.length===0)throw new Error("Query does not contain any CTEs");if(!i.find(C=>this.getCTEName(C)===t))throw new Error(`CTE not found in query: ${t}`);if(this.findRecursiveCTEs(e,i).includes(t))return n.push("Recursive CTE restoration requires the full query context"),{name:t,executableSql:this.formatter.format(e).formattedSql,dependencies:this.getAllCTENames(i).filter(C=>C!==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(C=>C.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(C=>C.name),h=this.options.addComments?this.addRestorationComments(c,u,n):c;return{name:t,executableSql:h,dependencies:m,warnings:n}}flattenNestedWithClauses(e){let t=[],n=new Map;for(let r of e)try{if(/^\s*with\s+/i.test(r.query)){let o=P.parse(r.query);if(o.withClause&&o.withClause.tables){for(let p of o.withClause.tables){let m=this.getCTEName(p);if(!n.has(m)){let C=new Ue({identifierEscape:{start:"",end:""}}).format(p.query).formattedSql;n.set(m,C)}}let l=new w({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 Ue({identifierEscape:{start:"",end:""}}).format(l).formattedSql;t.push({name:r.name,query:c})}else t.push(r)}else t.push(r)}catch{t.push(r)}let i=[];for(let[r,s]of n)i.push({name:r,query:s});return i.push(...t),i}validateCircularDependencies(e){if(this.dependencyAnalyzer.hasCircularDependency()&&!e)throw new Error(a.ERROR_MESSAGES.CIRCULAR_REFERENCE)}processCTENodes(e,t,n){let i=[];for(let r of t){if(r.type==="ROOT")continue;n.includes(r.name)?i.push(this.createRecursiveCTE(r,e)):i.push(this.createStandardCTE(r,t))}return i}createRecursiveCTE(e,t){let n=this.formatter.format(t).formattedSql,i=e.dependents.filter(s=>s!=="MAIN_QUERY"),r=this.addCommentsToQuery(n,e.name,e.dependencies,e.dependents,!0);return{name:e.name,query:r,dependencies:[...e.dependencies],dependents:i,isRecursive:!0}}createStandardCTE(e,t){let n=this.buildExecutableQuery(e,t),i=this.addCommentsToQuery(n,e.name,e.dependencies,e.dependents,!1),r=e.dependents.filter(s=>s!=="MAIN_QUERY");return{name:e.name,query:i,dependencies:[...e.dependencies],dependents:r,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 i=this.buildWithClause(n),r=this.formatter.format(e.cte.query).formattedSql;return`${i} ${r}`}collectRequiredCTEs(e,t){let n=new Set,i=[],r=new Map;for(let o of t)r.set(o.name,o);let s=o=>{if(n.has(o))return;n.add(o);let l=r.get(o);if(l){for(let u of l.dependencies)s(u);o!==e.name&&l.type!=="ROOT"&&i.push(l)}};for(let o of e.dependencies)s(o);return i}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 i=n.name,r=this.formatter.format(n.cte.query).formattedSql;return`${i} as (${r})`}).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,i,r){if(this.options.addComments!==!0)return e;try{let s=P.parse(e);return this.generateComments(t,n,i,r).forEach(u=>{Fi.addComment(s,u)}),new Ue({...this.options,exportComment:!0}).format(s).formattedSql}catch(s){return console.warn(`${a.ERROR_MESSAGES.PARSING_FAILED}: ${s}`),this.addTextCommentsToQuery(e,t,n,i,r)}}generateComments(e,t,n,i){let{AUTO_GENERATED:r,ORIGINAL_CTE:s,DEPENDENCIES:o,DEPENDENTS:l,RECURSIVE_TYPE:u,NONE:c}=a.COMMENT_TEXTS,p=[];p.push(r),p.push(`${s} ${e}`),i&&p.push(u);let m=t.length>0?t.join(", "):c;p.push(`${o} ${m}`);let h=n.filter(f=>f!=="MAIN_QUERY"),C=h.length>0?h.join(", "):c;return p.push(`${l} ${C}`),p}addTextCommentsToQuery(e,t,n,i,r){return`${this.generateComments(t,n,i,r).map(l=>`-- ${l}`).join(` +`);return{line:i.length,column:i[i.length-1].length+1}}static extractCTERegions(e){let t=Be.getAllLexemesWithPosition(e),n=[],i=0,r=!1;for(;i0;){if(e[i].value==="("?n++:e[i].value===")"&&n--,n===0)return{index:i,endPosition:e[i].position.endPosition};i++}return null}static extractCTESQL(e,t,n,i){let r=t[n+1].position.startPosition,s=t[i-1].position.endPosition;return e.substring(r,s).trim()}static isMainQuerySelect(e,t){let n=0;for(let i=t-1;i>=0;i--)e[i].value===")"?n++:e[i].value==="("&&n--;return n===0}static calculateExtendedCTEBoundaries(e,t){return t.length===0?[]:t.map((n,i)=>{let r;return i{n.push({name:i.name,startPosition:i.startPosition,type:"CTE"})}),t.length>0){let r=t[t.length-1].endPosition;for(;r=t.length)return e.length;let i=t[n];if(i.position?.startPosition!==void 0)return i.position.startPosition;let r=0;for(let u=0;uu.value),s=t[i.newIndex],o=this.calculateCharacterPosition(e,t,i.newIndex);return{success:!1,query:i.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:r}}return{success:!0,query:i.value}}catch(n){let i,r=n instanceof Error?n.message:String(n),s=r.match(/position (\d+)/);if(s){let o=parseInt(s[1],10);i=this.calculateCharacterPosition(e,t,o)}return{success:!1,error:r,errorPosition:i}}}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 extractUnionTokenComments(e){let t=[];if(e.positionedComments&&e.positionedComments.length>0){for(let n of e.positionedComments)n.comments&&n.comments.length>0&&t.push(...n.comments);e.positionedComments=void 0}return e.comments&&e.comments.length>0&&(t.push(...e.comments),e.comments=null),t.length>0?t: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 i=e[n].value;if(!this.selectCommandSet.has(i)&&i!=="values")throw new Error(`Syntax error at position ${n}: Expected 'SELECT' or 'VALUES' keyword but found "${e[n].value}".`);let r=this.selectCommandSet.has(i)?this.parseSimpleSelectQuery(e,n):this.parseValuesQuery(e,n),s=r.value;for(n=r.newIndex;n=e.length)throw new Error(`Syntax error at position ${n}: Expected a query after '${u.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 O(s,u,p.value);this.transferHeaderComments(s,m),l&&l.length>0&&(p.value.headerComments?p.value.headerComments=[...l,...p.value.headerComments]:p.value.headerComments=l),s=m,n=p.newIndex}else if(c==="values"){let p=this.parseValuesQuery(e,n),m=new O(s,u,p.value);this.transferHeaderComments(s,m),l&&l.length>0&&(p.value.headerComments?p.value.headerComments=[...l,...p.value.headerComments]:p.value.headerComments=l),s=m,n=p.newIndex}else throw new Error(`Syntax error at position ${n}: Expected 'SELECT' or 'VALUES' after '${u.toUpperCase()}' but found "${e[n].value}".`)}return{value:s,newIndex:n}}static parseSimpleSelectQuery(e,t){let n=t,{withClauseResult:i,newIndex:r,selectQuery:s}=this.parseWithClauseAndComments(e,n);n=r;let{clauses:o,newIndex:u,selectTokenComments:l}=this.parseAllClauses(e,n,i);if(n=u,l&&l.length>0)if(i){let m=[...s.betweenClauseComments??[]];for(let h of l)m.includes(h)||m.push(h);s.betweenClauseComments=m,s.mainSelectPrefixComments=void 0}else{let p=s.headerComments??[];s.headerComments=[...p,...l]}let c=new w({withClause:i?i.value:null,...o});return this.applyCommentsToQuery(c,s,i),{value:c,newIndex:n}}static parseWithClauseAndComments(e,t){let n=t,i=null,r={};for(r.headerComments=this.collectHeaderComments(e,n);n0&&n.push(...r.comments),i++}return n}static collectWithTokenHeaderComments(e,t){if(!e.positionedComments)return;t.headerComments||(t.headerComments=[]);let n=[];for(let i of e.positionedComments)i.position==="before"&&i.comments?t.headerComments.push(...i.comments):n.push(i);e.positionedComments=n.length>0?n:void 0}static collectMainSelectPrefixComments(e,t,n){let i=[];t?.value.trailingComments&&i.push(...t.value.trailingComments);let r=this.findMainSelectIndex(e,t,n);if(t&&r>t.newIndex)for(let s=t.newIndex;s0&&i.push(...o.comments)}return i}static collectBetweenClauseComments(e,t,n){if(!t)return[];let i=[],r=t.newIndex,s=Math.max(0,r-1);for(let o=s;o0){for(let l of u.positionedComments)l.comments&&i.push(...l.comments);u.positionedComments=void 0}u.comments&&u.comments.length>0&&(i.push(...u.comments),u.comments=null)}return i}static findMainSelectIndex(e,t,n){if(t){for(let i=t.newIndex;i=e.length||e[i].value!=="select")throw new Error(`Syntax error at position ${i}: Expected 'SELECT' keyword but found "${i0&&(i.push(...n.comments),n.comments=null),n.positionedComments&&n.positionedComments.length>0){for(let r of n.positionedComments)r.position==="before"&&r.comments&&i.push(...r.comments);n.positionedComments=void 0}return i}static applyCommentsToQuery(e,t,n){t.headerComments?.length>0&&(e.headerComments=t.headerComments);let i=r=>{if(!r||r.length===0)return;let s=e.comments??[],o=[];for(let u of r)o.includes(u)||o.push(u);for(let u of s)o.includes(u)||o.push(u);e.comments=o};i(t.mainSelectPrefixComments),i(t.betweenClauseComments)}static parseValuesQuery(e,t){let n=cn.parseFromLexeme(e,t);return{value:n.value,newIndex:n.newIndex}}static getCursorCte(e,t){return At.getCursorCte(e,t)}static getCursorCteAt(e,t,n){return At.getCursorCteAt(e,t,n)}static positionToLineColumn(e,t){return At.positionToLineColumn(e,t)}};var Ot=class{static parseFromLexeme(e,t){let n=t;if(e[n]?.value!=="returning")throw new Error(`Syntax error at position ${n}: Expected 'RETURNING' but found '${e[n]?.value}'.`);n++;let i=[];for(;n=e.length)throw new Error("Syntax error: Unexpected end of input while parsing INSERT statement. VALUES or SELECT clause expected.");let o=e[n].value.toLowerCase(),u;if(o==="values"){let c=cn.parseFromLexeme(e,n);u=c.value,n=c.newIndex}else{let c=P.parseFromLexeme(e,n);u=c.value,n=c.newIndex}let l=null;if(e[n]?.value==="returning"){let c=Ot.parseFromLexeme(e,n);l=c.value,n=c.newIndex}return{value:new tt({withClause:i,insertClause:new xt(r.value,s??null),selectQuery:u,returning:l}),newIndex:n}}};var Si=class{static parseFromLexeme(e,t){let n=pe.parseFromLexeme(e,t);return{value:new bt(n.value),newIndex:n.newIndex}}};var bi=class{static parseFromLexeme(e,t){if(e[t].value!=="set")throw new Error(`Syntax error at position ${t}: Expected 'SET' but found '${e[t].value}'.`);t++;let n=[];for(;t=e.length)throw new Error(`[DeleteClauseParser] Unexpected end of input at position ${t}: expected 'DELETE FROM'.`);if(e[t]?.value?.toLowerCase()!=="delete from"){let r=e[t]?.position?.startPosition??t;throw new Error(`[DeleteClauseParser] Syntax error at position ${r}: expected 'DELETE FROM' but found '${e[t]?.value}'.`)}let i=pe.parseFromLexeme(e,t+1);return{value:new Et(i.value),newIndex:i.newIndex}}};var Ti=class{static parseFromLexeme(e,t){if(e[t].value!=="using")throw new Error(`Syntax error at position ${t}: Expected 'USING' but found '${e[t].value}'.`);let n=t+1,i=[],r=pe.parseFromLexeme(e,n);for(i.push(r.value),n=r.newIndex;e[n]?.type===16;){n++;let s=pe.parseFromLexeme(e,n);i.push(s.value),n=s.newIndex}return{value:new Jt(i),newIndex:n}}};var ki=class{static parse(e){let n=new T(e).readLexemes(),i=this.parseFromLexeme(n,0);if(i.newIndex=e.length)throw new Error(`[CreateTableParser] Unexpected end of input at position ${n}.`);let i=e[n].value.toLowerCase(),r=i==="create temporary table";if(i!=="create table"&&!r)throw new Error(`[CreateTableParser] Syntax error at position ${n}: expected 'CREATE TABLE' but found '${e[n].value}'.`);n++;let s=y=>e[n+y]?.value.toLowerCase(),o=!1;s(0)==="if not exists"&&(n++,o=!0);let u=this.parseQualifiedName(e,n);n=u.newIndex;let l=u.name,c=u.namespaces,p=l.positionedComments?[...l.positionedComments]:null,m=l.comments?[...l.comments]:null,h=[],C=[],f=null,A;if(e[n]?.type===4&&({columns:h,tableConstraints:C,newIndex:n}=this.parseDefinitionList(e,n)),nn&&(f=new R(ft(e,n,M)),n=M)}}let V=s(0);if(V==="as"){n++;let y=P.parseFromLexeme(e,n);A=y.value,n=y.newIndex}else if(V==="select"||V==="with"||V==="values"){let y=P.parseFromLexeme(e,n);A=y.value,n=y.newIndex}let v=new Pt({tableName:l.name,namespaces:c,isTemporary:r,ifNotExists:o,columns:h,tableConstraints:C,tableOptions:f,asSelectQuery:A});return p&&(v.tableName.positionedComments=p.map(y=>({position:y.position,comments:[...y.comments]}))),m&&(v.tableName.comments=[...m]),{value:v,newIndex:n}}static parseQualifiedName(e,t){let{namespaces:n,name:i,newIndex:r}=j.parseFromLexeme(e,t);return{namespaces:n?[...n]:null,name:i,newIndex:r}}static parseDefinitionList(e,t){let n=t,i=[],r=[];for(n++;n0){let l=[...i.namespaces,i.name.name].join(".");throw new Error(`[CreateTableParser] Column name '${l}' must not include a schema or namespace qualifier.`)}let r=i.name,s;if(n0&&(o=l.leadingComments),n||l.rawText.trim().length===0))&&(u++,r.push(this.dispatchParse(l,u)))}return r}static dispatchParse(e,t){if(e.lexemes.length===0)throw new Error(`[SqlParser] Statement ${t} does not contain any tokens.`);let n=e.lexemes[0].value.toLowerCase();if(n==="with"){let i=this.getCommandAfterWith(e.lexemes);return i==="insert into"?this.parseInsertStatement(e,t):i==="update"?this.parseUpdateStatement(e,t):i==="delete from"?this.parseDeleteStatement(e,t):i==="merge into"?this.parseMergeStatement(e,t):this.parseSelectStatement(e,t)}if(n==="select"||n==="values")return this.parseSelectStatement(e,t);if(n==="insert into")return this.parseInsertStatement(e,t);if(n==="update")return this.parseUpdateStatement(e,t);if(n==="delete from")return this.parseDeleteStatement(e,t);if(n==="create table"||n==="create temporary table")return this.parseCreateTableStatement(e,t);if(n==="merge into")return this.parseMergeStatement(e,t);if(n==="create index"||n==="create unique index")return this.parseCreateIndexStatement(e,t);if(n==="drop table")return this.parseDropTableStatement(e,t);if(n==="drop index")return this.parseDropIndexStatement(e,t);if(n==="alter table")return this.parseAlterTableStatement(e,t);if(n==="drop constraint")return this.parseDropConstraintStatement(e,t);throw new Error(`[SqlParser] Statement ${t} starts with unsupported token "${e.lexemes[0].value}". Support for additional statement types will be introduced soon.`)}static parseSelectStatement(e,t){try{let n=P.parseFromLexeme(e.lexemes,0);if(n.newIndex({...t,comments:t.comments?[...t.comments]:null,positionedComments:t.positionedComments?t.positionedComments.map(n=>({position:n.position,comments:[...n.comments]})):void 0,position:t.position?{...t.position}:void 0}))}static consumeNextStatement(e,t,n){let i=t,r=null;for(;;){let s=e.readNextStatement(i,r);if(r=null,!s)return null;if(i=s.nextPosition,!(s.lexemes.length===0&&(s.leadingComments&&s.leadingComments.length>0&&(r=s.leadingComments),n||s.rawText.trim().length===0)))return{segment:s,nextCursor:i}}}};var Ri=class{constructor(){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(w.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(O.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(ae.kind,e=>this.visitValuesQuery(e)),this.handlers.set(_.kind,e=>this.visitFromClause(e)),this.handlers.set(ve.kind,e=>this.visitJoinClause(e)),this.handlers.set(we.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Te.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set($.kind,e=>this.visitSourceExpression(e)),this.handlers.set(B.kind,e=>this.visitTableSource(e)),this.handlers.set(nt.kind,e=>this.visitFunctionSource(e)),this.handlers.set(je.kind,e=>this.visitParenSource(e)),this.handlers.set(K.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(de.kind,e=>this.visitInlineQuery(e)),this.handlers.set(re.kind,e=>this.visitWhereClause(e)),this.handlers.set(ye.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ge.kind,e=>this.visitHavingClause(e)),this.handlers.set(Ce.kind,e=>this.visitOrderByClause(e)),this.handlers.set(Oe.kind,e=>this.visitWindowFrameClause(e)),this.handlers.set(ce.kind,e=>this.visitLimitClause(e)),this.handlers.set($e.kind,e=>this.visitOffsetClause(e)),this.handlers.set(He.kind,e=>this.visitFetchClause(e)),this.handlers.set(Re.kind,e=>this.visitForClause(e)),this.handlers.set(Qe.kind,e=>this.visitOrderByItem(e)),this.handlers.set(z.kind,e=>this.visitSelectClause(e)),this.handlers.set(J.kind,e=>this.visitSelectItem(e)),this.handlers.set(ee.kind,e=>this.visitParenExpression(e)),this.handlers.set(b.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ue.kind,e=>this.visitCaseExpression(e)),this.handlers.set(Ne.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(Le.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(Ee.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(H.kind,e=>this.visitFunctionCall(e)),this.handlers.set(Se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(be.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(xe.kind,e=>this.visitTupleExpression(e)),this.handlers.set(fe.kind,e=>this.visitCastExpression(e)),this.handlers.set(W.kind,e=>this.visitValueList(e)),this.handlers.set(ze.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 R?e.qualifiedName.name.value:e.qualifiedName.name.name):e.qualifiedName.name instanceof R?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 Qt=class a{constructor(){this.dependencyGraph=null;this.cteMap=new Map;this.sourceCollector=new rt(!1),this.cteReferenceCollector=new Ri,this.cteCollector=new ne}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=[],i=new Map;for(let s of this.dependencyGraph.nodes)i.set(s.name,new Set(s.dependencies));let r=s=>{if(e.has(s))return;if(t.has(s))throw new Error(`${a.ERROR_MESSAGES.CIRCULAR_REFERENCE}: ${s}`);t.add(s);let o=i.get(s)||new Set;for(let u of o)r(u);t.delete(s),e.add(s),n.push(s)};for(let s of this.dependencyGraph.nodes)e.has(s.name)||r(s.name);return n}buildDependencyGraph(e,t){let n=[],i=[],r=new Map,s=new Map;for(let u of e){let l=a.getCTEName(u);r.set(l,new Set),s.set(l,new Set)}r.set(a.MAIN_QUERY_NAME,new Set),s.set(a.MAIN_QUERY_NAME,new Set);for(let u of e){let l=a.getCTEName(u),c=this.sourceCollector.collect(u.query);for(let p of c){let m=p.table.name;this.cteMap.has(m)&&m!==l&&(r.get(l).add(m),s.get(m).add(l),i.push({from:l,to:m}))}}let o=this.getMainQueryWithoutCTE(t);if(o){let u=this.cteReferenceCollector.collect(o);for(let l of u){let c=l.table.name;this.cteMap.has(c)&&(r.get(a.MAIN_QUERY_NAME).add(c),s.get(c).add(a.MAIN_QUERY_NAME),i.push({from:a.MAIN_QUERY_NAME,to:c}))}}for(let u of e){let l=a.getCTEName(u);n.push({name:l,type:"CTE",cte:u,dependencies:Array.from(r.get(l)||new Set),dependents:Array.from(s.get(l)||new Set)})}return n.push({name:a.MAIN_QUERY_NAME,type:"ROOT",cte:null,dependencies:Array.from(r.get(a.MAIN_QUERY_NAME)||new Set),dependents:Array.from(s.get(a.MAIN_QUERY_NAME)||new Set)}),{nodes:n,edges:i}}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 w({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 Fi=class{static addComment(e,t,n="before"){if(this.isSelectQuery(e)){let i=e;i.headerComments||(i.headerComments=[]),i.headerComments.push(t)}else e.addPositionedComments(n,[t])}static isSelectQuery(e){return"__selectQueryType"in e&&e.__selectQueryType==="SelectQuery"}static editComment(e,t,n,i="before"){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{let r=e.getPositionedComments(i);if(!r||t<0||t>=r.length)throw new Error(`Invalid comment index: ${t}. Component has ${r?.length||0} ${i} positioned comments.`);let s=e.positionedComments?.find(o=>o.position===i);s&&(s.comments[t]=n)}}static deleteComment(e,t,n="before"){if(this.isSelectQuery(e)){let i=e;if(!i.headerComments||t<0||t>=i.headerComments.length)throw new Error(`Invalid comment index: ${t}. Component has ${i.headerComments?.length||0} comments.`);i.headerComments.splice(t,1),i.headerComments.length===0&&(i.headerComments=null)}else{let i=e.getPositionedComments(n);if(!i||t<0||t>=i.length)throw new Error(`Invalid comment index: ${t}. Component has ${i?.length||0} ${n} positioned comments.`);let r=e.positionedComments?.find(s=>s.position===n);r&&(r.comments.splice(t,1),r.comments.length===0&&(e.positionedComments=e.positionedComments?.filter(s=>s.position!==n)||null,e.positionedComments?.length===0&&(e.positionedComments=null)))}}static deleteAllComments(e){if(this.isSelectQuery(e)){let t=e;t.headerComments=null}else e.positionedComments=null}static getComments(e){return this.isSelectQuery(e)?e.headerComments||[]:e.getAllPositionedComments()}static findComponentsWithComment(e,t,n=!1){let i=[],r=n?t:t.toLowerCase(),s=o=>{if(o&&o instanceof g){let u=!1,l=o.getAllPositionedComments();if(l&&l.some(c=>(n?c:c.toLowerCase()).includes(r))&&(u=!0),this.isSelectQuery(o)){let c=o;c.headerComments&&c.headerComments.some(p=>(n?p:p.toLowerCase()).includes(r))&&(u=!0)}u&&i.push(o)}for(let u in o)o[u]&&typeof o[u]=="object"&&(Array.isArray(o[u])?o[u].forEach(s):s(o[u]))};return s(e),i}static replaceInComments(e,t,n,i=!1){let r=0,s=o=>{if(o&&o instanceof g){if(o.comments)for(let u=0;u{if(i&&i instanceof g){let r=i.getAllPositionedComments();if(r&&(t+=r.length),this.isSelectQuery(i)){let s=i;s.headerComments&&(t+=s.headerComments.length)}}for(let r in i)i[r]&&typeof i[r]=="object"&&(Array.isArray(i[r])?i[r].forEach(n):n(i[r]))};return n(e),t}static getAllComments(e){let t=[],n=i=>{if(i&&i instanceof g){let r=i.getAllPositionedComments();if(r&&r.forEach((s,o)=>{t.push({comment:s,component:i,index:o})}),this.isSelectQuery(i)){let s=i;s.headerComments&&s.headerComments.forEach((o,u)=>{t.push({comment:o,component:i,index:u})})}}for(let r in i)i[r]&&typeof i[r]=="object"&&(Array.isArray(i[r])?i[r].forEach(n):n(i[r]))};return n(e),t}};var St=class{constructor(e,t){this.name=e,this.columns=t}},pn=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(w.kind,n=>this.visitSimpleSelectQuery(n)),this.handlers.set(O.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 w||e instanceof O))throw new Error(`Unsupported SQL component type for schema collection. Received: ${e.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let t=new ne;this.commonTables=t.collect(e),this.visitNode(e),this.consolidateTableSchemas()}finally{this.running=!1}}visitNode(e){if(this.visitedNodes.has(e))return;this.visitedNodes.add(e);let t=this.handlers.get(e.getKind());if(t){t(e);return}}reset(){this.tableSchemas=[],this.visitedNodes=new Set,this.commonTables=[],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(i=>n?.add(i))}this.tableSchemas=Array.from(e.entries()).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>new St(t,Array.from(n).sort()))}handleSourceExpression(e,t,n){if(e.datasource instanceof B){let i=e.datasource.getSourceName(),r=this.commonTables.filter(s=>s.getSourceAliasName()===i);if(r.length>0){r[0].query.accept(this);let s=e.getAliasName()??i;this.processCTETableSchema(r[0],s,t,n)}else{let s=e.getAliasName()??i;this.processCollectTableSchema(i,s,t,n)}}else e.datasource instanceof K&&this.visitNode(e.datasource.query)}visitSimpleSelectQuery(e){if(e.fromClause===null)return;let n=new Ae(this.tableColumnResolver,!0,"fullName").collect(e),i;if(this.allowWildcardWithoutResolver){let r=this.getSelectClauseColumns(e);i=n.filter(s=>s.value instanceof E).map(s=>s.value).filter(s=>{let o=s.getNamespace(),u=s.column.name;return r.some(l=>{if(l.value instanceof E){let c=l.value.getNamespace(),p=l.value.column.name;if(c===o&&p===u)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 i=n.filter(r=>r.value instanceof E).map(r=>r.value).map(r=>({table:r.getNamespace(),column:r.column.name}));if(e.fromClause.joins!==null&&e.fromClause.joins.length>0){let r=i.filter(s=>s.table==="").map(s=>s.column);if(r.length>0)if(this.isAnalyzeMode)this.unresolvedColumns.push(...r),this.analysisError=`Column reference(s) without table name found in query: ${r.join(", ")}`;else throw new Error(`Column reference(s) without table name found in query: ${r.join(", ")}`)}if(e.fromClause.source.datasource instanceof B?this.handleSourceExpression(e.fromClause.source,i,!0):e.fromClause.source.datasource instanceof K&&e.fromClause.source.datasource.query.accept(this),e.fromClause?.joins)for(let r of e.fromClause.joins)r.source.datasource instanceof B?this.handleSourceExpression(r.source,i,!1):r.source.datasource instanceof K&&r.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 E){let i=n.value.column.name;t.push({name:i,value:n.value})}return t}processCollectTableSchema(e,t,n,i=!1){if(this.tableColumnResolver===null&&n.filter(u=>u.table===t||i&&u.table==="").filter(u=>u.column==="*").length>0&&!this.allowWildcardWithoutResolver){let u=e?`Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards. Target table: ${e}`:"Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards.";if(this.isAnalyzeMode){this.analysisError=u;let l=n.filter(c=>c.table===t||i&&c.table==="").filter(c=>c.column==="*").map(c=>c.table?`${c.table}.*`:"*");this.unresolvedColumns.push(...l)}else throw new Error(u)}let r=n.filter(o=>o.column!=="*").filter(o=>o.table===t||i&&o.table==="").map(o=>o.column),s=new St(e,r);this.tableSchemas.push(s)}processCTETableSchema(e,t,n,i=!1){let r=e.getSourceAliasName(),s=this.getCTEColumns(e),o=n.filter(c=>c.table===t||i&&c.table==="").map(c=>c.column);if(o.includes("*")){if(this.tableColumnResolver!==null){let c=this.tableColumnResolver(r);if(c.length>0){let p=new St(r,c);this.tableSchemas.push(p);return}}if(s.length>0){let c=new St(r,s);this.tableSchemas.push(c);return}else if(this.allowWildcardWithoutResolver){let c=new St(r,[]);this.tableSchemas.push(c);return}else{let c=`Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards. Target table: ${r}`;if(this.isAnalyzeMode)this.analysisError=c,this.unresolvedColumns.push(t?`${t}.*`:"*");else throw new Error(c);return}}let u=o.filter(c=>c!=="*");if(this.isAnalyzeMode){let c=s;if(this.tableColumnResolver){let p=this.tableColumnResolver(r);p.length>0&&(c=p)}if(c.length>0){let p=u.filter(m=>!c.includes(m));p.length>0&&(this.unresolvedColumns.push(...p),this.analysisError||(this.analysisError=`Undefined column(s) found in CTE "${r}": ${p.join(", ")}`))}else if(!this.allowWildcardWithoutResolver){let p=u;p.length>0&&(this.unresolvedColumns.push(...p),this.analysisError||(this.analysisError=`Undefined column(s) found in CTE "${r}": ${p.join(", ")}`))}}let l=new St(r,u);this.tableSchemas.push(l)}getCTEColumns(e){try{return e.query instanceof w&&e.query.selectClause?this.extractColumnsFromSelectItems(e.query.selectClause.items,e):this.extractColumnsUsingCollector(e.query)}catch{return[]}}extractColumnsFromSelectItems(e,t){let n=[];for(let i of e)if(i.value instanceof E){let r=i.identifier?.name||i.value.column.name;if(i.value.column.name==="*"){let s=this.resolveWildcardInCTE(i.value,t);if(s===null)return[];n.push(...s)}else n.push(r)}else i.identifier&&n.push(i.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 w)||!e.query.fromClause)return null;let t=e.query.fromClause.source;return t.datasource instanceof B?this.resolveTableWildcard(t.datasource.table.name):(t.datasource instanceof K,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 Ae(null,!0,"fullName").collect(e).filter(i=>i.value instanceof E).map(i=>i.value).map(i=>i.column.name).filter((i,r,s)=>s.indexOf(i)===r)}removeDuplicates(e){return e.filter((t,n,i)=>i.indexOf(t)===n)}};var Bi=class{static validate(e,t){let n=typeof e=="string"?P.parse(e):e,i=Array.isArray(t)?u=>{let l=t.find(c=>c.name===u);return l?l.columns:[]}:t,s=new pn(i).collect(n),o=[];for(let u of s){let l=i(u.name);if(l.length===0){o.push(`Table '${u.name}' is not defined.`);continue}let c=u.columns.filter(p=>!l.includes(p));c.length>0&&o.push(`Table '${u.name}' contains undefined columns: ${c.join(", ")}.`)}if(o.length>0)throw new Error(o.join(` +`))}};var Mi=class{constructor(e={}){this.knownCTENames=[];this.options=e,this.formatter=new Ue(e),this.dependencyAnalyzer=new Qt}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)})),i=this.buildTempQueryForAnalysis(n,t),r=this.dependencyAnalyzer.analyzeDependencies(i),s=this.sortCTEsByDependencies(n,r),o=this.detectRecursiveFromOriginalQueries(e),u=s.map(p=>`${p.name} as (${p.query})`),c=`${o?"with recursive":"with"} ${u.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 r=P.parse(e);if(r.withClause&&r.withClause.tables){let s=this.getKnownCTENames();if(r.withClause.tables.map(l=>this.getCTEName(l)).every(l=>s.includes(l))){let l=new w({selectClause:r.selectClause,fromClause:r.fromClause,whereClause:r.whereClause,groupByClause:r.groupByClause,havingClause:r.havingClause,orderByClause:r.orderByClause,windowClause:r.windowClause,limitClause:r.limitClause,offsetClause:r.offsetClause,fetchClause:r.fetchClause,forClause:r.forClause,withClause:void 0});return new Ue({identifierEscape:{start:"",end:""}}).format(l).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"),i=e.match(n);if(!i)return e;let r=i.index+i[0].length,s=1,o=r;for(;o0;){let u=e[o];u==="("?s++:u===")"&&s--,o++}return s===0?e.substring(r,o-1).trim():e}buildTempQueryForAnalysis(e,t){let i=`with ${e.map(r=>`${r.name} as (${r.query})`).join(", ")} ${t}`;try{return P.parse(i)}catch(r){throw new Error(`Failed to parse temporary query for dependency analysis: ${r}`)}}sortCTEsByDependencies(e,t){let n=new Map;return e.forEach(i=>n.set(i.name,i.query)),t.nodes.map(i=>({name:i.name,query:n.get(i.name)||""})).filter(i=>i.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=P.parse(e),n=Object.entries(this.options.schema).map(([i,r])=>({name:i,columns:r}));Bi.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=P.parse(e);return this.formatter.format(t).formattedSql}catch{return e}return e}};var Nr=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 Qt,this.cteCollector=new ne,this.formatter=new Ue(e)}decompose(e){let t=this.cteCollector.collect(e);if(t.length===0)return[];let n=this.findRecursiveCTEs(e,t),i=this.dependencyAnalyzer.analyzeDependencies(e);return this.validateCircularDependencies(n.length>0),this.processCTENodes(e,i.nodes,n)}synchronize(e,t){if(e.length===0)return[];let n=this.flattenNestedWithClauses(e),i={...this.options,addComments:void 0},s=new Mi(i).compose(n,t),o=P.parse(s);return this.decompose(o)}extractCTE(e,t){let n=[],i=this.cteCollector.collect(e);if(i.length===0)throw new Error("Query does not contain any CTEs");if(!i.find(C=>this.getCTEName(C)===t))throw new Error(`CTE not found in query: ${t}`);if(this.findRecursiveCTEs(e,i).includes(t))return n.push("Recursive CTE restoration requires the full query context"),{name:t,executableSql:this.formatter.format(e).formattedSql,dependencies:this.getAllCTENames(i).filter(C=>C!==t),warnings:n};let u=this.dependencyAnalyzer.analyzeDependencies(e);if(this.dependencyAnalyzer.hasCircularDependency())throw new Error("Circular dependency detected in CTEs");let l=u.nodes.find(C=>C.name===t);if(!l||!l.cte)throw new Error(`CTE not found in dependency graph: ${t}`);let c=this.buildExecutableQuery(l,u.nodes),m=this.collectRequiredCTEs(l,u.nodes).map(C=>C.name),h=this.options.addComments?this.addRestorationComments(c,l,n):c;return{name:t,executableSql:h,dependencies:m,warnings:n}}flattenNestedWithClauses(e){let t=[],n=new Map;for(let r of e)try{if(/^\s*with\s+/i.test(r.query)){let o=P.parse(r.query);if(o.withClause&&o.withClause.tables){for(let p of o.withClause.tables){let m=this.getCTEName(p);if(!n.has(m)){let C=new Ue({identifierEscape:{start:"",end:""}}).format(p.query).formattedSql;n.set(m,C)}}let u=new w({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 Ue({identifierEscape:{start:"",end:""}}).format(u).formattedSql;t.push({name:r.name,query:c})}else t.push(r)}else t.push(r)}catch{t.push(r)}let i=[];for(let[r,s]of n)i.push({name:r,query:s});return i.push(...t),i}validateCircularDependencies(e){if(this.dependencyAnalyzer.hasCircularDependency()&&!e)throw new Error(a.ERROR_MESSAGES.CIRCULAR_REFERENCE)}processCTENodes(e,t,n){let i=[];for(let r of t){if(r.type==="ROOT")continue;n.includes(r.name)?i.push(this.createRecursiveCTE(r,e)):i.push(this.createStandardCTE(r,t))}return i}createRecursiveCTE(e,t){let n=this.formatter.format(t).formattedSql,i=e.dependents.filter(s=>s!=="MAIN_QUERY"),r=this.addCommentsToQuery(n,e.name,e.dependencies,e.dependents,!0);return{name:e.name,query:r,dependencies:[...e.dependencies],dependents:i,isRecursive:!0}}createStandardCTE(e,t){let n=this.buildExecutableQuery(e,t),i=this.addCommentsToQuery(n,e.name,e.dependencies,e.dependents,!1),r=e.dependents.filter(s=>s!=="MAIN_QUERY");return{name:e.name,query:i,dependencies:[...e.dependencies],dependents:r,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 i=this.buildWithClause(n),r=this.formatter.format(e.cte.query).formattedSql;return`${i} ${r}`}collectRequiredCTEs(e,t){let n=new Set,i=[],r=new Map;for(let o of t)r.set(o.name,o);let s=o=>{if(n.has(o))return;n.add(o);let u=r.get(o);if(u){for(let l of u.dependencies)s(l);o!==e.name&&u.type!=="ROOT"&&i.push(u)}};for(let o of e.dependencies)s(o);return i}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 i=n.name,r=this.formatter.format(n.cte.query).formattedSql;return`${i} as (${r})`}).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,i,r){if(this.options.addComments!==!0)return e;try{let s=P.parse(e);return this.generateComments(t,n,i,r).forEach(l=>{Fi.addComment(s,l)}),new Ue({...this.options,exportComment:!0}).format(s).formattedSql}catch(s){return console.warn(`${a.ERROR_MESSAGES.PARSING_FAILED}: ${s}`),this.addTextCommentsToQuery(e,t,n,i,r)}}generateComments(e,t,n,i){let{AUTO_GENERATED:r,ORIGINAL_CTE:s,DEPENDENCIES:o,DEPENDENTS:u,RECURSIVE_TYPE:l,NONE:c}=a.COMMENT_TEXTS,p=[];p.push(r),p.push(`${s} ${e}`),i&&p.push(l);let m=t.length>0?t.join(", "):c;p.push(`${o} ${m}`);let h=n.filter(f=>f!=="MAIN_QUERY"),C=h.length>0?h.join(", "):c;return p.push(`${u} ${C}`),p}addTextCommentsToQuery(e,t,n,i,r){return`${this.generateComments(t,n,i,r).map(u=>`-- ${u}`).join(` `)} ${e}`}addRestorationComments(e,t,n){let i=[];return i.push("-- CTE Restoration: "+t.name),t.dependencies.length>0?i.push("-- Dependencies: "+t.dependencies.join(", ")):i.push("-- Dependencies: none"),n.length>0&&i.push("-- Warnings: "+n.join(", ")),i.push("-- Generated by CTEQueryDecomposer.extractCTE()"),i.push(""),i.join(` -`)+e}getAllCTENames(e){return e.map(t=>this.getCTEName(t))}getCTEName(e){return e.aliasExpression.table.name}};var mn=class{constructor(){this.columnReferences=[];this.visitedNodes=new Set;this.handlers=new Map,this.handlers.set(he.kind,e=>this.visitWithClause(e)),this.handlers.set(oe.kind,e=>this.visitCommonTable(e)),this.handlers.set(z.kind,e=>this.visitSelectClause(e)),this.handlers.set(_.kind,e=>this.visitFromClause(e)),this.handlers.set(re.kind,e=>this.visitWhereClause(e)),this.handlers.set(ge.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ye.kind,e=>this.visitHavingClause(e)),this.handlers.set(Ce.kind,e=>this.visitOrderByClause(e)),this.handlers.set(ct.kind,e=>this.visitWindowsClause(e)),this.handlers.set(ce.kind,e=>this.visitLimitClause(e)),this.handlers.set($e.kind,e=>this.visitOffsetClause(e)),this.handlers.set(He.kind,e=>this.visitFetchClause(e)),this.handlers.set(Re.kind,e=>this.visitForClause(e)),this.handlers.set(ve.kind,e=>this.visitJoinClause(e)),this.handlers.set(we.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Te.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set($.kind,e=>this.visitSourceExpression(e)),this.handlers.set(U.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(E.kind,e=>this.visitColumnReference(e)),this.handlers.set(b.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(H.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ue.kind,e=>this.visitCaseExpression(e)),this.handlers.set(fe.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ee.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(ee.kind,e=>this.visitParenExpression(e)),this.handlers.set(de.kind,e=>this.visitInlineQuery(e)),this.handlers.set(Se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(be.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(W.kind,e=>this.visitValueList(e)),this.handlers.set(Ke.kind,e=>this.visitWindowFrameExpression(e))}collect(e){return this.columnReferences=[],this.visitedNodes.clear(),e instanceof w?this.collectFromSimpleQuery(e):e instanceof O?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 U&&(e.datasource.query instanceof w?this.collectFromSimpleQuery(e.datasource.query):e.datasource.query instanceof O&&this.collectFromSimpleQuery(e.datasource.query.toSimpleQuery()))}collectFromValueComponent(e){if(e instanceof E)this.columnReferences.push(e);else if(e instanceof b)this.collectFromValueComponent(e.left),this.collectFromValueComponent(e.right);else if(e instanceof te)this.collectFromValueComponent(e.expression);else if(e instanceof H&&e.argument)this.collectFromValueComponent(e.argument);else if(e instanceof ue){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 ee?this.collectFromValueComponent(e.expression):e instanceof de&&(e.selectQuery instanceof w?this.collectFromSimpleQuery(e.selectQuery):e.selectQuery instanceof O&&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 ot={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`},Vi=class{constructor(){this.dependencyAnalyzer=new Qt,this.columnReferenceCollector=new mn,this.tableSourceCollector=new rt,this.keywordParser=new Pe(wn)}renameCTE(e,t,n){this.validateInputs(e,t,n);let i=t.trim(),r=n.trim();if(e instanceof w)this.renameInSimpleQuery(e,i,r);else if(e instanceof O)this.renameInBinaryQuery(e,i,r);else throw new Error(ot.unsupportedQuery)}validateInputs(e,t,n){if(!e)throw new Error(ot.nullQuery);if(!t||typeof t!="string"||t.trim()==="")throw new Error(ot.invalidOldName);if(!n||typeof n!="string"||n.trim()==="")throw new Error(ot.invalidNewName);if(t.trim()===n.trim())throw new Error(ot.sameNames)}renameInSimpleQuery(e,t,n){let i=e.getCTENames();if(!i.includes(t))throw new Error(ot.cteNotExists(t));if(i.includes(n))throw new Error(ot.cteAlreadyExists(n));this.renameCTEDefinition(e,t,n),this.updateAllReferences(e,t,n)}renameInBinaryQuery(e,t,n){let i=e.toSimpleQuery(),r=[];if(i.withClause&&i.withClause.tables&&(r=i.withClause.tables.map(s=>s.aliasExpression.table.name)),!r.includes(t))throw new Error(ot.cteNotExists(t));if(r.includes(n))throw new Error(ot.cteAlreadyExists(n));this.renameCTEDefinition(i,t,n),i.withClause&&(e.withClause=i.withClause,e.left instanceof w&&(e.left.withClause=i.withClause)),this.renameInSelectQuery(e.left,t,n),this.renameInSelectQuery(e.right,t,n)}renameInSelectQuery(e,t,n){e instanceof w?this.updateAllReferences(e,t,n):e instanceof O&&(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(ot.cteNotFound(t));let i=e.withClause.tables.find(r=>r.aliasExpression.table.name===t);if(!i)throw new Error(ot.cteNotFound(t));i.aliasExpression.table.name=n}updateAllReferences(e,t,n){let i=this.columnReferenceCollector.collect(e);for(let s of i)if(s.namespaces&&s.namespaces.length>0){for(let o of s.namespaces)if(o.name===t){o.name=n;break}}let r=this.tableSourceCollector.collect(e);for(let s of r)s.getSourceName()===t&&(s.qualifiedName.name instanceof E||("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 i of e.withClause.tables)this.updateTableSourcesInQuery(i.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 i of e.fromClause.joins)i.source.datasource&&this.updateTableSource(i.source.datasource,t,n)}updateTableSource(e,t,n){if(!e||typeof e!="object")return;let i=e;if(typeof i.getSourceName=="function")try{if(i.getSourceName()===t&&i.qualifiedName&&typeof i.qualifiedName=="object"){let s=i.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(r){console.warn("Warning: Failed to update table source:",r)}}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 i=Be.findLexemeAtLineColumn(e,t);if(!i)throw new Error(`No CTE name found at line ${t.line}, column ${t.column}`);let r=i.value,s=P.parse(e);if(!this.isCTENameInQuery(s,r))throw new Error(`'${r}' is not a CTE name in this query`);if(!(i.type&2112))throw new Error(`Token at position is not a CTE name: '${i.value}'`);let o=this.checkNameConflicts(s,n,r);if(o.length>0)throw new Error(o.join(", "));return this.renameCTE(s,r,n),new Ue().format(s).formattedSql}checkNameConflicts(e,t,n){let i=[];return n===t||(i.push(...this.checkKeywordConflicts(t)),this.isCTENameInQuery(e,t)&&i.push(`CTE name '${t}' already exists`)),i}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 w&&e.withClause?e.withClause.tables.some(n=>n.aliasExpression&&n.aliasExpression.table&&n.aliasExpression.table.name===t):e instanceof O?this.isCTENameInQuery(e.left,t)||this.isCTENameInQuery(e.right,t):!1}};var Wt={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`},Di=class{constructor(){this.keywordParser=new Pe(wn)}renameAlias(e,t,n,i={}){try{this.validateInputs(e,t,n);let r=Be.findLexemeAtLineColumn(e,t);if(!r)throw new Error(Wt.noLexemeAtPosition);this.validateLexemeIsAlias(r);let s=P.parse(e),o=this.detectAliasScope(e,s,r,i.scopeType),l=this.collectAliasReferences(o,r.value),u=this.checkNameConflicts(o,n,r.value);if(u.length>0)return{success:!1,originalSql:e,changes:[],conflicts:u,scope:o};let c=this.prepareChanges(l,n);if(i.dryRun)return{success:!0,originalSql:e,changes:c,conflicts:u,scope:o};let p=this.performLexemeBasedRename(e,r.value,n,o);return{success:!0,originalSql:e,newSql:p,changes:c,scope:o}}catch(r){return{success:!1,originalSql:e,changes:[],conflicts:[r instanceof Error?r.message:String(r)]}}}validateInputs(e,t,n){if(!e||typeof e!="string"||e.trim()==="")throw new Error(Wt.invalidSql);if(!t||typeof t.line!="number"||typeof t.column!="number"||t.line<1||t.column<1)throw new Error(Wt.invalidPosition);if(!n||typeof n!="string"||n.trim()==="")throw new Error(Wt.invalidNewName)}validateLexemeIsAlias(e){if(!(e.type&64))throw new Error(Wt.notAnAlias)}detectAliasScope(e,t,n,i){if(!n.position)return{type:"main",query:t,startPosition:0,endPosition:e.length};let r=n.position.startPosition;return i&&i!=="auto"?this.createScopeForType(i,e,t,r):this.autoDetectScope(e,t,r)}createScopeForType(e,t,n,i){switch(e){case"cte":return this.detectCTEScope(t,n,i);case"subquery":return this.detectSubqueryScope(t,n,i);case"main":default:return{type:"main",query:n,startPosition:0,endPosition:t.length}}}autoDetectScope(e,t,n){let i=this.detectCTEScope(e,t,n);if(i.type==="cte")return i;let r=this.detectSubqueryScope(e,t,n);return r.type==="subquery"?r:{type:"main",query:t,startPosition:0,endPosition:e.length}}detectCTEScope(e,t,n){try{let i=Nt.analyzeCursorPosition(e,n);if(i.isInCTE&&i.cteRegion){let r=this.findCTEQueryByName(t,i.cteRegion.name);return{type:"cte",name:i.cteRegion.name,query:r||t,startPosition:i.cteRegion.startPosition,endPosition:i.cteRegion.endPosition}}}catch(i){console.warn("CTE scope detection failed:",i)}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 w&&e.withClause?.tables){for(let n of e.withClause.tables)if(n.aliasExpression.table.name===t)return n.query}else if(e instanceof O){let n=this.findCTEQueryByName(e.left,t);if(n)return n;let i=this.findCTEQueryByName(e.right,t);if(i)return i}return null}collectAliasReferences(e,t){let n=[];try{let i=this.collectTableAliasReferences(e,t);n.push(...i);let r=this.collectColumnAliasReferences(e,t);n.push(...r)}catch(i){console.warn(`Failed to collect alias references for '${t}':`,i)}return n}collectTableAliasReferences(e,t){let n=[];try{let r=new rt(!0).collect(e.query);for(let s of r)if(s.getSourceName()===t){let l=this.createLexemeFromTableSource(s,t);l&&n.push({lexeme:l,scope:e,referenceType:"definition",context:"table"})}}catch(i){console.warn(`Failed to collect table alias references for '${t}':`,i)}return n}collectColumnAliasReferences(e,t){let n=[];try{let r=new mn().collect(e.query);for(let s of r)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(i){console.warn(`Failed to collect column alias references for '${t}':`,i)}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 i=[];if(t.toLowerCase()===n.toLowerCase())return i.push(Wt.sameNames),i;try{let r=this.checkTableAliasConflicts(e,t);i.push(...r);let s=this.checkKeywordConflicts(t);i.push(...s)}catch(r){console.warn(`Error during conflict detection for '${t}':`,r),i.push(`Unable to verify conflicts for name '${t}'`)}return i}checkTableAliasConflicts(e,t){let n=[];try{let r=new rt(!0).collect(e.query);for(let s of r){let o=s.getSourceName();if(o&&o.toLowerCase()===t.toLowerCase()){n.push(Wt.nameConflict(t));continue}let l=this.extractTableName(s);l&&l.toLowerCase()===t.toLowerCase()&&n.push(`'${t}' conflicts with table name in this scope`)}}catch(i){console.warn(`Failed to check table alias conflicts for '${t}':`,i)}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:Be.charOffsetToLineColumn("",n.lexeme.position?.startPosition||0)||{line:1,column:1},context:n.context,referenceType:n.referenceType}))}performLexemeBasedRename(e,t,n,i){try{let s=Be.getAllLexemesWithPosition(e).filter(l=>l.value===t&&l.position&&l.position.startPosition>=i.startPosition&&l.position.endPosition<=i.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(r){throw console.error("Failed to perform lexeme-based rename:",r),new Error(`Unable to rename alias using lexeme approach: ${r instanceof Error?r.message:String(r)}`)}}};var $i=class{renameIdentifiers(e,t){if(t.size===0)return e;let n=e;for(let[i,r]of t)n=this.replaceIdentifierSafely(n,i,r);return n}renameIdentifier(e,t,n){return this.replaceIdentifierSafely(e,t,n)}renameIdentifierInScope(e,t,n,i){if(!i)return this.replaceIdentifierSafely(e,t,n);let r=e.slice(0,i.start),s=e.slice(i.start,i.end),o=e.slice(i.end),l=this.replaceIdentifierSafely(s,t,n);return r+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 i=this.getIdentifierAtPosition(e,n);if(!i)return{canRename:!1,reason:"No identifier found at position"};let r=this.determineIdentifierType(e,n,i),s=this.calculateScopeRange(e,n,r);return{canRename:!0,currentName:i,type:r,scopeRange:s}}renameAtPosition(e,t,n){let i=this.checkRenameability(e,t);if(!i.canRename||!i.currentName)throw new Error(i.reason||"Cannot rename at this position");return this.renameIdentifierInScope(e,i.currentName,n,i.scopeRange)}positionToCharIndex(e,t){let n=e.split(` -`),i=0;for(let r=0;r=e.length)return null;let n=t;for(;n>0&&this.isIdentifierChar(e.charCodeAt(n-1));)n--;let i=t;for(;i0&&this.isIdentifierChar(e.charCodeAt(C-1));)C--;let f=t;for(;f=0?e[c]:null,h=p=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 i=0;i=65&&r<=90?r+32:r,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)),i=t===null||!this.isIdentifierChar(t.charCodeAt(0));return n&&i}countWordOccurrences(e,t){let n=0,i=0,r=e.length,s=t.length;for(;i<=r-s;){if(this.matchesIdentifierAt(e,i,t)){let o=i-1,l=i+s,u=o>=0?e[o]:null,c=ln.aliasExpression&&n.aliasExpression.table&&n.aliasExpression.table.name===t):e instanceof O?this.isCTEName(e.left,t)||this.isCTEName(e.right,t):!1}attemptFormattingPreservationRename(e,t,n,i,r){let s=this.performStandardRename(e,t,n,i,r);if(!s.success)return{...s,formattingPreserved:!1,formattingMethod:"smart-renamer-only"};let o=new Map([[i,n]]);try{let l=this.identifierRenamer.renameIdentifiers(e,o);if(this.validateRenameResult(e,l,i,n))return{success:!0,originalSql:e,newSql:l,renamerType:r,originalName:i,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,i,r){try{let s;if(r==="cte")s=this.cteRenamer.renameCTEAtPosition(e,t,n);else if(r==="alias"){let o=this.aliasRenamer.renameAlias(e,t,n);if(!o.success)return{success:!1,originalSql:e,renamerType:"alias",originalName:i,newName:n,error:o.conflicts?.join(", ")||"Alias rename failed"};s=o.newSql}else return{success:!1,originalSql:e,renamerType:"unknown",originalName:i,newName:n,error:`Cannot determine if '${i}' is a CTE name or table alias`};return{success:!0,originalSql:e,newSql:s,renamerType:r,originalName:i,newName:n}}catch(s){return{success:!1,originalSql:e,renamerType:r,originalName:i,newName:n,error:`${r.toUpperCase()} rename failed: ${s instanceof Error?s.message:String(s)}`}}}validateRenameResult(e,t,n,i){if(e===t||!t.includes(i))return!1;let r=this.countWordOccurrences(e,n);return this.countWordOccurrences(t,n)0)for(let r of i.inlineComments)r.trim().length>0&&(n+=` -- ${r}`);i.followingWhitespace&&(n+=i.followingWhitespace)}return n}analyzeFormatting(e){let t=0,n=0,i=0,r=0,s=0,o=0;for(let u of e){if(u.followingWhitespace){t+=u.followingWhitespace.length;let c=u.followingWhitespace.split(` -`);for(let p=1;p0||C>0)&&(s++,o+=h+C*4,i+=h,r+=C)}}u.inlineComments&&(n+=u.inlineComments.length)}let l="none";return i>0&&r>0?l="mixed":i>0?l="spaces":r>0&&(l="tabs"),{totalWhitespace:t,totalComments:n,indentationStyle:l,averageIndentSize:s>0?o/s:0}}validateFormattingLexemes(e){let t=[];for(let n=0;n=i.position.endPosition&&t.push(`Lexeme ${n} has invalid position range`)}return{isValid:t.length===0,issues:t}}};var Wi=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 i=[e],r=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,r,p,n,t);i.push(m),r=p}return{ctes:i,lastCteAlias:r,columnMappings:this.columnMappings}}generateUniqueJsonColumnName(e,t,n){this.jsonColumnCounter++;let i=`${e.toLowerCase()}_json_${this.jsonColumnCounter}`;return this.columnMappings.push({entityId:t,entityName:e,generatedColumnName:i,depth:n}),i}collectAndSortObjectEntities(e,t){let n=[],i=r=>{let s=t.get(r);if(!s)throw new Error(`Entity ${r} not found for depth calculation.`);if(s.isRoot)return 0;if(!s.parentId)return 1;let o=s.parentId,l=0,u=new Set;for(u.add(r);o;){if(u.has(o))throw new Error(`Circular dependency detected: ${o} already visited in path for ${r}`);u.add(o);let c=t.get(o);if(!c)throw new Error(`Parent entity ${o} not found during depth calculation for ${r}`);let p=!1;if(c.isRoot)p=!0;else{let m=e.nestedEntities.find(h=>h.id===o);if(m)m.relationshipType==="object"&&(p=!0);else throw new Error(`Parent entity ${o} (ancestor of ${r}) 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(r=>{if(r.relationshipType==="object"){let s=t.get(r.id);s&&!s.isRoot&&n.push({entity:s,depth:i(r.id)})}}),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let i=n.depth;t.has(i)||t.set(i,[]),t.get(i).push(n)}),t}buildDepthCte(e,t,n,i,r){let s=[new q(new E(null,new I(a.WILDCARD_COLUMN)))];for(let{entity:l}of e){let u=this.buildEntityJsonColumn(l,i,r);s.push(u)}let o=new w({selectClause:new z(s),fromClause:new _(new $(new B(null,new I(t)),null),null)});return new oe(o,new se(n,null),null)}buildEntityJsonColumn(e,t,n){let{jsonObjectArgs:i,nullChecks:r}=this.prepareEntityColumns(e);this.addChildObjectRelationships(e,i,t,n);let s=this.createJsonObject(i),o=this.buildNullCondition(r),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 q(l,c)}calculateApproximateDepth(e,t){if(e.isRoot)return 0;if(!e.parentId)return 1;let n=1,i=e.parentId;for(;i&&i!==t.rootEntity.id;){let r=t.nestedEntities.find(s=>s.id===i);if(!r)break;n++,i=r.parentId}return n}prepareEntityColumns(e){let t=[],n=[];return Object.entries(e.columns).forEach(([i,r])=>{t.push(new Z(i,void 0,!0)),t.push(new E(null,new I(r))),n.push(new b(new E(null,new I(r)),"is",new Z(null)))}),{jsonObjectArgs:t,nullChecks:n}}addChildObjectRelationships(e,t,n,i){n.nestedEntities.filter(s=>s.parentId===e.id&&s.relationshipType==="object").forEach(s=>{let o=i.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 E(null,new I(l)))}})}createJsonObject(e){let t="jsonb_build_object";return new H(null,new R(t),new W(e),null)}buildNullCondition(e){return e.reduce((t,n)=>t?new b(t,"and",n):n)}createCaseExpression(e,t){return new ue(null,new Le([new Ae(e,new Z(null))],t))}};var Ui=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,i,r){let s=[...e],o=t,l=this.collectAndSortArrayEntities(i,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:h,newCteAlias:C}=this.buildDepthCte(m,o,s,p,i,r);s.push(h),o=C}return{updatedCtes:s,lastCteAlias:o}}collectAndSortArrayEntities(e,t){let n=[],i=r=>{let s=t.get(r);return!s||s.isRoot?0:s.parentId?1+i(s.parentId):1};return e.nestedEntities.forEach(r=>{if(r.relationshipType==="array"){let s=t.get(r.id),o=t.get(r.parentId);if(!s||!o)throw new Error(`Configuration error: Array entity '${r.id}' or its parent '${r.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 '${r.name}'.`);let u=l[0];n.push({entity:s,parentEntity:o,parentIdColumnSqlName:u,depth:i(r.id)})}}),n.sort((r,s)=>s.depth-r.depth),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let i=n.depth;t.has(i)||t.set(i,[]),t.get(i).push(n)}),t}buildDepthCte(e,t,n,i,r,s){let o=new Set;e.forEach(v=>{Object.values(v.entity.columns).forEach(M=>o.add(M));let g=M=>{r.nestedEntities.filter(L=>L.parentId===M).forEach(L=>{Object.values(L.columns).forEach(J=>{let k=typeof J=="string"?J:J.column;o.add(k)}),g(L.id)})};g(v.entity.id)});let l=n.find(v=>v.aliasExpression.table.name===t)?.query;if(!l)throw new Error(`CTE not found: ${t}`);let u=new Ze(null,n).collect(l),c=[],p=[],m=new Set;e.forEach(v=>{Object.values(v.entity.columns).forEach(g=>m.add(g))});let h=this.collectArrayEntityColumnsByDepth(r,i),C=new Set;s&&e.forEach(v=>{r.nestedEntities.filter(g=>g.parentId===v.entity.id&&g.relationshipType==="object").forEach(g=>{let M=s.find(L=>L.entityId===g.id);M&&C.add(M.generatedColumnName)})}),this.processSelectVariablesForGroupBy(u,o,h,i,p,c,C);for(let v of e){let g=this.buildAggregationDetailsForArrayEntity(v.entity,r.nestedEntities,new Map,s);p.push(new q(g.jsonAgg,v.entity.propertyName))}let f=`${a.CTE_ARRAY_PREFIX}${i}`,N=new w({selectClause:new z(p),fromClause:new _(new $(new B(null,new I(t)),null),null),groupByClause:c.length>0?new ge(c):null});return{cte:new oe(N,new se(f,null),null),newCteAlias:f}}buildAggregationDetailsForArrayEntity(e,t,n,i){let r=a.JSON_FUNCTIONS.BUILD_OBJECT,s=[];Object.entries(e.columns).forEach(([m,h])=>{s.push(new Z(m,void 0,!0)),s.push(new E(null,new I(h)))}),t.filter(m=>m.parentId===e.id).forEach(m=>{let h=m.originalPropertyName||m.propertyName;if(s.push(new Z(h,void 0,!0)),m.relationshipType==="object"){if(!i)throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mappings not provided +`)+e}getAllCTENames(e){return e.map(t=>this.getCTEName(t))}getCTEName(e){return e.aliasExpression.table.name}};var mn=class{constructor(){this.columnReferences=[];this.visitedNodes=new Set;this.handlers=new Map,this.handlers.set(he.kind,e=>this.visitWithClause(e)),this.handlers.set(oe.kind,e=>this.visitCommonTable(e)),this.handlers.set(z.kind,e=>this.visitSelectClause(e)),this.handlers.set(_.kind,e=>this.visitFromClause(e)),this.handlers.set(re.kind,e=>this.visitWhereClause(e)),this.handlers.set(ye.kind,e=>this.visitGroupByClause(e)),this.handlers.set(ge.kind,e=>this.visitHavingClause(e)),this.handlers.set(Ce.kind,e=>this.visitOrderByClause(e)),this.handlers.set(ct.kind,e=>this.visitWindowsClause(e)),this.handlers.set(ce.kind,e=>this.visitLimitClause(e)),this.handlers.set($e.kind,e=>this.visitOffsetClause(e)),this.handlers.set(He.kind,e=>this.visitFetchClause(e)),this.handlers.set(Re.kind,e=>this.visitForClause(e)),this.handlers.set(ve.kind,e=>this.visitJoinClause(e)),this.handlers.set(we.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(Te.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set($.kind,e=>this.visitSourceExpression(e)),this.handlers.set(K.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(E.kind,e=>this.visitColumnReference(e)),this.handlers.set(b.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(te.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(H.kind,e=>this.visitFunctionCall(e)),this.handlers.set(ue.kind,e=>this.visitCaseExpression(e)),this.handlers.set(fe.kind,e=>this.visitCastExpression(e)),this.handlers.set(Ee.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(ee.kind,e=>this.visitParenExpression(e)),this.handlers.set(de.kind,e=>this.visitInlineQuery(e)),this.handlers.set(Se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(be.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(W.kind,e=>this.visitValueList(e)),this.handlers.set(Ke.kind,e=>this.visitWindowFrameExpression(e))}collect(e){return this.columnReferences=[],this.visitedNodes.clear(),e instanceof w?this.collectFromSimpleQuery(e):e instanceof O?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 K&&(e.datasource.query instanceof w?this.collectFromSimpleQuery(e.datasource.query):e.datasource.query instanceof O&&this.collectFromSimpleQuery(e.datasource.query.toSimpleQuery()))}collectFromValueComponent(e){if(e instanceof E)this.columnReferences.push(e);else if(e instanceof b)this.collectFromValueComponent(e.left),this.collectFromValueComponent(e.right);else if(e instanceof te)this.collectFromValueComponent(e.expression);else if(e instanceof H&&e.argument)this.collectFromValueComponent(e.argument);else if(e instanceof ue){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 ee?this.collectFromValueComponent(e.expression):e instanceof de&&(e.selectQuery instanceof w?this.collectFromSimpleQuery(e.selectQuery):e.selectQuery instanceof O&&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 ot={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`},Vi=class{constructor(){this.dependencyAnalyzer=new Qt,this.columnReferenceCollector=new mn,this.tableSourceCollector=new rt,this.keywordParser=new Pe(wn)}renameCTE(e,t,n){this.validateInputs(e,t,n);let i=t.trim(),r=n.trim();if(e instanceof w)this.renameInSimpleQuery(e,i,r);else if(e instanceof O)this.renameInBinaryQuery(e,i,r);else throw new Error(ot.unsupportedQuery)}validateInputs(e,t,n){if(!e)throw new Error(ot.nullQuery);if(!t||typeof t!="string"||t.trim()==="")throw new Error(ot.invalidOldName);if(!n||typeof n!="string"||n.trim()==="")throw new Error(ot.invalidNewName);if(t.trim()===n.trim())throw new Error(ot.sameNames)}renameInSimpleQuery(e,t,n){let i=e.getCTENames();if(!i.includes(t))throw new Error(ot.cteNotExists(t));if(i.includes(n))throw new Error(ot.cteAlreadyExists(n));this.renameCTEDefinition(e,t,n),this.updateAllReferences(e,t,n)}renameInBinaryQuery(e,t,n){let i=e.toSimpleQuery(),r=[];if(i.withClause&&i.withClause.tables&&(r=i.withClause.tables.map(s=>s.aliasExpression.table.name)),!r.includes(t))throw new Error(ot.cteNotExists(t));if(r.includes(n))throw new Error(ot.cteAlreadyExists(n));this.renameCTEDefinition(i,t,n),i.withClause&&(e.withClause=i.withClause,e.left instanceof w&&(e.left.withClause=i.withClause)),this.renameInSelectQuery(e.left,t,n),this.renameInSelectQuery(e.right,t,n)}renameInSelectQuery(e,t,n){e instanceof w?this.updateAllReferences(e,t,n):e instanceof O&&(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(ot.cteNotFound(t));let i=e.withClause.tables.find(r=>r.aliasExpression.table.name===t);if(!i)throw new Error(ot.cteNotFound(t));i.aliasExpression.table.name=n}updateAllReferences(e,t,n){let i=this.columnReferenceCollector.collect(e);for(let s of i)if(s.namespaces&&s.namespaces.length>0){for(let o of s.namespaces)if(o.name===t){o.name=n;break}}let r=this.tableSourceCollector.collect(e);for(let s of r)s.getSourceName()===t&&(s.qualifiedName.name instanceof E||("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 i of e.withClause.tables)this.updateTableSourcesInQuery(i.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 i of e.fromClause.joins)i.source.datasource&&this.updateTableSource(i.source.datasource,t,n)}updateTableSource(e,t,n){if(!e||typeof e!="object")return;let i=e;if(typeof i.getSourceName=="function")try{if(i.getSourceName()===t&&i.qualifiedName&&typeof i.qualifiedName=="object"){let s=i.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(r){console.warn("Warning: Failed to update table source:",r)}}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 i=Be.findLexemeAtLineColumn(e,t);if(!i)throw new Error(`No CTE name found at line ${t.line}, column ${t.column}`);let r=i.value,s=P.parse(e);if(!this.isCTENameInQuery(s,r))throw new Error(`'${r}' is not a CTE name in this query`);if(!(i.type&2112))throw new Error(`Token at position is not a CTE name: '${i.value}'`);let o=this.checkNameConflicts(s,n,r);if(o.length>0)throw new Error(o.join(", "));return this.renameCTE(s,r,n),new Ue().format(s).formattedSql}checkNameConflicts(e,t,n){let i=[];return n===t||(i.push(...this.checkKeywordConflicts(t)),this.isCTENameInQuery(e,t)&&i.push(`CTE name '${t}' already exists`)),i}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 w&&e.withClause?e.withClause.tables.some(n=>n.aliasExpression&&n.aliasExpression.table&&n.aliasExpression.table.name===t):e instanceof O?this.isCTENameInQuery(e.left,t)||this.isCTENameInQuery(e.right,t):!1}};var Wt={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`},Di=class{constructor(){this.keywordParser=new Pe(wn)}renameAlias(e,t,n,i={}){try{this.validateInputs(e,t,n);let r=Be.findLexemeAtLineColumn(e,t);if(!r)throw new Error(Wt.noLexemeAtPosition);this.validateLexemeIsAlias(r);let s=P.parse(e),o=this.detectAliasScope(e,s,r,i.scopeType),u=this.collectAliasReferences(o,r.value),l=this.checkNameConflicts(o,n,r.value);if(l.length>0)return{success:!1,originalSql:e,changes:[],conflicts:l,scope:o};let c=this.prepareChanges(u,n);if(i.dryRun)return{success:!0,originalSql:e,changes:c,conflicts:l,scope:o};let p=this.performLexemeBasedRename(e,r.value,n,o);return{success:!0,originalSql:e,newSql:p,changes:c,scope:o}}catch(r){return{success:!1,originalSql:e,changes:[],conflicts:[r instanceof Error?r.message:String(r)]}}}validateInputs(e,t,n){if(!e||typeof e!="string"||e.trim()==="")throw new Error(Wt.invalidSql);if(!t||typeof t.line!="number"||typeof t.column!="number"||t.line<1||t.column<1)throw new Error(Wt.invalidPosition);if(!n||typeof n!="string"||n.trim()==="")throw new Error(Wt.invalidNewName)}validateLexemeIsAlias(e){if(!(e.type&64))throw new Error(Wt.notAnAlias)}detectAliasScope(e,t,n,i){if(!n.position)return{type:"main",query:t,startPosition:0,endPosition:e.length};let r=n.position.startPosition;return i&&i!=="auto"?this.createScopeForType(i,e,t,r):this.autoDetectScope(e,t,r)}createScopeForType(e,t,n,i){switch(e){case"cte":return this.detectCTEScope(t,n,i);case"subquery":return this.detectSubqueryScope(t,n,i);case"main":default:return{type:"main",query:n,startPosition:0,endPosition:t.length}}}autoDetectScope(e,t,n){let i=this.detectCTEScope(e,t,n);if(i.type==="cte")return i;let r=this.detectSubqueryScope(e,t,n);return r.type==="subquery"?r:{type:"main",query:t,startPosition:0,endPosition:e.length}}detectCTEScope(e,t,n){try{let i=At.analyzeCursorPosition(e,n);if(i.isInCTE&&i.cteRegion){let r=this.findCTEQueryByName(t,i.cteRegion.name);return{type:"cte",name:i.cteRegion.name,query:r||t,startPosition:i.cteRegion.startPosition,endPosition:i.cteRegion.endPosition}}}catch(i){console.warn("CTE scope detection failed:",i)}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 w&&e.withClause?.tables){for(let n of e.withClause.tables)if(n.aliasExpression.table.name===t)return n.query}else if(e instanceof O){let n=this.findCTEQueryByName(e.left,t);if(n)return n;let i=this.findCTEQueryByName(e.right,t);if(i)return i}return null}collectAliasReferences(e,t){let n=[];try{let i=this.collectTableAliasReferences(e,t);n.push(...i);let r=this.collectColumnAliasReferences(e,t);n.push(...r)}catch(i){console.warn(`Failed to collect alias references for '${t}':`,i)}return n}collectTableAliasReferences(e,t){let n=[];try{let r=new rt(!0).collect(e.query);for(let s of r)if(s.getSourceName()===t){let u=this.createLexemeFromTableSource(s,t);u&&n.push({lexeme:u,scope:e,referenceType:"definition",context:"table"})}}catch(i){console.warn(`Failed to collect table alias references for '${t}':`,i)}return n}collectColumnAliasReferences(e,t){let n=[];try{let r=new mn().collect(e.query);for(let s of r)if(s.namespaces&&s.namespaces.length>0){for(let o of s.namespaces)if(o.name===t){let u=this.createLexemeFromNamespace(o,t);u&&n.push({lexeme:u,scope:e,referenceType:"usage",context:"column"})}}}catch(i){console.warn(`Failed to collect column alias references for '${t}':`,i)}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 i=[];if(t.toLowerCase()===n.toLowerCase())return i.push(Wt.sameNames),i;try{let r=this.checkTableAliasConflicts(e,t);i.push(...r);let s=this.checkKeywordConflicts(t);i.push(...s)}catch(r){console.warn(`Error during conflict detection for '${t}':`,r),i.push(`Unable to verify conflicts for name '${t}'`)}return i}checkTableAliasConflicts(e,t){let n=[];try{let r=new rt(!0).collect(e.query);for(let s of r){let o=s.getSourceName();if(o&&o.toLowerCase()===t.toLowerCase()){n.push(Wt.nameConflict(t));continue}let u=this.extractTableName(s);u&&u.toLowerCase()===t.toLowerCase()&&n.push(`'${t}' conflicts with table name in this scope`)}}catch(i){console.warn(`Failed to check table alias conflicts for '${t}':`,i)}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:Be.charOffsetToLineColumn("",n.lexeme.position?.startPosition||0)||{line:1,column:1},context:n.context,referenceType:n.referenceType}))}performLexemeBasedRename(e,t,n,i){try{let s=Be.getAllLexemesWithPosition(e).filter(u=>u.value===t&&u.position&&u.position.startPosition>=i.startPosition&&u.position.endPosition<=i.endPosition&&u.type&64);if(s.length===0)return e;s.sort((u,l)=>l.position.startPosition-u.position.startPosition);let o=e;for(let u of s){let l=u.position;o=o.substring(0,l.startPosition)+n+o.substring(l.endPosition)}return o}catch(r){throw console.error("Failed to perform lexeme-based rename:",r),new Error(`Unable to rename alias using lexeme approach: ${r instanceof Error?r.message:String(r)}`)}}};var $i=class{renameIdentifiers(e,t){if(t.size===0)return e;let n=e;for(let[i,r]of t)n=this.replaceIdentifierSafely(n,i,r);return n}renameIdentifier(e,t,n){return this.replaceIdentifierSafely(e,t,n)}renameIdentifierInScope(e,t,n,i){if(!i)return this.replaceIdentifierSafely(e,t,n);let r=e.slice(0,i.start),s=e.slice(i.start,i.end),o=e.slice(i.end),u=this.replaceIdentifierSafely(s,t,n);return r+u+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 i=this.getIdentifierAtPosition(e,n);if(!i)return{canRename:!1,reason:"No identifier found at position"};let r=this.determineIdentifierType(e,n,i),s=this.calculateScopeRange(e,n,r);return{canRename:!0,currentName:i,type:r,scopeRange:s}}renameAtPosition(e,t,n){let i=this.checkRenameability(e,t);if(!i.canRename||!i.currentName)throw new Error(i.reason||"Cannot rename at this position");return this.renameIdentifierInScope(e,i.currentName,n,i.scopeRange)}positionToCharIndex(e,t){let n=e.split(` +`),i=0;for(let r=0;r=e.length)return null;let n=t;for(;n>0&&this.isIdentifierChar(e.charCodeAt(n-1));)n--;let i=t;for(;i0&&this.isIdentifierChar(e.charCodeAt(C-1));)C--;let f=t;for(;f=0?e[c]:null,h=p=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 i=0;i=65&&r<=90?r+32:r,u=s>=65&&s<=90?s+32:s;if(o!==u)return!1}return!0}hasValidWordBoundaries(e,t){let n=e===null||!this.isIdentifierChar(e.charCodeAt(0)),i=t===null||!this.isIdentifierChar(t.charCodeAt(0));return n&&i}countWordOccurrences(e,t){let n=0,i=0,r=e.length,s=t.length;for(;i<=r-s;){if(this.matchesIdentifierAt(e,i,t)){let o=i-1,u=i+s,l=o>=0?e[o]:null,c=un.aliasExpression&&n.aliasExpression.table&&n.aliasExpression.table.name===t):e instanceof O?this.isCTEName(e.left,t)||this.isCTEName(e.right,t):!1}attemptFormattingPreservationRename(e,t,n,i,r){let s=this.performStandardRename(e,t,n,i,r);if(!s.success)return{...s,formattingPreserved:!1,formattingMethod:"smart-renamer-only"};let o=new Map([[i,n]]);try{let u=this.identifierRenamer.renameIdentifiers(e,o);if(this.validateRenameResult(e,u,i,n))return{success:!0,originalSql:e,newSql:u,renamerType:r,originalName:i,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,i,r){try{let s;if(r==="cte")s=this.cteRenamer.renameCTEAtPosition(e,t,n);else if(r==="alias"){let o=this.aliasRenamer.renameAlias(e,t,n);if(!o.success)return{success:!1,originalSql:e,renamerType:"alias",originalName:i,newName:n,error:o.conflicts?.join(", ")||"Alias rename failed"};s=o.newSql}else return{success:!1,originalSql:e,renamerType:"unknown",originalName:i,newName:n,error:`Cannot determine if '${i}' is a CTE name or table alias`};return{success:!0,originalSql:e,newSql:s,renamerType:r,originalName:i,newName:n}}catch(s){return{success:!1,originalSql:e,renamerType:r,originalName:i,newName:n,error:`${r.toUpperCase()} rename failed: ${s instanceof Error?s.message:String(s)}`}}}validateRenameResult(e,t,n,i){if(e===t||!t.includes(i))return!1;let r=this.countWordOccurrences(e,n);return this.countWordOccurrences(t,n)0)for(let r of i.inlineComments)r.trim().length>0&&(n+=` -- ${r}`);i.followingWhitespace&&(n+=i.followingWhitespace)}return n}analyzeFormatting(e){let t=0,n=0,i=0,r=0,s=0,o=0;for(let l of e){if(l.followingWhitespace){t+=l.followingWhitespace.length;let c=l.followingWhitespace.split(` +`);for(let p=1;p0||C>0)&&(s++,o+=h+C*4,i+=h,r+=C)}}l.inlineComments&&(n+=l.inlineComments.length)}let u="none";return i>0&&r>0?u="mixed":i>0?u="spaces":r>0&&(u="tabs"),{totalWhitespace:t,totalComments:n,indentationStyle:u,averageIndentSize:s>0?o/s:0}}validateFormattingLexemes(e){let t=[];for(let n=0;n=i.position.endPosition&&t.push(`Lexeme ${n} has invalid position range`)}return{isValid:t.length===0,issues:t}}};var Wi=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 i=[e],r=e.aliasExpression.table.name,s=this.collectAndSortObjectEntities(n,t),o=this.groupEntitiesByDepth(s),u=Array.from(o.keys()).sort((l,c)=>c-l);for(let l of u){let c=o.get(l),p=`${a.CTE_OBJECT_PREFIX}${l}`,m=this.buildDepthCte(c,r,p,n,t);i.push(m),r=p}return{ctes:i,lastCteAlias:r,columnMappings:this.columnMappings}}generateUniqueJsonColumnName(e,t,n){this.jsonColumnCounter++;let i=`${e.toLowerCase()}_json_${this.jsonColumnCounter}`;return this.columnMappings.push({entityId:t,entityName:e,generatedColumnName:i,depth:n}),i}collectAndSortObjectEntities(e,t){let n=[],i=r=>{let s=t.get(r);if(!s)throw new Error(`Entity ${r} not found for depth calculation.`);if(s.isRoot)return 0;if(!s.parentId)return 1;let o=s.parentId,u=0,l=new Set;for(l.add(r);o;){if(l.has(o))throw new Error(`Circular dependency detected: ${o} already visited in path for ${r}`);l.add(o);let c=t.get(o);if(!c)throw new Error(`Parent entity ${o} not found during depth calculation for ${r}`);let p=!1;if(c.isRoot)p=!0;else{let m=e.nestedEntities.find(h=>h.id===o);if(m)m.relationshipType==="object"&&(p=!0);else throw new Error(`Parent entity ${o} (ancestor of ${r}) has no definition in mapping.nestedEntities and is not root.`)}if(p&&u++,c.isRoot)break;o=c.parentId}return u};return e.nestedEntities.forEach(r=>{if(r.relationshipType==="object"){let s=t.get(r.id);s&&!s.isRoot&&n.push({entity:s,depth:i(r.id)})}}),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let i=n.depth;t.has(i)||t.set(i,[]),t.get(i).push(n)}),t}buildDepthCte(e,t,n,i,r){let s=[new J(new E(null,new I(a.WILDCARD_COLUMN)))];for(let{entity:u}of e){let l=this.buildEntityJsonColumn(u,i,r);s.push(l)}let o=new w({selectClause:new z(s),fromClause:new _(new $(new B(null,new I(t)),null),null)});return new oe(o,new se(n,null),null)}buildEntityJsonColumn(e,t,n){let{jsonObjectArgs:i,nullChecks:r}=this.prepareEntityColumns(e);this.addChildObjectRelationships(e,i,t,n);let s=this.createJsonObject(i),o=this.buildNullCondition(r),u=this.createCaseExpression(o,s),l=this.calculateApproximateDepth(e,t),c=this.generateUniqueJsonColumnName(e.name,e.id,l);return this.entityToJsonColumnMap.set(e.id,c),new J(u,c)}calculateApproximateDepth(e,t){if(e.isRoot)return 0;if(!e.parentId)return 1;let n=1,i=e.parentId;for(;i&&i!==t.rootEntity.id;){let r=t.nestedEntities.find(s=>s.id===i);if(!r)break;n++,i=r.parentId}return n}prepareEntityColumns(e){let t=[],n=[];return Object.entries(e.columns).forEach(([i,r])=>{t.push(new Z(i,void 0,!0)),t.push(new E(null,new I(r))),n.push(new b(new E(null,new I(r)),"is",new Z(null)))}),{jsonObjectArgs:t,nullChecks:n}}addChildObjectRelationships(e,t,n,i){n.nestedEntities.filter(s=>s.parentId===e.id&&s.relationshipType==="object").forEach(s=>{let o=i.get(s.id);if(o){t.push(new Z(s.propertyName,void 0,!0));let u=this.entityToJsonColumnMap.get(o.id);if(!u)throw new Error(`JSON column name not found for child entity: ${o.id}`);t.push(new E(null,new I(u)))}})}createJsonObject(e){let t="jsonb_build_object";return new H(null,new R(t),new W(e),null)}buildNullCondition(e){return e.reduce((t,n)=>t?new b(t,"and",n):n)}createCaseExpression(e,t){return new ue(null,new Le([new Ne(e,new Z(null))],t))}};var Ui=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,i,r){let s=[...e],o=t,u=this.collectAndSortArrayEntities(i,n);if(u.length===0)return{updatedCtes:s,lastCteAlias:o};let l=this.groupEntitiesByDepth(u),c=Array.from(l.keys()).sort((p,m)=>m-p);for(let p of c){let m=l.get(p),{cte:h,newCteAlias:C}=this.buildDepthCte(m,o,s,p,i,r);s.push(h),o=C}return{updatedCtes:s,lastCteAlias:o}}collectAndSortArrayEntities(e,t){let n=[],i=r=>{let s=t.get(r);return!s||s.isRoot?0:s.parentId?1+i(s.parentId):1};return e.nestedEntities.forEach(r=>{if(r.relationshipType==="array"){let s=t.get(r.id),o=t.get(r.parentId);if(!s||!o)throw new Error(`Configuration error: Array entity '${r.id}' or its parent '${r.parentId}' not found.`);let u=Object.values(o.columns);if(u.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 '${r.name}'.`);let l=u[0];n.push({entity:s,parentEntity:o,parentIdColumnSqlName:l,depth:i(r.id)})}}),n.sort((r,s)=>s.depth-r.depth),n}groupEntitiesByDepth(e){let t=new Map;return e.forEach(n=>{let i=n.depth;t.has(i)||t.set(i,[]),t.get(i).push(n)}),t}buildDepthCte(e,t,n,i,r,s){let o=new Set;e.forEach(v=>{Object.values(v.entity.columns).forEach(M=>o.add(M));let y=M=>{r.nestedEntities.filter(L=>L.parentId===M).forEach(L=>{Object.values(L.columns).forEach(U=>{let k=typeof U=="string"?U:U.column;o.add(k)}),y(L.id)})};y(v.entity.id)});let u=n.find(v=>v.aliasExpression.table.name===t)?.query;if(!u)throw new Error(`CTE not found: ${t}`);let l=new Ze(null,n).collect(u),c=[],p=[],m=new Set;e.forEach(v=>{Object.values(v.entity.columns).forEach(y=>m.add(y))});let h=this.collectArrayEntityColumnsByDepth(r,i),C=new Set;s&&e.forEach(v=>{r.nestedEntities.filter(y=>y.parentId===v.entity.id&&y.relationshipType==="object").forEach(y=>{let M=s.find(L=>L.entityId===y.id);M&&C.add(M.generatedColumnName)})}),this.processSelectVariablesForGroupBy(l,o,h,i,p,c,C);for(let v of e){let y=this.buildAggregationDetailsForArrayEntity(v.entity,r.nestedEntities,new Map,s);p.push(new J(y.jsonAgg,v.entity.propertyName))}let f=`${a.CTE_ARRAY_PREFIX}${i}`,A=new w({selectClause:new z(p),fromClause:new _(new $(new B(null,new I(t)),null),null),groupByClause:c.length>0?new ye(c):null});return{cte:new oe(A,new se(f,null),null),newCteAlias:f}}buildAggregationDetailsForArrayEntity(e,t,n,i){let r=a.JSON_FUNCTIONS.BUILD_OBJECT,s=[];Object.entries(e.columns).forEach(([m,h])=>{s.push(new Z(m,void 0,!0)),s.push(new E(null,new I(h)))}),t.filter(m=>m.parentId===e.id).forEach(m=>{let h=m.originalPropertyName||m.propertyName;if(s.push(new Z(h,void 0,!0)),m.relationshipType==="object"){if(!i)throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mappings not provided \u{1F50D} Details: - Entity ID: ${m.id} @@ -54,7 +54,7 @@ ${e}`}addRestorationComments(e,t,n){let i=[];return i.push("-- CTE Restoration: \u{1F527} Check: 1. Ensure PostgresJsonQueryBuilder.buildJsonWithCteStrategy() passes columnMappings 2. Verify PostgresObjectEntityCteBuilder.buildObjectEntityCtes() returns columnMappings - 3. Check that Model-driven mapping conversion generates unique entity IDs`);let C=i.find(f=>f.entityId===m.id);if(!C){let f=i.map(N=>`${N.entityId} \u2192 ${N.generatedColumnName}`).join(", ");throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mapping not found + 3. Check that Model-driven mapping conversion generates unique entity IDs`);let C=i.find(f=>f.entityId===m.id);if(!C){let f=i.map(A=>`${A.entityId} \u2192 ${A.generatedColumnName}`).join(", ");throw new Error(`\u274C PostgresArrayEntityCteBuilder Error: Column mapping not found \u{1F50D} Details: - Looking for Entity ID: ${m.id} @@ -72,21 +72,21 @@ ${e}`}addRestorationComments(e,t,n){let i=[];return i.push("-- CTE Restoration: \u{1F527} Check: 1. Model-driven mapping conversion generates consistent entity IDs 2. PostgresObjectEntityCteBuilder processes all entities correctly - 3. Entity hierarchy and parentId relationships are correct`)}s.push(new E(null,new I(C.generatedColumnName)))}else m.relationshipType==="array"&&s.push(new E(null,new I(m.propertyName)))});let l=new H(null,new R(r),new W(s),null),u=a.JSON_FUNCTIONS.AGGREGATE,c=Object.values(e.columns)[0];return{jsonAgg:new H(null,new R(u),new W([l]),null)}}collectArrayEntityColumnsByDepth(e,t){let n=new Map,i=Math.max(t+3,5);for(let r=t;r<=i;r++)n.set(r,new Set);return e.nestedEntities.filter(r=>r.relationshipType==="array").forEach(r=>{let s=this.calculateEntityDepth(r,e);n.has(s)||n.set(s,new Set),this.addEntityColumnsToDepthSet(r,s,n),this.collectDescendantColumns(r.id,s,e,n)}),n}calculateEntityDepth(e,t){let n=0,i=e;for(;i.parentId&&i.parentId!==t.rootEntity.id;)n++,i=t.nestedEntities.find(r=>r.id===i.parentId)||i;return n}addEntityColumnsToDepthSet(e,t,n){Object.values(e.columns).forEach(i=>{let r=typeof i=="string"?i:i.column;n.get(t).add(r)})}collectDescendantColumns(e,t,n,i){n.nestedEntities.filter(r=>r.parentId===e).forEach(r=>{this.addEntityColumnsToDepthSet(r,t,i),this.collectDescendantColumns(r.id,t,n,i)})}processSelectVariablesForGroupBy(e,t,n,i,r,s,o){e.forEach(l=>{if(!t.has(l.name)){if(o&&o.has(l.name))return;this.shouldIncludeColumnInGroupBy(l.name,n,i)&&(r.push(new q(new E(null,new I(l.name)),l.name)),l.name.endsWith("_json")||s.push(new E(null,new I(l.name))))}})}shouldIncludeColumnInGroupBy(e,t,n){let i=e.endsWith("_json"),r=!0;for(let[s,o]of t.entries())if(s>=n&&o.has(e)){r=!1;break}return i&&e.startsWith("entity_")&&(r=this.shouldIncludeJsonColumn(e,n)),r}shouldIncludeJsonColumn(e,t){let n=e.match(/entity_(\d+)_json/);return n&&t>0?parseInt(n[1])<=2:!0}};var Ki=class{constructor(){this.selectValueCollector=new Ze(null),this.objectEntityCteBuilder=new Wi,this.arrayEntityCteBuilder=new Ui}validateMapping(e,t){let i=new Ze().collect(e),r=new Set(i.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(!r.has(p))throw new Error(`Validation Error: Column "${p}" for JSON key "${u}" in root entity "${t.rootEntity.name}" not found in the query's select list.`)}let s=new Set([t.rootEntity.id]),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(!r.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(h=>h.parentId===u);if(c.filter(h=>h.relationshipType==="array").length>1){let h=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(C=>C.id===u)?.name;throw new Error(`Validation Error: Parent entity "${h}" (ID: ${u}) has multiple direct array children. This is not supported.`)}let m=new Set;for(let h of c){if(m.has(h.propertyName)){let C=u===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(f=>f.id===u)?.name;throw new Error(`Validation Error: Parent entity "${C}" (ID: ${u}) has duplicate property name "${h.propertyName}" for its children.`)}m.add(h.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 i=e instanceof w?e:Ie.buildSimpleQuery(e);return this.buildJsonWithCteStrategy(i,t)}buildJson(e,t){return console.warn("buildJson is deprecated. Use buildJsonQuery instead."),this.buildJsonQuery(e,t)}buildJsonWithCteStrategy(e,t){this.validateMapping(e,t);let{initialCte:n,initialCteAlias:i}=this.createInitialCte(e),r=[n],s=i,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);r=l.ctes,s=l.lastCteAlias;let u=l.columnMappings,c=this.arrayEntityCteBuilder.buildArrayEntityCtes(r,s,o,t,u);return r=c.updatedCtes,s=c.lastCteAlias,this.buildFinalSelectQuery(r,s,o,t,u)}createInitialCte(e){let t="origin_query";return{initialCte:new oe(e,new se(t,null),null),initialCteAlias:t}}buildFinalSelectQuery(e,t,n,i,r){let s=[...e],o=`cte_root_${i.rootName.toLowerCase().replace(/[^a-z0-9_]/g,"_")}`,l=n.get(i.rootEntity.id);if(!l)throw new Error(`Root entity ${i.rootEntity.id} not found`);if(i.resultFormat==="array"||!i.resultFormat){let u=this.buildEntityJsonObject(l,null,i.nestedEntities,n,r),c=new q(u,i.rootName),p=new oe(new w({selectClause:new z([c]),fromClause:new _(new $(new B(null,new I(t)),null),null)}),new se(o,null),null);s.push(p);let m="jsonb_agg",h=new H(null,new R(m),new W([new E(null,new I(i.rootName))]),null);return new w({withClause:new he(!1,s),selectClause:new z([new q(h,`${i.rootName}_array`)]),fromClause:new _(new $(new B(null,new I(o)),null),null)})}else{let u=this.buildEntityJsonObject(l,null,i.nestedEntities,n,r),c=new q(u,i.rootName),p=new oe(new w({selectClause:new z([c]),fromClause:new _(new $(new B(null,new I(t)),null),null)}),new se(o,null),null);return s.push(p),new w({withClause:new he(!1,s),selectClause:new z([new q(new E(null,new I(i.rootName)),i.rootName)]),fromClause:new _(new $(new B(null,new I(o)),null),null),limitClause:new ce(new Z(1))})}}buildEntityJsonObject(e,t,n,i,r){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 E(null,new I(p)))}),n.filter(u=>u.parentId===e.id).forEach(u=>{let c=i.get(u.id);if(c)if(o.push(new Z(u.propertyName,void 0,!0)),u.relationshipType==="object"){let p=r.find(m=>m.entityId===c.id);if(!p)throw new Error(`Column mapping not found for entity: ${c.id}`);o.push(new E(null,new I(p.generatedColumnName)))}else u.relationshipType==="array"&&o.push(new E(null,new I(u.propertyName)))}),new H(null,new R(s),new W(o),null)}};var Rt=class{static extractParameterNames(e){return kt.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),i={},r={};for(let[s,o]of Object.entries(t))n.includes(s)?i[s]=o:r[s]=o;return{hardcodedParams:i,dynamicFilters:r}}};var dn=class{constructor(e,t,n){this.name=e;this.type=t;this.tableName=n}},Ar=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 i=this.collectParameters(e);return t.push(...i),this.removeDuplicates(t)}collectColumns(e){let t=[];try{let i=new Ne(this.tableColumnResolver,!1,"fullName",{upstream:this.options.upstream}).collect(e);for(let r of i){let s,o;if(r.value&&typeof r.value.getNamespace=="function"){let u=r.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=r.name;this.options.qualified&&(o||s)&&(l=`${o||s}.${r.name}`),t.push(new dn(l,"column",s))}}catch(n){console.warn("Failed to collect columns with SelectableColumnCollector, using fallback:",n);try{let r=new pn(this.tableColumnResolver,!0).collect(e);for(let s of r)for(let o of s.columns){let l=o;this.options.qualified&&(l=`${s.name}.${o}`),t.push(new dn(l,"column",s.name))}}catch(i){console.warn("Failed to collect columns with both approaches:",n,i)}}return t}inferTableNameFromQuery(e){if(e instanceof w&&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 w&&n.fromClause){if(n.fromClause.source?.datasource){let r=n.fromClause.source,s=this.extractRealTableName(r,t);if(s)return s}let i=n.fromClause;if(i.joinClauses&&Array.isArray(i.joinClauses)){for(let r of i.joinClauses)if(r.source?.datasource){let s=this.extractRealTableName(r.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 i=e.alias||e.aliasExpression?.table?.name,r=n.table?.name;if(i===t&&r||!i&&r===t)return r}catch{}}collectParameters(e){let t=[];try{let n=Rt.extractParameterNames(e);for(let i of n)t.push(new dn(i,"parameter"))}catch(n){console.warn("Failed to collect parameters:",n)}return t}removeDuplicates(e){let t=new Set,n=[];for(let i of e){let r=`${i.type}:${i.name}:${i.tableName||"none"}`;t.has(r)||(t.add(r),n.push(i))}return n.sort((i,r)=>{if(i.type!==r.type)return i.type==="column"?-1:1;if(i.type==="column"){let s=i.tableName||"",o=r.tableName||"";if(s!==o)return s.localeCompare(o)}return i.name.localeCompare(r.name)})}};var ji=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=P.parse(e));let n=new an(this.tableColumnResolver,this.options),i=new Ne(this.tableColumnResolver,!1,"fullName",{upstream:!0}),r=v=>this.options.ignoreCaseAndUnderscore?v.toLowerCase().replace(/_/g,""):v,s=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"],o=Object.values(t);if(o.length>0&&o.every(v=>v===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[v,g]of Object.entries(t))g!==void 0&&(this.isQualifiedColumnName(v)?c.push([v,g]):p.push([v,g]));for(let[v,g]of c)this.processStateParameter(v,g,e,n,i,r,s,C,h,N,V,f);let m=new Set;for(let[v,g]of c){let M=this.parseQualifiedColumnName(v);M&&m.add(`${M.table.toLowerCase()}.${M.column.toLowerCase()}`)}for(let[v,g]of p)this.processUnqualifiedParameter(v,g,e,n,i,r,s,C,h,N,V,f,m);function h(v,g,M,L,J){for(let k=0;kL(j.name)===L(Q));if(!at)throw new Error(`Column '${Q}' not found in query for AND condition`);let Ve=at.value;if("="in S&&S["="]!==void 0){let j=`${g}_and_${k}_eq`,D=new A(j,S["="]);v.appendWhere(new b(Ve,"=",D))}if("min"in S&&S.min!==void 0){let j=`${g}_and_${k}_min`,D=new A(j,S.min);v.appendWhere(new b(Ve,">=",D))}if("max"in S&&S.max!==void 0){let j=`${g}_and_${k}_max`,D=new A(j,S.max);v.appendWhere(new b(Ve,"<=",D))}if("like"in S&&S.like!==void 0){let j=`${g}_and_${k}_like`,D=new A(j,S.like);v.appendWhere(new b(Ve,"like",D))}if("ilike"in S&&S.ilike!==void 0){let j=`${g}_and_${k}_ilike`,D=new A(j,S.ilike);v.appendWhere(new b(Ve,"ilike",D))}if("in"in S&&S.in!==void 0){let D=S.in.map((Y,X)=>new A(`${g}_and_${k}_in_${X}`,Y));v.appendWhere(new b(Ve,"in",new ee(new W(D))))}if("any"in S&&S.any!==void 0){let j=`${g}_and_${k}_any`,D=new A(j,S.any);v.appendWhere(new b(Ve,"=",new H(null,"any",D,null)))}if("<"in S&&S["<"]!==void 0){let j=`${g}_and_${k}_lt`,D=new A(j,S["<"]);v.appendWhere(new b(Ve,"<",D))}if(">"in S&&S[">"]!==void 0){let j=`${g}_and_${k}_gt`,D=new A(j,S[">"]);v.appendWhere(new b(Ve,">",D))}if("!="in S&&S["!="]!==void 0){let j=`${g}_and_${k}_neq`,D=new A(j,S["!="]);v.appendWhere(new b(Ve,"!=",D))}if("<>"in S&&S["<>"]!==void 0){let j=`${g}_and_${k}_ne`,D=new A(j,S["<>"]);v.appendWhere(new b(Ve,"<>",D))}if("<="in S&&S["<="]!==void 0){let j=`${g}_and_${k}_le`,D=new A(j,S["<="]);v.appendWhere(new b(Ve,"<=",D))}if(">="in S&&S[">="]!==void 0){let j=`${g}_and_${k}_ge`,D=new A(j,S[">="]);v.appendWhere(new b(Ve,">=",D))}}}function C(v,g,M,L,J){let k=[];for(let S=0;SL(Y.name)===L(at));if(!Ve)throw new Error(`Column '${at}' not found in query for OR condition`);let j=Ve.value,D=[];if("="in Q&&Q["="]!==void 0){let Y=`${g}_or_${S}_eq`,X=new A(Y,Q["="]);D.push(new b(j,"=",X))}if("min"in Q&&Q.min!==void 0){let Y=`${g}_or_${S}_min`,X=new A(Y,Q.min);D.push(new b(j,">=",X))}if("max"in Q&&Q.max!==void 0){let Y=`${g}_or_${S}_max`,X=new A(Y,Q.max);D.push(new b(j,"<=",X))}if("like"in Q&&Q.like!==void 0){let Y=`${g}_or_${S}_like`,X=new A(Y,Q.like);D.push(new b(j,"like",X))}if("ilike"in Q&&Q.ilike!==void 0){let Y=`${g}_or_${S}_ilike`,X=new A(Y,Q.ilike);D.push(new b(j,"ilike",X))}if("in"in Q&&Q.in!==void 0){let X=Q.in.map(($r,Wr)=>new A(`${g}_or_${S}_in_${Wr}`,$r));D.push(new b(j,"in",new ee(new W(X))))}if("any"in Q&&Q.any!==void 0){let Y=`${g}_or_${S}_any`,X=new A(Y,Q.any);D.push(new b(j,"=",new H(null,"any",X,null)))}if("<"in Q&&Q["<"]!==void 0){let Y=`${g}_or_${S}_lt`,X=new A(Y,Q["<"]);D.push(new b(j,"<",X))}if(">"in Q&&Q[">"]!==void 0){let Y=`${g}_or_${S}_gt`,X=new A(Y,Q[">"]);D.push(new b(j,">",X))}if("!="in Q&&Q["!="]!==void 0){let Y=`${g}_or_${S}_neq`,X=new A(Y,Q["!="]);D.push(new b(j,"!=",X))}if("<>"in Q&&Q["<>"]!==void 0){let Y=`${g}_or_${S}_ne`,X=new A(Y,Q["<>"]);D.push(new b(j,"<>",X))}if("<="in Q&&Q["<="]!==void 0){let Y=`${g}_or_${S}_le`,X=new A(Y,Q["<="]);D.push(new b(j,"<=",X))}if(">="in Q&&Q[">="]!==void 0){let Y=`${g}_or_${S}_ge`,X=new A(Y,Q[">="]);D.push(new b(j,">=",X))}if(D.length>0){let Y=D[0];for(let X=1;X1?k.push(new ee(Y)):k.push(Y)}}if(k.length>0){let S=k[0];for(let Q=1;Q{if(!g.includes(L))throw new Error(`Unsupported operator '${L}' for state key '${M}'`)})}function N(v,g,M,L){let J=new A(M,L);v.appendWhere(new b(g,"=",J))}function V(v,g,M,L){let J=[];if("="in L){let k=new A(M,L["="]);J.push(new b(g,"=",k))}if("min"in L){let k=new A(M+"_min",L.min);J.push(new b(g,">=",k))}if("max"in L){let k=new A(M+"_max",L.max);J.push(new b(g,"<=",k))}if("like"in L){let k=new A(M+"_like",L.like);J.push(new b(g,"like",k))}if("ilike"in L){let k=new A(M+"_ilike",L.ilike);J.push(new b(g,"ilike",k))}if("in"in L){let S=L.in.map((Q,at)=>new A(`${M}_in_${at}`,Q));J.push(new b(g,"in",new ee(new W(S))))}if("any"in L){let k=new A(M+"_any",L.any);J.push(new b(g,"=",new H(null,"any",k,null)))}if("<"in L){let k=new A(M+"_lt",L["<"]);J.push(new b(g,"<",k))}if(">"in L){let k=new A(M+"_gt",L[">"]);J.push(new b(g,">",k))}if("!="in L){let k=new A(M+"_neq",L["!="]);J.push(new b(g,"!=",k))}if("<>"in L){let k=new A(M+"_ne",L["<>"]);J.push(new b(g,"<>",k))}if("<="in L){let k=new A(M+"_le",L["<="]);J.push(new b(g,"<=",k))}if(">="in L){let k=new A(M+"_ge",L[">="]);J.push(new b(g,">=",k))}if(J.length===1)v.appendWhere(J[0]);else if(J.length>1){let k=J[0];for(let S=1;S0){let C=this.findTargetQueryForLogicalCondition(i,n,e,h),f=this.getAllAvailableColumns(C,r);l(C,e,h,s,f);return}}if(this.isAndCondition(t)){let h=t.and;if(h&&h.length>0){let C=this.findTargetQueryForLogicalCondition(i,n,e,h),f=this.getAllAvailableColumns(C,r);u(C,e,h,s,f);return}}if(this.isExplicitColumnMapping(t)){let h=t.column;if(h){let C=i.find(n,h);if(C.length===0)throw new Error(`Explicit column '${h}' not found in query`);for(let f of C){let V=this.getAllAvailableColumns(f,r).find(v=>s(v.name)===s(h));if(!V)throw new Error(`Explicit column '${h}' not found in query`);this.isValidatableObject(t)&&m(t,o,e),p(f,V.value,e,t)}return}}this.processRegularColumnCondition(e,t,n,i,r,s,o,c,p,m)}processUnqualifiedParameter(e,t,n,i,r,s,o,l,u,c,p,m,h){if(this.isOrCondition(t)){let f=t.or;if(f&&f.length>0){let N=this.findTargetQueryForLogicalCondition(i,n,e,f),V=this.getAllAvailableColumns(N,r);l(N,e,f,s,V);return}}if(this.isAndCondition(t)){let f=t.and;if(f&&f.length>0){let N=this.findTargetQueryForLogicalCondition(i,n,e,f),V=this.getAllAvailableColumns(N,r);u(N,e,f,s,V);return}}if(this.isExplicitColumnMapping(t)){let f=t.column;if(f){let N=i.find(n,f);if(N.length===0)throw new Error(`Explicit column '${f}' not found in query`);for(let V of N){let g=this.getAllAvailableColumns(V,r).find(M=>s(M.name)===s(f));if(!g)throw new Error(`Explicit column '${f}' not found in query`);this.isValidatableObject(t)&&m(t,o,e),p(V,g.value,e,t)}return}}let C=i.find(n,e);if(C.length===0){if(this.options.ignoreNonExistentColumns)return;throw new Error(`Column '${e}' not found in query`)}for(let f of C){let N=this.getAllAvailableColumns(f,r),V=this.buildTableMapping(f),v=N.filter(g=>s(g.name)===s(e));for(let g of v){let M=!1;if(g.value&&typeof g.value.getNamespace=="function"){let k=g.value.getNamespace();if(k){let S=V.aliasToRealTable.get(k.toLowerCase());if(S){let Q=`${S.toLowerCase()}.${e.toLowerCase()}`;h.has(Q)&&(M=!0)}}}if(M)continue;let L=g.value;this.isValidatableObject(t)&&m(t,o,e);let J=L;if(this.hasColumnMapping(t)){let k=t.column;if(k){let S=N.find(Q=>s(Q.name)===s(k));S&&(J=S.value)}}this.isSimpleValue(t)?c(f,J,e,t):p(f,J,e,t)}}}processRegularColumnCondition(e,t,n,i,r,s,o,l,u,c){let p=e,m;if(this.isQualifiedColumnName(e)){let C=this.parseQualifiedColumnName(e);C&&(p=C.column,m=C.table)}let h=i.find(n,p);if(h.length===0){if(this.options.ignoreNonExistentColumns)return;throw new Error(`Column '${p}' not found in query`)}for(let C of h){let f=this.getAllAvailableColumns(C,r),N;if(m){let M=this.buildTableMapping(C);if(N=f.find(L=>{if(!(s(L.name)===s(p)))return!1;if(L.value&&typeof L.value.getNamespace=="function"){let k=L.value.getNamespace();if(k){let S=s(k),Q=s(m),at=M.aliasToRealTable.get(S);if(at&&s(at)===Q)return!0}}return!1}),!N){if(this.options.ignoreNonExistentColumns)continue;let L=this.buildTableMapping(C),J=Array.from(L.realTableToAlias.keys()).some(S=>s(S)===s(m)),k=Array.from(L.aliasToRealTable.keys()).some(S=>s(S)===s(m));throw!J&&!k?new Error(`Column '${e}' (qualified as ${e}) not found in query`):k&&!J?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(N=f.find(M=>s(M.name)===s(p)),!N)throw new Error(`Column '${p}' not found in query`);let V=N.value;this.isValidatableObject(t)&&c(t,o,e);let v=V;if(this.hasColumnMapping(t)){let M=t.column;if(M){let L=f.find(J=>s(J.name)===s(M));L&&(v=L.value)}}let g=this.sanitizeParameterName(e);this.isSimpleValue(t)?l(C,v,g,t):u(C,v,g,t)}}findTargetQueryForLogicalCondition(e,t,n,i){let r=i.map(o=>o.column||n).filter((o,l,u)=>u.indexOf(o)===l);for(let o of r){let l=e.find(t,o);if(l.length>0)return l[0]}let s=i===i.or?"OR":"AND";throw new Error(`None of the ${s} condition columns [${r.join(", ")}] found in query`)}getAllAvailableColumns(e,t){let n=t.collect(e),i=this.collectCTEColumns(e);return[...n,...i]}collectCTEColumns(e){let t=[];if(e.withClause)for(let n of e.withClause.tables)try{let i=this.collectColumnsFromSelectQuery(n.query);t.push(...i)}catch(i){console.warn(`Failed to collect columns from CTE '${n.getSourceAliasName()}':`,i)}return t}collectColumnsFromSelectQuery(e){return e instanceof w?new Ne(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(e):e instanceof O?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 i of e.fromClause.joins)this.processSourceForMapping(i.source,t,n);if(e.withClause)for(let i of e.withClause.tables){let r=i.getSourceAliasName();r&&(t.set(r.toLowerCase(),r),n.set(r.toLowerCase(),r))}}catch(i){console.warn("Failed to build table mapping:",i)}return{aliasToRealTable:t,realTableToAlias:n}}processSourceForMapping(e,t,n){try{if(e.datasource instanceof B){let i=e.datasource.getSourceName(),r=e.aliasExpression?.table?.name||i;i&&r&&(t.set(r.toLowerCase(),i),n.set(i.toLowerCase(),r),r===i&&t.set(i.toLowerCase(),i))}}catch(i){console.warn("Failed to process source for mapping:",i)}}};var qi=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=P.parse(e)),!(e instanceof w))throw new Error("Complex queries are not supported for ORDER BY removal");return new w({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=P.parse(e)),!(e instanceof w))throw new Error("Complex queries are not supported for sorting");let i=new Ne(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(e);for(let l of Object.keys(t))if(!i.find(c=>c.name===l))throw new Error(`Column or alias '${l}' not found in current query`);let r=[];for(let[l,u]of Object.entries(t)){let c=i.find(f=>f.name===l);if(!c)continue;let p=c.value;this.validateSortCondition(l,u);let m;u.desc?m="desc":m="asc";let h=null;u.nullsFirst?h="first":u.nullsLast&&(h="last");let C=new Qe(p,m,h);r.push(C)}let s=[];e.orderByClause?s=[...e.orderByClause.order,...r]:s=r;let o=s.length>0?new Ce(s):null;return new w({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 Ji=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=P.parse(e)),!(e instanceof w))throw new Error("Complex queries are not supported for pagination");if(e.limitClause||e.offsetClause)throw new Error("Query already contains LIMIT or OFFSET clause. Use removePagination() first if you want to override existing pagination.");let n=(t.page-1)*t.pageSize,i=new ce(new A("paging_limit",t.pageSize)),r=new $e(new A("paging_offset",n));return new w({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,windowClause:e.windowClause,limitClause:i,offsetClause:r,fetchClause:e.fetchClause,forClause:e.forClause})}static removePagination(e){if(typeof e=="string"&&(e=P.parse(e)),!(e instanceof w))throw new Error("Complex queries are not supported for pagination removal");return new w({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 zi=class{constructor(e={}){this.options={requireAllParameters:!0,...e}}bind(e,t){let n=e,i=Rt.extractParameterNames(n);if(this.options.requireAllParameters){let r=i.filter(s=>!(s in t)||t[s]===void 0);if(r.length>0)throw new Error(`Missing values for required parameters: ${r.join(", ")}`)}for(let[r,s]of Object.entries(t))if(i.includes(r))try{ht.set(n,r,s)}catch(o){throw new Error(`Failed to bind parameter '${r}': ${o instanceof Error?o.message:"Unknown error"}`)}return n}bindToSimpleQuery(e,t){return this.bind(e,t)}};var Nr=class{constructor(e){this.tableColumnResolver=e}buildQuery(e,t={}){let n;try{n=P.parse(e)}catch(r){throw new Error(`Failed to parse SQL: ${r instanceof Error?r.message:"Unknown error"}`)}let i=n;if(t.filter&&Object.keys(t.filter).length>0){let{hardcodedParams:r,dynamicFilters:s}=Rt.separateFilters(i,t.filter);if(Object.keys(r).length>0&&(i=new zi({requireAllParameters:!1}).bind(i,r)),Object.keys(s).length>0){let o=new ji(this.tableColumnResolver),l=Ie.buildSimpleQuery(i);i=o.inject(l,s)}}if(t.sort&&Object.keys(t.sort).length>0){let r=new qi(this.tableColumnResolver),s=Ie.buildSimpleQuery(i);i=r.inject(s,t.sort)}if(t.paging){let{page:r=1,pageSize:s}=t.paging;if(s!==void 0){let o=new Ji,l={page:r,pageSize:s},u=Ie.buildSimpleQuery(i);i=o.inject(u,l)}}if(t.serialize&&typeof t.serialize=="object"){let r=new Ki,s=Ie.buildSimpleQuery(i);i=r.buildJsonQuery(s,t.serialize)}return i}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 P.parse(e),!0}catch(t){throw new Error(`Invalid SQL: ${t instanceof Error?t.message:"Unknown error"}`)}}};function rr(a){let e=[],t=0,n={},i=()=>`entity_${++t}`,r=u=>(n[u]||(n[u]=0),n[u]++,n[u]===1?u:`${u}_${n[u]}`),s=(u,c=null)=>{let p={},m=[];for(let[h,C]of Object.entries(u))if(typeof C=="string")p[h]=C;else if("column"in C&&typeof C.column=="string"&&!("type"in C&&(C.type==="object"||C.type==="array"))){let f=C;typeof f=="object"&&"column"in f&&(p[h]=f.column,f.type==="string"&&e.push(f.column))}else if("from"in C&&typeof C.from=="string"&&!("type"in C&&(C.type==="object"||C.type==="array"))){let f=C;typeof f=="object"&&"from"in f&&(p[h]=f.from,f.type==="string"&&e.push(f.from))}else if("type"in C&&(C.type==="object"||C.type==="array")){let f=C,N=r(h),V=i(),v=s(f.structure,V);m.push({id:V,name:h.charAt(0).toUpperCase()+h.slice(1),parentId:c||"root",propertyName:N,originalPropertyName:h,relationshipType:f.type,columns:v.columns}),m.push(...v.nestedEntities.map(g=>({...g,parentId:g.parentId==="root"?V:g.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 rs(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 _i(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 Fb(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:_i(a.rootEntity.columns||{})},nestedEntities:(a.nestedEntities||[]).map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:_i(e.columns||{})})),resultFormat:a.resultFormat,emptyResult:a.emptyResult};throw new Error("Unsupported mapping format")}function Or(a){return{rootName:a.rootName,rootEntity:{id:a.rootEntity.id,name:a.rootEntity.name,columns:_i(a.rootEntity.columns)},nestedEntities:a.nestedEntities.map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:_i(e.columns)})),resultFormat:a.resultFormat,emptyResult:a.emptyResult}}function Qr(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[i,r]of Object.entries(a.rootEntity.columns))if(typeof r=="object"&&r.type){let s=r.column;switch(r.type){case"string":e.push(s);break;case"date":t.push(s);break;case"number":n.push(s);break}}for(let i of a.nestedEntities)for(let[r,s]of Object.entries(i.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 lr(a){return a!=null&&typeof a=="object"}var sr=class{detect(e){if(!lr(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=i=>!i||typeof i!="object"?!1:Object.values(i).some(r=>typeof r=="object"&&r!==null&&"column"in r);return n(t.rootEntity.columns)?!0:t.nestedEntities.some(i=>i&&typeof i=="object"&&n(i.columns))}convert(e){return{format:"enhanced",mapping:Or(e),typeProtection:Qr(e),originalInput:e,metadata:{typeInfo:e.typeInfo,version:e.metadata?.version,description:e.metadata?.description}}}},or=class{detect(e){if(!lr(e))return!1;let t=e;return t&&t.typeInfo&&t.structure&&typeof t.typeInfo.interface=="string"}convert(e){let t=rr(e);return{format:"model-driven",mapping:t.jsonMapping,typeProtection:t.typeProtection,originalInput:e,metadata:{typeInfo:e.typeInfo}}}},ar=class{detect(e){if(!lr(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=i=>!i||typeof i!="object"?!1:Object.values(i).some(r=>typeof r=="object"&&r!==null&&"column"in r);return!(n(t.rootEntity.columns)||t.nestedEntities&&Array.isArray(t.nestedEntities)&&t.nestedEntities.some(r=>r&&typeof r=="object"&&n(r.columns)))}convert(e){return{format:"legacy",mapping:e,typeProtection:{protectedStringFields:[]},originalInput:e}}},Pn=class{constructor(){this.strategies=[new sr,new or,new ar]}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 i of n.mapping.nestedEntities)i.id||t.push(`Nested entity missing id: ${i.propertyName}`),i.parentId||t.push(`Nested entity missing parentId: ${i.id}`),i.propertyName||t.push(`Nested entity missing propertyName: ${i.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 ur(a){return a.typeInfo&&a.structure?"model-driven":a.rootName&&a.rootEntity?"unified":(a.columns||a.relationships,"legacy")}function ss(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 i=n;e.nestedEntities.push({id:t,name:t.charAt(0).toUpperCase()+t.slice(1),parentId:"root",propertyName:t,relationshipType:i.type==="hasMany"?"array":"object",columns:i.columns||{}})}return e}function os(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:ss(a),originalInput:a,metadata:{}};let t=new Pn().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 as(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 Pn().toLegacyMapping(a)}function ls(a){return ur(a)==="model-driven"}function us(a){return ur(a)==="unified"}function cs(a){return ur(a)==="legacy"}var Hi=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,i]of Object.entries(e)){if(i==null){t[n]=i;continue}let r=this.config.columnTransformations?.[n];if(r){t[n]=this.applyTransformation(i,r);continue}if(this.config.enableValueBasedDetection){let o=this.detectValueBasedTransformation(i);if(o){t[n]=this.applyTransformation(i,o);continue}}let s=this.config.globalTransformations&&this.getGlobalTransformationForValue(i);if(s){t[n]=this.applyTransformation(i,s);continue}if(typeof i=="object"&&!Array.isArray(i)){t[n]=this.transformSingleObject(i);continue}if(Array.isArray(i)){t[n]=i.map(o=>typeof o=="object"?this.transformSingleObject(o):o);continue}t[n]=i}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 zb(a,e){return new Hi(e||Hi.createDefaultConfig()).transformResult(a)}var _b={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 hn=class{constructor(e,t,n,i,r){this.id=e;this.label=t;this.type=n;this.shape=i;this.details=r}},fn=class a extends hn{constructor(t,n,i){super(t,n,i,i==="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")}},Gi=class a extends hn{constructor(e,t,n=""){let i=n?`${n}_${t.toLowerCase().replace(/\s+/g,"_")}`:t.toLowerCase().replace(/\s+/g,"_");super(i,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)}},Ln=class a extends hn{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,i=t.trim().toLowerCase();return i==="join"?n="INNER JOIN":i.endsWith(" join")?n=i.toUpperCase():n=i.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(),i=`${n.toLowerCase().replace(/\s+/g,"_")}_${e}`;return new a(i,n,"rectangle")}},Yi=class extends hn{constructor(e="main"){let t=e==="main"?"Final Result":`${e} Result`;super(`${e}_output`,t,"output","stadium")}getMermaidRepresentation(){return`${this.id}([${this.label}])`}};var Xi=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 i=n?"NULLABLE":"NOT NULL";return new a(e,t,i)}},Zi=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(Xi.create(e,t,n))}addJoinConnection(e,t,n){this.add(Xi.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(` - `)}};var An=class{constructor(){this.nodes=new Map;this.edges=new Zi}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} + 3. Entity hierarchy and parentId relationships are correct`)}s.push(new E(null,new I(C.generatedColumnName)))}else m.relationshipType==="array"&&s.push(new E(null,new I(m.propertyName)))});let u=new H(null,new R(r),new W(s),null),l=a.JSON_FUNCTIONS.AGGREGATE,c=Object.values(e.columns)[0];return{jsonAgg:new H(null,new R(l),new W([u]),null)}}collectArrayEntityColumnsByDepth(e,t){let n=new Map,i=Math.max(t+3,5);for(let r=t;r<=i;r++)n.set(r,new Set);return e.nestedEntities.filter(r=>r.relationshipType==="array").forEach(r=>{let s=this.calculateEntityDepth(r,e);n.has(s)||n.set(s,new Set),this.addEntityColumnsToDepthSet(r,s,n),this.collectDescendantColumns(r.id,s,e,n)}),n}calculateEntityDepth(e,t){let n=0,i=e;for(;i.parentId&&i.parentId!==t.rootEntity.id;)n++,i=t.nestedEntities.find(r=>r.id===i.parentId)||i;return n}addEntityColumnsToDepthSet(e,t,n){Object.values(e.columns).forEach(i=>{let r=typeof i=="string"?i:i.column;n.get(t).add(r)})}collectDescendantColumns(e,t,n,i){n.nestedEntities.filter(r=>r.parentId===e).forEach(r=>{this.addEntityColumnsToDepthSet(r,t,i),this.collectDescendantColumns(r.id,t,n,i)})}processSelectVariablesForGroupBy(e,t,n,i,r,s,o){e.forEach(u=>{if(!t.has(u.name)){if(o&&o.has(u.name))return;this.shouldIncludeColumnInGroupBy(u.name,n,i)&&(r.push(new J(new E(null,new I(u.name)),u.name)),u.name.endsWith("_json")||s.push(new E(null,new I(u.name))))}})}shouldIncludeColumnInGroupBy(e,t,n){let i=e.endsWith("_json"),r=!0;for(let[s,o]of t.entries())if(s>=n&&o.has(e)){r=!1;break}return i&&e.startsWith("entity_")&&(r=this.shouldIncludeJsonColumn(e,n)),r}shouldIncludeJsonColumn(e,t){let n=e.match(/entity_(\d+)_json/);return n&&t>0?parseInt(n[1])<=2:!0}};var Ki=class{constructor(){this.selectValueCollector=new Ze(null),this.objectEntityCteBuilder=new Wi,this.arrayEntityCteBuilder=new Ui}validateMapping(e,t){let i=new Ze().collect(e),r=new Set(i.map(l=>l.name));for(let l in t.rootEntity.columns){let c=t.rootEntity.columns[l],p=typeof c=="string"?c:c.column;if(!r.has(p))throw new Error(`Validation Error: Column "${p}" for JSON key "${l}" 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(l=>{s.add(l.id),o.has(l.parentId)||o.set(l.parentId,[]),o.get(l.parentId).push(l.id)});for(let l of t.nestedEntities){if(!s.has(l.parentId))throw new Error(`Validation Error: Parent entity with ID "${l.parentId}" for nested entity "${l.name}" (ID: ${l.id}) not found.`);for(let c in l.columns){let p=l.columns[c],m=typeof p=="string"?p:p.column;if(!r.has(m))throw new Error(`Validation Error: Column "${m}" for JSON key "${c}" in nested entity "${l.name}" (ID: ${l.id}) not found in the query's select list.`)}}let u=new Set([t.rootEntity.id,...t.nestedEntities.map(l=>l.parentId)]);for(let l of u){let c=t.nestedEntities.filter(h=>h.parentId===l);if(c.filter(h=>h.relationshipType==="array").length>1){let h=l===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(C=>C.id===l)?.name;throw new Error(`Validation Error: Parent entity "${h}" (ID: ${l}) has multiple direct array children. This is not supported.`)}let m=new Set;for(let h of c){if(m.has(h.propertyName)){let C=l===t.rootEntity.id?t.rootEntity.name:t.nestedEntities.find(f=>f.id===l)?.name;throw new Error(`Validation Error: Parent entity "${C}" (ID: ${l}) has duplicate property name "${h.propertyName}" for its children.`)}m.add(h.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 i=e instanceof w?e:Ie.buildSimpleQuery(e);return this.buildJsonWithCteStrategy(i,t)}buildJson(e,t){return console.warn("buildJson is deprecated. Use buildJsonQuery instead."),this.buildJsonQuery(e,t)}buildJsonWithCteStrategy(e,t){this.validateMapping(e,t);let{initialCte:n,initialCteAlias:i}=this.createInitialCte(e),r=[n],s=i,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 u=this.objectEntityCteBuilder.buildObjectEntityCtes(n,o,t);r=u.ctes,s=u.lastCteAlias;let l=u.columnMappings,c=this.arrayEntityCteBuilder.buildArrayEntityCtes(r,s,o,t,l);return r=c.updatedCtes,s=c.lastCteAlias,this.buildFinalSelectQuery(r,s,o,t,l)}createInitialCte(e){let t="origin_query";return{initialCte:new oe(e,new se(t,null),null),initialCteAlias:t}}buildFinalSelectQuery(e,t,n,i,r){let s=[...e],o=`cte_root_${i.rootName.toLowerCase().replace(/[^a-z0-9_]/g,"_")}`,u=n.get(i.rootEntity.id);if(!u)throw new Error(`Root entity ${i.rootEntity.id} not found`);if(i.resultFormat==="array"||!i.resultFormat){let l=this.buildEntityJsonObject(u,null,i.nestedEntities,n,r),c=new J(l,i.rootName),p=new oe(new w({selectClause:new z([c]),fromClause:new _(new $(new B(null,new I(t)),null),null)}),new se(o,null),null);s.push(p);let m="jsonb_agg",h=new H(null,new R(m),new W([new E(null,new I(i.rootName))]),null);return new w({withClause:new he(!1,s),selectClause:new z([new J(h,`${i.rootName}_array`)]),fromClause:new _(new $(new B(null,new I(o)),null),null)})}else{let l=this.buildEntityJsonObject(u,null,i.nestedEntities,n,r),c=new J(l,i.rootName),p=new oe(new w({selectClause:new z([c]),fromClause:new _(new $(new B(null,new I(t)),null),null)}),new se(o,null),null);return s.push(p),new w({withClause:new he(!1,s),selectClause:new z([new J(new E(null,new I(i.rootName)),i.rootName)]),fromClause:new _(new $(new B(null,new I(o)),null),null),limitClause:new ce(new Z(1))})}}buildEntityJsonObject(e,t,n,i,r){let s="jsonb_build_object",o=[];return Object.entries(e.columns).forEach(([l,c])=>{let p=typeof c=="string"?c:c.column;o.push(new Z(l,void 0,!0)),o.push(new E(null,new I(p)))}),n.filter(l=>l.parentId===e.id).forEach(l=>{let c=i.get(l.id);if(c)if(o.push(new Z(l.propertyName,void 0,!0)),l.relationshipType==="object"){let p=r.find(m=>m.entityId===c.id);if(!p)throw new Error(`Column mapping not found for entity: ${c.id}`);o.push(new E(null,new I(p.generatedColumnName)))}else l.relationshipType==="array"&&o.push(new E(null,new I(l.propertyName)))}),new H(null,new R(s),new W(o),null)}};var Rt=class{static extractParameterNames(e){return kt.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),i={},r={};for(let[s,o]of Object.entries(t))n.includes(s)?i[s]=o:r[s]=o;return{hardcodedParams:i,dynamicFilters:r}}};var dn=class{constructor(e,t,n){this.name=e;this.type=t;this.tableName=n}},Qr=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 i=this.collectParameters(e);return t.push(...i),this.removeDuplicates(t)}collectColumns(e){let t=[];try{let i=new Ae(this.tableColumnResolver,!1,"fullName",{upstream:this.options.upstream}).collect(e);for(let r of i){let s,o;if(r.value&&typeof r.value.getNamespace=="function"){let l=r.value.getNamespace();l&&l.trim()!==""&&(s=l,this.options.qualified&&(o=this.getRealTableName(e,l)))}s||(s=this.inferTableNameFromQuery(e),s&&this.options.qualified&&(o=s));let u=r.name;this.options.qualified&&(o||s)&&(u=`${o||s}.${r.name}`),t.push(new dn(u,"column",s))}}catch(n){console.warn("Failed to collect columns with SelectableColumnCollector, using fallback:",n);try{let r=new pn(this.tableColumnResolver,!0).collect(e);for(let s of r)for(let o of s.columns){let u=o;this.options.qualified&&(u=`${s.name}.${o}`),t.push(new dn(u,"column",s.name))}}catch(i){console.warn("Failed to collect columns with both approaches:",n,i)}}return t}inferTableNameFromQuery(e){if(e instanceof w&&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 w&&n.fromClause){if(n.fromClause.source?.datasource){let r=n.fromClause.source,s=this.extractRealTableName(r,t);if(s)return s}let i=n.fromClause;if(i.joinClauses&&Array.isArray(i.joinClauses)){for(let r of i.joinClauses)if(r.source?.datasource){let s=this.extractRealTableName(r.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 i=e.alias||e.aliasExpression?.table?.name,r=n.table?.name;if(i===t&&r||!i&&r===t)return r}catch{}}collectParameters(e){let t=[];try{let n=Rt.extractParameterNames(e);for(let i of n)t.push(new dn(i,"parameter"))}catch(n){console.warn("Failed to collect parameters:",n)}return t}removeDuplicates(e){let t=new Set,n=[];for(let i of e){let r=`${i.type}:${i.name}:${i.tableName||"none"}`;t.has(r)||(t.add(r),n.push(i))}return n.sort((i,r)=>{if(i.type!==r.type)return i.type==="column"?-1:1;if(i.type==="column"){let s=i.tableName||"",o=r.tableName||"";if(s!==o)return s.localeCompare(o)}return i.name.localeCompare(r.name)})}};var ji=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=P.parse(e));let n=new an(this.tableColumnResolver,this.options),i=new Ae(this.tableColumnResolver,!1,"fullName",{upstream:!0}),r=v=>this.options.ignoreCaseAndUnderscore?v.toLowerCase().replace(/_/g,""):v,s=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"],o=Object.values(t);if(o.length>0&&o.every(v=>v===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[v,y]of Object.entries(t))y!==void 0&&(this.isQualifiedColumnName(v)?c.push([v,y]):p.push([v,y]));for(let[v,y]of c)this.processStateParameter(v,y,e,n,i,r,s,C,h,A,V,f);let m=new Set;for(let[v,y]of c){let M=this.parseQualifiedColumnName(v);M&&m.add(`${M.table.toLowerCase()}.${M.column.toLowerCase()}`)}for(let[v,y]of p)this.processUnqualifiedParameter(v,y,e,n,i,r,s,C,h,A,V,f,m);function h(v,y,M,L,U){for(let k=0;kL(q.name)===L(Q));if(!at)throw new Error(`Column '${Q}' not found in query for AND condition`);let Ve=at.value;if("="in S&&S["="]!==void 0){let q=`${y}_and_${k}_eq`,D=new N(q,S["="]);v.appendWhere(new b(Ve,"=",D))}if("min"in S&&S.min!==void 0){let q=`${y}_and_${k}_min`,D=new N(q,S.min);v.appendWhere(new b(Ve,">=",D))}if("max"in S&&S.max!==void 0){let q=`${y}_and_${k}_max`,D=new N(q,S.max);v.appendWhere(new b(Ve,"<=",D))}if("like"in S&&S.like!==void 0){let q=`${y}_and_${k}_like`,D=new N(q,S.like);v.appendWhere(new b(Ve,"like",D))}if("ilike"in S&&S.ilike!==void 0){let q=`${y}_and_${k}_ilike`,D=new N(q,S.ilike);v.appendWhere(new b(Ve,"ilike",D))}if("in"in S&&S.in!==void 0){let D=S.in.map((Y,X)=>new N(`${y}_and_${k}_in_${X}`,Y));v.appendWhere(new b(Ve,"in",new ee(new W(D))))}if("any"in S&&S.any!==void 0){let q=`${y}_and_${k}_any`,D=new N(q,S.any);v.appendWhere(new b(Ve,"=",new H(null,"any",D,null)))}if("<"in S&&S["<"]!==void 0){let q=`${y}_and_${k}_lt`,D=new N(q,S["<"]);v.appendWhere(new b(Ve,"<",D))}if(">"in S&&S[">"]!==void 0){let q=`${y}_and_${k}_gt`,D=new N(q,S[">"]);v.appendWhere(new b(Ve,">",D))}if("!="in S&&S["!="]!==void 0){let q=`${y}_and_${k}_neq`,D=new N(q,S["!="]);v.appendWhere(new b(Ve,"!=",D))}if("<>"in S&&S["<>"]!==void 0){let q=`${y}_and_${k}_ne`,D=new N(q,S["<>"]);v.appendWhere(new b(Ve,"<>",D))}if("<="in S&&S["<="]!==void 0){let q=`${y}_and_${k}_le`,D=new N(q,S["<="]);v.appendWhere(new b(Ve,"<=",D))}if(">="in S&&S[">="]!==void 0){let q=`${y}_and_${k}_ge`,D=new N(q,S[">="]);v.appendWhere(new b(Ve,">=",D))}}}function C(v,y,M,L,U){let k=[];for(let S=0;SL(Y.name)===L(at));if(!Ve)throw new Error(`Column '${at}' not found in query for OR condition`);let q=Ve.value,D=[];if("="in Q&&Q["="]!==void 0){let Y=`${y}_or_${S}_eq`,X=new N(Y,Q["="]);D.push(new b(q,"=",X))}if("min"in Q&&Q.min!==void 0){let Y=`${y}_or_${S}_min`,X=new N(Y,Q.min);D.push(new b(q,">=",X))}if("max"in Q&&Q.max!==void 0){let Y=`${y}_or_${S}_max`,X=new N(Y,Q.max);D.push(new b(q,"<=",X))}if("like"in Q&&Q.like!==void 0){let Y=`${y}_or_${S}_like`,X=new N(Y,Q.like);D.push(new b(q,"like",X))}if("ilike"in Q&&Q.ilike!==void 0){let Y=`${y}_or_${S}_ilike`,X=new N(Y,Q.ilike);D.push(new b(q,"ilike",X))}if("in"in Q&&Q.in!==void 0){let X=Q.in.map((Kr,jr)=>new N(`${y}_or_${S}_in_${jr}`,Kr));D.push(new b(q,"in",new ee(new W(X))))}if("any"in Q&&Q.any!==void 0){let Y=`${y}_or_${S}_any`,X=new N(Y,Q.any);D.push(new b(q,"=",new H(null,"any",X,null)))}if("<"in Q&&Q["<"]!==void 0){let Y=`${y}_or_${S}_lt`,X=new N(Y,Q["<"]);D.push(new b(q,"<",X))}if(">"in Q&&Q[">"]!==void 0){let Y=`${y}_or_${S}_gt`,X=new N(Y,Q[">"]);D.push(new b(q,">",X))}if("!="in Q&&Q["!="]!==void 0){let Y=`${y}_or_${S}_neq`,X=new N(Y,Q["!="]);D.push(new b(q,"!=",X))}if("<>"in Q&&Q["<>"]!==void 0){let Y=`${y}_or_${S}_ne`,X=new N(Y,Q["<>"]);D.push(new b(q,"<>",X))}if("<="in Q&&Q["<="]!==void 0){let Y=`${y}_or_${S}_le`,X=new N(Y,Q["<="]);D.push(new b(q,"<=",X))}if(">="in Q&&Q[">="]!==void 0){let Y=`${y}_or_${S}_ge`,X=new N(Y,Q[">="]);D.push(new b(q,">=",X))}if(D.length>0){let Y=D[0];for(let X=1;X1?k.push(new ee(Y)):k.push(Y)}}if(k.length>0){let S=k[0];for(let Q=1;Q{if(!y.includes(L))throw new Error(`Unsupported operator '${L}' for state key '${M}'`)})}function A(v,y,M,L){let U=new N(M,L);v.appendWhere(new b(y,"=",U))}function V(v,y,M,L){let U=[];if("="in L){let k=new N(M,L["="]);U.push(new b(y,"=",k))}if("min"in L){let k=new N(M+"_min",L.min);U.push(new b(y,">=",k))}if("max"in L){let k=new N(M+"_max",L.max);U.push(new b(y,"<=",k))}if("like"in L){let k=new N(M+"_like",L.like);U.push(new b(y,"like",k))}if("ilike"in L){let k=new N(M+"_ilike",L.ilike);U.push(new b(y,"ilike",k))}if("in"in L){let S=L.in.map((Q,at)=>new N(`${M}_in_${at}`,Q));U.push(new b(y,"in",new ee(new W(S))))}if("any"in L){let k=new N(M+"_any",L.any);U.push(new b(y,"=",new H(null,"any",k,null)))}if("<"in L){let k=new N(M+"_lt",L["<"]);U.push(new b(y,"<",k))}if(">"in L){let k=new N(M+"_gt",L[">"]);U.push(new b(y,">",k))}if("!="in L){let k=new N(M+"_neq",L["!="]);U.push(new b(y,"!=",k))}if("<>"in L){let k=new N(M+"_ne",L["<>"]);U.push(new b(y,"<>",k))}if("<="in L){let k=new N(M+"_le",L["<="]);U.push(new b(y,"<=",k))}if(">="in L){let k=new N(M+"_ge",L[">="]);U.push(new b(y,">=",k))}if(U.length===1)v.appendWhere(U[0]);else if(U.length>1){let k=U[0];for(let S=1;S0){let C=this.findTargetQueryForLogicalCondition(i,n,e,h),f=this.getAllAvailableColumns(C,r);u(C,e,h,s,f);return}}if(this.isAndCondition(t)){let h=t.and;if(h&&h.length>0){let C=this.findTargetQueryForLogicalCondition(i,n,e,h),f=this.getAllAvailableColumns(C,r);l(C,e,h,s,f);return}}if(this.isExplicitColumnMapping(t)){let h=t.column;if(h){let C=i.find(n,h);if(C.length===0)throw new Error(`Explicit column '${h}' not found in query`);for(let f of C){let V=this.getAllAvailableColumns(f,r).find(v=>s(v.name)===s(h));if(!V)throw new Error(`Explicit column '${h}' not found in query`);this.isValidatableObject(t)&&m(t,o,e),p(f,V.value,e,t)}return}}this.processRegularColumnCondition(e,t,n,i,r,s,o,c,p,m)}processUnqualifiedParameter(e,t,n,i,r,s,o,u,l,c,p,m,h){if(this.isOrCondition(t)){let f=t.or;if(f&&f.length>0){let A=this.findTargetQueryForLogicalCondition(i,n,e,f),V=this.getAllAvailableColumns(A,r);u(A,e,f,s,V);return}}if(this.isAndCondition(t)){let f=t.and;if(f&&f.length>0){let A=this.findTargetQueryForLogicalCondition(i,n,e,f),V=this.getAllAvailableColumns(A,r);l(A,e,f,s,V);return}}if(this.isExplicitColumnMapping(t)){let f=t.column;if(f){let A=i.find(n,f);if(A.length===0)throw new Error(`Explicit column '${f}' not found in query`);for(let V of A){let y=this.getAllAvailableColumns(V,r).find(M=>s(M.name)===s(f));if(!y)throw new Error(`Explicit column '${f}' not found in query`);this.isValidatableObject(t)&&m(t,o,e),p(V,y.value,e,t)}return}}let C=i.find(n,e);if(C.length===0){if(this.options.ignoreNonExistentColumns)return;throw new Error(`Column '${e}' not found in query`)}for(let f of C){let A=this.getAllAvailableColumns(f,r),V=this.buildTableMapping(f),v=A.filter(y=>s(y.name)===s(e));for(let y of v){let M=!1;if(y.value&&typeof y.value.getNamespace=="function"){let k=y.value.getNamespace();if(k){let S=V.aliasToRealTable.get(k.toLowerCase());if(S){let Q=`${S.toLowerCase()}.${e.toLowerCase()}`;h.has(Q)&&(M=!0)}}}if(M)continue;let L=y.value;this.isValidatableObject(t)&&m(t,o,e);let U=L;if(this.hasColumnMapping(t)){let k=t.column;if(k){let S=A.find(Q=>s(Q.name)===s(k));S&&(U=S.value)}}this.isSimpleValue(t)?c(f,U,e,t):p(f,U,e,t)}}}processRegularColumnCondition(e,t,n,i,r,s,o,u,l,c){let p=e,m;if(this.isQualifiedColumnName(e)){let C=this.parseQualifiedColumnName(e);C&&(p=C.column,m=C.table)}let h=i.find(n,p);if(h.length===0){if(this.options.ignoreNonExistentColumns)return;throw new Error(`Column '${p}' not found in query`)}for(let C of h){let f=this.getAllAvailableColumns(C,r),A;if(m){let M=this.buildTableMapping(C);if(A=f.find(L=>{if(!(s(L.name)===s(p)))return!1;if(L.value&&typeof L.value.getNamespace=="function"){let k=L.value.getNamespace();if(k){let S=s(k),Q=s(m),at=M.aliasToRealTable.get(S);if(at&&s(at)===Q)return!0}}return!1}),!A){if(this.options.ignoreNonExistentColumns)continue;let L=this.buildTableMapping(C),U=Array.from(L.realTableToAlias.keys()).some(S=>s(S)===s(m)),k=Array.from(L.aliasToRealTable.keys()).some(S=>s(S)===s(m));throw!U&&!k?new Error(`Column '${e}' (qualified as ${e}) not found in query`):k&&!U?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(A=f.find(M=>s(M.name)===s(p)),!A)throw new Error(`Column '${p}' not found in query`);let V=A.value;this.isValidatableObject(t)&&c(t,o,e);let v=V;if(this.hasColumnMapping(t)){let M=t.column;if(M){let L=f.find(U=>s(U.name)===s(M));L&&(v=L.value)}}let y=this.sanitizeParameterName(e);this.isSimpleValue(t)?u(C,v,y,t):l(C,v,y,t)}}findTargetQueryForLogicalCondition(e,t,n,i){let r=i.map(o=>o.column||n).filter((o,u,l)=>l.indexOf(o)===u);for(let o of r){let u=e.find(t,o);if(u.length>0)return u[0]}let s=i===i.or?"OR":"AND";throw new Error(`None of the ${s} condition columns [${r.join(", ")}] found in query`)}getAllAvailableColumns(e,t){let n=t.collect(e),i=this.collectCTEColumns(e);return[...n,...i]}collectCTEColumns(e){let t=[];if(e.withClause)for(let n of e.withClause.tables)try{let i=this.collectColumnsFromSelectQuery(n.query);t.push(...i)}catch(i){console.warn(`Failed to collect columns from CTE '${n.getSourceAliasName()}':`,i)}return t}collectColumnsFromSelectQuery(e){return e instanceof w?new Ae(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(e):e instanceof O?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 i of e.fromClause.joins)this.processSourceForMapping(i.source,t,n);if(e.withClause)for(let i of e.withClause.tables){let r=i.getSourceAliasName();r&&(t.set(r.toLowerCase(),r),n.set(r.toLowerCase(),r))}}catch(i){console.warn("Failed to build table mapping:",i)}return{aliasToRealTable:t,realTableToAlias:n}}processSourceForMapping(e,t,n){try{if(e.datasource instanceof B){let i=e.datasource.getSourceName(),r=e.aliasExpression?.table?.name||i;i&&r&&(t.set(r.toLowerCase(),i),n.set(i.toLowerCase(),r),r===i&&t.set(i.toLowerCase(),i))}}catch(i){console.warn("Failed to process source for mapping:",i)}}};var qi=class{constructor(e){this.tableColumnResolver=e}static removeOrderBy(e){if(typeof e=="string"&&(e=P.parse(e)),!(e instanceof w))throw new Error("Complex queries are not supported for ORDER BY removal");return new w({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=P.parse(e)),!(e instanceof w))throw new Error("Complex queries are not supported for sorting");let i=new Ae(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(e);for(let u of Object.keys(t))if(!i.find(c=>c.name===u))throw new Error(`Column or alias '${u}' not found in current query`);let r=[];for(let[u,l]of Object.entries(t)){let c=i.find(f=>f.name===u);if(!c)continue;let p=c.value;this.validateSortCondition(u,l);let m;l.desc?m="desc":m="asc";let h=null;l.nullsFirst?h="first":l.nullsLast&&(h="last");let C=new Qe(p,m,h);r.push(C)}let s=[];e.orderByClause?s=[...e.orderByClause.order,...r]:s=r;let o=s.length>0?new Ce(s):null;return new w({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 Ji=class{inject(e,t){if(this.validatePaginationOptions(t),typeof e=="string"&&(e=P.parse(e)),!(e instanceof w))throw new Error("Complex queries are not supported for pagination");if(e.limitClause||e.offsetClause)throw new Error("Query already contains LIMIT or OFFSET clause. Use removePagination() first if you want to override existing pagination.");let n=(t.page-1)*t.pageSize,i=new ce(new N("paging_limit",t.pageSize)),r=new $e(new N("paging_offset",n));return new w({withClause:e.withClause,selectClause:e.selectClause,fromClause:e.fromClause,whereClause:e.whereClause,groupByClause:e.groupByClause,havingClause:e.havingClause,orderByClause:e.orderByClause,windowClause:e.windowClause,limitClause:i,offsetClause:r,fetchClause:e.fetchClause,forClause:e.forClause})}static removePagination(e){if(typeof e=="string"&&(e=P.parse(e)),!(e instanceof w))throw new Error("Complex queries are not supported for pagination removal");return new w({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 zi=class{constructor(e={}){this.options={requireAllParameters:!0,...e}}bind(e,t){let n=e,i=Rt.extractParameterNames(n);if(this.options.requireAllParameters){let r=i.filter(s=>!(s in t)||t[s]===void 0);if(r.length>0)throw new Error(`Missing values for required parameters: ${r.join(", ")}`)}for(let[r,s]of Object.entries(t))if(i.includes(r))try{ht.set(n,r,s)}catch(o){throw new Error(`Failed to bind parameter '${r}': ${o instanceof Error?o.message:"Unknown error"}`)}return n}bindToSimpleQuery(e,t){return this.bind(e,t)}};var Rr=class{constructor(e){this.tableColumnResolver=e}buildQuery(e,t={}){let n;try{n=P.parse(e)}catch(r){throw new Error(`Failed to parse SQL: ${r instanceof Error?r.message:"Unknown error"}`)}let i=n;if(t.filter&&Object.keys(t.filter).length>0){let{hardcodedParams:r,dynamicFilters:s}=Rt.separateFilters(i,t.filter);if(Object.keys(r).length>0&&(i=new zi({requireAllParameters:!1}).bind(i,r)),Object.keys(s).length>0){let o=new ji(this.tableColumnResolver),u=Ie.buildSimpleQuery(i);i=o.inject(u,s)}}if(t.sort&&Object.keys(t.sort).length>0){let r=new qi(this.tableColumnResolver),s=Ie.buildSimpleQuery(i);i=r.inject(s,t.sort)}if(t.paging){let{page:r=1,pageSize:s}=t.paging;if(s!==void 0){let o=new Ji,u={page:r,pageSize:s},l=Ie.buildSimpleQuery(i);i=o.inject(l,u)}}if(t.serialize&&typeof t.serialize=="object"){let r=new Ki,s=Ie.buildSimpleQuery(i);i=r.buildJsonQuery(s,t.serialize)}return i}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 P.parse(e),!0}catch(t){throw new Error(`Invalid SQL: ${t instanceof Error?t.message:"Unknown error"}`)}}};function rr(a){let e=[],t=0,n={},i=()=>`entity_${++t}`,r=l=>(n[l]||(n[l]=0),n[l]++,n[l]===1?l:`${l}_${n[l]}`),s=(l,c=null)=>{let p={},m=[];for(let[h,C]of Object.entries(l))if(typeof C=="string")p[h]=C;else if("column"in C&&typeof C.column=="string"&&!("type"in C&&(C.type==="object"||C.type==="array"))){let f=C;typeof f=="object"&&"column"in f&&(p[h]=f.column,f.type==="string"&&e.push(f.column))}else if("from"in C&&typeof C.from=="string"&&!("type"in C&&(C.type==="object"||C.type==="array"))){let f=C;typeof f=="object"&&"from"in f&&(p[h]=f.from,f.type==="string"&&e.push(f.from))}else if("type"in C&&(C.type==="object"||C.type==="array")){let f=C,A=r(h),V=i(),v=s(f.structure,V);m.push({id:V,name:h.charAt(0).toUpperCase()+h.slice(1),parentId:c||"root",propertyName:A,originalPropertyName:h,relationshipType:f.type,columns:v.columns}),m.push(...v.nestedEntities.map(y=>({...y,parentId:y.parentId==="root"?V:y.parentId})))}return{columns:p,nestedEntities:m}},o=s(a.structure),u={rootName:"root",rootEntity:{id:"root",name:"Root",columns:o.columns},nestedEntities:o.nestedEntities};return u.typeInfo=a.typeInfo,{jsonMapping:u,typeProtection:{protectedStringFields:e}}}function as(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 _i(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 Db(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:_i(a.rootEntity.columns||{})},nestedEntities:(a.nestedEntities||[]).map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:_i(e.columns||{})})),resultFormat:a.resultFormat,emptyResult:a.emptyResult};throw new Error("Unsupported mapping format")}function Fr(a){return{rootName:a.rootName,rootEntity:{id:a.rootEntity.id,name:a.rootEntity.name,columns:_i(a.rootEntity.columns)},nestedEntities:a.nestedEntities.map(e=>({id:e.id,name:e.name,parentId:e.parentId,propertyName:e.propertyName,relationshipType:e.relationshipType,columns:_i(e.columns)})),resultFormat:a.resultFormat,emptyResult:a.emptyResult}}function Br(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[i,r]of Object.entries(a.rootEntity.columns))if(typeof r=="object"&&r.type){let s=r.column;switch(r.type){case"string":e.push(s);break;case"date":t.push(s);break;case"number":n.push(s);break}}for(let i of a.nestedEntities)for(let[r,s]of Object.entries(i.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 lr(a){return a!=null&&typeof a=="object"}var sr=class{detect(e){if(!lr(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=i=>!i||typeof i!="object"?!1:Object.values(i).some(r=>typeof r=="object"&&r!==null&&"column"in r);return n(t.rootEntity.columns)?!0:t.nestedEntities.some(i=>i&&typeof i=="object"&&n(i.columns))}convert(e){return{format:"enhanced",mapping:Fr(e),typeProtection:Br(e),originalInput:e,metadata:{typeInfo:e.typeInfo,version:e.metadata?.version,description:e.metadata?.description}}}},or=class{detect(e){if(!lr(e))return!1;let t=e;return t&&t.typeInfo&&t.structure&&typeof t.typeInfo.interface=="string"}convert(e){let t=rr(e);return{format:"model-driven",mapping:t.jsonMapping,typeProtection:t.typeProtection,originalInput:e,metadata:{typeInfo:e.typeInfo}}}},ar=class{detect(e){if(!lr(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=i=>!i||typeof i!="object"?!1:Object.values(i).some(r=>typeof r=="object"&&r!==null&&"column"in r);return!(n(t.rootEntity.columns)||t.nestedEntities&&Array.isArray(t.nestedEntities)&&t.nestedEntities.some(r=>r&&typeof r=="object"&&n(r.columns)))}convert(e){return{format:"legacy",mapping:e,typeProtection:{protectedStringFields:[]},originalInput:e}}},Pn=class{constructor(){this.strategies=[new sr,new or,new ar]}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 i of n.mapping.nestedEntities)i.id||t.push(`Nested entity missing id: ${i.propertyName}`),i.parentId||t.push(`Nested entity missing parentId: ${i.id}`),i.propertyName||t.push(`Nested entity missing propertyName: ${i.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 ur(a){return a.typeInfo&&a.structure?"model-driven":a.rootName&&a.rootEntity?"unified":(a.columns||a.relationships,"legacy")}function ls(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 i=n;e.nestedEntities.push({id:t,name:t.charAt(0).toUpperCase()+t.slice(1),parentId:"root",propertyName:t,relationshipType:i.type==="hasMany"?"array":"object",columns:i.columns||{}})}return e}function us(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:ls(a),originalInput:a,metadata:{}};let t=new Pn().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 cs(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 Pn().toLegacyMapping(a)}function ps(a){return ur(a)==="model-driven"}function ms(a){return ur(a)==="unified"}function ds(a){return ur(a)==="legacy"}var Hi=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,i]of Object.entries(e)){if(i==null){t[n]=i;continue}let r=this.config.columnTransformations?.[n];if(r){t[n]=this.applyTransformation(i,r);continue}if(this.config.enableValueBasedDetection){let o=this.detectValueBasedTransformation(i);if(o){t[n]=this.applyTransformation(i,o);continue}}let s=this.config.globalTransformations&&this.getGlobalTransformationForValue(i);if(s){t[n]=this.applyTransformation(i,s);continue}if(typeof i=="object"&&!Array.isArray(i)){t[n]=this.transformSingleObject(i);continue}if(Array.isArray(i)){t[n]=i.map(o=>typeof o=="object"?this.transformSingleObject(o):o);continue}t[n]=i}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 Yb(a,e){return new Hi(e||Hi.createDefaultConfig()).transformResult(a)}var Xb={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 hn=class{constructor(e,t,n,i,r){this.id=e;this.label=t;this.type=n;this.shape=i;this.details=r}},fn=class a extends hn{constructor(t,n,i){super(t,n,i,i==="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")}},Gi=class a extends hn{constructor(e,t,n=""){let i=n?`${n}_${t.toLowerCase().replace(/\s+/g,"_")}`:t.toLowerCase().replace(/\s+/g,"_");super(i,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)}},Ln=class a extends hn{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,i=t.trim().toLowerCase();return i==="join"?n="INNER JOIN":i.endsWith(" join")?n=i.toUpperCase():n=i.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(),i=`${n.toLowerCase().replace(/\s+/g,"_")}_${e}`;return new a(i,n,"rectangle")}},Yi=class extends hn{constructor(e="main"){let t=e==="main"?"Final Result":`${e} Result`;super(`${e}_output`,t,"output","stadium")}getMermaidRepresentation(){return`${this.id}([${this.label}])`}};var Xi=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 i=n?"NULLABLE":"NOT NULL";return new a(e,t,i)}},Zi=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(Xi.create(e,t,n))}addJoinConnection(e,t,n){this.add(Xi.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(` + `)}};var Nn=class{constructor(){this.nodes=new Map;this.edges=new Zi}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} `;t&&(n+=` %% ${t} `);let i=Array.from(this.nodes.values()).map(s=>` ${s.getMermaidRepresentation()}`).join(` `);i&&(n+=i+` `),this.nodes.size>0&&this.edges.getAll().length>0&&(n+=` `);let r=this.edges.getMermaidRepresentation();return r&&(n+=` ${r} -`),n}getOrCreateTable(e){let t=`table_${e}`,n=this.nodes.get(t);return n||(n=fn.createTable(e),this.addNode(n)),n}getOrCreateCTE(e){let t=`cte_${e}`,n=this.nodes.get(t);return n||(n=fn.createCTE(e),this.addNode(n)),n}getOrCreateSubquery(e){let t=`subquery_${e}`,n=this.nodes.get(t);return n||(n=fn.createSubquery(e),this.addNode(n)),n}createProcessNode(e,t){let n=new Gi(t,e);return this.addNode(n),n}createJoinNode(e,t){let n=Ln.createJoin(e,t);return this.addNode(n),n}createSetOperationNode(e,t){let n=Ln.createSetOperation(e,t);return this.addNode(n),n}createOutputNode(e="main"){let t=new Yi(e);return this.addNode(t),t}};var Nn=class{constructor(e){this.graph=e}processSource(e,t,n){if(e.datasource instanceof B)return this.processTableSource(e.datasource,t);if(e.datasource instanceof U)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 i=e.aliasExpression?.table.name||"subquery",r=this.graph.getOrCreateSubquery(i),s=n(e.datasource.query,`subquery_${i}_internal`,t);return s&&!this.graph.hasConnection(s,r.id)&&this.graph.addConnection(s,r.id),r.id}extractTableNodeIds(e,t){let n=[],i=e.source;if(i.datasource instanceof B){let r=i.datasource.getSourceName();if(t.has(r)){let s=this.graph.getOrCreateCTE(r);n.push(s.id)}else{let s=this.graph.getOrCreateTable(r);n.push(s.id)}}if(e.joins&&e.joins.length>0)for(let r of e.joins){let s=r.source;if(s.datasource instanceof B){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 On=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 i=this.dataSourceHandler.processSource(e.source,t,n);return e.joins&&e.joins.length>0?this.processJoins(e.joins,i,t,n):i}processJoins(e,t,n,i){let r=t;for(let s of e){let o=this.dataSourceHandler.processSource(s.source,n,i),l=this.getNextJoinId(),u=this.graph.createJoinNode(l,s.joinType.value),{leftLabel:c,rightLabel:p}=this.getJoinNullabilityLabels(s.joinType.value);r&&!this.graph.hasConnection(r,u.id)&&this.graph.addConnection(r,u.id,c),o&&!this.graph.hasConnection(o,u.id)&&this.graph.addConnection(o,u.id,p),r=u.id}return r}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 Qn=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t}processQueryClauses(e,t,n,i,r){return n}};var Rn=class{constructor(e){this.graph=e}processCTEs(e,t,n){for(let i=0;i0?i=this.joinHandler.processFromClause(e.fromClause,n,this.processQuery.bind(this)):i=this.dataSourceHandler.processSource(e.fromClause.source,n,this.processQuery.bind(this))),i&&(i=this.processHandler.processQueryClauses(e,t,i,n,this.processQuery.bind(this))),this.handleOutputNode(i,t)}processBinaryQuery(e,t,n){let i=this.flattenBinaryChain(e,e.operator.value);return i.length>2?this.processMultiPartOperation(i,e.operator.value,t,n):this.processSimpleBinaryOperation(e,t,n)}processSimpleBinaryOperation(e,t,n){let i=this.processQuery(e.left,`${t}_left`,n),r=this.processQuery(e.right,`${t}_right`,n),s=t==="main"?"main":t.replace(/^cte_/,""),o=this.graph.createSetOperationNode(s,e.operator.value);return i&&!this.graph.hasConnection(i,o.id)&&this.graph.addConnection(i,o.id),r&&!this.graph.hasConnection(r,o.id)&&this.graph.addConnection(r,o.id),o.id}processMultiPartOperation(e,t,n,i){let r=[],s=n==="main"?"main":n.replace(/^cte_/,""),o=this.graph.createSetOperationNode(s,t);for(let l=0;l{r instanceof O&&r.operator.value===t?(i(r.left),i(r.right)):n.push(r)};return i(e),n}};var Fr=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 i=["JsonMapping validation failed:",...n.errors].join(` -`);throw new Error(i)}}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(i=>{n[i]="primitive"}),t.nestedEntities&&t.nestedEntities.filter(i=>i.parentId===e.id).forEach(i=>{i.propertyName&&i.columns&&(i.relationshipType==="object"?n[i.propertyName]=this.extractNestedEntityStructure(i,t):i.relationshipType==="array"&&(n[i.propertyName]=[this.extractNestedEntityStructure(i,t)]))}),n}static compareStructures(e,t,n=""){let i=[],r=[],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}[]`);i.push(...u.errors),r.push(...u.missingProperties),s.push(...u.extraProperties)}return{isValid:i.length===0,errors:i,missingProperties:r,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)){r.push(c),i.push(`Missing property: ${c}`);return}let p=o[u],m=l[u],h=this.compareStructures(p,m,c);i.push(...h.errors),r.push(...h.missingProperties),s.push(...h.extraProperties)}),Object.keys(o).forEach(u=>{let c=n?`${n}.${u}`:u;u in l||s.push(c)}),{isValid:i.length===0,errors:i,missingProperties:r,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 i=["JsonMapping validation against sample object failed:",...n.errors].join(` -`);throw new Error(i)}}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 Fn=class{constructor(e){this.schemas=e,this.validateSchemas()}validateSchemas(){let e=Object.keys(this.schemas),t=[];if(Object.entries(this.schemas).forEach(([n,i])=>{Object.entries(i.columns).filter(([s,o])=>o.isPrimaryKey).map(([s,o])=>s).length===0&&t.push(`Table '${n}' has no primary key defined`),i.relationships?.forEach(s=>{e.includes(s.table)||t.push(`Table '${n}' references unknown table '${s.table}' in relationship`)})}),t.length>0)throw new Error(`Schema validation failed:\\n${t.join("\\n")}`)}getTableColumns(e){let t=this.schemas[e];return t?Object.keys(t.columns):[]}createTableColumnResolver(){return e=>this.getTableColumns(e)}createJsonMapping(e){let t=this.schemas[e];if(!t)throw new Error(`Table '${e}' not found in schema registry`);let n={};Object.entries(t.columns).forEach(([r,s])=>{n[r]=s.jsonAlias||s.name});let i=[];return t.relationships?.forEach(r=>{let s=this.schemas[r.table];if(!s)throw new Error(`Related table '${r.table}' not found in schema registry`);let o={};Object.entries(s.columns).forEach(([u,c])=>{o[u]=c.jsonAlias||c.name});let l=r.type;i.push({id:r.propertyName,name:s.displayName||r.table,parentId:e,propertyName:r.propertyName,relationshipType:l,columns:o})}),{rootName:e,rootEntity:{id:e,name:t.displayName||e,columns:n},nestedEntities:i,resultFormat:"single"}}getTableNames(){return Object.keys(this.schemas)}getTable(e){return this.schemas[e]}getPrimaryKey(e){let t=this.schemas[e];if(!t)return;let n=Object.entries(t.columns).find(([i,r])=>r.isPrimaryKey);return n?n[0]:void 0}getForeignKeys(e){let t=this.schemas[e];if(!t)return[];let n=[];return Object.entries(t.columns).forEach(([i,r])=>{r.foreignKey&&n.push({column:i,referencedTable:r.foreignKey.table,referencedColumn:r.foreignKey.column})}),n}};function yE(a){return new Fn(a)}function wE(a){return new Fn(a).createTableColumnResolver()}function vE(a,e){return new Fn(a).createJsonMapping(e)}var Me=class{static lineColumnToCharOffset(e,t){if(t.line<1||t.column<1)return-1;let n=e.split(` +`),n}getOrCreateTable(e){let t=`table_${e}`,n=this.nodes.get(t);return n||(n=fn.createTable(e),this.addNode(n)),n}getOrCreateCTE(e){let t=`cte_${e}`,n=this.nodes.get(t);return n||(n=fn.createCTE(e),this.addNode(n)),n}getOrCreateSubquery(e){let t=`subquery_${e}`,n=this.nodes.get(t);return n||(n=fn.createSubquery(e),this.addNode(n)),n}createProcessNode(e,t){let n=new Gi(t,e);return this.addNode(n),n}createJoinNode(e,t){let n=Ln.createJoin(e,t);return this.addNode(n),n}createSetOperationNode(e,t){let n=Ln.createSetOperation(e,t);return this.addNode(n),n}createOutputNode(e="main"){let t=new Yi(e);return this.addNode(t),t}};var An=class{constructor(e){this.graph=e}processSource(e,t,n){if(e.datasource instanceof B)return this.processTableSource(e.datasource,t);if(e.datasource instanceof K)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 i=e.aliasExpression?.table.name||"subquery",r=this.graph.getOrCreateSubquery(i),s=n(e.datasource.query,`subquery_${i}_internal`,t);return s&&!this.graph.hasConnection(s,r.id)&&this.graph.addConnection(s,r.id),r.id}extractTableNodeIds(e,t){let n=[],i=e.source;if(i.datasource instanceof B){let r=i.datasource.getSourceName();if(t.has(r)){let s=this.graph.getOrCreateCTE(r);n.push(s.id)}else{let s=this.graph.getOrCreateTable(r);n.push(s.id)}}if(e.joins&&e.joins.length>0)for(let r of e.joins){let s=r.source;if(s.datasource instanceof B){let o=s.datasource.getSourceName();if(t.has(o)){let u=this.graph.getOrCreateCTE(o);n.push(u.id)}else{let u=this.graph.getOrCreateTable(o);n.push(u.id)}}}return n}};var On=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 i=this.dataSourceHandler.processSource(e.source,t,n);return e.joins&&e.joins.length>0?this.processJoins(e.joins,i,t,n):i}processJoins(e,t,n,i){let r=t;for(let s of e){let o=this.dataSourceHandler.processSource(s.source,n,i),u=this.getNextJoinId(),l=this.graph.createJoinNode(u,s.joinType.value),{leftLabel:c,rightLabel:p}=this.getJoinNullabilityLabels(s.joinType.value);r&&!this.graph.hasConnection(r,l.id)&&this.graph.addConnection(r,l.id,c),o&&!this.graph.hasConnection(o,l.id)&&this.graph.addConnection(o,l.id,p),r=l.id}return r}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 Qn=class{constructor(e,t){this.graph=e;this.dataSourceHandler=t}processQueryClauses(e,t,n,i,r){return n}};var Rn=class{constructor(e){this.graph=e}processCTEs(e,t,n){for(let i=0;i0?i=this.joinHandler.processFromClause(e.fromClause,n,this.processQuery.bind(this)):i=this.dataSourceHandler.processSource(e.fromClause.source,n,this.processQuery.bind(this))),i&&(i=this.processHandler.processQueryClauses(e,t,i,n,this.processQuery.bind(this))),this.handleOutputNode(i,t)}processBinaryQuery(e,t,n){let i=this.flattenBinaryChain(e,e.operator.value);return i.length>2?this.processMultiPartOperation(i,e.operator.value,t,n):this.processSimpleBinaryOperation(e,t,n)}processSimpleBinaryOperation(e,t,n){let i=this.processQuery(e.left,`${t}_left`,n),r=this.processQuery(e.right,`${t}_right`,n),s=t==="main"?"main":t.replace(/^cte_/,""),o=this.graph.createSetOperationNode(s,e.operator.value);return i&&!this.graph.hasConnection(i,o.id)&&this.graph.addConnection(i,o.id),r&&!this.graph.hasConnection(r,o.id)&&this.graph.addConnection(r,o.id),o.id}processMultiPartOperation(e,t,n,i){let r=[],s=n==="main"?"main":n.replace(/^cte_/,""),o=this.graph.createSetOperationNode(s,t);for(let u=0;u{r instanceof O&&r.operator.value===t?(i(r.left),i(r.right)):n.push(r)};return i(e),n}};var Vr=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 i=["JsonMapping validation failed:",...n.errors].join(` +`);throw new Error(i)}}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(i=>{n[i]="primitive"}),t.nestedEntities&&t.nestedEntities.filter(i=>i.parentId===e.id).forEach(i=>{i.propertyName&&i.columns&&(i.relationshipType==="object"?n[i.propertyName]=this.extractNestedEntityStructure(i,t):i.relationshipType==="array"&&(n[i.propertyName]=[this.extractNestedEntityStructure(i,t)]))}),n}static compareStructures(e,t,n=""){let i=[],r=[],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 l=this.compareStructures(e[0],t[0],`${n}[]`);i.push(...l.errors),r.push(...l.missingProperties),s.push(...l.extraProperties)}return{isValid:i.length===0,errors:i,missingProperties:r,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,u=t;return Object.keys(u).forEach(l=>{let c=n?`${n}.${l}`:l;if(!(l in o)){r.push(c),i.push(`Missing property: ${c}`);return}let p=o[l],m=u[l],h=this.compareStructures(p,m,c);i.push(...h.errors),r.push(...h.missingProperties),s.push(...h.extraProperties)}),Object.keys(o).forEach(l=>{let c=n?`${n}.${l}`:l;l in u||s.push(c)}),{isValid:i.length===0,errors:i,missingProperties:r,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 i=["JsonMapping validation against sample object failed:",...n.errors].join(` +`);throw new Error(i)}}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 Fn=class{constructor(e){this.schemas=e,this.validateSchemas()}validateSchemas(){let e=Object.keys(this.schemas),t=[];if(Object.entries(this.schemas).forEach(([n,i])=>{Object.entries(i.columns).filter(([s,o])=>o.isPrimaryKey).map(([s,o])=>s).length===0&&t.push(`Table '${n}' has no primary key defined`),i.relationships?.forEach(s=>{e.includes(s.table)||t.push(`Table '${n}' references unknown table '${s.table}' in relationship`)})}),t.length>0)throw new Error(`Schema validation failed:\\n${t.join("\\n")}`)}getTableColumns(e){let t=this.schemas[e];return t?Object.keys(t.columns):[]}createTableColumnResolver(){return e=>this.getTableColumns(e)}createJsonMapping(e){let t=this.schemas[e];if(!t)throw new Error(`Table '${e}' not found in schema registry`);let n={};Object.entries(t.columns).forEach(([r,s])=>{n[r]=s.jsonAlias||s.name});let i=[];return t.relationships?.forEach(r=>{let s=this.schemas[r.table];if(!s)throw new Error(`Related table '${r.table}' not found in schema registry`);let o={};Object.entries(s.columns).forEach(([l,c])=>{o[l]=c.jsonAlias||c.name});let u=r.type;i.push({id:r.propertyName,name:s.displayName||r.table,parentId:e,propertyName:r.propertyName,relationshipType:u,columns:o})}),{rootName:e,rootEntity:{id:e,name:t.displayName||e,columns:n},nestedEntities:i,resultFormat:"single"}}getTableNames(){return Object.keys(this.schemas)}getTable(e){return this.schemas[e]}getPrimaryKey(e){let t=this.schemas[e];if(!t)return;let n=Object.entries(t.columns).find(([i,r])=>r.isPrimaryKey);return n?n[0]:void 0}getForeignKeys(e){let t=this.schemas[e];if(!t)return[];let n=[];return Object.entries(t.columns).forEach(([i,r])=>{r.foreignKey&&n.push({column:i,referencedTable:r.foreignKey.table,referencedColumn:r.foreignKey.column})}),n}};function bE(a){return new Fn(a)}function EE(a){return new Fn(a).createTableColumnResolver()}function xE(a,e){return new Fn(a).createJsonMapping(e)}var Me=class{static lineColumnToCharOffset(e,t){if(t.line<1||t.column<1)return-1;let n=e.split(` `);if(t.line>n.length)return-1;let i=n[t.line-1];if(t.column>i.length+1)return-1;let r=0;for(let s=0;se.length)return null;let n=e.split(` `),i=0;for(let r=0;rn.length?null:n[t-1]}static getLineCount(e){return e.split(` -`).length}};var Cn=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(i=>{i.length>1&&n.add(i.slice(1).join(" ").toUpperCase())}),e.forEach(i=>{for(let r=0;r{if(o.length>r+1&&o[r]===s){let l=o.slice(r+1).join(" ").toUpperCase();t.get(s).add(l)}})}}),t.forEach((i,r)=>{this.joinSuggestionCache.set(r.toLowerCase(),Array.from(i))}),this.initializeCommandKeywords(),this.initialized=!0}static getJoinSuggestions(e){return this.initialize(),this.joinSuggestionCache.get(e.toLowerCase())||[]}static isValidJoinKeyword(e){return vn.parse(e,0)!==null}static getPartialSuggestions(e){this.initialize();let t=e.toLowerCase(),n=[];return this.joinSuggestionCache.forEach((i,r)=>{r.startsWith(t)&&(n.push(r),i.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(i=>e.add(i))}),Array.from(e)}static initializeCommandKeywords(){let e=this.extractCommandPatternsFromTrie(),t=new Map;e.forEach(n=>{for(let i=0;i{this.commandSuggestionCache.set(i.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 gn=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 i=["from","join"],r=["select","where","on","having","by"];for(let s of i)this.isKeywordInDictionary(s)&&t.add(s);for(let s of r)this.isKeywordInDictionary(s)&&n.add(s);this.extractRequiresKeywordPatterns(e)}static isKeywordInDictionary(e){return Cn.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 i=this.findPossibleFollowups(n);i.length>0&&e.set(n,i)}}static findPossibleFollowups(e){let t=new Set;return Cn.getJoinSuggestions(e.toLowerCase()).forEach(r=>t.add(r.toUpperCase())),Cn.getCommandSuggestions(e.toLowerCase()).forEach(r=>t.add(r.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=Be.getAllLexemesWithPosition(e),i=-1,r;for(let c=0;c=p.position.startPosition&&t<=p.position.endPosition){r=p,i=c;break}else if(p.position.startPosition>t){i=Math.max(0,c-1),r=i>=0?n[i]:void 0;break}}}i===-1&&n.length>0&&(i=n.length-1,r=n[i]);let s=i>0?n[i-1]:void 0;if(this.isAfterDot(e,t,s))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,tableScope:this.findPrecedingIdentifier(e,t,n),currentToken:r,previousToken:s};if(r){let c=r.value.toLowerCase(),p=this.requiresSpecificKeywords(c);if(p)return{suggestTables:!1,suggestColumns:!1,...p,currentToken:r,previousToken:s}}let l=r?.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:r,previousToken:s};if(c.suggestsColumns.has(l))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,currentToken:r,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:r,previousToken:s};if(c.suggestsTables.has(u))return{suggestTables:!0,suggestColumns:!1,suggestKeywords:!1,currentToken:r,previousToken:s};if(c.suggestsColumns.has(u))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,currentToken:r,previousToken:s}}return{suggestTables:!1,suggestColumns:!1,suggestKeywords:!0,currentToken:r,previousToken:s}}catch{return{suggestTables:!1,suggestColumns:!1,suggestKeywords:!1}}}static analyzeIntelliSenseAt(e,t){let n=Me.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 i=t-1;for(;i>=0&&/\s/.test(e[i]);)i--;return i>=0&&e[i]==="."}static findPrecedingIdentifier(e,t,n){if(this.isAfterDot(e,t)){let i=t-1;for(;i>=0&&/\s/.test(e[i]);)i--;if(i>=0&&e[i]==="."){let r=i;for(;i>=0&&/\s/.test(e[i]);)i--;for(;i>=0&&/[a-zA-Z0-9_]/.test(e[i]);)i--;let s=i+1;if(s=0;r--)if(n[r].value==="."&&n[r].position&&n[r].position.startPosition0&&this.isIdentifier(n[r-1]))return n[r-1].value;break}}}static isIdentifier(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.value)}};var Bn=class{static resolve(e,t){return this.createEmptyScope()}static resolveAt(e,t){let n=Me.lineColumnToCharOffset(e,t);return n===-1?this.createEmptyScope():this.resolve(e,n)}static getColumnsForTable(e,t,n){let i=this.resolve(e,t),r=i.availableTables.find(s=>s.name===n||s.alias===n);return r?i.visibleColumns.filter(s=>s.tableName===r.name||r.alias&&s.tableAlias===r.alias):[]}static analyzeScopeFromQuery(e){let t={availableTables:[],availableCTEs:[],subqueryLevel:0,visibleColumns:[],currentQuery:e,parentQueries:[]};if(e instanceof w)t.availableCTEs=this.collectCTEs(e),t.availableTables=this.collectTablesFromQuery(e),t.visibleColumns=this.collectVisibleColumns(t.availableTables,t.availableCTEs);else if(e instanceof O){let n=this.analyzeScopeFromQuery(e.left),i=this.analyzeScopeFromQuery(e.right);t.availableTables=[...n.availableTables,...i.availableTables],t.availableCTEs=[...n.availableCTEs,...i.availableCTEs],t.visibleColumns=[...n.visibleColumns,...i.visibleColumns]}return t}static collectCTEs(e){let t=[];if(e.withClause){let i=new ne().collect(e);for(let r of i)t.push({name:r.getSourceAliasName(),query:r.query,columns:this.extractCTEColumns(r.query),materialized:r.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 B){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 U){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 i=this.extractTablesFromJoin(n);t.push(...i)}return t}static extractTablesFromJoin(e){let t=[];if(e.source.datasource instanceof B){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 U){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 w&&e.selectClause){let t=[];for(let n of e.selectClause.items)if(n.identifier)t.push(n.identifier.name);else{let i=this.extractColumnNameFromExpression(n.value);i&&t.push(i)}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 i of t)if(i.columns)for(let r of i.columns)n.push({name:r,tableName:i.name,fullReference:`${i.name}.${r}`});for(let i of e)i.sourceType==="table"&&n.push({name:"*",tableName:i.name,tableAlias:i.alias,fullReference:`${i.alias||i.name}.*`});return n}static createEmptyScope(){return{availableTables:[],availableCTEs:[],subqueryLevel:0,visibleColumns:[],parentQueries:[]}}};var er=class{static parseToPosition(e,t,n={}){let i=typeof t=="number"?t:Me.lineColumnToCharOffset(e,t);if(i===-1)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};try{let r=this.tryNormalParse(e,i,n);return r.success?r:n.errorRecovery?this.tryErrorRecovery(e,i,n):r}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r),stoppedAtCursor:!1}}}static parseCurrentQuery(e,t,n={}){let i=typeof t=="number"?t:Me.lineColumnToCharOffset(e,t);if(i===-1)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};let r=this.findQueryBoundaries(e),s=this.findQueryAtPosition(r,i);if(!s)return{success:!1,error:"No query found at cursor position",stoppedAtCursor:!1};let o=i-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 i=e.trim(),s=[".",",","SELECT","FROM","WHERE","JOIN","ON","GROUP BY","ORDER BY"].some(p=>i.toLowerCase().endsWith(p.toLowerCase())),o=P.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:tthis.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(r>=i)break;r++;try{let l=o();if(l.success)return l.recoveryAttempts=r,l}catch{continue}}return{success:!1,error:"All error recovery attempts failed",recoveryAttempts:r,stoppedAtCursor:!1}}static recoverWithTokenInsertion(e,t,n){if(!n.insertMissingTokens)throw new Error("Token insertion disabled");let i=[{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 "}],r=e;for(let l of i)if(l.pattern.test(e)){r=e.replace(l.pattern,l.replacement);break}if(r===e)throw new Error("No applicable token insertion found");let s=P.analyze(r),o=this.getAllTokens(e);return{...s,parsedTokens:o,tokenBeforeCursor:this.findTokenBeforePosition(o,t),stoppedAtCursor:!0,recoveryAttempts:1}}static recoverWithTruncation(e,t,n){let i=e.substring(0,t),r=[""," 1"," FROM dual"," WHERE 1=1"];for(let s of r)try{let o=i+s,l=P.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 i=e.substring(0,t),r=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(i)){let l=i+o.completion+r;try{let u=P.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 i="SELECT 1 FROM dual WHERE 1=1";try{let r=P.analyze(i),s=this.getAllTokens(e);return{success:!0,query:r.query,parsedTokens:s.filter(o=>o.position&&o.position.startPosition<=t),tokenBeforeCursor:this.findTokenBeforePosition(s,t),stoppedAtCursor:!0,partialAST:r.query,recoveryAttempts:1}}catch{throw new Error("Minimal SQL recovery failed")}}static getAllTokens(e){try{return Be.getAllLexemesWithPosition(e)}catch{return[]}}static findTokenAtPosition(e,t){return e.find(n=>n.position&&t>=n.position.startPosition&&tt>=n.start&&t<=n.end)}};var yn=class{static split(e){let t=[];if(!e||e.trim()==="")return{queries:[],originalText:e,getActive:()=>{},getQuery:()=>{},getNonEmpty:()=>[]};let n=this.splitRespectingQuotesAndComments(e),i=this.mergeTrailingCommentSegments(n,e),r=0;for(let s of i){let o=s.text.trim(),l=this.isEmptyQuery(o),u=o,c=Me.charOffsetToLineColumn(e,s.start),p=Me.charOffsetToLineColumn(e,s.end);t.push({sql:u,start:s.start,end:s.end,startLine:c?.line||1,endLine:p?.line||1,index:r++,isEmpty:l})}return{queries:t,originalText:e,getActive:s=>{let o=typeof s=="number"?s:Me.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,i=0;for(;i<=e.length;){if(i===e.length||i0||i0){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,r.end),start:p.start,end:r.end}}else n.push(r)}else n.push(r)}return n}static cleanSqlComments(e){if(!e)return null;let t=e;t=t.split(` +`).length}};var Cn=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(i=>{i.length>1&&n.add(i.slice(1).join(" ").toUpperCase())}),e.forEach(i=>{for(let r=0;r{if(o.length>r+1&&o[r]===s){let u=o.slice(r+1).join(" ").toUpperCase();t.get(s).add(u)}})}}),t.forEach((i,r)=>{this.joinSuggestionCache.set(r.toLowerCase(),Array.from(i))}),this.initializeCommandKeywords(),this.initialized=!0}static getJoinSuggestions(e){return this.initialize(),this.joinSuggestionCache.get(e.toLowerCase())||[]}static isValidJoinKeyword(e){return vn.parse(e,0)!==null}static getPartialSuggestions(e){this.initialize();let t=e.toLowerCase(),n=[];return this.joinSuggestionCache.forEach((i,r)=>{r.startsWith(t)&&(n.push(r),i.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(i=>e.add(i))}),Array.from(e)}static initializeCommandKeywords(){let e=this.extractCommandPatternsFromTrie(),t=new Map;e.forEach(n=>{for(let i=0;i{this.commandSuggestionCache.set(i.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 yn=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 i=["from","join"],r=["select","where","on","having","by"];for(let s of i)this.isKeywordInDictionary(s)&&t.add(s);for(let s of r)this.isKeywordInDictionary(s)&&n.add(s);this.extractRequiresKeywordPatterns(e)}static isKeywordInDictionary(e){return Cn.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 i=this.findPossibleFollowups(n);i.length>0&&e.set(n,i)}}static findPossibleFollowups(e){let t=new Set;return Cn.getJoinSuggestions(e.toLowerCase()).forEach(r=>t.add(r.toUpperCase())),Cn.getCommandSuggestions(e.toLowerCase()).forEach(r=>t.add(r.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=Be.getAllLexemesWithPosition(e),i=-1,r;for(let c=0;c=p.position.startPosition&&t<=p.position.endPosition){r=p,i=c;break}else if(p.position.startPosition>t){i=Math.max(0,c-1),r=i>=0?n[i]:void 0;break}}}i===-1&&n.length>0&&(i=n.length-1,r=n[i]);let s=i>0?n[i-1]:void 0;if(this.isAfterDot(e,t,s))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,tableScope:this.findPrecedingIdentifier(e,t,n),currentToken:r,previousToken:s};if(r){let c=r.value.toLowerCase(),p=this.requiresSpecificKeywords(c);if(p)return{suggestTables:!1,suggestColumns:!1,...p,currentToken:r,previousToken:s}}let u=r?.value.toLowerCase(),l=s?.value.toLowerCase();if(u){let c=this.getKeywordPatterns();if(c.suggestsTables.has(u))return{suggestTables:!0,suggestColumns:!1,suggestKeywords:!1,currentToken:r,previousToken:s};if(c.suggestsColumns.has(u))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,currentToken:r,previousToken:s}}if(l){let c=this.getKeywordPatterns(),p=this.requiresSpecificKeywords(l);if(p&&u!=="join"&&u!=="outer"&&u!=="by")return{suggestTables:!1,suggestColumns:!1,...p,currentToken:r,previousToken:s};if(c.suggestsTables.has(l))return{suggestTables:!0,suggestColumns:!1,suggestKeywords:!1,currentToken:r,previousToken:s};if(c.suggestsColumns.has(l))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,currentToken:r,previousToken:s}}return{suggestTables:!1,suggestColumns:!1,suggestKeywords:!0,currentToken:r,previousToken:s}}catch{return{suggestTables:!1,suggestColumns:!1,suggestKeywords:!1}}}static analyzeIntelliSenseAt(e,t){let n=Me.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 i=t-1;for(;i>=0&&/\s/.test(e[i]);)i--;return i>=0&&e[i]==="."}static findPrecedingIdentifier(e,t,n){if(this.isAfterDot(e,t)){let i=t-1;for(;i>=0&&/\s/.test(e[i]);)i--;if(i>=0&&e[i]==="."){let r=i;for(;i>=0&&/\s/.test(e[i]);)i--;for(;i>=0&&/[a-zA-Z0-9_]/.test(e[i]);)i--;let s=i+1;if(s=0;r--)if(n[r].value==="."&&n[r].position&&n[r].position.startPosition0&&this.isIdentifier(n[r-1]))return n[r-1].value;break}}}static isIdentifier(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.value)}};var Bn=class{static resolve(e,t){return this.createEmptyScope()}static resolveAt(e,t){let n=Me.lineColumnToCharOffset(e,t);return n===-1?this.createEmptyScope():this.resolve(e,n)}static getColumnsForTable(e,t,n){let i=this.resolve(e,t),r=i.availableTables.find(s=>s.name===n||s.alias===n);return r?i.visibleColumns.filter(s=>s.tableName===r.name||r.alias&&s.tableAlias===r.alias):[]}static analyzeScopeFromQuery(e){let t={availableTables:[],availableCTEs:[],subqueryLevel:0,visibleColumns:[],currentQuery:e,parentQueries:[]};if(e instanceof w)t.availableCTEs=this.collectCTEs(e),t.availableTables=this.collectTablesFromQuery(e),t.visibleColumns=this.collectVisibleColumns(t.availableTables,t.availableCTEs);else if(e instanceof O){let n=this.analyzeScopeFromQuery(e.left),i=this.analyzeScopeFromQuery(e.right);t.availableTables=[...n.availableTables,...i.availableTables],t.availableCTEs=[...n.availableCTEs,...i.availableCTEs],t.visibleColumns=[...n.visibleColumns,...i.visibleColumns]}return t}static collectCTEs(e){let t=[];if(e.withClause){let i=new ne().collect(e);for(let r of i)t.push({name:r.getSourceAliasName(),query:r.query,columns:this.extractCTEColumns(r.query),materialized:r.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 B){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 K){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 i=this.extractTablesFromJoin(n);t.push(...i)}return t}static extractTablesFromJoin(e){let t=[];if(e.source.datasource instanceof B){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 K){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 w&&e.selectClause){let t=[];for(let n of e.selectClause.items)if(n.identifier)t.push(n.identifier.name);else{let i=this.extractColumnNameFromExpression(n.value);i&&t.push(i)}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 i of t)if(i.columns)for(let r of i.columns)n.push({name:r,tableName:i.name,fullReference:`${i.name}.${r}`});for(let i of e)i.sourceType==="table"&&n.push({name:"*",tableName:i.name,tableAlias:i.alias,fullReference:`${i.alias||i.name}.*`});return n}static createEmptyScope(){return{availableTables:[],availableCTEs:[],subqueryLevel:0,visibleColumns:[],parentQueries:[]}}};var er=class{static parseToPosition(e,t,n={}){let i=typeof t=="number"?t:Me.lineColumnToCharOffset(e,t);if(i===-1)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};try{let r=this.tryNormalParse(e,i,n);return r.success?r:n.errorRecovery?this.tryErrorRecovery(e,i,n):r}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r),stoppedAtCursor:!1}}}static parseCurrentQuery(e,t,n={}){let i=typeof t=="number"?t:Me.lineColumnToCharOffset(e,t);if(i===-1)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};let r=this.findQueryBoundaries(e),s=this.findQueryAtPosition(r,i);if(!s)return{success:!1,error:"No query found at cursor position",stoppedAtCursor:!1};let o=i-s.start,u=e.substring(s.start,s.end);return this.parseToPosition(u,o,n)}static tryNormalParse(e,t,n){if(t<0||t>e.length)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};let i=e.trim(),s=[".",",","SELECT","FROM","WHERE","JOIN","ON","GROUP BY","ORDER BY"].some(p=>i.toLowerCase().endsWith(p.toLowerCase())),o=P.analyze(e);if(!o.success||s)return{...o,success:!1};let u=this.getAllTokens(e),l=this.findTokenAtPosition(u,t),c=this.findTokenBeforePosition(u,t);return{...o,parsedTokens:u,tokenBeforeCursor:c,stoppedAtCursor:tthis.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(r>=i)break;r++;try{let u=o();if(u.success)return u.recoveryAttempts=r,u}catch{continue}}return{success:!1,error:"All error recovery attempts failed",recoveryAttempts:r,stoppedAtCursor:!1}}static recoverWithTokenInsertion(e,t,n){if(!n.insertMissingTokens)throw new Error("Token insertion disabled");let i=[{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 "}],r=e;for(let u of i)if(u.pattern.test(e)){r=e.replace(u.pattern,u.replacement);break}if(r===e)throw new Error("No applicable token insertion found");let s=P.analyze(r),o=this.getAllTokens(e);return{...s,parsedTokens:o,tokenBeforeCursor:this.findTokenBeforePosition(o,t),stoppedAtCursor:!0,recoveryAttempts:1}}static recoverWithTruncation(e,t,n){let i=e.substring(0,t),r=[""," 1"," FROM dual"," WHERE 1=1"];for(let s of r)try{let o=i+s,u=P.analyze(o);if(u.success){let l=this.getAllTokens(e);return{...u,parsedTokens:l.filter(c=>c.position&&c.position.startPosition<=t),tokenBeforeCursor:this.findTokenBeforePosition(l,t),stoppedAtCursor:!0,recoveryAttempts:1}}}catch{continue}throw new Error("Truncation recovery failed")}static recoverWithCompletion(e,t,n){let i=e.substring(0,t),r=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(i)){let u=i+o.completion+r;try{let l=P.analyze(u);if(l.success){let c=this.getAllTokens(e);return{...l,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 i="SELECT 1 FROM dual WHERE 1=1";try{let r=P.analyze(i),s=this.getAllTokens(e);return{success:!0,query:r.query,parsedTokens:s.filter(o=>o.position&&o.position.startPosition<=t),tokenBeforeCursor:this.findTokenBeforePosition(s,t),stoppedAtCursor:!0,partialAST:r.query,recoveryAttempts:1}}catch{throw new Error("Minimal SQL recovery failed")}}static getAllTokens(e){try{return Be.getAllLexemesWithPosition(e)}catch{return[]}}static findTokenAtPosition(e,t){return e.find(n=>n.position&&t>=n.position.startPosition&&tt>=n.start&&t<=n.end)}};var gn=class{static split(e){let t=[];if(!e||e.trim()==="")return{queries:[],originalText:e,getActive:()=>{},getQuery:()=>{},getNonEmpty:()=>[]};let n=this.splitRespectingQuotesAndComments(e),i=this.mergeTrailingCommentSegments(n,e),r=0;for(let s of i){let o=s.text.trim(),u=this.isEmptyQuery(o),l=o,c=Me.charOffsetToLineColumn(e,s.start),p=Me.charOffsetToLineColumn(e,s.end);t.push({sql:l,start:s.start,end:s.end,startLine:c?.line||1,endLine:p?.line||1,index:r++,isEmpty:u})}return{queries:t,originalText:e,getActive:s=>{let o=typeof s=="number"?s:Me.lineColumnToCharOffset(e,s);if(o!==-1)return t.find(u=>o>=u.start&&o<=u.end)},getQuery:s=>t[s],getNonEmpty:()=>t.filter(s=>!s.isEmpty)}}static splitRespectingQuotesAndComments(e){let t=[],n=0,i=0;for(;i<=e.length;){if(i===e.length||i0||i0){let u=n[n.length-1].text.trim(),l=s.startsWith("--"),c=!this.isEmptyQuery(u);if(l&&c){let p=n[n.length-1];n[n.length-1]={text:t.substring(p.start,r.end),start:p.start,end:r.end}}else n.push(r)}else n.push(r)}return n}static cleanSqlComments(e){if(!e)return null;let t=e;t=t.split(` `).map(i=>{let r=i.indexOf("--");return r>=0?i.substring(0,r):i}).join(` -`),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}},Br=class{static getContextAt(e,t){let i=yn.split(e).getActive(t);if(!i)return;let r=typeof t=="number"?t:Me.lineColumnToCharOffset(e,t);if(r===-1)return;let s=r-i.start;return{query:i,relativePosition:s}}static extractQueries(e){return yn.split(e).getNonEmpty().map(n=>n.sql)}};function Mr(a,e,t={}){return er.parseToPosition(a,e,t)}function Vr(a,e){return typeof e=="number"?gn.analyzeIntelliSense(a,e):gn.analyzeIntelliSenseAt(a,e)}function cr(a,e){return typeof e=="number"?Bn.resolve(a,e):Bn.resolveAt(a,e)}function Dr(a){return yn.split(a)}function ps(a,e,t={}){let n=typeof e=="number"?e:Me.lineColumnToCharOffset(a,e);if(n===-1)return;let r=Dr(a).getActive(n);if(!r)return;let s=n-r.start,o=r.sql,l=Vr(o,s),u=cr(o,s),c=Mr(o,s,t);return{context:l,scope:u,parseResult:c,currentQuery:o,relativePosition:s}}function ms(a,e){let t=typeof e=="number"?e:Me.lineColumnToCharOffset(a,e);if(t===-1)return[];let n=gn.analyzeIntelliSense(a,t),i=cr(a,e),r=[];return n.suggestKeywords&&(n.requiredKeywords?n.requiredKeywords.forEach(s=>{r.push({type:"keyword",value:s,detail:`Required keyword: ${s}`})}):ds(n).forEach(o=>{r.push({type:"keyword",value:o.value,detail:o.detail})})),n.suggestTables&&(i.availableTables.forEach(s=>{r.push({type:"table",value:s.alias||s.name,detail:`Table: ${s.fullName}`,documentation:`Available table${s.alias?` (alias: ${s.alias})`:""}`})}),i.availableCTEs.forEach(s=>{r.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?i.visibleColumns.filter(o=>o.tableName===n.tableScope||o.tableAlias===n.tableScope).forEach(o=>{r.push({type:"column",value:o.name,detail:`Column: ${o.fullReference}`,documentation:`Column from ${o.tableName}${o.type?` (${o.type})`:""}`})}):i.visibleColumns.forEach(s=>{r.push({type:"column",value:s.name==="*"?"*":`${s.tableAlias||s.tableName}.${s.name}`,detail:`Column: ${s.fullReference}`,documentation:`Column from ${s.tableName}`})})),r}function ds(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{Di as AliasRenamer,tn as AlterTableAddConstraint,nn as AlterTableDropConstraint,Oi as AlterTableParser,rn as AlterTableStatement,Se as ArrayExpression,ut as ArrayIndexExpression,be as ArrayQueryExpression,lt as ArraySliceExpression,Ee as BetweenExpression,b as BinaryExpression,O as BinarySelectQuery,ne as CTECollector,Mi as CTEComposer,Qt as CTEDependencyAnalyzer,Ht as CTEDisabler,dt as CTENormalizer,Tn as CTENotFoundError,Ir as CTEQueryDecomposer,Nt as CTERegionDetector,Vi as CTERenamer,Ri as CTETableReferenceCollector,ue as CaseExpression,Ae as CaseKeyValuePair,fe as CastExpression,et as ColumnConstraintDefinition,E as ColumnReference,mn as ColumnReferenceCollector,Fi as CommentEditor,Ni as CreateIndexParser,en as CreateIndexStatement,Ii as CreateTableParser,Pt as CreateTableQuery,gn as CursorContextAnalyzer,gt as DeleteQuery,ki as DeleteQueryParser,Qi as DropConstraintParser,sn as DropConstraintStatement,Ai as DropIndexParser,Zt as DropIndexStatement,Li as DropTableParser,Xt as DropTableStatement,xn as DuplicateCTEError,Vt as DuplicateDetectionMode,Nr as DynamicQueryBuilder,dn as FilterableItem,Ar as FilterableItemCollector,At as Formatter,H as FunctionCall,I as IdentifierString,Mt as IndexColumnDefinition,de as InlineQuery,tt as InsertQuery,vi as InsertQueryParser,kn as InsertQuerySelectValuesConverter,on as InvalidCTENameError,Pn as JsonMappingConverter,Fr as JsonSchemaValidator,Be as LexemeCursor,Z as LiteralValue,Yt as MergeAction,yt as MergeDeleteAction,mt as MergeDoNothingAction,wt as MergeInsertAction,vt as MergeQuery,Pi as MergeQueryParser,Lt as MergeUpdateAction,Ge as MergeWhenClause,yn as MultiQuerySplitter,Br as MultiQueryUtils,Lr as OriginalFormatRestorer,A as ParameterExpression,ee as ParenExpression,er as PositionAwareParser,Ki as PostgresJsonQueryBuilder,G as QualifiedName,Ie as QueryBuilder,Rr as QueryFlowDiagramGenerator,R as RawString,It as ReferenceDefinition,pn as SchemaCollector,Fn as SchemaManager,Bn as ScopeResolver,P as SelectQueryParser,Ze as SelectValueCollector,Ne as SelectableColumnCollector,w as SimpleSelectQuery,Pr as SmartRenamer,y as SqlComponent,pr as SqlDialectConfiguration,Ue as SqlFormatter,$i as SqlIdentifierRenamer,Ji as SqlPaginationInjector,ji as SqlParamInjector,kr as SqlParser,Bi as SqlSchemaValidator,qi as SqlSortInjector,ze as StringSpecifierExpression,Le as SwitchCaseArgument,Gt as TableColumnDefinition,We as TableConstraintDefinition,St as TableSchema,rt as TableSourceCollector,F as TokenType,xe as TupleExpression,Hi as TypeTransformationPostProcessor,_b as TypeTransformers,De as TypeValue,te as UnaryExpression,Ct as UpdateQuery,Ei as UpdateQueryParser,an as UpstreamSelectQueryFinder,Ip as VALID_PRESETS,W as ValueList,ae as ValuesQuery,dr as WindowFrameBound,Ut as WindowFrameBoundStatic,Kt as WindowFrameBoundaryValue,Ke as WindowFrameExpression,it as WindowFrameSpec,mr as WindowFrameType,Ye as WithClauseParser,_i as convertColumnsToLegacy,rr as convertModelDrivenMapping,Fb as convertToLegacyJsonMapping,vE as createJsonMappingFromSchema,yE as createSchemaManager,wE as createTableColumnResolver,Qr as extractTypeProtection,ms as getCompletionSuggestions,Vr as getCursorContext,ps as getIntelliSenseInfo,cs as isLegacyFormat,ls as isModelDrivenFormat,us as isUnifiedFormat,Mr as parseToPosition,os as processJsonMapping,cr as resolveScope,Dr as splitQueries,Or as toLegacyMapping,zb as transformDatabaseResult,as as unifyJsonMapping,rs as validateModelDrivenMapping}; +`),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 i=gn.split(e).getActive(t);if(!i)return;let r=typeof t=="number"?t:Me.lineColumnToCharOffset(e,t);if(r===-1)return;let s=r-i.start;return{query:i,relativePosition:s}}static extractQueries(e){return gn.split(e).getNonEmpty().map(n=>n.sql)}};function $r(a,e,t={}){return er.parseToPosition(a,e,t)}function Wr(a,e){return typeof e=="number"?yn.analyzeIntelliSense(a,e):yn.analyzeIntelliSenseAt(a,e)}function cr(a,e){return typeof e=="number"?Bn.resolve(a,e):Bn.resolveAt(a,e)}function Ur(a){return gn.split(a)}function hs(a,e,t={}){let n=typeof e=="number"?e:Me.lineColumnToCharOffset(a,e);if(n===-1)return;let r=Ur(a).getActive(n);if(!r)return;let s=n-r.start,o=r.sql,u=Wr(o,s),l=cr(o,s),c=$r(o,s,t);return{context:u,scope:l,parseResult:c,currentQuery:o,relativePosition:s}}function fs(a,e){let t=typeof e=="number"?e:Me.lineColumnToCharOffset(a,e);if(t===-1)return[];let n=yn.analyzeIntelliSense(a,t),i=cr(a,e),r=[];return n.suggestKeywords&&(n.requiredKeywords?n.requiredKeywords.forEach(s=>{r.push({type:"keyword",value:s,detail:`Required keyword: ${s}`})}):Cs(n).forEach(o=>{r.push({type:"keyword",value:o.value,detail:o.detail})})),n.suggestTables&&(i.availableTables.forEach(s=>{r.push({type:"table",value:s.alias||s.name,detail:`Table: ${s.fullName}`,documentation:`Available table${s.alias?` (alias: ${s.alias})`:""}`})}),i.availableCTEs.forEach(s=>{r.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?i.visibleColumns.filter(o=>o.tableName===n.tableScope||o.tableAlias===n.tableScope).forEach(o=>{r.push({type:"column",value:o.name,detail:`Column: ${o.fullReference}`,documentation:`Column from ${o.tableName}${o.type?` (${o.type})`:""}`})}):i.visibleColumns.forEach(s=>{r.push({type:"column",value:s.name==="*"?"*":`${s.tableAlias||s.tableName}.${s.name}`,detail:`Column: ${s.fullReference}`,documentation:`Column from ${s.tableName}`})})),r}function Cs(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{Di as AliasRenamer,tn as AlterTableAddConstraint,nn as AlterTableDropConstraint,Oi as AlterTableParser,rn as AlterTableStatement,Se as ArrayExpression,ut as ArrayIndexExpression,be as ArrayQueryExpression,lt as ArraySliceExpression,Ee as BetweenExpression,b as BinaryExpression,O as BinarySelectQuery,ne as CTECollector,Mi as CTEComposer,Qt as CTEDependencyAnalyzer,Ht as CTEDisabler,dt as CTENormalizer,Tn as CTENotFoundError,Nr as CTEQueryDecomposer,At as CTERegionDetector,Vi as CTERenamer,Ri as CTETableReferenceCollector,ue as CaseExpression,Ne as CaseKeyValuePair,fe as CastExpression,et as ColumnConstraintDefinition,E as ColumnReference,mn as ColumnReferenceCollector,Fi as CommentEditor,Ai as CreateIndexParser,en as CreateIndexStatement,Ii as CreateTableParser,Pt as CreateTableQuery,yn as CursorContextAnalyzer,yt as DeleteQuery,ki as DeleteQueryParser,Qi as DropConstraintParser,sn as DropConstraintStatement,Ni as DropIndexParser,Zt as DropIndexStatement,Li as DropTableParser,Xt as DropTableStatement,xn as DuplicateCTEError,Vt as DuplicateDetectionMode,Rr as DynamicQueryBuilder,dn as FilterableItem,Qr as FilterableItemCollector,Nt as Formatter,H as FunctionCall,I as IdentifierString,Mt as IndexColumnDefinition,de as InlineQuery,tt as InsertQuery,vi as InsertQueryParser,kn as InsertQuerySelectValuesConverter,on as InvalidCTENameError,Pn as JsonMappingConverter,Vr as JsonSchemaValidator,Be as LexemeCursor,Z as LiteralValue,Yt as MergeAction,gt as MergeDeleteAction,mt as MergeDoNothingAction,wt as MergeInsertAction,vt as MergeQuery,Pi as MergeQueryParser,Lt as MergeUpdateAction,Ge as MergeWhenClause,gn as MultiQuerySplitter,Dr as MultiQueryUtils,Or as OriginalFormatRestorer,N as ParameterExpression,ee as ParenExpression,er as PositionAwareParser,Ki as PostgresJsonQueryBuilder,G as QualifiedName,Ie as QueryBuilder,Mr as QueryFlowDiagramGenerator,R as RawString,It as ReferenceDefinition,pn as SchemaCollector,Fn as SchemaManager,Bn as ScopeResolver,P as SelectQueryParser,Ze as SelectValueCollector,Ae as SelectableColumnCollector,w as SimpleSelectQuery,Ar as SmartRenamer,g as SqlComponent,pr as SqlDialectConfiguration,Ue as SqlFormatter,$i as SqlIdentifierRenamer,Ji as SqlPaginationInjector,ji as SqlParamInjector,Lr as SqlParser,Bi as SqlSchemaValidator,qi as SqlSortInjector,ze as StringSpecifierExpression,Le as SwitchCaseArgument,Gt as TableColumnDefinition,We as TableConstraintDefinition,St as TableSchema,rt as TableSourceCollector,F as TokenType,xe as TupleExpression,Hi as TypeTransformationPostProcessor,Xb as TypeTransformers,De as TypeValue,te as UnaryExpression,Ct as UpdateQuery,Ei as UpdateQueryParser,an as UpstreamSelectQueryFinder,Ap as VALID_PRESETS,W as ValueList,ae as ValuesQuery,dr as WindowFrameBound,Ut as WindowFrameBoundStatic,Kt as WindowFrameBoundaryValue,Ke as WindowFrameExpression,it as WindowFrameSpec,mr as WindowFrameType,Ye as WithClauseParser,_i as convertColumnsToLegacy,rr as convertModelDrivenMapping,Db as convertToLegacyJsonMapping,xE as createJsonMappingFromSchema,bE as createSchemaManager,EE as createTableColumnResolver,Br as extractTypeProtection,fs as getCompletionSuggestions,Wr as getCursorContext,hs as getIntelliSenseInfo,ds as isLegacyFormat,ps as isModelDrivenFormat,ms as isUnifiedFormat,$r as parseToPosition,us as processJsonMapping,cr as resolveScope,Ur as splitQueries,Fr as toLegacyMapping,Yb as transformDatabaseResult,cs as unifyJsonMapping,as as validateModelDrivenMapping}; diff --git a/packages/core/src/parsers/CreateTableParser.ts b/packages/core/src/parsers/CreateTableParser.ts index b8e0075..dba98ca 100644 --- a/packages/core/src/parsers/CreateTableParser.ts +++ b/packages/core/src/parsers/CreateTableParser.ts @@ -473,12 +473,20 @@ export class CreateTableParser { if (value === "unique" || value === "unique key") { idx++; + let inlineKeyName: IdentifierString | undefined; + if (idx < lexemes.length && + lexemes[idx].value !== "(" && + !(lexemes[idx].type & TokenType.Command)) { + const inlineNameResult = this.parseQualifiedName(lexemes, idx); + inlineKeyName = inlineNameResult.name; + idx = inlineNameResult.newIndex; + } const { identifiers, newIndex } = this.parseIdentifierList(lexemes, idx); idx = newIndex; return { value: new TableConstraintDefinition({ kind: "unique", - constraintName, + constraintName: constraintName ?? inlineKeyName, columns: identifiers }), newIndex: idx @@ -487,6 +495,14 @@ export class CreateTableParser { if (value === "foreign key") { idx++; + let inlineKeyName: IdentifierString | undefined; + if (idx < lexemes.length && + lexemes[idx].value !== "(" && + !(lexemes[idx].type & TokenType.Command)) { + const inlineNameResult = this.parseQualifiedName(lexemes, idx); + inlineKeyName = inlineNameResult.name; + idx = inlineNameResult.newIndex; + } const { identifiers, newIndex } = this.parseIdentifierList(lexemes, idx); idx = newIndex; const referenceResult = this.parseReferenceDefinition(lexemes, idx); @@ -494,7 +510,7 @@ export class CreateTableParser { return { value: new TableConstraintDefinition({ kind: "foreign-key", - constraintName, + constraintName: constraintName ?? inlineKeyName, columns: identifiers, reference: referenceResult.value, deferrable: referenceResult.value.deferrable, diff --git a/packages/core/src/parsers/SqlPrintTokenParser.ts b/packages/core/src/parsers/SqlPrintTokenParser.ts index 5dc4df4..3ea2b72 100644 --- a/packages/core/src/parsers/SqlPrintTokenParser.ts +++ b/packages/core/src/parsers/SqlPrintTokenParser.ts @@ -66,6 +66,8 @@ export enum ParameterStyle { export type CastStyle = 'postgres' | 'standard'; +export type ConstraintStyle = 'postgres' | 'mysql'; + export interface FormatterConfig { identifierEscape?: { start: string; @@ -78,6 +80,8 @@ export interface FormatterConfig { parameterStyle?: ParameterStyle; /** Controls how CAST expressions are rendered */ castStyle?: CastStyle; + /** Controls how table/column constraints are rendered */ + constraintStyle?: ConstraintStyle; } export const PRESETS: Record = { @@ -85,38 +89,45 @@ export const PRESETS: Record = { identifierEscape: { start: '`', end: '`' }, parameterSymbol: '?', parameterStyle: ParameterStyle.Anonymous, + constraintStyle: 'mysql', }, postgres: { identifierEscape: { start: '"', end: '"' }, parameterSymbol: '$', parameterStyle: ParameterStyle.Indexed, castStyle: 'postgres', + constraintStyle: 'postgres', }, postgresWithNamedParams: { identifierEscape: { start: '"', end: '"' }, parameterSymbol: ':', parameterStyle: ParameterStyle.Named, castStyle: 'postgres', + constraintStyle: 'postgres', }, sqlserver: { identifierEscape: { start: '[', end: ']' }, parameterSymbol: '@', parameterStyle: ParameterStyle.Named, + constraintStyle: 'postgres', }, sqlite: { identifierEscape: { start: '"', end: '"' }, parameterSymbol: ':', parameterStyle: ParameterStyle.Named, + constraintStyle: 'postgres', }, oracle: { identifierEscape: { start: '"', end: '"' }, parameterSymbol: ':', parameterStyle: ParameterStyle.Named, + constraintStyle: 'postgres', }, clickhouse: { identifierEscape: { start: '`', end: '`' }, parameterSymbol: '?', parameterStyle: ParameterStyle.Anonymous, + constraintStyle: 'postgres', }, firebird: { identifierEscape: { start: '"', end: '"' }, @@ -226,13 +237,15 @@ export class SqlPrintTokenParser implements SqlComponentVisitor { identifierDecorator: IdentifierDecorator; index: number = 1; private castStyle: CastStyle; + private constraintStyle: ConstraintStyle; constructor(options?: { preset?: FormatterConfig, identifierEscape?: { start: string; end: string }, parameterSymbol?: string | { start: string; end: string }, parameterStyle?: 'anonymous' | 'indexed' | 'named', - castStyle?: CastStyle + castStyle?: CastStyle, + constraintStyle?: ConstraintStyle, }) { if (options?.preset) { const preset = options.preset @@ -251,6 +264,7 @@ export class SqlPrintTokenParser implements SqlComponentVisitor { }); this.castStyle = options?.castStyle ?? 'standard'; + this.constraintStyle = options?.constraintStyle ?? 'postgres'; this.handlers.set(ValueList.kind, (expr) => this.visitValueList(expr as ValueList)); this.handlers.set(ColumnReference.kind, (expr) => this.visitColumnReference(expr as ColumnReference)); @@ -2809,7 +2823,11 @@ export class SqlPrintTokenParser implements SqlComponentVisitor { token.innerTokens.push(SqlPrintTokenParser.PAREN_CLOSE_TOKEN); }; - if (arg.constraintName) { + const useMysqlConstraintStyle = this.constraintStyle === 'mysql'; + const inlineNameKinds = new Set(['primary-key', 'unique', 'foreign-key']); + const shouldInlineConstraintName = useMysqlConstraintStyle && !!arg.constraintName && inlineNameKinds.has(arg.kind); + + if (arg.constraintName && !shouldInlineConstraintName) { appendKeyword('constraint'); token.innerTokens.push(SqlPrintTokenParser.SPACE_TOKEN); token.innerTokens.push(arg.constraintName.accept(this)); @@ -2818,14 +2836,30 @@ export class SqlPrintTokenParser implements SqlComponentVisitor { switch (arg.kind) { case 'primary-key': appendKeyword('primary key'); + if (shouldInlineConstraintName && arg.constraintName) { + token.innerTokens.push(SqlPrintTokenParser.SPACE_TOKEN); + token.innerTokens.push(arg.constraintName.accept(this)); + } appendColumns(arg.columns ?? []); break; case 'unique': - appendKeyword('unique'); + if (useMysqlConstraintStyle) { + appendKeyword('unique key'); + if (shouldInlineConstraintName && arg.constraintName) { + token.innerTokens.push(SqlPrintTokenParser.SPACE_TOKEN); + token.innerTokens.push(arg.constraintName.accept(this)); + } + } else { + appendKeyword('unique'); + } appendColumns(arg.columns ?? []); break; case 'foreign-key': appendKeyword('foreign key'); + if (shouldInlineConstraintName && arg.constraintName) { + token.innerTokens.push(SqlPrintTokenParser.SPACE_TOKEN); + token.innerTokens.push(arg.constraintName.accept(this)); + } appendColumns(arg.columns ?? []); if (arg.reference) { token.innerTokens.push(SqlPrintTokenParser.SPACE_TOKEN); diff --git a/packages/core/src/transformers/SqlFormatter.ts b/packages/core/src/transformers/SqlFormatter.ts index 8004e6d..0b126da 100644 --- a/packages/core/src/transformers/SqlFormatter.ts +++ b/packages/core/src/transformers/SqlFormatter.ts @@ -1,4 +1,4 @@ -import { SqlPrintTokenParser, FormatterConfig, PRESETS, CastStyle } from '../parsers/SqlPrintTokenParser'; +import { SqlPrintTokenParser, FormatterConfig, PRESETS, CastStyle, ConstraintStyle } from '../parsers/SqlPrintTokenParser'; import { SqlPrinter, CommaBreakStyle, AndBreakStyle, OrBreakStyle } from './SqlPrinter'; import { IndentCharOption, NewlineOption } from './LinePrinter'; // Import types for compatibility import { IdentifierEscapeOption, resolveIdentifierEscapeOption } from './FormatOptionResolver'; @@ -100,6 +100,8 @@ export interface SqlFormatterOptions extends BaseFormattingOptions { parameterStyle?: 'anonymous' | 'indexed' | 'named'; /** Preferred CAST rendering style */ castStyle?: CastStyle; + /** Constraint rendering style (affects CREATE TABLE constraint layout) */ + constraintStyle?: ConstraintStyle; } /** @@ -136,8 +138,18 @@ export class SqlFormatter { castStyle: options.castStyle ?? presetConfig?.castStyle, }; - this.parser = new SqlPrintTokenParser({ + const constraintStyle: ConstraintStyle = + options.constraintStyle ?? + presetConfig?.constraintStyle ?? + 'postgres'; + + const parserConfig = { ...parserOptions, + constraintStyle, + }; + + this.parser = new SqlPrintTokenParser({ + ...parserConfig, }); this.printer = new SqlPrinter({ ...options, diff --git a/packages/core/src/transformers/SqlPrinter.ts b/packages/core/src/transformers/SqlPrinter.ts index b31a7f4..5925839 100644 --- a/packages/core/src/transformers/SqlPrinter.ts +++ b/packages/core/src/transformers/SqlPrinter.ts @@ -8,6 +8,10 @@ import { CommaBreakStyle as HelperCommaBreakStyle, } from "./OnelineFormattingHelper"; +const CREATE_TABLE_SINGLE_PAREN_KEYWORDS = new Set(['unique', 'check', 'key', 'index']); +const CREATE_TABLE_MULTI_PAREN_KEYWORDS = new Set(['primary key', 'foreign key', 'unique key']); +const CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER = new Set(['references']); + /** * CommaBreakStyle determines how commas are placed in formatted SQL output. * - 'none': No line break for commas @@ -319,6 +323,10 @@ export class SqlPrinter { for (let i = 0; i < token.innerTokens.length; i++) { const child = token.innerTokens[i]; const nextChild = token.innerTokens[i + 1]; + const previousEntry = this.findPreviousSignificantToken(token.innerTokens, i); + const previousChild = previousEntry?.token; + const priorEntry = previousEntry ? this.findPreviousSignificantToken(token.innerTokens, previousEntry.index) : undefined; + const priorChild = priorEntry?.token; if (child.type === SqlPrintTokenType.space) { if (this.shouldConvertSpaceToClauseBreak(token.containerType, nextChild)) { @@ -327,7 +335,7 @@ export class SqlPrinter { } continue; } - this.handleSpaceToken(child, token.containerType, nextChild); + this.handleSpaceToken(child, token.containerType, nextChild, previousChild, priorChild); continue; } @@ -660,7 +668,13 @@ export class SqlPrinter { * Handles space tokens with context-aware filtering. * Skips spaces in CommentBlocks when in specific CTE modes to prevent duplication. */ - private handleSpaceToken(token: SqlPrintToken, parentContainerType?: SqlPrintTokenContainerType, nextToken?: SqlPrintToken): void { + private handleSpaceToken( + token: SqlPrintToken, + parentContainerType?: SqlPrintTokenContainerType, + nextToken?: SqlPrintToken, + previousToken?: SqlPrintToken, + priorToken?: SqlPrintToken, + ): void { if (this.smartCommentBlockBuilder && this.smartCommentBlockBuilder.mode === 'line') { this.flushSmartCommentBlockBuilder(); } @@ -675,9 +689,127 @@ export class SqlPrinter { } return; } + // Skip redundant spaces before structural parentheses in CREATE TABLE DDL. + if (this.shouldSkipSpaceBeforeParenthesis(parentContainerType, nextToken, previousToken, priorToken)) { + return; + } this.linePrinter.appendText(token.text); } + private findPreviousSignificantToken(tokens: SqlPrintToken[], index: number): { token: SqlPrintToken; index: number } | undefined { + for (let i = index - 1; i >= 0; i--) { + const candidate = tokens[i]; + if (candidate.type === SqlPrintTokenType.space || candidate.type === SqlPrintTokenType.commentNewline) { + continue; + } + if (candidate.type === SqlPrintTokenType.comment && !this.exportComment) { + continue; + } + return { token: candidate, index: i }; + } + return undefined; + } + + private shouldSkipSpaceBeforeParenthesis( + parentContainerType?: SqlPrintTokenContainerType, + nextToken?: SqlPrintToken, + previousToken?: SqlPrintToken, + priorToken?: SqlPrintToken, + ): boolean { + if (!nextToken || nextToken.type !== SqlPrintTokenType.parenthesis || nextToken.text !== '(') { + return false; + } + if (!parentContainerType || !this.isCreateTableSpacingContext(parentContainerType)) { + return false; + } + if (!previousToken) { + return false; + } + + if (this.isCreateTableNameToken(previousToken, parentContainerType)) { + return true; + } + + if (this.isCreateTableConstraintKeyword(previousToken, parentContainerType)) { + return true; + } + + if (priorToken && this.isCreateTableConstraintKeyword(priorToken, parentContainerType)) { + if (this.isIdentifierAttachedToConstraint(previousToken, priorToken, parentContainerType)) { + return true; + } + } + + return false; + } + + private isCreateTableSpacingContext(parentContainerType: SqlPrintTokenContainerType): boolean { + switch (parentContainerType) { + case SqlPrintTokenContainerType.CreateTableQuery: + case SqlPrintTokenContainerType.CreateTableDefinition: + case SqlPrintTokenContainerType.TableConstraintDefinition: + case SqlPrintTokenContainerType.ColumnConstraintDefinition: + case SqlPrintTokenContainerType.ReferenceDefinition: + return true; + default: + return false; + } + } + + private isCreateTableNameToken(previousToken: SqlPrintToken, parentContainerType: SqlPrintTokenContainerType): boolean { + if (parentContainerType !== SqlPrintTokenContainerType.CreateTableQuery) { + return false; + } + + return previousToken.containerType === SqlPrintTokenContainerType.QualifiedName; + } + + private isCreateTableConstraintKeyword(token: SqlPrintToken, parentContainerType: SqlPrintTokenContainerType): boolean { + if (token.type !== SqlPrintTokenType.keyword) { + return false; + } + + const text = token.text.toLowerCase(); + if (parentContainerType === SqlPrintTokenContainerType.ReferenceDefinition) { + return CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER.has(text); + } + + if (CREATE_TABLE_SINGLE_PAREN_KEYWORDS.has(text)) { + return true; + } + if (CREATE_TABLE_MULTI_PAREN_KEYWORDS.has(text)) { + return true; + } + + return false; + } + + private isIdentifierAttachedToConstraint( + token: SqlPrintToken, + keywordToken: SqlPrintToken, + parentContainerType: SqlPrintTokenContainerType, + ): boolean { + if (!token) { + return false; + } + + if (parentContainerType === SqlPrintTokenContainerType.ReferenceDefinition) { + return token.containerType === SqlPrintTokenContainerType.QualifiedName && + CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER.has(keywordToken.text.toLowerCase()); + } + + if (parentContainerType === SqlPrintTokenContainerType.TableConstraintDefinition || + parentContainerType === SqlPrintTokenContainerType.ColumnConstraintDefinition) { + const normalized = keywordToken.text.toLowerCase(); + if (CREATE_TABLE_SINGLE_PAREN_KEYWORDS.has(normalized) || + CREATE_TABLE_MULTI_PAREN_KEYWORDS.has(normalized)) { + return token.containerType === SqlPrintTokenContainerType.IdentifierString; + } + } + + return false; + } + private printCommentToken(text: string, level: number, parentContainerType?: SqlPrintTokenContainerType): void { const trimmed = text.trim(); if (!trimmed) { diff --git a/packages/core/tests/parsers/CreateTableParser.test.ts b/packages/core/tests/parsers/CreateTableParser.test.ts index a5f8bb3..205c880 100644 --- a/packages/core/tests/parsers/CreateTableParser.test.ts +++ b/packages/core/tests/parsers/CreateTableParser.test.ts @@ -92,7 +92,7 @@ describe("CreateTableParser", () => { expect(referenceConstraint?.reference?.onDelete).toBe("cascade"); expect(formatted).toContain('create table "public"."users"'); - expect(formatted).toContain('foreign key ("role_id") references "auth"."roles"("id") deferrable initially deferred'); + expect(formatted).toContain('foreign key("role_id") references "auth"."roles"("id") deferrable initially deferred'); expect(formatted).toContain('with (fillfactor = 80)'); }); }); diff --git a/packages/core/tests/parsers/DDLParsers.test.ts b/packages/core/tests/parsers/DDLParsers.test.ts index 44d36fc..4878398 100644 --- a/packages/core/tests/parsers/DDLParsers.test.ts +++ b/packages/core/tests/parsers/DDLParsers.test.ts @@ -81,7 +81,7 @@ WHERE active = true`; const dropAction = ast.actions[2] as AlterTableDropConstraint; expect(dropAction.ifExists).toBe(true); expect(dropAction.behavior).toBe("cascade"); - expect(formatted).toContain('alter table if exists only "public"."users" add constraint "users_email_key" unique ("email"),'); + expect(formatted).toContain('alter table if exists only "public"."users" add constraint "users_email_key" unique("email"),'); expect(formatted).toContain('drop constraint if exists "users_old_fk" cascade'); }); diff --git a/packages/core/tests/transformers/SqlFormatter.create-table-spacing.test.ts b/packages/core/tests/transformers/SqlFormatter.create-table-spacing.test.ts new file mode 100644 index 0000000..2cc9c38 --- /dev/null +++ b/packages/core/tests/transformers/SqlFormatter.create-table-spacing.test.ts @@ -0,0 +1,106 @@ +import { describe, it, expect } from 'vitest'; +import { CreateTableParser } from '../../src/parsers/CreateTableParser'; +import { SqlFormatter } from '../../src/transformers/SqlFormatter'; + +describe('SqlFormatter CREATE TABLE spacing', () => { + it('omits spaces before parentheses for table name and constraint keywords', () => { + const sql = [ + 'CREATE TABLE public.child_table (', + ' child_id serial4 NOT NULL', + ' , child_name VARCHAR(100) NOT NULL', + ' , CONSTRAINT child_table_pkey PRIMARY KEY (child_id)', + ' , CONSTRAINT child_table_name_unique UNIQUE (child_name)', + ' , CONSTRAINT child_table_value_check CHECK (child_id > 0)', + ')', + ].join('\n'); + + const ast = CreateTableParser.parse(sql); + const formatter = new SqlFormatter({ + indentChar: ' ', + indentSize: 4, + newline: '\n', + keywordCase: 'lower', + commaBreak: 'before', + identifierEscape: 'none', + }); + + const { formattedSql } = formatter.format(ast); + + const expected = [ + 'create table public.child_table(', + ' child_id serial4 not null', + ' , child_name varchar(100) not null', + ' , constraint child_table_pkey primary key(child_id)', + ' , constraint child_table_name_unique unique(child_name)', + ' , constraint child_table_value_check check(child_id > 0)', + ')', + ].join('\n'); + + expect(formattedSql).toBe(expected); + }); + + it('omits spaces before parentheses for foreign key references', () => { + const sql = [ + 'CREATE TABLE public.order_item (', + ' item_id serial4 NOT NULL', + ' , order_id int4 NOT NULL', + ' , CONSTRAINT order_item_fk FOREIGN KEY (order_id) REFERENCES public.order (order_id)', + ')', + ].join('\n'); + + const ast = CreateTableParser.parse(sql); + const formatter = new SqlFormatter({ + indentChar: ' ', + indentSize: 4, + newline: '\n', + keywordCase: 'lower', + commaBreak: 'before', + identifierEscape: 'none', + }); + + const { formattedSql } = formatter.format(ast); + + const expected = [ + 'create table public.order_item(', + ' item_id serial4 not null', + ' , order_id int4 not null', + ' , constraint order_item_fk foreign key(order_id) references public.order(order_id)', + ')', + ].join('\n'); + + expect(formattedSql).toBe(expected); + }); + + it('handles MySQL-style constraint names without extra spaces before parentheses', () => { + const sql = [ + 'CREATE TABLE t (', + ' id int NOT NULL', + ' , UNIQUE KEY uk (id)', + ' , FOREIGN KEY fk (id) REFERENCES parent (pid)', + ')', + ].join('\n'); + + const ast = CreateTableParser.parse(sql); + const formatter = new SqlFormatter({ + indentChar: ' ', + indentSize: 4, + newline: '\n', + keywordCase: 'lower', + commaBreak: 'before', + identifierEscape: 'none', + constraintStyle: 'mysql', + }); + + const { formattedSql } = formatter.format(ast); + + const expected = [ + 'create table t(', + ' id int not null', + ' , unique key uk(id)', + ' , foreign key fk(id) references parent(pid)', + ')', + ].join('\n'); + + expect(formattedSql).toBe(expected); + }); +});