rawsql-ts 0.11.44-beta → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/esm/index.min.js +9 -9
  2. package/dist/esm/index.min.js.map +3 -3
  3. package/dist/esm/src/models/DDLStatements.d.ts +38 -0
  4. package/dist/esm/src/models/DDLStatements.js +61 -1
  5. package/dist/esm/src/models/DDLStatements.js.map +1 -1
  6. package/dist/esm/src/models/SqlPrintToken.d.ts +3 -0
  7. package/dist/esm/src/models/SqlPrintToken.js +3 -0
  8. package/dist/esm/src/models/SqlPrintToken.js.map +1 -1
  9. package/dist/esm/src/parsers/AnalyzeStatementParser.d.ts +13 -0
  10. package/dist/esm/src/parsers/AnalyzeStatementParser.js +90 -0
  11. package/dist/esm/src/parsers/AnalyzeStatementParser.js.map +1 -0
  12. package/dist/esm/src/parsers/ExplainStatementParser.d.ts +23 -0
  13. package/dist/esm/src/parsers/ExplainStatementParser.js +185 -0
  14. package/dist/esm/src/parsers/ExplainStatementParser.js.map +1 -0
  15. package/dist/esm/src/parsers/ParenExpressionParser.js +25 -0
  16. package/dist/esm/src/parsers/ParenExpressionParser.js.map +1 -1
  17. package/dist/esm/src/parsers/SqlParser.d.ts +4 -2
  18. package/dist/esm/src/parsers/SqlParser.js +56 -0
  19. package/dist/esm/src/parsers/SqlParser.js.map +1 -1
  20. package/dist/esm/src/parsers/SqlPrintTokenParser.d.ts +8 -0
  21. package/dist/esm/src/parsers/SqlPrintTokenParser.js +131 -7
  22. package/dist/esm/src/parsers/SqlPrintTokenParser.js.map +1 -1
  23. package/dist/esm/src/tokenReaders/CommandTokenReader.js +1 -0
  24. package/dist/esm/src/tokenReaders/CommandTokenReader.js.map +1 -1
  25. package/dist/esm/src/transformers/OnelineFormattingHelper.js +7 -0
  26. package/dist/esm/src/transformers/OnelineFormattingHelper.js.map +1 -1
  27. package/dist/esm/src/transformers/SqlPrinter.d.ts +1 -0
  28. package/dist/esm/src/transformers/SqlPrinter.js +29 -1
  29. package/dist/esm/src/transformers/SqlPrinter.js.map +1 -1
  30. package/dist/esm/tsconfig.browser.tsbuildinfo +1 -1
  31. package/dist/index.min.js +9 -9
  32. package/dist/index.min.js.map +3 -3
  33. package/dist/src/models/DDLStatements.d.ts +38 -0
  34. package/dist/src/models/DDLStatements.js +64 -1
  35. package/dist/src/models/DDLStatements.js.map +1 -1
  36. package/dist/src/models/SqlPrintToken.d.ts +3 -0
  37. package/dist/src/models/SqlPrintToken.js +3 -0
  38. package/dist/src/models/SqlPrintToken.js.map +1 -1
  39. package/dist/src/parsers/AnalyzeStatementParser.d.ts +13 -0
  40. package/dist/src/parsers/AnalyzeStatementParser.js +94 -0
  41. package/dist/src/parsers/AnalyzeStatementParser.js.map +1 -0
  42. package/dist/src/parsers/ExplainStatementParser.d.ts +23 -0
  43. package/dist/src/parsers/ExplainStatementParser.js +189 -0
  44. package/dist/src/parsers/ExplainStatementParser.js.map +1 -0
  45. package/dist/src/parsers/ParenExpressionParser.js +25 -0
  46. package/dist/src/parsers/ParenExpressionParser.js.map +1 -1
  47. package/dist/src/parsers/SqlParser.d.ts +4 -2
  48. package/dist/src/parsers/SqlParser.js +56 -0
  49. package/dist/src/parsers/SqlParser.js.map +1 -1
  50. package/dist/src/parsers/SqlPrintTokenParser.d.ts +8 -0
  51. package/dist/src/parsers/SqlPrintTokenParser.js +130 -6
  52. package/dist/src/parsers/SqlPrintTokenParser.js.map +1 -1
  53. package/dist/src/tokenReaders/CommandTokenReader.js +1 -0
  54. package/dist/src/tokenReaders/CommandTokenReader.js.map +1 -1
  55. package/dist/src/transformers/OnelineFormattingHelper.js +7 -0
  56. package/dist/src/transformers/OnelineFormattingHelper.js.map +1 -1
  57. package/dist/src/transformers/SqlPrinter.d.ts +1 -0
  58. package/dist/src/transformers/SqlPrinter.js +29 -1
  59. package/dist/src/transformers/SqlPrinter.js.map +1 -1
  60. package/dist/tsconfig.tsbuildinfo +1 -1
  61. package/package.json +3 -3
@@ -1,35 +1,35 @@
1
1
  var TokenType=(TokenType2=>(TokenType2[TokenType2.None=0]="None",TokenType2[TokenType2.Literal=1]="Literal",TokenType2[TokenType2.Operator=2]="Operator",TokenType2[TokenType2.OpenParen=4]="OpenParen",TokenType2[TokenType2.CloseParen=8]="CloseParen",TokenType2[TokenType2.Comma=16]="Comma",TokenType2[TokenType2.Dot=32]="Dot",TokenType2[TokenType2.Identifier=64]="Identifier",TokenType2[TokenType2.Command=128]="Command",TokenType2[TokenType2.Parameter=256]="Parameter",TokenType2[TokenType2.OpenBracket=512]="OpenBracket",TokenType2[TokenType2.CloseBracket=1024]="CloseBracket",TokenType2[TokenType2.Function=2048]="Function",TokenType2[TokenType2.StringSpecifier=4096]="StringSpecifier",TokenType2[TokenType2.Type=8192]="Type",TokenType2))(TokenType||{});var CharLookupTable=class{static isWhitespace(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code===32||code===9||code===10||code===13}static isDigit(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code>=48&&code<=57}static isHexChar(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code>=48&&code<=57||code>=97&&code<=102||code>=65&&code<=70}static isOperatorSymbol(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code===43||code===45||code===42||code===47||code===37||code===126||code===64||code===35||code===94||code===38||code===58||code===33||code===60||code===62||code===61||code===124||code===63}static isDelimiter(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code===46||code===44||code===40||code===41||code===91||code===93||code===123||code===125||code===59||code===32||code===9||code===10||code===13?!0:code===43||code===45||code===42||code===47||code===37||code===126||code===64||code===35||code===94||code===38||code===58||code===33||code===60||code===62||code===61||code===124||code===63}static isNamedParameterPrefix(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code===64||code===58||code===36}};var StringUtils=class _StringUtils{static getDebugPositionInfo(input,errPosition){let start=Math.max(0,errPosition-5),end=Math.min(input.length,errPosition+5),debugInfo=input.slice(start,end),caret=" ".repeat(errPosition-start)+"^";return`${debugInfo}
2
2
  ${caret}`}static skipWhiteSpace(input,position){let length=input.length;for(;position+4<=length&&input.slice(position,position+4)===" ";)position+=4;for(;position<length;){let charCode=input.charCodeAt(position);if(charCode!==32&&charCode!==9&&charCode!==10&&charCode!==13)break;position++}return position}static readLineComment(input,position){if(position+1>=input.length)return{newPosition:position,comment:null};if(input.charCodeAt(position)===45&&input.charCodeAt(position+1)===45){let start=position;for(position+=2;position<input.length&&input.charCodeAt(position)!==10;)position++;let comment=input.slice(start+2,position).trim();return{newPosition:position,comment}}return{newPosition:position,comment:null}}static readBlockComment(input,position){if(position+1>=input.length)return{newPosition:position,comments:null};if(input.charCodeAt(position)!==47||input.charCodeAt(position+1)!==42)return{newPosition:position,comments:null};if(position+2<input.length&&input.charCodeAt(position+2)===43)return{newPosition:position,comments:null};let start=position;for(position+=2;position+1<input.length;){if(input.charCodeAt(position)===42&&input.charCodeAt(position+1)===47){position+=2;let processedLines=this.processBlockCommentContent(input.slice(start+2,position-2));return{newPosition:position,comments:processedLines}}position++}let processedLinesUnterminated=this.processBlockCommentContent(input.slice(start+2));return{newPosition:input.length,comments:processedLinesUnterminated}}static processBlockCommentContent(rawContent){let rawLines=rawContent.replace(/\r/g,"").split(`
3
3
  `),processedLines=[];for(let rawLine of rawLines){let trimmedLine=rawLine.trim(),isSeparatorLine=/^\s*[-=_+*#]+\s*$/.test(rawLine);trimmedLine!==""||isSeparatorLine?processedLines.push(isSeparatorLine?rawLine.trim():trimmedLine):processedLines.push("")}for(;processedLines.length>0&&processedLines[0]==="";)processedLines.shift();for(;processedLines.length>0&&processedLines[processedLines.length-1]==="";)processedLines.pop();return processedLines}static readWhiteSpaceAndComment(input,position){let lines=null,length=input.length;for(;position<length;){let oldPosition=position;if(position=_StringUtils.skipWhiteSpace(input,position),position!==oldPosition)continue;let charCode=input.charCodeAt(position);if(charCode===45){let lineCommentResult=_StringUtils.readLineComment(input,position);if(lineCommentResult.newPosition!==position){position=lineCommentResult.newPosition,lineCommentResult.comment&&(lines===null&&(lines=[]),lines.push(lineCommentResult.comment.trim()));continue}}else if(charCode===47){let blockCommentResult=_StringUtils.readBlockComment(input,position);if(blockCommentResult.newPosition!==position){position=blockCommentResult.newPosition,blockCommentResult.comments&&(lines===null&&(lines=[]),lines.push(...blockCommentResult.comments));continue}}break}return{position,lines}}static readRegularIdentifier(input,position){let result=this.tryReadRegularIdentifier(input,position);if(!result)throw new Error(`Unexpected character. position: ${position}
4
- ${_StringUtils.getDebugPositionInfo(input,position)}`);return result}static tryReadRegularIdentifier(input,position){let start=position;for(;position<input.length&&!CharLookupTable.isDelimiter(input[position]);)position++;if(start===position)return null;for(;position+1<input.length&&input[position]==="["&&input[position+1]==="]";){let beforeIdentifier=input.slice(0,start).trim();if(beforeIdentifier===""||/[)]$/.test(beforeIdentifier)||/\b(select|from|where|and|or|set|values|insert|update|delete)\s*$/i.test(beforeIdentifier))break;position+=2}return{identifier:input.slice(start,position),newPosition:position}}};var BaseTokenReader=class{constructor(input,position=0){this.input=input,this.position=position}getPosition(){return this.position}setPosition(position){this.position=position}isEndOfInput(shift=0){return this.position+shift>=this.input.length}canRead(shift=0){return!this.isEndOfInput(shift)}read(expectChar){if(this.isEndOfInput())throw new Error(`Unexpected character. expect: ${expectChar}, actual: EndOfInput, position: ${this.position}`);let char=this.input[this.position];if(char!==expectChar)throw new Error(`Unexpected character. expect: ${expectChar}, actual: ${char}, position: ${this.position}`);return this.position++,char}createLexeme(type,value,comments=null,startPosition,endPosition){let lexeme={type,value:type===128||type===2||type===2048?value.toLowerCase():value,comments};return startPosition!==void 0&&endPosition!==void 0&&(lexeme.position={startPosition,endPosition}),lexeme}createLexemeWithPosition(type,value,startPos,comments=null){return this.createLexeme(type,value,comments,startPos,startPos+value.length)}getDebugPositionInfo(errPosition){return StringUtils.getDebugPositionInfo(this.input,errPosition)}};var KeywordParser=class{constructor(trie5){this.trie=trie5}isEndOfInput(input,position,shift=0){return position+shift>=input.length}canParse(input,position,shift=0){return!this.isEndOfInput(input,position,shift)}parse(input,position){if(this.isEndOfInput(input,position))return null;this.trie.reset();let result=StringUtils.tryReadRegularIdentifier(input,position);if(result===null)return null;let matchResult=this.trie.pushLexeme(result.identifier.toLowerCase());if(matchResult===0)return null;if(matchResult===3)return{keyword:result.identifier,newPosition:result.newPosition};let lexeme=result.identifier,commentResult=StringUtils.readWhiteSpaceAndComment(input,result.newPosition);position=commentResult.position;let collectedComments=commentResult.lines?[...commentResult.lines]:[];if(this.isEndOfInput(input,position))return matchResult===2?{keyword:lexeme,newPosition:position,comments:collectedComments.length>0?collectedComments:void 0}:null;for(;this.canParse(input,position);){let previousMatchResult=matchResult,result2=StringUtils.tryReadRegularIdentifier(input,position);if(result2!==null){if(matchResult=this.trie.pushLexeme(result2.identifier.toLowerCase()),matchResult===0){if(previousMatchResult===2)break;return null}lexeme+=" "+result2.identifier;let nextCommentResult=StringUtils.readWhiteSpaceAndComment(input,result2.newPosition);if(position=nextCommentResult.position,nextCommentResult.lines&&nextCommentResult.lines.length>0&&collectedComments.push(...nextCommentResult.lines),matchResult===3)break}else{if(previousMatchResult===2)break;return null}}return{keyword:lexeme,newPosition:position,comments:collectedComments.length>0?collectedComments:void 0}}};var KeywordTrie=class{constructor(keywords2){this.root=new Map;this.hasEndProperty=!1;this.hasMoreProperties=!1;for(let keyword of keywords2)this.addKeyword(keyword);this.currentNode=this.root}addKeyword(keyword){let node=this.root;for(let word of keyword)node.has(word)||node.set(word,new Map),node=node.get(word);node.set("__end__",!0)}reset(){this.currentNode=this.root,this.hasEndProperty=!1,this.hasMoreProperties=!1}pushLexeme(lexeme){return this.currentNode.has(lexeme)?(this.currentNode=this.currentNode.get(lexeme),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 joinTrie=new KeywordTrie([["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"]]),keywordTrie=new KeywordTrie([["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"]]),keywordParser=new KeywordParser(keywordTrie),joinkeywordParser=new KeywordParser(joinTrie);var CommandTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let keywordJoin=joinkeywordParser.parse(this.input,this.position);if(keywordJoin!==null)return this.position=keywordJoin.newPosition,this.createLexeme(128,keywordJoin.keyword);let keyword=keywordParser.parse(this.input,this.position);if(keyword!==null){this.position=keyword.newPosition;let lexeme=this.createLexeme(128,keyword.keyword,keyword.comments);return keyword.comments&&keyword.comments.length>0&&(lexeme.positionedComments=[{position:"after",comments:keyword.comments}]),lexeme}if(this.canRead(2)&&this.input[this.position]==="/"&&this.input[this.position+1]==="*"&&this.input[this.position+2]==="+"){this.position+=3;let start=this.position;for(;this.position+1<this.input.length;){if(this.input[this.position]==="*"&&this.input[this.position+1]==="/")return this.position+=2,this.createLexeme(128,"/*+ "+this.input.slice(start,this.position-2).trim()+" */");this.position++}throw new Error(`Block comment is not closed. position: ${this.position}`)}return null}};var EscapedIdentifierTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(char==="`"){let identifier=this.readEscapedIdentifier("`");return this.createLexeme(64,identifier)}if(char==='"'){let identifier=this.readEscapedIdentifier('"');return this.createLexeme(64,identifier)}if(char==="["&&this.isSqlServerBracketIdentifier(previous)){let identifier=this.readEscapedIdentifier("]");return this.createLexeme(64,identifier)}return null}isSqlServerBracketIdentifier(previous){if(previous?.value==="array")return!1;let start=this.position+1,pos=start;for(;pos<this.input.length&&this.input[pos]!=="]";){let char=this.input[pos];if(char===":"||char===","||char==="+"||char==="-"||char==="*"||char==="/"||char==="("||char===")")return!1;pos++}if(pos>=this.input.length)return!1;let content=this.input.slice(start,pos).trim();return content===""?!1:/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$/.test(content)}readEscapedIdentifier(delimiter){let start=this.position;this.position++;let foundClosing=!1;for(;this.canRead();){if(this.input[this.position]===delimiter){foundClosing=!0;break}this.position++}if(!foundClosing)throw new Error(`Closing delimiter is not found. position: ${start}, delimiter: ${delimiter}
4
+ ${_StringUtils.getDebugPositionInfo(input,position)}`);return result}static tryReadRegularIdentifier(input,position){let start=position;for(;position<input.length&&!CharLookupTable.isDelimiter(input[position]);)position++;if(start===position)return null;for(;position+1<input.length&&input[position]==="["&&input[position+1]==="]";){let beforeIdentifier=input.slice(0,start).trim();if(beforeIdentifier===""||/[)]$/.test(beforeIdentifier)||/\b(select|from|where|and|or|set|values|insert|update|delete)\s*$/i.test(beforeIdentifier))break;position+=2}return{identifier:input.slice(start,position),newPosition:position}}};var BaseTokenReader=class{constructor(input,position=0){this.input=input,this.position=position}getPosition(){return this.position}setPosition(position){this.position=position}isEndOfInput(shift=0){return this.position+shift>=this.input.length}canRead(shift=0){return!this.isEndOfInput(shift)}read(expectChar){if(this.isEndOfInput())throw new Error(`Unexpected character. expect: ${expectChar}, actual: EndOfInput, position: ${this.position}`);let char=this.input[this.position];if(char!==expectChar)throw new Error(`Unexpected character. expect: ${expectChar}, actual: ${char}, position: ${this.position}`);return this.position++,char}createLexeme(type,value,comments=null,startPosition,endPosition){let lexeme={type,value:type===128||type===2||type===2048?value.toLowerCase():value,comments};return startPosition!==void 0&&endPosition!==void 0&&(lexeme.position={startPosition,endPosition}),lexeme}createLexemeWithPosition(type,value,startPos,comments=null){return this.createLexeme(type,value,comments,startPos,startPos+value.length)}getDebugPositionInfo(errPosition){return StringUtils.getDebugPositionInfo(this.input,errPosition)}};var KeywordParser=class{constructor(trie5){this.trie=trie5}isEndOfInput(input,position,shift=0){return position+shift>=input.length}canParse(input,position,shift=0){return!this.isEndOfInput(input,position,shift)}parse(input,position){if(this.isEndOfInput(input,position))return null;this.trie.reset();let result=StringUtils.tryReadRegularIdentifier(input,position);if(result===null)return null;let matchResult=this.trie.pushLexeme(result.identifier.toLowerCase());if(matchResult===0)return null;if(matchResult===3)return{keyword:result.identifier,newPosition:result.newPosition};let lexeme=result.identifier,commentResult=StringUtils.readWhiteSpaceAndComment(input,result.newPosition);position=commentResult.position;let collectedComments=commentResult.lines?[...commentResult.lines]:[];if(this.isEndOfInput(input,position))return matchResult===2?{keyword:lexeme,newPosition:position,comments:collectedComments.length>0?collectedComments:void 0}:null;for(;this.canParse(input,position);){let previousMatchResult=matchResult,result2=StringUtils.tryReadRegularIdentifier(input,position);if(result2!==null){if(matchResult=this.trie.pushLexeme(result2.identifier.toLowerCase()),matchResult===0){if(previousMatchResult===2)break;return null}lexeme+=" "+result2.identifier;let nextCommentResult=StringUtils.readWhiteSpaceAndComment(input,result2.newPosition);if(position=nextCommentResult.position,nextCommentResult.lines&&nextCommentResult.lines.length>0&&collectedComments.push(...nextCommentResult.lines),matchResult===3)break}else{if(previousMatchResult===2)break;return null}}return{keyword:lexeme,newPosition:position,comments:collectedComments.length>0?collectedComments:void 0}}};var KeywordTrie=class{constructor(keywords2){this.root=new Map;this.hasEndProperty=!1;this.hasMoreProperties=!1;for(let keyword of keywords2)this.addKeyword(keyword);this.currentNode=this.root}addKeyword(keyword){let node=this.root;for(let word of keyword)node.has(word)||node.set(word,new Map),node=node.get(word);node.set("__end__",!0)}reset(){this.currentNode=this.root,this.hasEndProperty=!1,this.hasMoreProperties=!1}pushLexeme(lexeme){return this.currentNode.has(lexeme)?(this.currentNode=this.currentNode.get(lexeme),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 joinTrie=new KeywordTrie([["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"]]),keywordTrie=new KeywordTrie([["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"],["analyze"],["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"]]),keywordParser=new KeywordParser(keywordTrie),joinkeywordParser=new KeywordParser(joinTrie);var CommandTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let keywordJoin=joinkeywordParser.parse(this.input,this.position);if(keywordJoin!==null)return this.position=keywordJoin.newPosition,this.createLexeme(128,keywordJoin.keyword);let keyword=keywordParser.parse(this.input,this.position);if(keyword!==null){this.position=keyword.newPosition;let lexeme=this.createLexeme(128,keyword.keyword,keyword.comments);return keyword.comments&&keyword.comments.length>0&&(lexeme.positionedComments=[{position:"after",comments:keyword.comments}]),lexeme}if(this.canRead(2)&&this.input[this.position]==="/"&&this.input[this.position+1]==="*"&&this.input[this.position+2]==="+"){this.position+=3;let start=this.position;for(;this.position+1<this.input.length;){if(this.input[this.position]==="*"&&this.input[this.position+1]==="/")return this.position+=2,this.createLexeme(128,"/*+ "+this.input.slice(start,this.position-2).trim()+" */");this.position++}throw new Error(`Block comment is not closed. position: ${this.position}`)}return null}};var EscapedIdentifierTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(char==="`"){let identifier=this.readEscapedIdentifier("`");return this.createLexeme(64,identifier)}if(char==='"'){let identifier=this.readEscapedIdentifier('"');return this.createLexeme(64,identifier)}if(char==="["&&this.isSqlServerBracketIdentifier(previous)){let identifier=this.readEscapedIdentifier("]");return this.createLexeme(64,identifier)}return null}isSqlServerBracketIdentifier(previous){if(previous?.value==="array")return!1;let start=this.position+1,pos=start;for(;pos<this.input.length&&this.input[pos]!=="]";){let char=this.input[pos];if(char===":"||char===","||char==="+"||char==="-"||char==="*"||char==="/"||char==="("||char===")")return!1;pos++}if(pos>=this.input.length)return!1;let content=this.input.slice(start,pos).trim();return content===""?!1:/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$/.test(content)}readEscapedIdentifier(delimiter){let start=this.position;this.position++;let foundClosing=!1;for(;this.canRead();){if(this.input[this.position]===delimiter){foundClosing=!0;break}this.position++}if(!foundClosing)throw new Error(`Closing delimiter is not found. position: ${start}, delimiter: ${delimiter}
5
5
  ${this.getDebugPositionInfo(start)}`);if(start===this.position)throw new Error(`Closing delimiter is not found. position: ${start}, delimiter: ${delimiter}
6
6
  ${this.getDebugPositionInfo(start)}`);return this.position++,this.input.slice(start+1,this.position-1)}};var trie=new KeywordTrie([["grouping","sets"],["array"]]),keywordParser2=new KeywordParser(trie),FunctionTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let keyword=keywordParser2.parse(this.input,this.position);if(keyword!==null)return this.position=keyword.newPosition,this.createLexeme(2048,keyword.keyword);let result=StringUtils.tryReadRegularIdentifier(this.input,this.position);if(!result)return null;this.position=result.newPosition;var shift=StringUtils.readWhiteSpaceAndComment(this.input,this.position).position-this.position;return this.canRead(shift)&&this.input[this.position+shift]==="("?this.createLexeme(2048,result.identifier):null}};var IdentifierTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(char==="*")return this.position++,this.createLexeme(64,char);let result=StringUtils.readRegularIdentifier(this.input,this.position);return this.position=result.newPosition,this.createLexeme(64,result.identifier)}};var keywords=[["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"]],trie2=new KeywordTrie(keywords),literalKeywordParser=new KeywordParser(trie2),LiteralTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(char==="'"){let value=this.readSingleQuotedString();return this.createLexeme(1,value)}let keyword=this.tryReadKeyword();if(keyword)return keyword;if(char==="."&&this.canRead(1)&&CharLookupTable.isDigit(this.input[this.position+1]))return this.createLexeme(1,this.readDigit());if(CharLookupTable.isDigit(char))return this.createLexeme(1,this.readDigit());if(char==="$"&&this.isDollarQuotedString())return this.createLexeme(1,this.readDollarQuotedString());if(char==="$"&&this.canRead(1)&&CharLookupTable.isDigit(this.input[this.position+1])){let pos=this.position+1,hasDecimalOrComma=!1;for(;pos<this.input.length&&(CharLookupTable.isDigit(this.input[pos])||this.input[pos]===","||this.input[pos]===".");){if(this.input[pos]==="."||this.input[pos]===","){hasDecimalOrComma=!0;break}pos++}if(hasDecimalOrComma){this.position++;let numberPart=this.readMoneyDigit();return this.createLexeme(1,"$"+numberPart)}}if((char==="+"||char==="-")&&this.determineSignOrOperator(previous)==="sign"){let sign=char;this.position++;let pos=this.position;for(;this.canRead()&&CharLookupTable.isWhitespace(this.input[this.position]);)this.position++;if(this.canRead()&&(CharLookupTable.isDigit(this.input[this.position])||this.input[this.position]==="."&&this.canRead(1)&&CharLookupTable.isDigit(this.input[this.position+1])))return this.createLexeme(1,sign==="-"?sign+this.readDigit():this.readDigit());this.position=pos-1}return null}tryReadKeyword(){let result=literalKeywordParser.parse(this.input,this.position);return result?(this.position=result.newPosition,this.createLexeme(1,result.keyword)):null}determineSignOrOperator(previous){if(previous===null)return"sign";let operatorContextFlags=9545;return(previous.type&operatorContextFlags)!==0?"operator":"sign"}readDigit(){let start=this.position,hasDot=!1,hasExponent=!1;if(this.canRead(1)&&this.input[this.position]==="0"&&"xbo".includes(this.input[this.position+1].toLowerCase())){let prefixType=this.input[this.position+1].toLowerCase();this.position+=2;let isHex=prefixType==="x";for(;this.canRead();){let c=this.input[this.position];if(CharLookupTable.isDigit(c)||isHex&&CharLookupTable.isHexChar(c))this.position++;else break}return this.input.slice(start,this.position)}for(this.input[start]==="."&&(hasDot=!0,this.position++);this.canRead();){let char=this.input[this.position];if(char==="."&&!hasDot)hasDot=!0;else if((char==="e"||char==="E")&&!hasExponent)hasExponent=!0,this.canRead(1)&&(this.input[this.position+1]==="+"||this.input[this.position+1]==="-")&&this.position++;else if(!CharLookupTable.isDigit(char))break;this.position++}if(start===this.position)throw new Error(`Unexpected character. position: ${start}
7
7
  ${this.getDebugPositionInfo(start)}`);return this.input[start]==="."?"0"+this.input.slice(start,this.position):this.input.slice(start,this.position)}readMoneyDigit(){let start=this.position,hasDot=!1;for(;this.canRead();){let char=this.input[this.position];if(char==="."&&!hasDot)hasDot=!0;else if(!(char===","&&!hasDot)){if(!CharLookupTable.isDigit(char))break}this.position++}if(start===this.position)throw new Error(`Unexpected character. position: ${start}
8
8
  ${this.getDebugPositionInfo(start)}`);return this.input.slice(start,this.position)}readSingleQuotedString(){let start=this.position,closed=!1;for(this.read("'");this.canRead();){let char=this.input[this.position];if(this.position++,char==="\\"&&this.canRead(1)){this.position++;continue}else if(char==="'"){closed=!0;break}}if(closed===!1)throw new Error(`Single quote is not closed. position: ${start}
9
9
  ${this.getDebugPositionInfo(start)}`);return this.input.slice(start,this.position)}isDollarQuotedString(){if(!this.canRead(1))return!1;if(this.input[this.position+1]==="$")return!0;let pos=this.position+1;for(;pos<this.input.length;){let char=this.input[pos];if(char==="$")return!0;if(!this.isAlphanumeric(char)&&char!=="_")return!1;pos++}return!1}readDollarQuotedString(){let start=this.position;this.position++;let tag="";for(;this.canRead()&&this.input[this.position]!=="$";)tag+=this.input[this.position],this.position++;if(!this.canRead())throw new Error(`Unexpected end of input while reading dollar-quoted string tag at position ${start}`);this.position++;let openingTag="$"+tag+"$",closingTag=openingTag,content="";for(;this.canRead();){if(this.input.substring(this.position,this.position+closingTag.length)===closingTag)return this.position+=closingTag.length,openingTag+content+closingTag;content+=this.input[this.position],this.position++}throw new Error(`Unclosed dollar-quoted string starting at position ${start}. Expected closing tag: ${closingTag}`)}isAlphanumeric(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122}};var trie3=new KeywordTrie([["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"]]),operatorOrTypeTrie=new KeywordTrie([["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"]]),keywordParser3=new KeywordParser(trie3),operatorOrTypeParser=new KeywordParser(operatorOrTypeTrie);var OperatorTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(CharLookupTable.isOperatorSymbol(char)){let start=this.position;for(;this.canRead()&&CharLookupTable.isOperatorSymbol(this.input[this.position])&&(this.position++,!!this.canRead());){let previous2=this.input[this.position-1],next=this.input[this.position];if(previous2==="-"&&next==="-"||previous2==="/"&&next==="*")break}this.position===start&&this.position++;let resut=this.input.slice(start,this.position);return this.createLexeme(2,resut)}let result=operatorOrTypeParser.parse(this.input,this.position);if(result!==null){this.position=result.newPosition;let lexeme=this.createLexeme(8258,result.keyword);return result.comments&&result.comments.length>0&&(lexeme.positionedComments=[...lexeme.positionedComments??[],{position:"after",comments:[...result.comments]}]),lexeme}return result=keywordParser3.parse(this.input,this.position),result!==null?(this.position=result.newPosition,this.createLexeme(2,result.keyword)):null}};var ParameterTokenReader=class extends BaseTokenReader{constructor(input){super(input)}tryRead(previous){if(this.isEndOfInput())return null;if(this.canRead(1)&&this.input[this.position]==="$"&&this.input[this.position+1]==="{"){this.position+=2;let start=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 ${start}`);let identifier=this.input.slice(start,this.position);if(identifier.length===0)throw new Error("Empty parameter name is not allowed: found ${} at position "+(start-2));return this.position++,this.createLexeme(256,"${"+identifier+"}")}let char=this.input[this.position];if(CharLookupTable.isNamedParameterPrefix(char)){if(this.canRead(1)&&CharLookupTable.isOperatorSymbol(this.input[this.position+1])||char===":"&&this.isInArraySliceContext()||char==="$"&&this.isDollarQuotedString())return null;if(char==="$"&&this.canRead(1)&&CharLookupTable.isDigit(this.input[this.position+1])){let pos=this.position+1,hasDecimalOrComma=!1;for(;pos<this.input.length&&(CharLookupTable.isDigit(this.input[pos])||this.input[pos]===","||this.input[pos]===".");){if(this.input[pos]==="."||this.input[pos]===","){hasDecimalOrComma=!0;break}pos++}if(hasDecimalOrComma)return null}this.position++;let start=this.position;for(;this.canRead()&&!CharLookupTable.isDelimiter(this.input[this.position]);)this.position++;let identifier=this.input.slice(start,this.position);return this.createLexeme(256,char+identifier)}if(char==="?"){if(this.canRead(1)){let nextChar=this.input[this.position+1];if(nextChar==="|"||nextChar==="&")return null}return previous&&(previous.type&64||previous.type&1)?null:(this.position++,this.createLexeme(256,char))}return null}isInArraySliceContext(){let pos=this.position-1,bracketDepth=0,parenDepth=0;for(;pos>=0;){let char=this.input[pos];if(char==="]")bracketDepth++;else if(char==="["){if(bracketDepth--,bracketDepth<0){if(pos>0){let prevChar=this.input[pos-1];if(/[a-zA-Z0-9_)\]]/.test(prevChar))return!0}if(pos===0)return!1;break}}else char===")"?parenDepth++:char==="("&&parenDepth--;pos--}return!1}isDollarQuotedString(){if(!this.canRead(1))return!1;if(this.input[this.position+1]==="$")return!0;let pos=this.position+1;for(;pos<this.input.length;){let char=this.input[pos];if(char==="$")return!0;if(!this.isAlphanumeric(char)&&char!=="_")return!1;pos++}return!1}isAlphanumeric(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122}};var SpecialSymbolTokenReader=class _SpecialSymbolTokenReader extends BaseTokenReader{static{this.SPECIAL_SYMBOL_TOKENS={".":32,",":16,"(":4,")":8,"[":512,"]":1024}}tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];return char in _SpecialSymbolTokenReader.SPECIAL_SYMBOL_TOKENS?(this.position++,this.createLexeme(_SpecialSymbolTokenReader.SPECIAL_SYMBOL_TOKENS[char],char)):null}};var STRING_SPECIFIERS=new Set(["e'","E'","x'","X'","b'","B'"]),UNICODE_STRING_SPECIFIERS=new Set(["u&'","U&'"]),StringSpecifierTokenReader=class extends BaseTokenReader{tryRead(previous){let start=this.position;return this.canRead(1)&&STRING_SPECIFIERS.has(this.input.slice(start,start+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(start,this.position))):this.canRead(2)&&UNICODE_STRING_SPECIFIERS.has(this.input.slice(start,start+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(start,this.position))):null}};var TokenReaderManager=class{constructor(input,position=0){this.cacheHits=0;this.cacheMisses=0;this.input=input,this.position=position,this.readers=[],this.tokenCache=new Map}register(reader){return this.readers.push(reader),this}registerAll(readers){return readers.forEach(reader=>this.register(reader)),this}setPosition(position){this.position=position;for(let reader of this.readers)reader.setPosition(position)}tryRead(position,previous){if(this.tokenCache.has(position))return this.cacheHits++,this.tokenCache.get(position)||null;this.cacheMisses++,this.setPosition(position);let lexeme=null;for(let reader of this.readers)if(lexeme=reader.tryRead(previous),lexeme){this.position=reader.getPosition();break}for(let reader of this.readers)reader.setPosition(this.position);return this.tokenCache.set(position,lexeme),lexeme}getMaxPosition(){let maxPosition=this.position;for(let reader of this.readers){let position=reader.getPosition();position>maxPosition&&(maxPosition=position)}return maxPosition}getInput(){return this.input}getCacheStats(){let total=this.cacheHits+this.cacheMisses,ratio=total>0?this.cacheHits/total:0;return{hits:this.cacheHits,misses:this.cacheMisses,ratio}}};var trie4=new KeywordTrie([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),typeParser=new KeywordParser(trie4),TypeTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let keyword=typeParser.parse(this.input,this.position);if(keyword!==null){this.position=keyword.newPosition;let lexeme=this.createLexeme(8192,keyword.keyword);if(keyword.comments&&keyword.comments.length>0){let existing=lexeme.positionedComments??[];lexeme.positionedComments=[...existing,{position:"after",comments:[...keyword.comments]}]}return lexeme}if(previous===null)return null;let result=StringUtils.tryReadRegularIdentifier(this.input,this.position);return result?(this.position=result.newPosition,previous.type&128&&previous.value==="as"?this.createLexeme(8256,result.identifier):previous.type&2&&previous.value==="::"?this.createLexeme(8192,result.identifier):null):null}};var SqlTokenizer=class _SqlTokenizer{constructor(input){this.lineStartPositions=null;this.input=input,this.position=0,this.readerManager=new TokenReaderManager(input).register(new EscapedIdentifierTokenReader(input)).register(new ParameterTokenReader(input)).register(new StringSpecifierTokenReader(input)).register(new LiteralTokenReader(input)).register(new SpecialSymbolTokenReader(input)).register(new CommandTokenReader(input)).register(new OperatorTokenReader(input)).register(new TypeTokenReader(input)).register(new FunctionTokenReader(input)).register(new IdentifierTokenReader(input))}isEndOfInput(shift=0){return this.position+shift>=this.input.length}canRead(shift=0){return!this.isEndOfInput(shift)}tokenize(options){return options?.preserveFormatting?this.tokenizeWithFormatting():new _SqlTokenizer(this.input).readLexemes()}readLexmes(){return this.readLexemes()}readLexemes(){let segment=this.readNextStatement(0);return segment?segment.lexemes:[]}tokenizeBasic(){let segment=this.readNextStatement(0);return segment?segment.lexemes:[]}readNextStatement(startPosition=0,carryComments=null){let length=this.input.length;if(startPosition>=length)return null;this.position=startPosition;let statementStart=startPosition,pendingLeading=carryComments?[...carryComments]:null,tokenData=[],previous=null;for(;this.canRead();){let prefixComment=this.readComment();if(this.position=prefixComment.position,!this.canRead()){pendingLeading=this.mergeComments(pendingLeading,prefixComment.lines);break}if(this.input[this.position]===";"){pendingLeading=this.mergeComments(pendingLeading,prefixComment.lines);break}let lexeme=this.readerManager.tryRead(this.position,previous);if(lexeme===null)throw new Error(`Unexpected character. actual: ${this.input[this.position]}, position: ${this.position}
10
- ${this.getDebugPositionInfo(this.position)}`);let tokenStartPos=this.position,tokenEndPos=this.position=this.readerManager.getMaxPosition(),suffixComment=this.readComment();this.position=suffixComment.position;let prefixComments=this.mergeComments(pendingLeading,prefixComment.lines);pendingLeading=null,tokenData.push({lexeme,startPos:tokenStartPos,endPos:tokenEndPos,prefixComments,suffixComments:suffixComment.lines}),previous=lexeme}let statementEnd=this.position,lexemes=this.buildLexemesFromTokenData(tokenData),nextPosition=this.skipPastTerminator(statementEnd);return{lexemes,statementStart,statementEnd,nextPosition,rawText:this.input.slice(statementStart,statementEnd),leadingComments:pendingLeading}}buildLexemesFromTokenData(tokenData){let lexemes=new Array(tokenData.length);for(let i=0;i<tokenData.length;i++){let current=tokenData[i],lexeme=current.lexeme;if(lexeme.value.toLowerCase()==="select"&&current.suffixComments&&current.suffixComments.length>0){let suffixComments=current.suffixComments,targetIndex=i+1;for(;targetIndex<tokenData.length;){let target=tokenData[targetIndex],isStarOperator=target.lexeme.type&2&&target.lexeme.value==="*";if(target.lexeme.type&64||target.lexeme.type&1||isStarOperator||!(target.lexeme.type&128)&&!(target.lexeme.type&16)&&!(target.lexeme.type&2)){target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null;break}targetIndex++}}if(lexeme.value.toLowerCase()==="from"&&current.suffixComments&&current.suffixComments.length>0){let suffixComments=current.suffixComments,targetIndex=i+1;for(;targetIndex<tokenData.length;){let target=tokenData[targetIndex];if(!((target.lexeme.type&128)!==0)){target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null;break}targetIndex++}}if(lexeme.type&16&&current.suffixComments&&current.suffixComments.length>0){let suffixComments=current.suffixComments,targetIndex=i+1;if(targetIndex<tokenData.length){let target=tokenData[targetIndex];target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null}}if((lexeme.value.toLowerCase()==="union"||lexeme.value.toLowerCase()==="intersect"||lexeme.value.toLowerCase()==="except")&&current.suffixComments&&current.suffixComments.length>0){let suffixComments=current.suffixComments,targetIndex=i+1;for(;targetIndex<tokenData.length;){let target=tokenData[targetIndex];if(target.lexeme.value.toLowerCase()==="select"){target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null;break}targetIndex++}}this.attachCommentsToLexeme(lexeme,current),lexeme.position={startPosition:current.startPos,endPosition:current.endPos,...this.getLineColumnInfo(current.startPos,current.endPos)},lexemes[i]=lexeme}return lexemes}skipPastTerminator(position){let next=position;return next<this.input.length&&this.input[next]===";"&&next++,this.skipWhitespaceAndComments(next)}mergeComments(base,addition){return addition&&addition.length>0?!base||base.length===0?[...addition]:[...base,...addition]:base?[...base]:null}attachCommentsToLexeme(lexeme,tokenData){let newPositionedComments=[],allLegacyComments=[];lexeme.positionedComments&&lexeme.positionedComments.length>0&&newPositionedComments.push(...lexeme.positionedComments),tokenData.prefixComments&&tokenData.prefixComments.length>0&&(allLegacyComments.push(...tokenData.prefixComments),newPositionedComments.push({position:"before",comments:[...tokenData.prefixComments]})),tokenData.suffixComments&&tokenData.suffixComments.length>0&&(allLegacyComments.push(...tokenData.suffixComments),newPositionedComments.push({position:"after",comments:[...tokenData.suffixComments]})),newPositionedComments.length>0?(lexeme.positionedComments=newPositionedComments,lexeme.comments=null):allLegacyComments.length>0?(lexeme.comments=allLegacyComments,lexeme.positionedComments=void 0):(lexeme.comments=null,lexeme.positionedComments=void 0)}readComment(){return StringUtils.readWhiteSpaceAndComment(this.input,this.position)}getDebugPositionInfo(errPosition){return StringUtils.getDebugPositionInfo(this.input,errPosition)}tokenizeWithFormatting(){let regularLexemes=this.tokenizeBasic();return this.mapToFormattingLexemes(regularLexemes)}mapToFormattingLexemes(regularLexemes){if(regularLexemes.length===0)return[];let lexemePositions=[],searchPos=0;for(let lexeme of regularLexemes){searchPos=this.skipWhitespaceAndComments(searchPos);let lexemeInfo=this.findLexemeAtPosition(lexeme,searchPos);if(lexemeInfo)lexemePositions.push(lexemeInfo),searchPos=lexemeInfo.endPosition;else{let fallbackInfo={startPosition:searchPos,endPosition:searchPos+lexeme.value.length};lexemePositions.push(fallbackInfo),searchPos=fallbackInfo.endPosition}}let formattingLexemes=[];for(let i=0;i<regularLexemes.length;i++){let lexeme=regularLexemes[i],lexemeInfo=lexemePositions[i],nextLexemeStartPos=i<regularLexemes.length-1?lexemePositions[i+1].startPosition:this.input.length,whitespaceSegment=this.input.slice(lexemeInfo.endPosition,nextLexemeStartPos),inlineComments=this.extractCommentsFromWhitespace(whitespaceSegment),formattingLexeme={...lexeme,followingWhitespace:whitespaceSegment,inlineComments,position:{startPosition:lexemeInfo.startPosition,endPosition:lexemeInfo.endPosition,...this.getLineColumnInfo(lexemeInfo.startPosition,lexemeInfo.endPosition)}};formattingLexemes.push(formattingLexeme)}return formattingLexemes}findLexemeAtPosition(lexeme,expectedPos){if(expectedPos>=this.input.length)return null;let valuesToTry=[lexeme.value,lexeme.value.toUpperCase(),lexeme.value.toLowerCase()];for(let valueToTry of valuesToTry)if(expectedPos+valueToTry.length<=this.input.length&&this.input.substring(expectedPos,expectedPos+valueToTry.length)===valueToTry&&this.isValidLexemeMatch(valueToTry,expectedPos))return{startPosition:expectedPos,endPosition:expectedPos+valueToTry.length};return null}isValidLexemeMatch(value,position){if(position>0){let charBefore=this.input[position-1];if(this.isAlphanumericUnderscore(charBefore))return!1}let endPosition=position+value.length;if(endPosition<this.input.length){let charAfter=this.input[endPosition];if(this.isAlphanumericUnderscore(charAfter))return!1}return!0}isAlphanumericUnderscore(char){let code=char.charCodeAt(0);return code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122||code===95}isWhitespace(char){let code=char.charCodeAt(0);return code===32||code===9||code===10||code===13}extractCommentsFromWhitespace(whitespaceSegment){let inlineComments=[],pos=0;for(;pos<whitespaceSegment.length;){let oldPos=pos,result=StringUtils.readWhiteSpaceAndComment(whitespaceSegment,pos),lines=result.lines;lines&&lines.length>0&&inlineComments.push(...lines),pos=result.position,pos===oldPos&&pos++}return inlineComments}skipWhitespaceAndComments(pos){return StringUtils.readWhiteSpaceAndComment(this.input,pos).position}getLineColumnInfo(startPos,endPos){let startInfo=this.getLineColumn(startPos),endInfo=this.getLineColumn(endPos);return{startLine:startInfo.line,startColumn:startInfo.column,endLine:endInfo.line,endColumn:endInfo.column}}getLineColumn(position){let starts=this.ensureLineStartPositions(),low=0,high=starts.length-1;for(;low<=high;){let mid=low+high>>>1;starts[mid]<=position?low=mid+1:high=mid-1}let lineIndex=high>=0?high:0,lineStart=starts[lineIndex];return{line:lineIndex+1,column:position-lineStart+1}}ensureLineStartPositions(){if(this.lineStartPositions)return this.lineStartPositions;let starts=[0];for(let i=0;i<this.input.length;i++)this.input.charCodeAt(i)===10&&starts.push(i+1);return this.lineStartPositions=starts,starts}};var SqlComponent=class{constructor(){this.comments=null;this.positionedComments=null}getKind(){return this.constructor.kind}accept(visitor){return visitor.visit(this)}toSqlString(formatter){return this.accept(formatter)}addPositionedComments(position,comments){if(!comments||comments.length===0)return;this.positionedComments||(this.positionedComments=[]);let existing=this.positionedComments.find(pc=>pc.position===position);existing?existing.comments.push(...comments):this.positionedComments.push({position,comments:[...comments]})}getPositionedComments(position){if(!this.positionedComments)return[];let positioned=this.positionedComments.find(pc=>pc.position===position);return positioned?positioned.comments:[]}getAllPositionedComments(){if(!this.positionedComments)return[];let result=[],beforeComments=this.getPositionedComments("before");result.push(...beforeComments);let afterComments=this.getPositionedComments("after");return result.push(...afterComments),result}},SqlDialectConfiguration=class{constructor(){this.parameterSymbol=":";this.identifierEscape={start:'"',end:'"'};this.exportComment="none"}};var InsertQuery=class extends SqlComponent{static{this.kind=Symbol("InsertQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.insertClause=params.insertClause,this.selectQuery=params.selectQuery??null,this.returningClause=params.returning??null}};var InlineQuery=class extends SqlComponent{static{this.kind=Symbol("InlineQuery")}constructor(selectQuery){super(),this.selectQuery=selectQuery}},ValueList=class extends SqlComponent{static{this.kind=Symbol("ValueList")}constructor(values){super(),this.values=values}},ColumnReference=class extends SqlComponent{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof IdentifierString?this.qualifiedName.name:new IdentifierString(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(namespaces,column){super();let col=typeof column=="string"?new IdentifierString(column):column;this.qualifiedName=new QualifiedName(toIdentifierStringArray(namespaces),col)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(namespace=>namespace.name).join("."):""}},FunctionCall=class extends SqlComponent{static{this.kind=Symbol("FunctionCall")}constructor(namespaces,name,argument,over,withinGroup=null,withOrdinality=!1,internalOrderBy=null){super(),this.qualifiedName=new QualifiedName(namespaces,name),this.argument=argument,this.over=over,this.withinGroup=withinGroup,this.withOrdinality=withOrdinality,this.internalOrderBy=internalOrderBy}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},WindowFrameType=(WindowFrameType2=>(WindowFrameType2.Rows="rows",WindowFrameType2.Range="range",WindowFrameType2.Groups="groups",WindowFrameType2))(WindowFrameType||{}),WindowFrameBound=(WindowFrameBound2=>(WindowFrameBound2.UnboundedPreceding="unbounded preceding",WindowFrameBound2.UnboundedFollowing="unbounded following",WindowFrameBound2.CurrentRow="current row",WindowFrameBound2))(WindowFrameBound||{}),WindowFrameBoundStatic=class extends SqlComponent{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(bound){super(),this.bound=bound}},WindowFrameBoundaryValue=class extends SqlComponent{static{this.kind=Symbol("WindowFrameBoundary")}constructor(value,isFollowing){super(),this.value=value,this.isFollowing=isFollowing}},WindowFrameSpec=class extends SqlComponent{static{this.kind=Symbol("WindowFrameSpec")}constructor(frameType,startBound,endBound){super(),this.frameType=frameType,this.startBound=startBound,this.endBound=endBound}},WindowFrameExpression=class extends SqlComponent{static{this.kind=Symbol("WindowFrameExpression")}constructor(partition,order,frameSpec=null){super(),this.partition=partition,this.order=order,this.frameSpec=frameSpec}},UnaryExpression=class extends SqlComponent{static{this.kind=Symbol("UnaryExpression")}constructor(operator,expression){super(),this.operator=new RawString(operator),this.expression=expression}},BinaryExpression=class extends SqlComponent{static{this.kind=Symbol("BinaryExpression")}constructor(left,operator,right){super(),this.left=left,this.operator=new RawString(operator),this.right=right}},LiteralValue=class extends SqlComponent{static{this.kind=Symbol("LiteralExpression")}constructor(value,_deprecated,isStringLiteral){super(),this.value=value,this.isStringLiteral=isStringLiteral}},ParameterExpression=class extends SqlComponent{static{this.kind=Symbol("ParameterExpression")}constructor(name,value=null){super(),this.name=new RawString(name),this.value=value,this.index=null}},SwitchCaseArgument=class extends SqlComponent{static{this.kind=Symbol("SwitchCaseArgument")}constructor(cases,elseValue=null){super(),this.cases=cases,this.elseValue=elseValue}},CaseKeyValuePair=class extends SqlComponent{static{this.kind=Symbol("CaseKeyValuePair")}constructor(key,value){super(),this.key=key,this.value=value}},RawString=class extends SqlComponent{static{this.kind=Symbol("RawString")}constructor(value){super(),this.value=value}},IdentifierString=class extends SqlComponent{static{this.kind=Symbol("IdentifierString")}constructor(alias){super(),this.name=alias}},ParenExpression=class extends SqlComponent{static{this.kind=Symbol("ParenExpression")}constructor(expression){super(),this.expression=expression}},CastExpression=class extends SqlComponent{static{this.kind=Symbol("CastExpression")}constructor(input,castType){super(),this.input=input,this.castType=castType}},CaseExpression=class extends SqlComponent{static{this.kind=Symbol("CaseExpression")}constructor(condition,switchCase){super(),this.condition=condition,this.switchCase=switchCase}},ArrayExpression=class extends SqlComponent{static{this.kind=Symbol("ArrayExpression")}constructor(expression){super(),this.expression=expression}},ArrayQueryExpression=class extends SqlComponent{static{this.kind=Symbol("ArrayQueryExpression")}constructor(query){super(),this.query=query}},BetweenExpression=class extends SqlComponent{static{this.kind=Symbol("BetweenExpression")}constructor(expression,lower,upper,negated){super(),this.expression=expression,this.lower=lower,this.upper=upper,this.negated=negated}},StringSpecifierExpression=class extends SqlComponent{static{this.kind=Symbol("StringSpecifierExpression")}constructor(specifier,value){super(),this.specifier=new RawString(specifier),this.value=new LiteralValue(value)}},TypeValue=class extends SqlComponent{static{this.kind=Symbol("TypeValue")}constructor(namespaces,name,argument=null){super(),this.qualifiedName=new QualifiedName(namespaces,name),this.argument=argument}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let nameValue=this.qualifiedName.name instanceof RawString?this.qualifiedName.name.value:this.qualifiedName.name.name;return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(ns=>ns.name).join(".")+"."+nameValue:nameValue}},TupleExpression=class extends SqlComponent{static{this.kind=Symbol("TupleExpression")}constructor(values){super(),this.values=values}},ArraySliceExpression=class extends SqlComponent{static{this.kind=Symbol("ArraySliceExpression")}constructor(array,startIndex,endIndex){super(),this.array=array,this.startIndex=startIndex,this.endIndex=endIndex}},ArrayIndexExpression=class extends SqlComponent{static{this.kind=Symbol("ArrayIndexExpression")}constructor(array,index){super(),this.array=array,this.index=index}};function toIdentifierStringArray(input){if(input==null)return null;if(typeof input=="string")return input.trim()===""?null:[new IdentifierString(input)];if(Array.isArray(input)){if(input.length===0)return null;if(typeof input[0]=="string"){let filteredStrings=input.filter(ns=>ns.trim()!=="");return filteredStrings.length===0?null:filteredStrings.map(ns=>new IdentifierString(ns))}else{let filteredIdentifiers=input.filter(ns=>ns.name.trim()!=="");return filteredIdentifiers.length===0?null:filteredIdentifiers}}return null}var QualifiedName=class extends SqlComponent{static{this.kind=Symbol("QualifiedName")}constructor(namespaces,name){super(),this.namespaces=toIdentifierStringArray(namespaces),typeof name=="string"?this.name=new RawString(name):this.name=name}toString(){let nameValue=this.name instanceof RawString?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(ns=>ns.name).join(".")+"."+nameValue:nameValue}};var SelectItem=class extends SqlComponent{static{this.kind=Symbol("SelectItem")}constructor(value,name=null){super(),this.value=value,this.identifier=name?new IdentifierString(name):null}},SelectClause=class extends SqlComponent{static{this.kind=Symbol("SelectClause")}constructor(items,distinct=null,hints=[]){super(),this.items=items,this.distinct=distinct,this.hints=hints}},Distinct=class extends SqlComponent{static{this.kind=Symbol("Distinct")}constructor(){super()}},DistinctOn=class extends SqlComponent{static{this.kind=Symbol("DistinctOn")}constructor(value){super(),this.value=value}},WhereClause=class extends SqlComponent{static{this.kind=Symbol("WhereClause")}constructor(condition){super(),this.condition=condition}},PartitionByClause=class extends SqlComponent{static{this.kind=Symbol("PartitionByClause")}constructor(value){super(),this.value=value}},WindowFrameClause=class extends SqlComponent{static{this.kind=Symbol("WindowFrameClause")}constructor(name,expression){super(),this.name=new IdentifierString(name),this.expression=expression}},WindowsClause=class extends SqlComponent{static{this.kind=Symbol("WindowsClause")}constructor(windows){super(),this.windows=windows}};var OrderByClause=class extends SqlComponent{static{this.kind=Symbol("OrderByClause")}constructor(items){super(),this.order=items}},OrderByItem=class extends SqlComponent{static{this.kind=Symbol("OrderByItem")}constructor(expression,sortDirection,nullsPosition){super(),this.value=expression,this.sortDirection=sortDirection===null?"asc":sortDirection,this.nullsPosition=nullsPosition}},GroupByClause=class extends SqlComponent{static{this.kind=Symbol("GroupByClause")}constructor(expression){super(),this.grouping=expression}},HavingClause=class extends SqlComponent{static{this.kind=Symbol("HavingClause")}constructor(condition){super(),this.condition=condition}},TableSource=class extends SqlComponent{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof IdentifierString?this.qualifiedName.name:new IdentifierString(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(namespaces,table){super();let tbl=typeof table=="string"?new IdentifierString(table):table;this.qualifiedName=new QualifiedName(namespaces,tbl)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(namespace=>namespace.name).join(".")+"."+(this.qualifiedName.name instanceof RawString?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof RawString?this.qualifiedName.name.value:this.qualifiedName.name.name}},FunctionSource=class extends SqlComponent{static{this.kind=Symbol("FunctionSource")}constructor(name,argument){if(super(),typeof name=="object"&&name!==null&&"name"in name){let nameObj=name;this.qualifiedName=new QualifiedName(nameObj.namespaces,nameObj.name)}else this.qualifiedName=new QualifiedName(null,name);this.argument=argument}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},ParenSource=class extends SqlComponent{static{this.kind=Symbol("ParenSource")}constructor(source){super(),this.source=source}},SubQuerySource=class extends SqlComponent{static{this.kind=Symbol("SubQuerySource")}constructor(query){super(),this.query=query}},SourceExpression=class extends SqlComponent{static{this.kind=Symbol("SourceExpression")}constructor(datasource,aliasExpression){super(),this.datasource=datasource,this.aliasExpression=aliasExpression}getAliasName(){return this.aliasExpression?this.aliasExpression.table.name:this.datasource instanceof TableSource?this.datasource.getSourceName():null}},JoinOnClause=class extends SqlComponent{static{this.kind=Symbol("JoinOnClause")}constructor(condition){super(),this.condition=condition}},JoinUsingClause=class extends SqlComponent{static{this.kind=Symbol("JoinUsingClause")}constructor(condition){super(),this.condition=condition}},JoinClause=class extends SqlComponent{static{this.kind=Symbol("JoinItem")}constructor(joinType,source,condition,lateral){super(),this.joinType=new RawString(joinType),this.source=source,this.condition=condition,this.lateral=lateral}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof TableSource?this.source.table.name:null}},FromClause=class extends SqlComponent{static{this.kind=Symbol("FromClause")}constructor(source,join){super(),this.source=source,this.joins=join}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof TableSource?this.source.datasource.table.name:null}getSources(){let sources=[this.source];if(this.joins)for(let join of this.joins)sources.push(join.source);return sources}},UsingClause=class extends SqlComponent{static{this.kind=Symbol("UsingClause")}constructor(sources){super(),this.sources=sources}getSources(){return[...this.sources]}},CommonTable=class extends SqlComponent{static{this.kind=Symbol("CommonTable")}constructor(query,aliasExpression,materialized){super(),this.query=query,this.materialized=materialized,typeof aliasExpression=="string"?this.aliasExpression=new SourceAliasExpression(aliasExpression,null):this.aliasExpression=aliasExpression}getSourceAliasName(){return this.aliasExpression.table.name}},WithClause=class extends SqlComponent{constructor(recursive,tables){super();this.trailingComments=null;this.globalComments=null;this.recursive=recursive,this.tables=tables}static{this.kind=Symbol("WithClause")}},LimitClause=class extends SqlComponent{static{this.kind=Symbol("LimitClause")}constructor(limit){super(),this.value=limit}};var OffsetClause=class extends SqlComponent{static{this.kind=Symbol("OffsetClause")}constructor(value){super(),this.value=value}},FetchClause=class extends SqlComponent{static{this.kind=Symbol("FetchClause")}constructor(expression){super(),this.expression=expression}},FetchExpression=class extends SqlComponent{static{this.kind=Symbol("FetchExpression")}constructor(type,count,unit){super(),this.type=type,this.count=count,this.unit=unit}};var ForClause=class extends SqlComponent{static{this.kind=Symbol("ForClause")}constructor(lockMode){super(),this.lockMode=lockMode}},SourceAliasExpression=class extends SqlComponent{static{this.kind=Symbol("SourceAliasExpression")}constructor(alias,columnAlias){super(),this.table=new IdentifierString(alias),this.columns=columnAlias!==null?columnAlias.map(alias2=>new IdentifierString(alias2)):null}},ReturningClause=class extends SqlComponent{static{this.kind=Symbol("ReturningClause")}constructor(columns){super(),this.columns=columns.map(col=>typeof col=="string"?new IdentifierString(col):col)}},SetClause=class extends SqlComponent{static{this.kind=Symbol("SetClause")}constructor(items){super(),this.items=items.map(item=>item instanceof SetClauseItem?item:new SetClauseItem(item.column,item.value))}},SetClauseItem=class extends SqlComponent{static{this.kind=Symbol("SetClauseItem")}constructor(column,value){if(super(),typeof column=="object"&&column!==null&&"column"in column){let colObj=column,col=typeof colObj.column=="string"?new IdentifierString(colObj.column):colObj.column;this.qualifiedName=new QualifiedName(colObj.namespaces,col)}else{let col=typeof column=="string"?new IdentifierString(column):column;this.qualifiedName=new QualifiedName(null,col)}this.value=value}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof IdentifierString?this.qualifiedName.name:new IdentifierString(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},UpdateClause=class extends SqlComponent{static{this.kind=Symbol("UpdateClause")}constructor(source){super(),this.source=source}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof TableSource?this.source.datasource.table.name:null}},DeleteClause=class extends SqlComponent{static{this.kind=Symbol("DeleteClause")}constructor(source){super(),this.source=source}getSourceAliasName(){return this.source.getAliasName()}},InsertClause=class extends SqlComponent{constructor(source,columns){super(),this.source=source,columns&&columns.length>0?this.columns=columns.map(col=>typeof col=="string"?new IdentifierString(col):col):this.columns=null}};var FullNameParser=class _FullNameParser{static parseFromLexeme(lexemes,index){let{identifiers,newIndex}=_FullNameParser.parseEscapedOrDotSeparatedIdentifiers(lexemes,index),{namespaces,name}=_FullNameParser.extractNamespacesAndName(identifiers),identifierString=new IdentifierString(name);if(newIndex>index){let lastLexeme=lexemes[newIndex-1];lastLexeme.positionedComments&&lastLexeme.positionedComments.length>0?identifierString.positionedComments=lastLexeme.positionedComments:lastLexeme.comments&&lastLexeme.comments.length>0}let lastTokenType=0;return newIndex>index&&(lastTokenType=lexemes[newIndex-1].type),{namespaces,name:identifierString,newIndex,lastTokenType}}static parse(str){let lexemes=new SqlTokenizer(str).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The name is complete but additional tokens were found.`);return{namespaces:result.namespaces,name:result.name}}static parseEscapedOrDotSeparatedIdentifiers(lexemes,index){let idx=index,identifiers=[];for(;idx<lexemes.length;){if(lexemes[idx].type&512){if(idx++,idx>=lexemes.length||!(lexemes[idx].type&64||lexemes[idx].type&128))throw new Error(`Expected identifier after '[' at position ${idx}`);if(identifiers.push(lexemes[idx].value),idx++,idx>=lexemes.length||lexemes[idx].value!=="]")throw new Error(`Expected closing ']' after identifier at position ${idx}`);idx++}else if(lexemes[idx].type&64)identifiers.push(lexemes[idx].value),idx++;else if(lexemes[idx].type&2048)identifiers.push(lexemes[idx].value),idx++;else if(lexemes[idx].type&8192)identifiers.push(lexemes[idx].value),idx++;else if(lexemes[idx].value==="*"){identifiers.push(lexemes[idx].value),idx++;break}if(idx<lexemes.length&&lexemes[idx].type&32)idx++;else break}return{identifiers,newIndex:idx}}static extractNamespacesAndName(identifiers){if(!identifiers||identifiers.length===0)throw new Error("Identifier list is empty");return identifiers.length===1?{namespaces:null,name:identifiers[0]}:{namespaces:identifiers.slice(0,-1),name:identifiers[identifiers.length-1]}}};var IdentifierParser=class{static parseFromLexeme(lexemes,index){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,index);return{value:new ColumnReference(namespaces,name),newIndex}}};var LiteralParser=class{static parseFromLexeme(lexemes,index){let idx=index,valueText=lexemes[idx].value,parsedValue,lex=literalKeywordParser.parse(valueText.toLowerCase(),0);if(lex){let value=new RawString(lex.keyword);return idx++,{value,newIndex:idx}}if(/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(valueText))return parsedValue=Number(valueText),idx++,{value:new LiteralValue(parsedValue),newIndex:idx};{/^\$[^$]*\$[\s\S]*\$[^$]*\$$/.test(valueText)?parsedValue=valueText:valueText.startsWith("'")&&valueText.endsWith("'")?parsedValue=valueText.slice(1,-1):parsedValue=valueText;let isStringLiteral=valueText.startsWith("'")&&valueText.endsWith("'");return idx++,{value:new LiteralValue(parsedValue,void 0,isStringLiteral),newIndex:idx}}}};var ParenExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(idx+1<lexemes.length&&lexemes[idx].type&4&&(lexemes[idx+1].value==="select"||lexemes[idx+1].value==="values"||lexemes[idx+1].value==="with")){let openLexeme=lexemes[idx],openPositionedComments=openLexeme.positionedComments?openLexeme.positionedComments.map(comment=>({position:comment.position,comments:[...comment.comments]})):null,openLegacyComments=openLexeme.comments?[...openLexeme.comments]:null;idx+=1;let result2=SelectQueryParser.parseFromLexeme(lexemes,idx);if(idx=result2.newIndex,idx>=lexemes.length||lexemes[idx].type!==8)throw new Error(`Expected ')' at index ${idx}, but found ${lexemes[idx].value}`);let closingLexeme=lexemes[idx],closingLegacyComments=closingLexeme.comments,closingPositionedComments=closingLexeme.positionedComments;idx++;let value2=new InlineQuery(result2.value);if(openPositionedComments&&openPositionedComments.length>0){let beforeComments=openPositionedComments.filter(comment=>comment.position==="after"&&comment.comments.length>0).map(comment=>({position:"before",comments:[...comment.comments]}));beforeComments.length>0&&(value2.positionedComments=value2.positionedComments?[...beforeComments,...value2.positionedComments]:beforeComments)}else if(openLegacyComments&&openLegacyComments.length>0){let beforeCommentBlock={position:"before",comments:[...openLegacyComments]};value2.positionedComments=value2.positionedComments?[beforeCommentBlock,...value2.positionedComments]:[beforeCommentBlock]}if(closingPositionedComments&&closingPositionedComments.length>0){let afterComments=closingPositionedComments.filter(comment=>comment.position==="after"&&comment.comments.length>0).map(comment=>({position:comment.position,comments:[...comment.comments]}));afterComments.length>0&&(value2.positionedComments=value2.positionedComments?[...value2.positionedComments,...afterComments]:afterComments)}else closingLegacyComments&&closingLegacyComments.length>0&&(value2.comments=closingLegacyComments);return{value:value2,newIndex:idx}}let result=ValueParser.parseArgument(4,8,lexemes,index);return idx=result.newIndex,{value:new ParenExpression(result.value),newIndex:idx}}};var UnaryExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&2){let operatorLexeme=lexemes[idx],operator=operatorLexeme.value;if(idx++,operator==="*")return{value:new ColumnReference(null,"*"),newIndex:idx};let result=ValueParser.parseFromLexeme(lexemes,idx);idx=result.newIndex;let value=new UnaryExpression(operator,result.value);return operatorLexeme.positionedComments&&operatorLexeme.positionedComments.length>0?value.positionedComments=operatorLexeme.positionedComments:operatorLexeme.comments&&operatorLexeme.comments.length>0&&(value.comments=operatorLexeme.comments),{value,newIndex:idx}}throw new Error(`Invalid unary expression at index ${index}: ${lexemes[index].value}`)}};var ParameterExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index,paramName=lexemes[idx].value;paramName.startsWith("${")&&paramName.endsWith("}")?paramName=paramName.slice(2,-1):paramName=paramName.slice(1);let value=new ParameterExpression(paramName);return idx++,{value,newIndex:idx}}};var StringSpecifierExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index,specifer=lexemes[idx].value;if(idx++,idx>=lexemes.length||lexemes[idx].type!==1)throw new Error(`Expected string literal after string specifier at index ${idx}`);let value=lexemes[idx].value;return idx++,{value:new StringSpecifierExpression(specifer,value),newIndex:idx}}};var CommandExpressionParser=class _CommandExpressionParser{static parseFromLexeme(lexemes,index){let idx=index,current=lexemes[idx];if(current.value==="case"){let caseKeywordComments=current.comments,caseKeywordPositionedComments=current.positionedComments;return idx++,this.parseCaseExpression(lexemes,idx,caseKeywordComments,caseKeywordPositionedComments)}else if(current.value==="case when"){let caseWhenKeywordComments=current.comments,caseWhenKeywordPositionedComments=current.positionedComments;return idx++,this.parseCaseWhenExpression(lexemes,idx,caseWhenKeywordComments,caseWhenKeywordPositionedComments)}return this.parseModifierUnaryExpression(lexemes,idx)}static parseModifierUnaryExpression(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&128){let command=lexemes[idx].value;idx++;let result=ValueParser.parseFromLexeme(lexemes,idx);return{value:new UnaryExpression(command,result.value),newIndex:result.newIndex}}throw new Error(`Invalid modifier unary expression at index ${idx}, Lexeme: ${lexemes[idx].value}`)}static parseCaseExpression(lexemes,index,caseKeywordComments,caseKeywordPositionedComments){let idx=index,condition=ValueParser.parseFromLexeme(lexemes,idx);idx=condition.newIndex;let switchCaseResult=this.parseSwitchCaseArgument(lexemes,idx,[]);idx=switchCaseResult.newIndex;let result=new CaseExpression(condition.value,switchCaseResult.value);return caseKeywordPositionedComments&&caseKeywordPositionedComments.length>0?result.positionedComments=caseKeywordPositionedComments:caseKeywordComments&&caseKeywordComments.length>0&&(result.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(caseKeywordComments,"before")]),{value:result,newIndex:idx}}static parseCaseWhenExpression(lexemes,index,caseWhenKeywordComments,caseWhenKeywordPositionedComments){let idx=index,casewhenResult=this.parseCaseConditionValuePair(lexemes,idx);idx=casewhenResult.newIndex;let caseWhenList=[casewhenResult.value],switchCaseResult=this.parseSwitchCaseArgument(lexemes,idx,caseWhenList);idx=switchCaseResult.newIndex;let result=new CaseExpression(null,switchCaseResult.value);return caseWhenKeywordPositionedComments&&caseWhenKeywordPositionedComments.length>0?result.positionedComments=caseWhenKeywordPositionedComments:caseWhenKeywordComments&&caseWhenKeywordComments.length>0&&(result.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(caseWhenKeywordComments,"before")]),{value:result,newIndex:idx}}static parseSwitchCaseArgument(lexemes,index,initialWhenThenList){let idx=index,whenThenList=[...initialWhenThenList];idx=this.parseAdditionalWhenClauses(lexemes,idx,whenThenList);let{elseValue,elseComments,newIndex:elseIndex}=this.parseElseClause(lexemes,idx);idx=elseIndex;let{endComments,newIndex:endIndex}=this.parseEndClause(lexemes,idx);if(idx=endIndex,whenThenList.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${idx})`);let switchCaseArg=new SwitchCaseArgument(whenThenList,elseValue);return this.applySwitchCaseComments(switchCaseArg,elseComments,endComments),{value:switchCaseArg,newIndex:idx}}static parseAdditionalWhenClauses(lexemes,index,whenThenList){let idx=index;for(;idx<lexemes.length&&this.isCommandWithValue(lexemes[idx],"when");){idx++;let whenResult=this.parseCaseConditionValuePair(lexemes,idx);idx=whenResult.newIndex,whenThenList.push(whenResult.value)}return idx}static parseElseClause(lexemes,index){let elseValue=null,elseComments=null,idx=index;if(idx<lexemes.length&&this.isCommandWithValue(lexemes[idx],"else")){elseComments=this.extractKeywordComments(lexemes[idx]),idx++;let elseResult=ValueParser.parseFromLexeme(lexemes,idx);elseValue=elseResult.value,idx=elseResult.newIndex}return{elseValue,elseComments,newIndex:idx}}static parseEndClause(lexemes,index){let idx=index,endComments=null;if(idx<lexemes.length&&this.isCommandWithValue(lexemes[idx],"end"))endComments=this.extractKeywordComments(lexemes[idx]),idx++;else throw new Error(`The CASE expression requires 'end' keyword at the end (index ${idx})`);return{endComments,newIndex:idx}}static extractKeywordComments(token){return{legacy:token.comments,positioned:token.positionedComments}}static applySwitchCaseComments(switchCaseArg,elseComments,endComments){let allPositionedComments=[],allLegacyComments=[];elseComments?.positioned&&elseComments.positioned.length>0&&allPositionedComments.push(...elseComments.positioned),elseComments?.legacy&&elseComments.legacy.length>0&&allLegacyComments.push(...elseComments.legacy),endComments?.positioned&&endComments.positioned.length>0&&allPositionedComments.push(...endComments.positioned),endComments?.legacy&&endComments.legacy.length>0&&allLegacyComments.push(...endComments.legacy),allPositionedComments.length>0?switchCaseArg.positionedComments=allPositionedComments:allLegacyComments.length>0&&(switchCaseArg.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(allLegacyComments,"after")])}static isCommandWithValue(lexeme,value){return(lexeme.type&128)!==0&&lexeme.value===value}static parseCaseConditionValuePair(lexemes,index){let idx=index,condition=ValueParser.parseFromLexeme(lexemes,idx);if(idx=condition.newIndex,idx>=lexemes.length||!(lexemes[idx].type&128)||lexemes[idx].value!=="then")throw new Error(`Expected 'then' after WHEN condition at index ${idx}`);let thenKeywordComments=lexemes[idx].comments,thenKeywordPositionedComments=lexemes[idx].positionedComments;idx++;let value=ValueParser.parseFromLexeme(lexemes,idx);idx=value.newIndex;let keyValuePair=new CaseKeyValuePair(condition.value,value.value);return thenKeywordPositionedComments&&thenKeywordPositionedComments.length>0?keyValuePair.positionedComments=thenKeywordPositionedComments:thenKeywordComments&&thenKeywordComments.length>0&&(keyValuePair.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(thenKeywordComments,"after")]),{value:keyValuePair,newIndex:idx}}static convertLegacyToPositioned(legacyComments,position="before"){return{position,comments:legacyComments}}};var OrderByClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The ORDER BY clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="order by")throw new Error(`Syntax error at position ${idx}: Expected 'ORDER BY' keyword but found "${lexemes[idx].value}". ORDER BY clauses must start with the ORDER BY keywords.`);idx++;let items=[],item=this.parseItem(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=this.parseItem(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No ordering expressions found. The ORDER BY clause requires at least one expression to order by.`);return{value:new OrderByClause(items),newIndex:idx}}static parseItem(lexemes,index){let idx=index,parsedValue=ValueParser.parseFromLexeme(lexemes,idx),value=parsedValue.value;if(idx=parsedValue.newIndex,idx>=lexemes.length)return{value,newIndex:idx};let sortDirectionComments=null,sortDirection=null;if(idx<lexemes.length){let token=lexemes[idx];if(token.value==="asc"?(sortDirection="asc",idx++):token.value==="desc"&&(sortDirection="desc",idx++),sortDirection!==null){if(token.positionedComments&&token.positionedComments.length>0){sortDirectionComments=[];for(let posComment of token.positionedComments)posComment.comments&&posComment.comments.length>0&&sortDirectionComments.push(...posComment.comments)}token.comments&&token.comments.length>0&&(sortDirectionComments||(sortDirectionComments=[]),sortDirectionComments.push(...token.comments))}}let nullsSortDirection=idx>=lexemes.length?null:lexemes[idx].value==="nulls first"?(idx++,"first"):lexemes[idx].value==="nulls last"?(idx++,"last"):null;return sortDirectionComments&&sortDirectionComments.length>0&&(value.comments?value.comments.push(...sortDirectionComments):value.comments=sortDirectionComments),sortDirection===null&&nullsSortDirection===null?{value,newIndex:idx}:{value:new OrderByItem(value,sortDirection,nullsSortDirection),newIndex:idx}}};var PartitionByParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The PARTITION BY clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="partition by")throw new Error(`Syntax error at position ${idx}: Expected 'PARTITION BY' keyword but found "${lexemes[idx].value}". PARTITION BY clauses must start with the PARTITION BY keywords.`);idx++;let items=[],item=ValueParser.parseFromLexeme(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=ValueParser.parseFromLexeme(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No partition expressions found. The PARTITION BY clause requires at least one expression to partition by.`);return items.length===1?{value:new PartitionByClause(items[0]),newIndex:idx}:{value:new PartitionByClause(new ValueList(items)),newIndex:idx}}};var WindowExpressionParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The window frame expression is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].type!==4)throw new Error(`Syntax error at position ${idx}: Expected opening parenthesis '(' but found "${lexemes[idx].value}".`);idx++;let partition=null,order=null,frameSpec=null;if(idx<lexemes.length&&lexemes[idx].value==="partition by"){let partitionResult=PartitionByParser.parseFromLexeme(lexemes,idx);partition=partitionResult.value,idx=partitionResult.newIndex}if(idx<lexemes.length&&lexemes[idx].value==="order by"){let orderResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);order=orderResult.value,idx=orderResult.newIndex}if(idx<lexemes.length&&this.isFrameTypeKeyword(lexemes[idx].value)){let frameSpecResult=this.parseFrameSpec(lexemes,idx);frameSpec=frameSpecResult.value,idx=frameSpecResult.newIndex}if(idx>=lexemes.length||lexemes[idx].type!==8)throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis ')' for window frame. Each opening parenthesis must have a matching closing parenthesis.`);return idx++,{value:new WindowFrameExpression(partition,order,frameSpec),newIndex:idx}}static isFrameTypeKeyword(value){let lowerValue=value;return lowerValue==="rows"||lowerValue==="range"||lowerValue==="groups"}static parseFrameSpec(lexemes,index){let idx=index,frameTypeStr=lexemes[idx].value,frameType;switch(frameTypeStr){case"rows":frameType="rows";break;case"range":frameType="range";break;case"groups":frameType="groups";break;default:throw new Error(`Syntax error at position ${idx}: Invalid frame type "${lexemes[idx].value}". Expected one of: ROWS, RANGE, GROUPS.`)}if(idx++,idx<lexemes.length&&lexemes[idx].value==="between"){idx++;let startBoundResult=this.parseFrameBoundary(lexemes,idx),startBound=startBoundResult.value;if(idx=startBoundResult.newIndex,idx>=lexemes.length||lexemes[idx].value!=="and")throw new Error(`Syntax error at position ${idx}: Expected 'AND' keyword in BETWEEN clause.`);idx++;let endBoundResult=this.parseFrameBoundary(lexemes,idx),endBound=endBoundResult.value;return idx=endBoundResult.newIndex,{value:new WindowFrameSpec(frameType,startBound,endBound),newIndex:idx}}else{let boundaryResult=this.parseFrameBoundary(lexemes,idx),startBound=boundaryResult.value;return idx=boundaryResult.newIndex,{value:new WindowFrameSpec(frameType,startBound,null),newIndex:idx}}}static parseFrameBoundary(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&128){let currentValue=lexemes[idx].value,frameBound;switch(currentValue){case"current row":frameBound="current row";break;case"unbounded preceding":frameBound="unbounded preceding";break;case"unbounded following":frameBound="unbounded following";break;default:throw new Error(`Syntax error at position ${idx}: Invalid frame type "${lexemes[idx].value}". Expected one of: ROWS, RANGE, GROUPS.`)}return{value:new WindowFrameBoundStatic(frameBound),newIndex:idx+1}}else if(idx<lexemes.length&&lexemes[idx].type&1){let valueResult=ValueParser.parseFromLexeme(lexemes,idx);if(idx=valueResult.newIndex,idx<lexemes.length&&lexemes[idx].type&128){let direction=lexemes[idx].value,isFollowing;if(direction==="preceding")isFollowing=!1;else if(direction==="following")isFollowing=!0;else throw new Error(`Syntax error at position ${idx}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`);return idx++,{value:new WindowFrameBoundaryValue(valueResult.value,isFollowing),newIndex:idx}}else throw new Error(`Syntax error at position ${idx}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`)}throw new Error(`Syntax error at position ${idx}: Expected a valid frame boundary component.`)}};var OverExpressionParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The OVER expression is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="over")throw new Error(`Syntax error at position ${idx}: Expected 'OVER' keyword but found "${lexemes[idx].value}". OVER expressions must start with the OVER keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'OVER' keyword. Expected either a window name or an opening parenthesis '('.");if(lexemes[idx].type&64){let name=lexemes[idx].value;return idx++,{value:new IdentifierString(name),newIndex:idx}}if(lexemes[idx].type&4)return WindowExpressionParser.parseFromLexeme(lexemes,idx);throw new Error(`Syntax error at position ${idx}: Expected a window name or opening parenthesis '(' after OVER keyword, but found "${lexemes[idx].value}".`)}};var ParseError=class _ParseError extends Error{constructor(message,index,context){super(message);this.index=index;this.context=context;this.name="ParseError"}static fromUnparsedLexemes(lexemes,index,messagePrefix){let start=Math.max(0,index-2),end=Math.min(lexemes.length,index+3),context=lexemes.slice(start,end).map((lexeme,idx)=>{let marker=idx+start===index?">":" ",typeName=TokenType[lexeme.type]||lexeme.type;return`${marker} ${idx+start}:${lexeme.value} [${typeName}]`}).join(`
10
+ ${this.getDebugPositionInfo(this.position)}`);let tokenStartPos=this.position,tokenEndPos=this.position=this.readerManager.getMaxPosition(),suffixComment=this.readComment();this.position=suffixComment.position;let prefixComments=this.mergeComments(pendingLeading,prefixComment.lines);pendingLeading=null,tokenData.push({lexeme,startPos:tokenStartPos,endPos:tokenEndPos,prefixComments,suffixComments:suffixComment.lines}),previous=lexeme}let statementEnd=this.position,lexemes=this.buildLexemesFromTokenData(tokenData),nextPosition=this.skipPastTerminator(statementEnd);return{lexemes,statementStart,statementEnd,nextPosition,rawText:this.input.slice(statementStart,statementEnd),leadingComments:pendingLeading}}buildLexemesFromTokenData(tokenData){let lexemes=new Array(tokenData.length);for(let i=0;i<tokenData.length;i++){let current=tokenData[i],lexeme=current.lexeme;if(lexeme.value.toLowerCase()==="select"&&current.suffixComments&&current.suffixComments.length>0){let suffixComments=current.suffixComments,targetIndex=i+1;for(;targetIndex<tokenData.length;){let target=tokenData[targetIndex],isStarOperator=target.lexeme.type&2&&target.lexeme.value==="*";if(target.lexeme.type&64||target.lexeme.type&1||isStarOperator||!(target.lexeme.type&128)&&!(target.lexeme.type&16)&&!(target.lexeme.type&2)){target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null;break}targetIndex++}}if(lexeme.value.toLowerCase()==="from"&&current.suffixComments&&current.suffixComments.length>0){let suffixComments=current.suffixComments,targetIndex=i+1;for(;targetIndex<tokenData.length;){let target=tokenData[targetIndex];if(!((target.lexeme.type&128)!==0)){target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null;break}targetIndex++}}if(lexeme.type&16&&current.suffixComments&&current.suffixComments.length>0){let suffixComments=current.suffixComments,targetIndex=i+1;if(targetIndex<tokenData.length){let target=tokenData[targetIndex];target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null}}if((lexeme.value.toLowerCase()==="union"||lexeme.value.toLowerCase()==="intersect"||lexeme.value.toLowerCase()==="except")&&current.suffixComments&&current.suffixComments.length>0){let suffixComments=current.suffixComments,targetIndex=i+1;for(;targetIndex<tokenData.length;){let target=tokenData[targetIndex];if(target.lexeme.value.toLowerCase()==="select"){target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null;break}targetIndex++}}this.attachCommentsToLexeme(lexeme,current),lexeme.position={startPosition:current.startPos,endPosition:current.endPos,...this.getLineColumnInfo(current.startPos,current.endPos)},lexemes[i]=lexeme}return lexemes}skipPastTerminator(position){let next=position;return next<this.input.length&&this.input[next]===";"&&next++,this.skipWhitespaceAndComments(next)}mergeComments(base,addition){return addition&&addition.length>0?!base||base.length===0?[...addition]:[...base,...addition]:base?[...base]:null}attachCommentsToLexeme(lexeme,tokenData){let newPositionedComments=[],allLegacyComments=[];lexeme.positionedComments&&lexeme.positionedComments.length>0&&newPositionedComments.push(...lexeme.positionedComments),tokenData.prefixComments&&tokenData.prefixComments.length>0&&(allLegacyComments.push(...tokenData.prefixComments),newPositionedComments.push({position:"before",comments:[...tokenData.prefixComments]})),tokenData.suffixComments&&tokenData.suffixComments.length>0&&(allLegacyComments.push(...tokenData.suffixComments),newPositionedComments.push({position:"after",comments:[...tokenData.suffixComments]})),newPositionedComments.length>0?(lexeme.positionedComments=newPositionedComments,lexeme.comments=null):allLegacyComments.length>0?(lexeme.comments=allLegacyComments,lexeme.positionedComments=void 0):(lexeme.comments=null,lexeme.positionedComments=void 0)}readComment(){return StringUtils.readWhiteSpaceAndComment(this.input,this.position)}getDebugPositionInfo(errPosition){return StringUtils.getDebugPositionInfo(this.input,errPosition)}tokenizeWithFormatting(){let regularLexemes=this.tokenizeBasic();return this.mapToFormattingLexemes(regularLexemes)}mapToFormattingLexemes(regularLexemes){if(regularLexemes.length===0)return[];let lexemePositions=[],searchPos=0;for(let lexeme of regularLexemes){searchPos=this.skipWhitespaceAndComments(searchPos);let lexemeInfo=this.findLexemeAtPosition(lexeme,searchPos);if(lexemeInfo)lexemePositions.push(lexemeInfo),searchPos=lexemeInfo.endPosition;else{let fallbackInfo={startPosition:searchPos,endPosition:searchPos+lexeme.value.length};lexemePositions.push(fallbackInfo),searchPos=fallbackInfo.endPosition}}let formattingLexemes=[];for(let i=0;i<regularLexemes.length;i++){let lexeme=regularLexemes[i],lexemeInfo=lexemePositions[i],nextLexemeStartPos=i<regularLexemes.length-1?lexemePositions[i+1].startPosition:this.input.length,whitespaceSegment=this.input.slice(lexemeInfo.endPosition,nextLexemeStartPos),inlineComments=this.extractCommentsFromWhitespace(whitespaceSegment),formattingLexeme={...lexeme,followingWhitespace:whitespaceSegment,inlineComments,position:{startPosition:lexemeInfo.startPosition,endPosition:lexemeInfo.endPosition,...this.getLineColumnInfo(lexemeInfo.startPosition,lexemeInfo.endPosition)}};formattingLexemes.push(formattingLexeme)}return formattingLexemes}findLexemeAtPosition(lexeme,expectedPos){if(expectedPos>=this.input.length)return null;let valuesToTry=[lexeme.value,lexeme.value.toUpperCase(),lexeme.value.toLowerCase()];for(let valueToTry of valuesToTry)if(expectedPos+valueToTry.length<=this.input.length&&this.input.substring(expectedPos,expectedPos+valueToTry.length)===valueToTry&&this.isValidLexemeMatch(valueToTry,expectedPos))return{startPosition:expectedPos,endPosition:expectedPos+valueToTry.length};return null}isValidLexemeMatch(value,position){if(position>0){let charBefore=this.input[position-1];if(this.isAlphanumericUnderscore(charBefore))return!1}let endPosition=position+value.length;if(endPosition<this.input.length){let charAfter=this.input[endPosition];if(this.isAlphanumericUnderscore(charAfter))return!1}return!0}isAlphanumericUnderscore(char){let code=char.charCodeAt(0);return code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122||code===95}isWhitespace(char){let code=char.charCodeAt(0);return code===32||code===9||code===10||code===13}extractCommentsFromWhitespace(whitespaceSegment){let inlineComments=[],pos=0;for(;pos<whitespaceSegment.length;){let oldPos=pos,result=StringUtils.readWhiteSpaceAndComment(whitespaceSegment,pos),lines=result.lines;lines&&lines.length>0&&inlineComments.push(...lines),pos=result.position,pos===oldPos&&pos++}return inlineComments}skipWhitespaceAndComments(pos){return StringUtils.readWhiteSpaceAndComment(this.input,pos).position}getLineColumnInfo(startPos,endPos){let startInfo=this.getLineColumn(startPos),endInfo=this.getLineColumn(endPos);return{startLine:startInfo.line,startColumn:startInfo.column,endLine:endInfo.line,endColumn:endInfo.column}}getLineColumn(position){let starts=this.ensureLineStartPositions(),low=0,high=starts.length-1;for(;low<=high;){let mid=low+high>>>1;starts[mid]<=position?low=mid+1:high=mid-1}let lineIndex=high>=0?high:0,lineStart=starts[lineIndex];return{line:lineIndex+1,column:position-lineStart+1}}ensureLineStartPositions(){if(this.lineStartPositions)return this.lineStartPositions;let starts=[0];for(let i=0;i<this.input.length;i++)this.input.charCodeAt(i)===10&&starts.push(i+1);return this.lineStartPositions=starts,starts}};var SqlComponent=class{constructor(){this.comments=null;this.positionedComments=null}getKind(){return this.constructor.kind}accept(visitor){return visitor.visit(this)}toSqlString(formatter){return this.accept(formatter)}addPositionedComments(position,comments){if(!comments||comments.length===0)return;this.positionedComments||(this.positionedComments=[]);let existing=this.positionedComments.find(pc=>pc.position===position);existing?existing.comments.push(...comments):this.positionedComments.push({position,comments:[...comments]})}getPositionedComments(position){if(!this.positionedComments)return[];let positioned=this.positionedComments.find(pc=>pc.position===position);return positioned?positioned.comments:[]}getAllPositionedComments(){if(!this.positionedComments)return[];let result=[],beforeComments=this.getPositionedComments("before");result.push(...beforeComments);let afterComments=this.getPositionedComments("after");return result.push(...afterComments),result}},SqlDialectConfiguration=class{constructor(){this.parameterSymbol=":";this.identifierEscape={start:'"',end:'"'};this.exportComment="none"}};var InsertQuery=class extends SqlComponent{static{this.kind=Symbol("InsertQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.insertClause=params.insertClause,this.selectQuery=params.selectQuery??null,this.returningClause=params.returning??null}};var InlineQuery=class extends SqlComponent{static{this.kind=Symbol("InlineQuery")}constructor(selectQuery){super(),this.selectQuery=selectQuery}},ValueList=class extends SqlComponent{static{this.kind=Symbol("ValueList")}constructor(values){super(),this.values=values}},ColumnReference=class extends SqlComponent{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof IdentifierString?this.qualifiedName.name:new IdentifierString(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(namespaces,column){super();let col=typeof column=="string"?new IdentifierString(column):column;this.qualifiedName=new QualifiedName(toIdentifierStringArray(namespaces),col)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(namespace=>namespace.name).join("."):""}},FunctionCall=class extends SqlComponent{static{this.kind=Symbol("FunctionCall")}constructor(namespaces,name,argument,over,withinGroup=null,withOrdinality=!1,internalOrderBy=null){super(),this.qualifiedName=new QualifiedName(namespaces,name),this.argument=argument,this.over=over,this.withinGroup=withinGroup,this.withOrdinality=withOrdinality,this.internalOrderBy=internalOrderBy}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},WindowFrameType=(WindowFrameType2=>(WindowFrameType2.Rows="rows",WindowFrameType2.Range="range",WindowFrameType2.Groups="groups",WindowFrameType2))(WindowFrameType||{}),WindowFrameBound=(WindowFrameBound2=>(WindowFrameBound2.UnboundedPreceding="unbounded preceding",WindowFrameBound2.UnboundedFollowing="unbounded following",WindowFrameBound2.CurrentRow="current row",WindowFrameBound2))(WindowFrameBound||{}),WindowFrameBoundStatic=class extends SqlComponent{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(bound){super(),this.bound=bound}},WindowFrameBoundaryValue=class extends SqlComponent{static{this.kind=Symbol("WindowFrameBoundary")}constructor(value,isFollowing){super(),this.value=value,this.isFollowing=isFollowing}},WindowFrameSpec=class extends SqlComponent{static{this.kind=Symbol("WindowFrameSpec")}constructor(frameType,startBound,endBound){super(),this.frameType=frameType,this.startBound=startBound,this.endBound=endBound}},WindowFrameExpression=class extends SqlComponent{static{this.kind=Symbol("WindowFrameExpression")}constructor(partition,order,frameSpec=null){super(),this.partition=partition,this.order=order,this.frameSpec=frameSpec}},UnaryExpression=class extends SqlComponent{static{this.kind=Symbol("UnaryExpression")}constructor(operator,expression){super(),this.operator=new RawString(operator),this.expression=expression}},BinaryExpression=class extends SqlComponent{static{this.kind=Symbol("BinaryExpression")}constructor(left,operator,right){super(),this.left=left,this.operator=new RawString(operator),this.right=right}},LiteralValue=class extends SqlComponent{static{this.kind=Symbol("LiteralExpression")}constructor(value,_deprecated,isStringLiteral){super(),this.value=value,this.isStringLiteral=isStringLiteral}},ParameterExpression=class extends SqlComponent{static{this.kind=Symbol("ParameterExpression")}constructor(name,value=null){super(),this.name=new RawString(name),this.value=value,this.index=null}},SwitchCaseArgument=class extends SqlComponent{static{this.kind=Symbol("SwitchCaseArgument")}constructor(cases,elseValue=null){super(),this.cases=cases,this.elseValue=elseValue}},CaseKeyValuePair=class extends SqlComponent{static{this.kind=Symbol("CaseKeyValuePair")}constructor(key,value){super(),this.key=key,this.value=value}},RawString=class extends SqlComponent{static{this.kind=Symbol("RawString")}constructor(value){super(),this.value=value}},IdentifierString=class extends SqlComponent{static{this.kind=Symbol("IdentifierString")}constructor(alias){super(),this.name=alias}},ParenExpression=class extends SqlComponent{static{this.kind=Symbol("ParenExpression")}constructor(expression){super(),this.expression=expression}},CastExpression=class extends SqlComponent{static{this.kind=Symbol("CastExpression")}constructor(input,castType){super(),this.input=input,this.castType=castType}},CaseExpression=class extends SqlComponent{static{this.kind=Symbol("CaseExpression")}constructor(condition,switchCase){super(),this.condition=condition,this.switchCase=switchCase}},ArrayExpression=class extends SqlComponent{static{this.kind=Symbol("ArrayExpression")}constructor(expression){super(),this.expression=expression}},ArrayQueryExpression=class extends SqlComponent{static{this.kind=Symbol("ArrayQueryExpression")}constructor(query){super(),this.query=query}},BetweenExpression=class extends SqlComponent{static{this.kind=Symbol("BetweenExpression")}constructor(expression,lower,upper,negated){super(),this.expression=expression,this.lower=lower,this.upper=upper,this.negated=negated}},StringSpecifierExpression=class extends SqlComponent{static{this.kind=Symbol("StringSpecifierExpression")}constructor(specifier,value){super(),this.specifier=new RawString(specifier),this.value=new LiteralValue(value)}},TypeValue=class extends SqlComponent{static{this.kind=Symbol("TypeValue")}constructor(namespaces,name,argument=null){super(),this.qualifiedName=new QualifiedName(namespaces,name),this.argument=argument}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let nameValue=this.qualifiedName.name instanceof RawString?this.qualifiedName.name.value:this.qualifiedName.name.name;return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(ns=>ns.name).join(".")+"."+nameValue:nameValue}},TupleExpression=class extends SqlComponent{static{this.kind=Symbol("TupleExpression")}constructor(values){super(),this.values=values}},ArraySliceExpression=class extends SqlComponent{static{this.kind=Symbol("ArraySliceExpression")}constructor(array,startIndex,endIndex){super(),this.array=array,this.startIndex=startIndex,this.endIndex=endIndex}},ArrayIndexExpression=class extends SqlComponent{static{this.kind=Symbol("ArrayIndexExpression")}constructor(array,index){super(),this.array=array,this.index=index}};function toIdentifierStringArray(input){if(input==null)return null;if(typeof input=="string")return input.trim()===""?null:[new IdentifierString(input)];if(Array.isArray(input)){if(input.length===0)return null;if(typeof input[0]=="string"){let filteredStrings=input.filter(ns=>ns.trim()!=="");return filteredStrings.length===0?null:filteredStrings.map(ns=>new IdentifierString(ns))}else{let filteredIdentifiers=input.filter(ns=>ns.name.trim()!=="");return filteredIdentifiers.length===0?null:filteredIdentifiers}}return null}var QualifiedName=class extends SqlComponent{static{this.kind=Symbol("QualifiedName")}constructor(namespaces,name){super(),this.namespaces=toIdentifierStringArray(namespaces),typeof name=="string"?this.name=new RawString(name):this.name=name}toString(){let nameValue=this.name instanceof RawString?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(ns=>ns.name).join(".")+"."+nameValue:nameValue}};var SelectItem=class extends SqlComponent{static{this.kind=Symbol("SelectItem")}constructor(value,name=null){super(),this.value=value,this.identifier=name?new IdentifierString(name):null}},SelectClause=class extends SqlComponent{static{this.kind=Symbol("SelectClause")}constructor(items,distinct=null,hints=[]){super(),this.items=items,this.distinct=distinct,this.hints=hints}},Distinct=class extends SqlComponent{static{this.kind=Symbol("Distinct")}constructor(){super()}},DistinctOn=class extends SqlComponent{static{this.kind=Symbol("DistinctOn")}constructor(value){super(),this.value=value}},WhereClause=class extends SqlComponent{static{this.kind=Symbol("WhereClause")}constructor(condition){super(),this.condition=condition}},PartitionByClause=class extends SqlComponent{static{this.kind=Symbol("PartitionByClause")}constructor(value){super(),this.value=value}},WindowFrameClause=class extends SqlComponent{static{this.kind=Symbol("WindowFrameClause")}constructor(name,expression){super(),this.name=new IdentifierString(name),this.expression=expression}},WindowsClause=class extends SqlComponent{static{this.kind=Symbol("WindowsClause")}constructor(windows){super(),this.windows=windows}};var OrderByClause=class extends SqlComponent{static{this.kind=Symbol("OrderByClause")}constructor(items){super(),this.order=items}},OrderByItem=class extends SqlComponent{static{this.kind=Symbol("OrderByItem")}constructor(expression,sortDirection,nullsPosition){super(),this.value=expression,this.sortDirection=sortDirection===null?"asc":sortDirection,this.nullsPosition=nullsPosition}},GroupByClause=class extends SqlComponent{static{this.kind=Symbol("GroupByClause")}constructor(expression){super(),this.grouping=expression}},HavingClause=class extends SqlComponent{static{this.kind=Symbol("HavingClause")}constructor(condition){super(),this.condition=condition}},TableSource=class extends SqlComponent{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof IdentifierString?this.qualifiedName.name:new IdentifierString(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(namespaces,table){super();let tbl=typeof table=="string"?new IdentifierString(table):table;this.qualifiedName=new QualifiedName(namespaces,tbl)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(namespace=>namespace.name).join(".")+"."+(this.qualifiedName.name instanceof RawString?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof RawString?this.qualifiedName.name.value:this.qualifiedName.name.name}},FunctionSource=class extends SqlComponent{static{this.kind=Symbol("FunctionSource")}constructor(name,argument){if(super(),typeof name=="object"&&name!==null&&"name"in name){let nameObj=name;this.qualifiedName=new QualifiedName(nameObj.namespaces,nameObj.name)}else this.qualifiedName=new QualifiedName(null,name);this.argument=argument}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},ParenSource=class extends SqlComponent{static{this.kind=Symbol("ParenSource")}constructor(source){super(),this.source=source}},SubQuerySource=class extends SqlComponent{static{this.kind=Symbol("SubQuerySource")}constructor(query){super(),this.query=query}},SourceExpression=class extends SqlComponent{static{this.kind=Symbol("SourceExpression")}constructor(datasource,aliasExpression){super(),this.datasource=datasource,this.aliasExpression=aliasExpression}getAliasName(){return this.aliasExpression?this.aliasExpression.table.name:this.datasource instanceof TableSource?this.datasource.getSourceName():null}},JoinOnClause=class extends SqlComponent{static{this.kind=Symbol("JoinOnClause")}constructor(condition){super(),this.condition=condition}},JoinUsingClause=class extends SqlComponent{static{this.kind=Symbol("JoinUsingClause")}constructor(condition){super(),this.condition=condition}},JoinClause=class extends SqlComponent{static{this.kind=Symbol("JoinItem")}constructor(joinType,source,condition,lateral){super(),this.joinType=new RawString(joinType),this.source=source,this.condition=condition,this.lateral=lateral}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof TableSource?this.source.table.name:null}},FromClause=class extends SqlComponent{static{this.kind=Symbol("FromClause")}constructor(source,join){super(),this.source=source,this.joins=join}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof TableSource?this.source.datasource.table.name:null}getSources(){let sources=[this.source];if(this.joins)for(let join of this.joins)sources.push(join.source);return sources}},UsingClause=class extends SqlComponent{static{this.kind=Symbol("UsingClause")}constructor(sources){super(),this.sources=sources}getSources(){return[...this.sources]}},CommonTable=class extends SqlComponent{static{this.kind=Symbol("CommonTable")}constructor(query,aliasExpression,materialized){super(),this.query=query,this.materialized=materialized,typeof aliasExpression=="string"?this.aliasExpression=new SourceAliasExpression(aliasExpression,null):this.aliasExpression=aliasExpression}getSourceAliasName(){return this.aliasExpression.table.name}},WithClause=class extends SqlComponent{constructor(recursive,tables){super();this.trailingComments=null;this.globalComments=null;this.recursive=recursive,this.tables=tables}static{this.kind=Symbol("WithClause")}},LimitClause=class extends SqlComponent{static{this.kind=Symbol("LimitClause")}constructor(limit){super(),this.value=limit}};var OffsetClause=class extends SqlComponent{static{this.kind=Symbol("OffsetClause")}constructor(value){super(),this.value=value}},FetchClause=class extends SqlComponent{static{this.kind=Symbol("FetchClause")}constructor(expression){super(),this.expression=expression}},FetchExpression=class extends SqlComponent{static{this.kind=Symbol("FetchExpression")}constructor(type,count,unit){super(),this.type=type,this.count=count,this.unit=unit}};var ForClause=class extends SqlComponent{static{this.kind=Symbol("ForClause")}constructor(lockMode){super(),this.lockMode=lockMode}},SourceAliasExpression=class extends SqlComponent{static{this.kind=Symbol("SourceAliasExpression")}constructor(alias,columnAlias){super(),this.table=new IdentifierString(alias),this.columns=columnAlias!==null?columnAlias.map(alias2=>new IdentifierString(alias2)):null}},ReturningClause=class extends SqlComponent{static{this.kind=Symbol("ReturningClause")}constructor(columns){super(),this.columns=columns.map(col=>typeof col=="string"?new IdentifierString(col):col)}},SetClause=class extends SqlComponent{static{this.kind=Symbol("SetClause")}constructor(items){super(),this.items=items.map(item=>item instanceof SetClauseItem?item:new SetClauseItem(item.column,item.value))}},SetClauseItem=class extends SqlComponent{static{this.kind=Symbol("SetClauseItem")}constructor(column,value){if(super(),typeof column=="object"&&column!==null&&"column"in column){let colObj=column,col=typeof colObj.column=="string"?new IdentifierString(colObj.column):colObj.column;this.qualifiedName=new QualifiedName(colObj.namespaces,col)}else{let col=typeof column=="string"?new IdentifierString(column):column;this.qualifiedName=new QualifiedName(null,col)}this.value=value}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof IdentifierString?this.qualifiedName.name:new IdentifierString(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},UpdateClause=class extends SqlComponent{static{this.kind=Symbol("UpdateClause")}constructor(source){super(),this.source=source}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof TableSource?this.source.datasource.table.name:null}},DeleteClause=class extends SqlComponent{static{this.kind=Symbol("DeleteClause")}constructor(source){super(),this.source=source}getSourceAliasName(){return this.source.getAliasName()}},InsertClause=class extends SqlComponent{constructor(source,columns){super(),this.source=source,columns&&columns.length>0?this.columns=columns.map(col=>typeof col=="string"?new IdentifierString(col):col):this.columns=null}};var FullNameParser=class _FullNameParser{static parseFromLexeme(lexemes,index){let{identifiers,newIndex}=_FullNameParser.parseEscapedOrDotSeparatedIdentifiers(lexemes,index),{namespaces,name}=_FullNameParser.extractNamespacesAndName(identifiers),identifierString=new IdentifierString(name);if(newIndex>index){let lastLexeme=lexemes[newIndex-1];lastLexeme.positionedComments&&lastLexeme.positionedComments.length>0?identifierString.positionedComments=lastLexeme.positionedComments:lastLexeme.comments&&lastLexeme.comments.length>0}let lastTokenType=0;return newIndex>index&&(lastTokenType=lexemes[newIndex-1].type),{namespaces,name:identifierString,newIndex,lastTokenType}}static parse(str){let lexemes=new SqlTokenizer(str).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The name is complete but additional tokens were found.`);return{namespaces:result.namespaces,name:result.name}}static parseEscapedOrDotSeparatedIdentifiers(lexemes,index){let idx=index,identifiers=[];for(;idx<lexemes.length;){if(lexemes[idx].type&512){if(idx++,idx>=lexemes.length||!(lexemes[idx].type&64||lexemes[idx].type&128))throw new Error(`Expected identifier after '[' at position ${idx}`);if(identifiers.push(lexemes[idx].value),idx++,idx>=lexemes.length||lexemes[idx].value!=="]")throw new Error(`Expected closing ']' after identifier at position ${idx}`);idx++}else if(lexemes[idx].type&64)identifiers.push(lexemes[idx].value),idx++;else if(lexemes[idx].type&2048)identifiers.push(lexemes[idx].value),idx++;else if(lexemes[idx].type&8192)identifiers.push(lexemes[idx].value),idx++;else if(lexemes[idx].value==="*"){identifiers.push(lexemes[idx].value),idx++;break}if(idx<lexemes.length&&lexemes[idx].type&32)idx++;else break}return{identifiers,newIndex:idx}}static extractNamespacesAndName(identifiers){if(!identifiers||identifiers.length===0)throw new Error("Identifier list is empty");return identifiers.length===1?{namespaces:null,name:identifiers[0]}:{namespaces:identifiers.slice(0,-1),name:identifiers[identifiers.length-1]}}};var IdentifierParser=class{static parseFromLexeme(lexemes,index){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,index);return{value:new ColumnReference(namespaces,name),newIndex}}};var LiteralParser=class{static parseFromLexeme(lexemes,index){let idx=index,valueText=lexemes[idx].value,parsedValue,lex=literalKeywordParser.parse(valueText.toLowerCase(),0);if(lex){let value=new RawString(lex.keyword);return idx++,{value,newIndex:idx}}if(/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(valueText))return parsedValue=Number(valueText),idx++,{value:new LiteralValue(parsedValue),newIndex:idx};{/^\$[^$]*\$[\s\S]*\$[^$]*\$$/.test(valueText)?parsedValue=valueText:valueText.startsWith("'")&&valueText.endsWith("'")?parsedValue=valueText.slice(1,-1):parsedValue=valueText;let isStringLiteral=valueText.startsWith("'")&&valueText.endsWith("'");return idx++,{value:new LiteralValue(parsedValue,void 0,isStringLiteral),newIndex:idx}}}};var ParenExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(idx+1<lexemes.length&&lexemes[idx].type&4&&(lexemes[idx+1].value==="select"||lexemes[idx+1].value==="values"||lexemes[idx+1].value==="with")){let openLexeme=lexemes[idx],openPositionedComments=openLexeme.positionedComments?openLexeme.positionedComments.map(comment=>({position:comment.position,comments:[...comment.comments]})):null,openLegacyComments=openLexeme.comments?[...openLexeme.comments]:null;idx+=1;let result2=SelectQueryParser.parseFromLexeme(lexemes,idx);if(idx=result2.newIndex,idx>=lexemes.length||lexemes[idx].type!==8)throw new Error(`Expected ')' at index ${idx}, but found ${lexemes[idx].value}`);let closingLexeme=lexemes[idx],closingLegacyComments=closingLexeme.comments,closingPositionedComments=closingLexeme.positionedComments;idx++;let value2=new InlineQuery(result2.value);if(openPositionedComments&&openPositionedComments.length>0){let beforeComments=openPositionedComments.filter(comment=>comment.position==="after"&&comment.comments.length>0).map(comment=>({position:"before",comments:[...comment.comments]}));beforeComments.length>0&&(value2.positionedComments=value2.positionedComments?[...beforeComments,...value2.positionedComments]:beforeComments)}else if(openLegacyComments&&openLegacyComments.length>0){let beforeCommentBlock={position:"before",comments:[...openLegacyComments]};value2.positionedComments=value2.positionedComments?[beforeCommentBlock,...value2.positionedComments]:[beforeCommentBlock]}if(closingPositionedComments&&closingPositionedComments.length>0){let afterComments=closingPositionedComments.filter(comment=>comment.position==="after"&&comment.comments.length>0).map(comment=>({position:comment.position,comments:[...comment.comments]}));afterComments.length>0&&(value2.positionedComments=value2.positionedComments?[...value2.positionedComments,...afterComments]:afterComments)}else closingLegacyComments&&closingLegacyComments.length>0&&(value2.comments=closingLegacyComments);return{value:value2,newIndex:idx}}let result=ValueParser.parseArgument(4,8,lexemes,index);idx=result.newIndex;let value=new ParenExpression(result.value),closingIndex=idx-1;if(closingIndex>=0&&closingIndex<lexemes.length){let closingLexeme=lexemes[closingIndex];if(closingLexeme.type&8)if(closingLexeme.positionedComments&&closingLexeme.positionedComments.length>0){let afterComments=closingLexeme.positionedComments.filter(comment=>comment.position==="after"&&comment.comments.length>0).map(comment=>({position:comment.position,comments:[...comment.comments]}));afterComments.length>0&&(value.positionedComments=value.positionedComments?[...value.positionedComments,...afterComments]:afterComments)}else closingLexeme.comments&&closingLexeme.comments.length>0&&(value.comments=value.comments?value.comments.concat(closingLexeme.comments):[...closingLexeme.comments])}return{value,newIndex:idx}}};var UnaryExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&2){let operatorLexeme=lexemes[idx],operator=operatorLexeme.value;if(idx++,operator==="*")return{value:new ColumnReference(null,"*"),newIndex:idx};let result=ValueParser.parseFromLexeme(lexemes,idx);idx=result.newIndex;let value=new UnaryExpression(operator,result.value);return operatorLexeme.positionedComments&&operatorLexeme.positionedComments.length>0?value.positionedComments=operatorLexeme.positionedComments:operatorLexeme.comments&&operatorLexeme.comments.length>0&&(value.comments=operatorLexeme.comments),{value,newIndex:idx}}throw new Error(`Invalid unary expression at index ${index}: ${lexemes[index].value}`)}};var ParameterExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index,paramName=lexemes[idx].value;paramName.startsWith("${")&&paramName.endsWith("}")?paramName=paramName.slice(2,-1):paramName=paramName.slice(1);let value=new ParameterExpression(paramName);return idx++,{value,newIndex:idx}}};var StringSpecifierExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index,specifer=lexemes[idx].value;if(idx++,idx>=lexemes.length||lexemes[idx].type!==1)throw new Error(`Expected string literal after string specifier at index ${idx}`);let value=lexemes[idx].value;return idx++,{value:new StringSpecifierExpression(specifer,value),newIndex:idx}}};var CommandExpressionParser=class _CommandExpressionParser{static parseFromLexeme(lexemes,index){let idx=index,current=lexemes[idx];if(current.value==="case"){let caseKeywordComments=current.comments,caseKeywordPositionedComments=current.positionedComments;return idx++,this.parseCaseExpression(lexemes,idx,caseKeywordComments,caseKeywordPositionedComments)}else if(current.value==="case when"){let caseWhenKeywordComments=current.comments,caseWhenKeywordPositionedComments=current.positionedComments;return idx++,this.parseCaseWhenExpression(lexemes,idx,caseWhenKeywordComments,caseWhenKeywordPositionedComments)}return this.parseModifierUnaryExpression(lexemes,idx)}static parseModifierUnaryExpression(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&128){let command=lexemes[idx].value;idx++;let result=ValueParser.parseFromLexeme(lexemes,idx);return{value:new UnaryExpression(command,result.value),newIndex:result.newIndex}}throw new Error(`Invalid modifier unary expression at index ${idx}, Lexeme: ${lexemes[idx].value}`)}static parseCaseExpression(lexemes,index,caseKeywordComments,caseKeywordPositionedComments){let idx=index,condition=ValueParser.parseFromLexeme(lexemes,idx);idx=condition.newIndex;let switchCaseResult=this.parseSwitchCaseArgument(lexemes,idx,[]);idx=switchCaseResult.newIndex;let result=new CaseExpression(condition.value,switchCaseResult.value);return caseKeywordPositionedComments&&caseKeywordPositionedComments.length>0?result.positionedComments=caseKeywordPositionedComments:caseKeywordComments&&caseKeywordComments.length>0&&(result.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(caseKeywordComments,"before")]),{value:result,newIndex:idx}}static parseCaseWhenExpression(lexemes,index,caseWhenKeywordComments,caseWhenKeywordPositionedComments){let idx=index,casewhenResult=this.parseCaseConditionValuePair(lexemes,idx);idx=casewhenResult.newIndex;let caseWhenList=[casewhenResult.value],switchCaseResult=this.parseSwitchCaseArgument(lexemes,idx,caseWhenList);idx=switchCaseResult.newIndex;let result=new CaseExpression(null,switchCaseResult.value);return caseWhenKeywordPositionedComments&&caseWhenKeywordPositionedComments.length>0?result.positionedComments=caseWhenKeywordPositionedComments:caseWhenKeywordComments&&caseWhenKeywordComments.length>0&&(result.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(caseWhenKeywordComments,"before")]),{value:result,newIndex:idx}}static parseSwitchCaseArgument(lexemes,index,initialWhenThenList){let idx=index,whenThenList=[...initialWhenThenList];idx=this.parseAdditionalWhenClauses(lexemes,idx,whenThenList);let{elseValue,elseComments,newIndex:elseIndex}=this.parseElseClause(lexemes,idx);idx=elseIndex;let{endComments,newIndex:endIndex}=this.parseEndClause(lexemes,idx);if(idx=endIndex,whenThenList.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${idx})`);let switchCaseArg=new SwitchCaseArgument(whenThenList,elseValue);return this.applySwitchCaseComments(switchCaseArg,elseComments,endComments),{value:switchCaseArg,newIndex:idx}}static parseAdditionalWhenClauses(lexemes,index,whenThenList){let idx=index;for(;idx<lexemes.length&&this.isCommandWithValue(lexemes[idx],"when");){idx++;let whenResult=this.parseCaseConditionValuePair(lexemes,idx);idx=whenResult.newIndex,whenThenList.push(whenResult.value)}return idx}static parseElseClause(lexemes,index){let elseValue=null,elseComments=null,idx=index;if(idx<lexemes.length&&this.isCommandWithValue(lexemes[idx],"else")){elseComments=this.extractKeywordComments(lexemes[idx]),idx++;let elseResult=ValueParser.parseFromLexeme(lexemes,idx);elseValue=elseResult.value,idx=elseResult.newIndex}return{elseValue,elseComments,newIndex:idx}}static parseEndClause(lexemes,index){let idx=index,endComments=null;if(idx<lexemes.length&&this.isCommandWithValue(lexemes[idx],"end"))endComments=this.extractKeywordComments(lexemes[idx]),idx++;else throw new Error(`The CASE expression requires 'end' keyword at the end (index ${idx})`);return{endComments,newIndex:idx}}static extractKeywordComments(token){return{legacy:token.comments,positioned:token.positionedComments}}static applySwitchCaseComments(switchCaseArg,elseComments,endComments){let allPositionedComments=[],allLegacyComments=[];elseComments?.positioned&&elseComments.positioned.length>0&&allPositionedComments.push(...elseComments.positioned),elseComments?.legacy&&elseComments.legacy.length>0&&allLegacyComments.push(...elseComments.legacy),endComments?.positioned&&endComments.positioned.length>0&&allPositionedComments.push(...endComments.positioned),endComments?.legacy&&endComments.legacy.length>0&&allLegacyComments.push(...endComments.legacy),allPositionedComments.length>0?switchCaseArg.positionedComments=allPositionedComments:allLegacyComments.length>0&&(switchCaseArg.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(allLegacyComments,"after")])}static isCommandWithValue(lexeme,value){return(lexeme.type&128)!==0&&lexeme.value===value}static parseCaseConditionValuePair(lexemes,index){let idx=index,condition=ValueParser.parseFromLexeme(lexemes,idx);if(idx=condition.newIndex,idx>=lexemes.length||!(lexemes[idx].type&128)||lexemes[idx].value!=="then")throw new Error(`Expected 'then' after WHEN condition at index ${idx}`);let thenKeywordComments=lexemes[idx].comments,thenKeywordPositionedComments=lexemes[idx].positionedComments;idx++;let value=ValueParser.parseFromLexeme(lexemes,idx);idx=value.newIndex;let keyValuePair=new CaseKeyValuePair(condition.value,value.value);return thenKeywordPositionedComments&&thenKeywordPositionedComments.length>0?keyValuePair.positionedComments=thenKeywordPositionedComments:thenKeywordComments&&thenKeywordComments.length>0&&(keyValuePair.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(thenKeywordComments,"after")]),{value:keyValuePair,newIndex:idx}}static convertLegacyToPositioned(legacyComments,position="before"){return{position,comments:legacyComments}}};var OrderByClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The ORDER BY clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="order by")throw new Error(`Syntax error at position ${idx}: Expected 'ORDER BY' keyword but found "${lexemes[idx].value}". ORDER BY clauses must start with the ORDER BY keywords.`);idx++;let items=[],item=this.parseItem(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=this.parseItem(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No ordering expressions found. The ORDER BY clause requires at least one expression to order by.`);return{value:new OrderByClause(items),newIndex:idx}}static parseItem(lexemes,index){let idx=index,parsedValue=ValueParser.parseFromLexeme(lexemes,idx),value=parsedValue.value;if(idx=parsedValue.newIndex,idx>=lexemes.length)return{value,newIndex:idx};let sortDirectionComments=null,sortDirection=null;if(idx<lexemes.length){let token=lexemes[idx];if(token.value==="asc"?(sortDirection="asc",idx++):token.value==="desc"&&(sortDirection="desc",idx++),sortDirection!==null){if(token.positionedComments&&token.positionedComments.length>0){sortDirectionComments=[];for(let posComment of token.positionedComments)posComment.comments&&posComment.comments.length>0&&sortDirectionComments.push(...posComment.comments)}token.comments&&token.comments.length>0&&(sortDirectionComments||(sortDirectionComments=[]),sortDirectionComments.push(...token.comments))}}let nullsSortDirection=idx>=lexemes.length?null:lexemes[idx].value==="nulls first"?(idx++,"first"):lexemes[idx].value==="nulls last"?(idx++,"last"):null;return sortDirectionComments&&sortDirectionComments.length>0&&(value.comments?value.comments.push(...sortDirectionComments):value.comments=sortDirectionComments),sortDirection===null&&nullsSortDirection===null?{value,newIndex:idx}:{value:new OrderByItem(value,sortDirection,nullsSortDirection),newIndex:idx}}};var PartitionByParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The PARTITION BY clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="partition by")throw new Error(`Syntax error at position ${idx}: Expected 'PARTITION BY' keyword but found "${lexemes[idx].value}". PARTITION BY clauses must start with the PARTITION BY keywords.`);idx++;let items=[],item=ValueParser.parseFromLexeme(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=ValueParser.parseFromLexeme(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No partition expressions found. The PARTITION BY clause requires at least one expression to partition by.`);return items.length===1?{value:new PartitionByClause(items[0]),newIndex:idx}:{value:new PartitionByClause(new ValueList(items)),newIndex:idx}}};var WindowExpressionParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The window frame expression is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].type!==4)throw new Error(`Syntax error at position ${idx}: Expected opening parenthesis '(' but found "${lexemes[idx].value}".`);idx++;let partition=null,order=null,frameSpec=null;if(idx<lexemes.length&&lexemes[idx].value==="partition by"){let partitionResult=PartitionByParser.parseFromLexeme(lexemes,idx);partition=partitionResult.value,idx=partitionResult.newIndex}if(idx<lexemes.length&&lexemes[idx].value==="order by"){let orderResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);order=orderResult.value,idx=orderResult.newIndex}if(idx<lexemes.length&&this.isFrameTypeKeyword(lexemes[idx].value)){let frameSpecResult=this.parseFrameSpec(lexemes,idx);frameSpec=frameSpecResult.value,idx=frameSpecResult.newIndex}if(idx>=lexemes.length||lexemes[idx].type!==8)throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis ')' for window frame. Each opening parenthesis must have a matching closing parenthesis.`);return idx++,{value:new WindowFrameExpression(partition,order,frameSpec),newIndex:idx}}static isFrameTypeKeyword(value){let lowerValue=value;return lowerValue==="rows"||lowerValue==="range"||lowerValue==="groups"}static parseFrameSpec(lexemes,index){let idx=index,frameTypeStr=lexemes[idx].value,frameType;switch(frameTypeStr){case"rows":frameType="rows";break;case"range":frameType="range";break;case"groups":frameType="groups";break;default:throw new Error(`Syntax error at position ${idx}: Invalid frame type "${lexemes[idx].value}". Expected one of: ROWS, RANGE, GROUPS.`)}if(idx++,idx<lexemes.length&&lexemes[idx].value==="between"){idx++;let startBoundResult=this.parseFrameBoundary(lexemes,idx),startBound=startBoundResult.value;if(idx=startBoundResult.newIndex,idx>=lexemes.length||lexemes[idx].value!=="and")throw new Error(`Syntax error at position ${idx}: Expected 'AND' keyword in BETWEEN clause.`);idx++;let endBoundResult=this.parseFrameBoundary(lexemes,idx),endBound=endBoundResult.value;return idx=endBoundResult.newIndex,{value:new WindowFrameSpec(frameType,startBound,endBound),newIndex:idx}}else{let boundaryResult=this.parseFrameBoundary(lexemes,idx),startBound=boundaryResult.value;return idx=boundaryResult.newIndex,{value:new WindowFrameSpec(frameType,startBound,null),newIndex:idx}}}static parseFrameBoundary(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&128){let currentValue=lexemes[idx].value,frameBound;switch(currentValue){case"current row":frameBound="current row";break;case"unbounded preceding":frameBound="unbounded preceding";break;case"unbounded following":frameBound="unbounded following";break;default:throw new Error(`Syntax error at position ${idx}: Invalid frame type "${lexemes[idx].value}". Expected one of: ROWS, RANGE, GROUPS.`)}return{value:new WindowFrameBoundStatic(frameBound),newIndex:idx+1}}else if(idx<lexemes.length&&lexemes[idx].type&1){let valueResult=ValueParser.parseFromLexeme(lexemes,idx);if(idx=valueResult.newIndex,idx<lexemes.length&&lexemes[idx].type&128){let direction=lexemes[idx].value,isFollowing;if(direction==="preceding")isFollowing=!1;else if(direction==="following")isFollowing=!0;else throw new Error(`Syntax error at position ${idx}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`);return idx++,{value:new WindowFrameBoundaryValue(valueResult.value,isFollowing),newIndex:idx}}else throw new Error(`Syntax error at position ${idx}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`)}throw new Error(`Syntax error at position ${idx}: Expected a valid frame boundary component.`)}};var OverExpressionParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The OVER expression is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="over")throw new Error(`Syntax error at position ${idx}: Expected 'OVER' keyword but found "${lexemes[idx].value}". OVER expressions must start with the OVER keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'OVER' keyword. Expected either a window name or an opening parenthesis '('.");if(lexemes[idx].type&64){let name=lexemes[idx].value;return idx++,{value:new IdentifierString(name),newIndex:idx}}if(lexemes[idx].type&4)return WindowExpressionParser.parseFromLexeme(lexemes,idx);throw new Error(`Syntax error at position ${idx}: Expected a window name or opening parenthesis '(' after OVER keyword, but found "${lexemes[idx].value}".`)}};var ParseError=class _ParseError extends Error{constructor(message,index,context){super(message);this.index=index;this.context=context;this.name="ParseError"}static fromUnparsedLexemes(lexemes,index,messagePrefix){let start=Math.max(0,index-2),end=Math.min(lexemes.length,index+3),context=lexemes.slice(start,end).map((lexeme,idx)=>{let marker=idx+start===index?">":" ",typeName=TokenType[lexeme.type]||lexeme.type;return`${marker} ${idx+start}:${lexeme.value} [${typeName}]`}).join(`
11
11
  `),message=`${messagePrefix} Unparsed lexeme remains at index ${index}: ${lexemes[index].value}
12
12
  Context:
13
- ${context}`;return new _ParseError(message,index,context)}};function extractLexemeComments(lexeme){let before=[],after=[];if(!lexeme)return{before,after};if(lexeme.positionedComments&&lexeme.positionedComments.length>0)for(let positioned of lexeme.positionedComments)!positioned.comments||positioned.comments.length===0||(positioned.position==="before"?before.push(...positioned.comments):positioned.position==="after"&&after.push(...positioned.comments));else lexeme.comments&&lexeme.comments.length>0&&before.push(...lexeme.comments);return{before,after}}var FunctionExpressionParser=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(lexemes,index){let idx=index;if(idx+1<lexemes.length&&lexemes[idx+1].type&512){idx++;let arg=ValueParser.parseArgument(512,1024,lexemes,idx);return idx=arg.newIndex,{value:new ArrayExpression(arg.value),newIndex:idx}}else if(idx+1<lexemes.length&&lexemes[idx+1].type&4){idx++,idx++;let arg=SelectQueryParser.parseFromLexeme(lexemes,idx);return idx=arg.newIndex,idx++,{value:new ArrayQueryExpression(arg.value),newIndex:idx}}throw new Error(`Invalid ARRAY syntax at index ${idx}, expected ARRAY[... or ARRAY(...)`)}static parseFromLexeme(lexemes,index){let idx=index,current=lexemes[idx];return current.value==="array"?this.parseArrayExpression(lexemes,idx):current.value==="substring"||current.value==="overlay"?this.parseKeywordFunction(lexemes,idx,[{key:"from",required:!1},{key:"for",required:!1}]):current.value==="cast"?this.parseKeywordFunction(lexemes,idx,[{key:"as",required:!0}]):current.value==="trim"?this.parseKeywordFunction(lexemes,idx,[{key:"from",required:!1}]):this.parseFunctionCall(lexemes,idx)}static tryParseBinaryExpression(lexemes,index,left,allowAndOperator=!0,allowOrOperator=!0){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&2){let operator=lexemes[idx].value.toLowerCase();if(!allowAndOperator&&operator==="and"||!allowOrOperator&&operator==="or")return null;if(idx++,operator==="between")return this.parseBetweenExpression(lexemes,idx,left,!1);if(operator==="not between")return this.parseBetweenExpression(lexemes,idx,left,!0);if(operator==="::"){let typeValue=this.parseTypeValue(lexemes,idx);return idx=typeValue.newIndex,{value:new CastExpression(left,typeValue.value),newIndex:idx}}let rightResult=ValueParser.parseFromLexeme(lexemes,idx);return idx=rightResult.newIndex,{value:new BinaryExpression(left,operator,rightResult.value),newIndex:idx}}return null}static parseBetweenExpression(lexemes,index,value,negated){let idx=index,lower=ValueParser.parseFromLexeme(lexemes,idx,!1);if(idx=lower.newIndex,idx<lexemes.length&&lexemes[idx].type&2&&lexemes[idx].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${idx}`);idx++;let upper=this.parseBetweenUpperBound(lexemes,idx);return idx=upper.newIndex,{value:new BetweenExpression(value,lower.value,upper.value,negated),newIndex:idx}}static parseBetweenUpperBound(lexemes,index){return ValueParser.parseFromLexeme(lexemes,index,!1,!1)}static parseFunctionCall(lexemes,index){let idx=index,fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx),namespaces=fullNameResult.namespaces,name=fullNameResult.name;if(idx=fullNameResult.newIndex,idx<lexemes.length&&lexemes[idx].type&4){let functionName=name.name.toLowerCase(),arg,closingComments=null,internalOrderBy=null;if(this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY.has(functionName)){let result=this.parseAggregateArguments(lexemes,idx);arg={value:result.arguments,newIndex:result.newIndex},internalOrderBy=result.orderByClause,closingComments=result.closingComments}else{let argWithComments=this.parseArgumentWithComments(lexemes,idx);arg={value:argWithComments.value,newIndex:argWithComments.newIndex},closingComments=argWithComments.closingComments}idx=arg.newIndex;let withinGroup=null;if(idx<lexemes.length&&lexemes[idx].value==="within group"){let withinGroupResult=this.parseWithinGroupClause(lexemes,idx);withinGroup=withinGroupResult.value,idx=withinGroupResult.newIndex}let withOrdinality=!1;if(idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++),idx<lexemes.length&&lexemes[idx].value==="over"){let over=OverExpressionParser.parseFromLexeme(lexemes,idx);idx=over.newIndex;let value=new FunctionCall(namespaces,name.name,arg.value,over.value,withinGroup,withOrdinality,internalOrderBy);return closingComments&&closingComments.length>0&&value.addPositionedComments("after",closingComments),{value,newIndex:idx}}else{let value=new FunctionCall(namespaces,name.name,arg.value,null,withinGroup,withOrdinality,internalOrderBy);return closingComments&&closingComments.length>0&&value.addPositionedComments("after",closingComments),{value,newIndex:idx}}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Expected opening parenthesis after function name '${name.name}'.`)}static parseKeywordFunction(lexemes,index,keywords2){let idx=index,fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx),namespaces=fullNameResult.namespaces,name=fullNameResult.name;if(idx=fullNameResult.newIndex,idx<lexemes.length&&lexemes[idx].type&4){idx++;let input=ValueParser.parseFromLexeme(lexemes,idx),arg=input.value;if(idx=input.newIndex,idx<lexemes.length&&lexemes[idx].type&16)return this.parseFunctionCall(lexemes,index);for(let{key,required}of keywords2)if(idx<lexemes.length&&lexemes[idx].type&128&&lexemes[idx].value===key)if(idx++,idx<lexemes.length&&lexemes[idx].type&8192){let typeValue=this.parseTypeValue(lexemes,idx);arg=new BinaryExpression(arg,key,typeValue.value),idx=typeValue.newIndex}else{let right=ValueParser.parseFromLexeme(lexemes,idx);arg=new BinaryExpression(arg,key,right.value),idx=right.newIndex}else if(required)throw ParseError.fromUnparsedLexemes(lexemes,idx,`Keyword '${key}' is required for ${name.name} function.`);if(idx<lexemes.length&&lexemes[idx].type&8){idx++;let withinGroup=null;if(idx<lexemes.length&&lexemes[idx].value==="within group"){let withinGroupResult=this.parseWithinGroupClause(lexemes,idx);withinGroup=withinGroupResult.value,idx=withinGroupResult.newIndex}let withOrdinality=!1;if(idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++),idx<lexemes.length&&lexemes[idx].value==="over"){idx++;let over=OverExpressionParser.parseFromLexeme(lexemes,idx);return idx=over.newIndex,{value:new FunctionCall(namespaces,name.name,arg,over.value,withinGroup,withOrdinality,null),newIndex:idx}}else return{value:new FunctionCall(namespaces,name.name,arg,null,withinGroup,withOrdinality,null),newIndex:idx}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Missing closing parenthesis for function '${name.name}'.`)}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Missing opening parenthesis for function '${name.name}'.`)}static parseTypeValue(lexemes,index){let idx=index,{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,idx<lexemes.length&&lexemes[idx].type&4){let arg=ValueParser.parseArgument(4,8,lexemes,idx);idx=arg.newIndex;let value=new TypeValue(namespaces,new RawString(name.name),arg.value);return arg.value.positionedComments&&(value.positionedComments=arg.value.positionedComments),arg.value.comments,{value,newIndex:idx}}else return{value:new TypeValue(namespaces,new RawString(name.name)),newIndex:idx}}static parseWithinGroupClause(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].value!=="within group")throw new Error(`Expected 'WITHIN GROUP' at index ${idx}`);if(idx++,idx>=lexemes.length||!(lexemes[idx].type&4))throw new Error(`Expected '(' after 'WITHIN GROUP' at index ${idx}`);idx++;let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);if(idx=orderByResult.newIndex,idx>=lexemes.length||!(lexemes[idx].type&8))throw new Error(`Expected ')' after WITHIN GROUP ORDER BY clause at index ${idx}`);return idx++,{value:orderByResult.value,newIndex:idx}}static parseAggregateArguments(lexemes,index){let idx=index,args=[],orderByClause=null;if(idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected opening parenthesis.");if(idx++,idx<lexemes.length&&lexemes[idx].type&8){let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{arguments:new ValueList([]),orderByClause:null,closingComments:closingComments2,newIndex:idx}}if(idx<lexemes.length&&lexemes[idx].value==="*"){let wildcard=new ColumnReference(null,"*");if(idx++,idx<lexemes.length&&lexemes[idx].type&8){let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{arguments:wildcard,orderByClause:null,closingComments:closingComments2,newIndex:idx}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis after wildcard '*'.")}let firstArg=ValueParser.parseFromLexeme(lexemes,idx);for(idx=firstArg.newIndex,args.push(firstArg.value);idx<lexemes.length&&(lexemes[idx].type&16||lexemes[idx].value==="order by");){if(lexemes[idx].value==="order by"){let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);idx=orderByResult.newIndex,orderByClause=orderByResult.value;break}if(lexemes[idx].type&16){if(idx++,idx<lexemes.length&&lexemes[idx].value==="order by"){let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);idx=orderByResult.newIndex,orderByClause=orderByResult.value;break}let argResult=ValueParser.parseFromLexeme(lexemes,idx);idx=argResult.newIndex,args.push(argResult.value)}}if(idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis.");let closingComments=this.getClosingComments(lexemes[idx]);return idx++,{arguments:args.length===1?args[0]:new ValueList(args),orderByClause,closingComments,newIndex:idx}}static parseArgumentWithComments(lexemes,index){let idx=index;if(idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected opening parenthesis.");let openParenToken=lexemes[idx];idx++;let args=[];if(idx<lexemes.length&&lexemes[idx].type&8){let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{value:new ValueList([]),closingComments:closingComments2,newIndex:idx}}if(idx<lexemes.length&&lexemes[idx].value==="*"){let wildcard=new ColumnReference(null,"*");if(idx++,idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis after wildcard '*'.");let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{value:wildcard,closingComments:closingComments2,newIndex:idx}}let result=ValueParser.parseFromLexeme(lexemes,idx);if(idx=result.newIndex,openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let afterComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){let beforeComments=afterComments.map(pc=>({position:"before",comments:pc.comments}));result.value.positionedComments=[...beforeComments,...result.value.positionedComments||[]],result.value,"qualifiedName"in result.value&&result.value.qualifiedName&&"name"in result.value.qualifiedName&&result.value.qualifiedName.name&&(result.value.qualifiedName.name.positionedComments=null,result.value.qualifiedName.name)}}for(args.push(result.value);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let argResult=ValueParser.parseFromLexeme(lexemes,idx);idx=argResult.newIndex,args.push(argResult.value)}if(idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis.");let closingComments=this.getClosingComments(lexemes[idx]);return idx++,{value:args.length===1?args[0]:new ValueList(args),closingComments,newIndex:idx}}static getClosingComments(lexeme){if(!lexeme)return null;let commentInfo=extractLexemeComments(lexeme);return commentInfo.after.length>0?commentInfo.after:commentInfo.before.length>0?commentInfo.before:null}};var OperatorPrecedence=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(operator){let precedence=this.precedenceMap[operator.toLowerCase()];return precedence!==void 0?precedence:0}static hasHigherOrEqualPrecedence(operator1,operator2){return this.getPrecedence(operator1)>=this.getPrecedence(operator2)}static isLogicalOperator(operator){let op=operator.toLowerCase();return op==="and"||op==="or"}static isBetweenOperator(operator){let op=operator.toLowerCase();return op==="between"||op==="not between"}static isComparisonOperator(operator){let lowerOp=operator.toLowerCase();return["=","!=","<>","<",">","<=",">=","like","ilike","similar to","in","not in","->","->>","#>","#>>","@>","<@","?","?|","?&","~","~*","!~","!~*","rlike","regexp"].includes(lowerOp)}};var ValueParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw ParseError.fromUnparsedLexemes(lexemes,result.newIndex,"[ValueParser]");return result.value}static parseFromLexeme(lexemes,index,allowAndOperator=!0,allowOrOperator=!0){return this.parseExpressionWithPrecedence(lexemes,index,0,allowAndOperator,allowOrOperator)}static parseExpressionWithPrecedence(lexemes,index,minPrecedence,allowAndOperator=!0,allowOrOperator=!0){let idx=index,comment=lexemes[idx].comments,positionedComments=lexemes[idx].positionedComments,left=this.parseItem(lexemes,idx);positionedComments&&positionedComments.length>0&&!left.value.positionedComments?left.value.positionedComments=positionedComments:left.value.comments===null&&comment&&comment.length>0&&(left.value.comments=comment),idx=left.newIndex;let result=left.value,arrayAccessResult=this.parseArrayAccess(lexemes,idx,result);for(result=arrayAccessResult.value,idx=arrayAccessResult.newIndex;idx<lexemes.length&&lexemes[idx].type&2;){let operatorToken=lexemes[idx],operator=operatorToken.value;if(!allowAndOperator&&operator.toLowerCase()==="and"||!allowOrOperator&&operator.toLowerCase()==="or")break;let precedence=OperatorPrecedence.getPrecedence(operator);if(precedence<minPrecedence)break;if(idx++,OperatorPrecedence.isBetweenOperator(operator)){let betweenResult=FunctionExpressionParser.parseBetweenExpression(lexemes,idx,result,operator.toLowerCase().includes("not"));result=betweenResult.value,idx=betweenResult.newIndex;continue}if(operator==="::"){let typeValue=FunctionExpressionParser.parseTypeValue(lexemes,idx);result=new CastExpression(result,typeValue.value),idx=typeValue.newIndex;continue}let nextMinPrecedence=precedence+1,rightResult=this.parseExpressionWithPrecedence(lexemes,idx,nextMinPrecedence,allowAndOperator,allowOrOperator);idx=rightResult.newIndex;let binaryExpr=new BinaryExpression(result,operator,rightResult.value);operatorToken.comments&&operatorToken.comments.length>0&&(binaryExpr.operator.comments=operatorToken.comments),operatorToken.positionedComments&&operatorToken.positionedComments.length>0&&(binaryExpr.operator.positionedComments=operatorToken.positionedComments),result=binaryExpr}return{value:result,newIndex:idx}}static transferPositionedComments(lexeme,value){lexeme.positionedComments&&lexeme.positionedComments.length>0&&!value.positionedComments?value.positionedComments=lexeme.positionedComments:value.comments===null&&lexeme.comments&&lexeme.comments.length>0&&(value.comments=lexeme.comments)}static parseItem(lexemes,index){let idx=index;if(idx>=lexemes.length)throw new Error(`Unexpected end of lexemes at index ${index}`);let current=lexemes[idx];if(current.type&64&&current.type&2&&current.type&8192){if(idx+1<lexemes.length&&lexemes[idx+1].type&4)if(this.isTypeConstructor(lexemes,idx+1,current.value)){let result=FunctionExpressionParser.parseTypeValue(lexemes,idx);return this.transferPositionedComments(current,result.value),{value:result.value,newIndex:result.newIndex}}else{let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}let first=IdentifierParser.parseFromLexeme(lexemes,idx);if(first.newIndex>=lexemes.length)return this.transferPositionedComments(current,first.value),first;if(lexemes[first.newIndex].type&1){let literalIndex=first.newIndex,literalLexeme=lexemes[literalIndex],second=LiteralParser.parseFromLexeme(lexemes,literalIndex);this.transferPositionedComments(literalLexeme,second.value);let result=new UnaryExpression(lexemes[idx].value,second.value);return this.transferPositionedComments(current,result),{value:result,newIndex:second.newIndex}}return this.transferPositionedComments(current,first.value),first}else if(current.type&64){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(lexemes[newIndex-1].type&2048){let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(lexemes[newIndex-1].type&8192)if(newIndex<lexemes.length&&lexemes[newIndex].type&4)if(this.isTypeConstructor(lexemes,newIndex,name.name)){let result=FunctionExpressionParser.parseTypeValue(lexemes,idx);return this.transferPositionedComments(current,result.value),{value:result.value,newIndex:result.newIndex}}else{let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else{let value2=new TypeValue(namespaces,name);return this.transferPositionedComments(current,value2),{value:value2,newIndex}}let value=new ColumnReference(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}else if(current.type&1){let result=LiteralParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&4){let result=ParenExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&2048){let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&2){let result=UnaryExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&256){let result=ParameterExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&4096){let result=StringSpecifierExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&128){let result=CommandExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&512){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx),value=new ColumnReference(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}else if(current.type&8192){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(newIndex<lexemes.length&&lexemes[newIndex].type&4)if(this.isTypeConstructor(lexemes,newIndex,name.name)){let result=FunctionExpressionParser.parseTypeValue(lexemes,idx);return this.transferPositionedComments(current,result.value),{value:result.value,newIndex:result.newIndex}}else{let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else{let value=new TypeValue(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}}throw ParseError.fromUnparsedLexemes(lexemes,idx,"[ValueParser] Invalid lexeme.")}static parseArgument(openToken,closeToken,lexemes,index){let idx=index,args=[];if(idx<lexemes.length&&lexemes[idx].type===openToken){let openParenToken=lexemes[idx];if(idx++,idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,{value:new ValueList([]),newIndex:idx};if(idx<lexemes.length&&lexemes[idx].value==="*"){let wildcard=new ColumnReference(null,"*");if(openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let beforeComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");beforeComments.length>0&&(wildcard.positionedComments=beforeComments.map(pc=>({position:"before",comments:pc.comments})))}else openParenToken.comments&&openParenToken.comments.length>0&&(wildcard.comments=openParenToken.comments);if(idx++,idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,{value:wildcard,newIndex:idx};throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis after wildcard '*'.")}let result=this.parseFromLexeme(lexemes,idx);if(idx=result.newIndex,openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let afterComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){let beforeComments=afterComments.map(pc=>({position:"before",comments:pc.comments}));result.value.positionedComments?result.value.positionedComments=[...beforeComments,...result.value.positionedComments]:result.value.positionedComments=beforeComments}}else openParenToken.comments&&openParenToken.comments.length>0&&(result.value.comments?result.value.comments=openParenToken.comments.concat(result.value.comments):result.value.comments=openParenToken.comments);for(args.push(result.value);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let argResult=this.parseFromLexeme(lexemes,idx);idx=argResult.newIndex,args.push(argResult.value)}if(idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,args.length===1?{value:args[0],newIndex:idx}:{value:new ValueList(args),newIndex:idx};throw ParseError.fromUnparsedLexemes(lexemes,idx,"Missing closing parenthesis.")}throw ParseError.fromUnparsedLexemes(lexemes,index,"Expected opening parenthesis.")}static parseArrayAccess(lexemes,index,baseExpression){let idx=index,result=baseExpression;for(;idx<lexemes.length&&lexemes[idx].type&512&&!this.isSqlServerBracketIdentifier(lexemes,idx);){if(idx++,idx>=lexemes.length)throw new Error(`Expected array index or slice after '[' at index ${idx-1}`);if(lexemes[idx].type&1024)throw new Error(`Empty array access brackets not supported at index ${idx}`);let startExpr=null,isSlice=!1;if(lexemes[idx].type&2&&lexemes[idx].value===":")isSlice=!0,idx++;else{let colonPrecedence=OperatorPrecedence.getPrecedence(":"),firstResult=this.parseExpressionWithPrecedence(lexemes,idx,colonPrecedence+1);startExpr=firstResult.value,idx=firstResult.newIndex,idx<lexemes.length&&lexemes[idx].type&2&&lexemes[idx].value===":"&&(isSlice=!0,idx++)}if(isSlice){let endExpr=null;if(idx<lexemes.length&&!(lexemes[idx].type&1024)){let colonPrecedence=OperatorPrecedence.getPrecedence(":"),endResult=this.parseExpressionWithPrecedence(lexemes,idx,colonPrecedence+1);endExpr=endResult.value,idx=endResult.newIndex}if(idx>=lexemes.length||!(lexemes[idx].type&1024))throw new Error(`Expected ']' after array slice at index ${idx}`);idx++,result=new ArraySliceExpression(result,startExpr,endExpr)}else{if(!startExpr){let indexResult=this.parseFromLexeme(lexemes,idx);startExpr=indexResult.value,idx=indexResult.newIndex}if(idx>=lexemes.length||!(lexemes[idx].type&1024))throw new Error(`Expected ']' after array index at index ${idx}`);idx++,result=new ArrayIndexExpression(result,startExpr)}}return{value:result,newIndex:idx}}static isSqlServerBracketIdentifier(lexemes,bracketIndex){let idx=bracketIndex+1;if(idx>=lexemes.length)return!1;for(;idx<lexemes.length&&!(lexemes[idx].type&1024);){let token=lexemes[idx];if(token.type&64||token.type&2&&token.value==="."){idx++;continue}return!1}if(idx>=lexemes.length)return!1;let closingBracketIndex=idx;if(closingBracketIndex+1<lexemes.length){let nextToken=lexemes[closingBracketIndex+1];if(nextToken.type&2&&nextToken.value===".")return!0}idx=bracketIndex+1;let hasOnlyIdentifiersAndDots=!0;for(;idx<closingBracketIndex;){let token=lexemes[idx];if(!(token.type&64||token.type&2&&token.value===".")){hasOnlyIdentifiersAndDots=!1;break}idx++}return hasOnlyIdentifiersAndDots}static isTypeConstructor(lexemes,openParenIndex,typeName){let alwaysTypeConstructors=["NUMERIC","DECIMAL","VARCHAR","CHAR","CHARACTER","TIMESTAMP","TIME","INTERVAL"],upperTypeName=typeName.toUpperCase();if(alwaysTypeConstructors.includes(upperTypeName))return!0;if(upperTypeName==="DATE"){let firstArgIndex=openParenIndex+1;if(firstArgIndex<lexemes.length){let firstArg=lexemes[firstArgIndex];return!(firstArg.type&1&&typeof firstArg.value=="string"&&isNaN(Number(firstArg.value)))}}return!1}};var CTECollector=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}getCommonTables(){return this.commonTables}reset(){this.commonTables=[],this.visitedNodes.clear()}collect(query){return this.visit(query),this.getCommonTables()}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}let kindSymbol=arg.getKind()?.toString()||"unknown",constructor=arg.constructor?.name||"unknown";throw new Error(`[CTECollector] No handler for ${constructor} with kind ${kindSymbol}.`)}visitSimpleSelectQuery(query){if(query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.orderByClause&&query.orderByClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.limitClause&&query.limitClause.accept(this),query.forClause&&query.forClause.accept(this),query.selectClause.accept(this),query.withClause&&query.withClause.accept(this)}visitBinarySelectQuery(query){query.left.accept(this),query.right.accept(this)}visitValuesQuery(query){for(let tuple of query.tuples)tuple.accept(this)}visitWithClause(withClause){for(let i=0;i<withClause.tables.length;i++)withClause.tables[i].accept(this)}visitCommonTable(commonTable){commonTable.query.accept(this),this.commonTables.push(commonTable)}visitSelectClause(clause){for(let item of clause.items)item.accept(this)}visitSelectItem(item){item.value.accept(this)}visitFromClause(fromClause){if(fromClause.source.accept(this),fromClause.joins)for(let join of fromClause.joins)join.accept(this)}visitSourceExpression(source){source.datasource.accept(this)}visitTableSource(source){}visitFunctionSource(source){source.argument&&source.argument.accept(this)}visitParenSource(source){source.source.accept(this)}visitSubQuerySource(subQuery){subQuery.query.accept(this)}visitInlineQuery(inlineQuery){inlineQuery.selectQuery.accept(this)}visitJoinClause(joinClause){joinClause.source.accept(this),joinClause.condition&&joinClause.condition.accept(this)}visitJoinOnClause(joinOn){joinOn.condition.accept(this)}visitJoinUsingClause(joinUsing){joinUsing.condition.accept(this)}visitWhereClause(whereClause){whereClause.condition.accept(this)}visitGroupByClause(clause){for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition.accept(this)}visitOrderByClause(clause){for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitLimitClause(clause){clause.value.accept(this)}visitForClause(clause){}visitOrderByItem(item){item.value.accept(this)}visitParenExpression(expr){expr.expression.accept(this)}visitBinaryExpression(expr){expr.left.accept(this),expr.right.accept(this)}visitUnaryExpression(expr){expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase.accept(this)}visitSwitchCaseArgument(switchCase){for(let caseItem of switchCase.cases)caseItem.accept(this);switchCase.elseValue&&switchCase.elseValue.accept(this)}visitCaseKeyValuePair(pair){pair.key.accept(this),pair.value.accept(this)}visitBetweenExpression(expr){expr.expression.accept(this),expr.lower.accept(this),expr.upper.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this)}visitArrayExpression(expr){expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitTupleExpression(expr){for(let value of expr.values)value.accept(this)}visitCastExpression(expr){expr.input.accept(this),expr.castType.accept(this)}visitTypeValue(expr){expr.argument&&expr.argument.accept(this)}visitWindowFrameExpression(expr){expr.partition&&expr.partition.accept(this),expr.order&&expr.order.accept(this),expr.frameSpec&&expr.frameSpec.accept(this)}visitWindowFrameSpec(spec){}visitIdentifierString(ident){}visitRawString(raw){}visitColumnReference(column){}visitParameterExpression(param){}visitLiteralValue(value){}visitPartitionByClause(partitionBy){}visitValueList(valueList){for(let value of valueList.values)value.accept(this)}visitStringSpecifierExpression(expr){}};var CTEDisabler=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}reset(){this.visitedNodes.clear()}execute(arg){return this.reset(),this.visit(arg)}visit(arg){if(!this.isRootVisit)return this.visitNode(arg);this.reset(),this.isRootVisit=!1;try{return this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return arg;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler)return handler(arg);let kindSymbol=arg.getKind()?.toString()||"unknown",constructor=arg.constructor?.name||"unknown";throw new Error(`[CTEDisabler] No handler for ${constructor} with kind ${kindSymbol}.`)}visitSimpleSelectQuery(arg){return arg.withClause&&arg.withClause.tables.forEach(table=>{this.visit(table.query)}),arg.withClause=null,arg.selectClause=this.visit(arg.selectClause),arg.fromClause=arg.fromClause?this.visit(arg.fromClause):null,arg.whereClause=arg.whereClause?this.visit(arg.whereClause):null,arg.groupByClause=arg.groupByClause?this.visit(arg.groupByClause):null,arg.havingClause=arg.havingClause?this.visit(arg.havingClause):null,arg.orderByClause=arg.orderByClause?this.visit(arg.orderByClause):null,arg.windowClause&&(arg.windowClause=new WindowsClause(arg.windowClause.windows.map(w=>this.visit(w)))),arg.limitClause=arg.limitClause?this.visit(arg.limitClause):null,arg.forClause=arg.forClause?this.visit(arg.forClause):null,arg}visitBinarySelectQuery(query){return query.left=this.visit(query.left),query.right=this.visit(query.right),query}visitValuesQuery(query){let newTuples=query.tuples.map(tuple=>this.visit(tuple));return new ValuesQuery(newTuples)}visitSelectClause(clause){let newItems=clause.items.map(item=>this.visit(item));return new SelectClause(newItems,clause.distinct)}visitFromClause(clause){let newSource=this.visit(clause.source),newJoins=clause.joins?clause.joins.map(join=>this.visit(join)):null;return new FromClause(newSource,newJoins)}visitSubQuerySource(subQuery){let newQuery=this.visit(subQuery.query);return new SubQuerySource(newQuery)}visitInlineQuery(inlineQuery){let newQuery=this.visit(inlineQuery.selectQuery);return new InlineQuery(newQuery)}visitJoinClause(joinClause){let newSource=this.visit(joinClause.source),newCondition=joinClause.condition?this.visit(joinClause.condition):null;return new JoinClause(joinClause.joinType.value,newSource,newCondition,joinClause.lateral)}visitJoinOnClause(joinOn){let newCondition=this.visit(joinOn.condition);return new JoinOnClause(newCondition)}visitJoinUsingClause(joinUsing){let newCondition=this.visit(joinUsing.condition);return new JoinUsingClause(newCondition)}visitWhereClause(whereClause){let newCondition=this.visit(whereClause.condition);return new WhereClause(newCondition)}visitGroupByClause(clause){let newGrouping=clause.grouping.map(item=>this.visit(item));return new GroupByClause(newGrouping)}visitHavingClause(clause){let newCondition=this.visit(clause.condition);return new HavingClause(newCondition)}visitOrderByClause(clause){let newOrder=clause.order.map(item=>this.visit(item));return new OrderByClause(newOrder)}visitWindowFrameClause(clause){let newExpression=this.visit(clause.expression);return new WindowFrameClause(clause.name.name,newExpression)}visitLimitClause(clause){let newLimit=this.visit(clause.value);return new LimitClause(newLimit)}visitForClause(clause){return new ForClause(clause.lockMode)}visitParenExpression(expr){let newExpression=this.visit(expr.expression);return new ParenExpression(newExpression)}visitBinaryExpression(expr){let newLeft=this.visit(expr.left),newRight=this.visit(expr.right);return new BinaryExpression(newLeft,expr.operator.value,newRight)}visitUnaryExpression(expr){let newExpression=this.visit(expr.expression);return new UnaryExpression(expr.operator.value,newExpression)}visitCaseExpression(expr){let newCondition=expr.condition?this.visit(expr.condition):null,newSwitchCase=this.visit(expr.switchCase);return new CaseExpression(newCondition,newSwitchCase)}visitSwitchCaseArgument(switchCase){let newCases=switchCase.cases.map(caseItem=>this.visit(caseItem)),newElseValue=switchCase.elseValue?this.visit(switchCase.elseValue):null;return new SwitchCaseArgument(newCases,newElseValue)}visitCaseKeyValuePair(pair){let newKey=this.visit(pair.key),newValue=this.visit(pair.value);return new CaseKeyValuePair(newKey,newValue)}visitBetweenExpression(expr){let newExpression=this.visit(expr.expression),newLower=this.visit(expr.lower),newUpper=this.visit(expr.upper);return new BetweenExpression(newExpression,newLower,newUpper,expr.negated)}visitFunctionCall(func){let newArgument=func.argument?this.visit(func.argument):null,newOver=func.over?this.visit(func.over):null;return new FunctionCall(func.namespaces,func.name,newArgument,newOver)}visitArrayExpression(expr){let newExpression=this.visit(expr.expression);return new ArrayExpression(newExpression)}visitArrayQueryExpression(expr){let newQuery=this.visit(expr.query);return new ArrayQueryExpression(newQuery)}visitTupleExpression(expr){let newValues=expr.values.map(value=>this.visit(value));return new TupleExpression(newValues)}visitCastExpression(expr){let newInput=this.visit(expr.input),newCastType=this.visit(expr.castType);return new CastExpression(newInput,newCastType)}visitTypeValue(typeValue){let newArgument=typeValue.argument?this.visit(typeValue.argument):null;return new TypeValue(typeValue.namespaces,typeValue.name,newArgument)}visitSelectItem(item){let newValue=this.visit(item.value);return new SelectItem(newValue,item.identifier?.name)}visitIdentifierString(ident){return ident}visitRawString(raw){return raw}visitColumnReference(column){return column}visitSourceExpression(source){let newSource=this.visit(source.datasource),newAlias=source.aliasExpression;return new SourceExpression(newSource,newAlias)}visitTableSource(source){return source}visitParenSource(source){let newSource=this.visit(source.source);return new ParenSource(newSource)}visitParameterExpression(param){return param}visitWindowFrameExpression(expr){let newPartition=expr.partition?this.visit(expr.partition):null,newOrder=expr.order?this.visit(expr.order):null,newFrameSpec=expr.frameSpec?this.visit(expr.frameSpec):null;return new WindowFrameExpression(newPartition,newOrder,newFrameSpec)}visitWindowFrameSpec(spec){return spec}visitLiteralValue(value){return value}visitOrderByItem(item){let newValue=this.visit(item.value);return new OrderByItem(newValue,item.sortDirection,item.nullsPosition)}visitValueList(valueList){let newValues=valueList.values.map(value=>this.visit(value));return new ValueList(newValues)}visitArraySliceExpression(expr){return expr}visitArrayIndexExpression(expr){return expr}visitStringSpecifierExpression(expr){return expr}visitPartitionByClause(clause){let newValue=this.visit(clause.value);return new PartitionByClause(newValue)}};var TableSourceCollector=class{constructor(selectableOnly=!0){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.cteNames=new Set;this.isRootVisit=!0;this.selectableOnly=selectableOnly,this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),selectableOnly||(this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.visitOffsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)))}getTableSources(){return this.tableSources}reset(){this.tableSources=[],this.tableNameMap.clear(),this.visitedNodes.clear(),this.cteNames.clear()}getTableIdentifier(source){return source.qualifiedName.namespaces&&source.qualifiedName.namespaces.length>0?source.qualifiedName.namespaces.map(ns=>ns.name).join(".")+"."+(source.qualifiedName.name instanceof RawString?source.qualifiedName.name.value:source.qualifiedName.name.name):source.qualifiedName.name instanceof RawString?source.qualifiedName.name.value:source.qualifiedName.name.name}collect(query){return this.visit(query),this.getTableSources()}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.selectableOnly||this.collectCTEs(arg),this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}}collectCTEs(query){let cteCollector=new CTECollector;cteCollector.visit(query);let commonTables=cteCollector.getCommonTables();for(let cte of commonTables)this.cteNames.add(cte.aliasExpression.table.name)}visitSimpleSelectQuery(query){if(query.fromClause&&query.fromClause.accept(this),!this.selectableOnly){if(query.withClause&&query.withClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.orderByClause&&query.orderByClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.limitClause&&query.limitClause.accept(this),query.offsetClause&&query.offsetClause.accept(this),query.fetchClause&&query.fetchClause.accept(this),query.forClause&&query.forClause.accept(this),query.selectClause.accept(this)}}visitBinarySelectQuery(query){query.left.accept(this),query.right.accept(this)}visitValuesQuery(query){if(!this.selectableOnly)for(let tuple of query.tuples)tuple.accept(this)}visitWithClause(withClause){if(!this.selectableOnly)for(let table of withClause.tables)table.accept(this)}visitCommonTable(commonTable){this.selectableOnly||commonTable.query.accept(this)}visitFromClause(fromClause){if(fromClause.source.accept(this),fromClause.joins)for(let join of fromClause.joins)join.accept(this)}visitSourceExpression(source){source.datasource.accept(this)}visitTableSource(source){let identifier=this.getTableIdentifier(source);!this.tableNameMap.has(identifier)&&!this.isCTETable(source.table.name)&&(this.tableNameMap.set(identifier,!0),this.tableSources.push(source))}visitFunctionSource(source){source.argument&&this.visitValueComponent(source.argument)}visitValueComponent(value){value.accept(this)}isCTETable(tableName){return this.cteNames.has(tableName)}visitParenSource(source){source.source.accept(this)}visitSubQuerySource(subQuery){this.selectableOnly||subQuery.query.accept(this)}visitInlineQuery(inlineQuery){this.selectableOnly||inlineQuery.selectQuery.accept(this)}visitJoinClause(joinClause){joinClause.source.accept(this),!this.selectableOnly&&joinClause.condition&&joinClause.condition.accept(this)}visitJoinOnClause(joinOn){this.selectableOnly||joinOn.condition.accept(this)}visitJoinUsingClause(joinUsing){this.selectableOnly||joinUsing.condition.accept(this)}visitWhereClause(whereClause){whereClause.condition.accept(this)}visitGroupByClause(clause){for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition.accept(this)}visitOrderByClause(clause){for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitLimitClause(clause){clause.value.accept(this)}visitOffsetClause(clause){clause.value.accept(this)}visitFetchClause(clause){clause.expression.accept(this)}visitForClause(_clause){}visitOrderByItem(item){item.value.accept(this)}visitSelectClause(clause){for(let item of clause.items)item.accept(this)}visitSelectItem(item){item.value.accept(this)}visitParenExpression(expr){expr.expression.accept(this)}visitBinaryExpression(expr){expr.left.accept(this),expr.right.accept(this)}visitUnaryExpression(expr){expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase.accept(this)}visitSwitchCaseArgument(switchCase){for(let caseItem of switchCase.cases)caseItem.accept(this);switchCase.elseValue&&switchCase.elseValue.accept(this)}visitCaseKeyValuePair(pair){pair.key.accept(this),pair.value.accept(this)}visitBetweenExpression(expr){expr.expression.accept(this),expr.lower.accept(this),expr.upper.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this)}visitArrayExpression(expr){expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitTupleExpression(expr){for(let value of expr.values)value.accept(this)}visitCastExpression(expr){expr.input.accept(this),expr.castType.accept(this)}visitValueList(valueList){for(let value of valueList.values)value.accept(this)}visitStringSpecifierExpression(_expr){}};var HintClause=class extends SqlComponent{static{this.kind=Symbol("HintClause")}constructor(hintContent){super(),this.hintContent=hintContent}getFullHint(){return"/*+ "+this.hintContent+" */"}static isHintClause(value){let trimmed=value.trim();return trimmed.length>=5&&trimmed.substring(0,3)==="/*+"&&trimmed.substring(trimmed.length-2)==="*/"}static extractHintContent(hintClause){let trimmed=hintClause.trim();if(!this.isHintClause(trimmed))throw new Error("Not a valid hint clause: "+hintClause);return trimmed.slice(3,-2).trim()}};var SqlPrintToken=class{constructor(type,text="",containerType=""){this.innerTokens=[];this.type=type,this.text=text,this.containerType=containerType}markAsHeaderComment(){if(this.containerType!=="CommentBlock")throw new Error("Header comment flag must only be applied to CommentBlock containers.");this.isHeaderComment=!0}};var ParameterCollector=class{static collect(node){let result=[];function walk(n){if(!(!n||typeof n!="object")){n.constructor&&n.constructor.kind===ParameterExpression.kind&&result.push(n);for(let key of Object.keys(n)){let v=n[key];Array.isArray(v)?v.forEach(walk):v&&typeof v=="object"&&v.constructor&&v.constructor.kind&&walk(v)}}}return walk(node),result}};var IdentifierDecorator=class{constructor(identifierEscape){this.start=identifierEscape?.start??'"',this.end=identifierEscape?.end??'"'}decorate(text){return text=this.start+text+this.end,text}};var ParameterDecorator=class{constructor(options){this.prefix=options?.prefix??":",this.suffix=options?.suffix??"",this.style=options?.style??"named"}decorate(text,index){let paramText="";return this.style==="anonymous"?paramText=this.prefix:this.style==="indexed"?paramText=this.prefix+index:this.style==="named"&&(paramText=this.prefix+text+this.suffix),text=paramText,text}};var UpdateQuery=class extends SqlComponent{static{this.kind=Symbol("UpdateQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.updateClause=params.updateClause,this.setClause=params.setClause instanceof SetClause?params.setClause:new SetClause(params.setClause),this.whereClause=params.whereClause??null,this.fromClause=params.fromClause??null,this.returningClause=params.returning??null}};var DeleteQuery=class extends SqlComponent{static{this.kind=Symbol("DeleteQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.deleteClause=params.deleteClause,this.usingClause=params.usingClause??null,this.whereClause=params.whereClause??null,this.returningClause=params.returning??null}};var SelectValueCollector=class _SelectValueCollector{constructor(tableColumnResolver=null,initialCommonTables=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=tableColumnResolver??null,this.commonTableCollector=new CTECollector,this.commonTables=[],this.initialCommonTables=initialCommonTables,this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr))}getValues(){return this.selectValues}reset(){this.selectValues=[],this.visitedNodes.clear(),this.initialCommonTables?this.commonTables=this.initialCommonTables:this.commonTables=[]}collect(arg){this.visit(arg);let items=this.getValues();return this.reset(),items}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}}visitSimpleSelectQuery(query){this.commonTables.length===0&&this.initialCommonTables===null&&(this.commonTables=this.commonTableCollector.collect(query)),query.selectClause&&query.selectClause.accept(this);let wildcards=this.selectValues.filter(item=>item.name==="*");if(wildcards.length===0)return;if(this.selectValues.some(item=>item.value instanceof ColumnReference&&item.value.namespaces===null)){query.fromClause&&this.processFromClause(query.fromClause,!0),this.selectValues=this.selectValues.filter(item=>item.name!=="*");return}let wildSourceNames=wildcards.filter(item=>item.value instanceof ColumnReference&&item.value.namespaces).map(item=>item.value.getNamespace());if(query.fromClause){let fromSourceName=query.fromClause.getSourceAliasName();if(fromSourceName&&wildSourceNames.includes(fromSourceName)&&this.processFromClause(query.fromClause,!1),query.fromClause.joins)for(let join of query.fromClause.joins){let joinSourceName=join.getSourceAliasName();joinSourceName&&wildSourceNames.includes(joinSourceName)&&this.processJoinClause(join)}}this.selectValues=this.selectValues.filter(item=>item.name!=="*")}processFromClause(clause,joinCascade){if(clause){let fromSourceName=clause.getSourceAliasName();if(this.processSourceExpression(fromSourceName,clause.source),clause.joins&&joinCascade)for(let join of clause.joins)this.processJoinClause(join)}}processJoinClause(clause){let sourceName=clause.getSourceAliasName();this.processSourceExpression(sourceName,clause.source)}processSourceExpression(sourceName,source){let commonTable=this.commonTables.find(item=>item.aliasExpression.table.name===sourceName);if(commonTable){let innerCommonTables=this.commonTables.filter(item=>item.aliasExpression.table.name!==sourceName);new _SelectValueCollector(this.tableColumnResolver,innerCommonTables).collect(commonTable.query).forEach(item=>{this.addSelectValueAsUnique(item.name,new ColumnReference(sourceName?[sourceName]:null,item.name))})}else new _SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(source).forEach(item=>{this.addSelectValueAsUnique(item.name,new ColumnReference(sourceName?[sourceName]:null,item.name))})}visitSelectClause(clause){for(let item of clause.items)this.processSelectItem(item)}processSelectItem(item){if(item.identifier)this.addSelectValueAsUnique(item.identifier.name,item.value);else if(item.value instanceof ColumnReference){let columnName=item.value.column.name;columnName==="*"?this.selectValues.push({name:columnName,value:item.value}):this.addSelectValueAsUnique(columnName,item.value)}}visitSourceExpression(source){if(source.aliasExpression&&source.aliasExpression.columns){let sourceName=source.getAliasName();source.aliasExpression.columns.forEach(column=>{this.addSelectValueAsUnique(column.name,new ColumnReference(sourceName?[sourceName]:null,column.name))});return}else if(source.datasource instanceof TableSource){if(this.tableColumnResolver){let sourceName=source.datasource.getSourceName();this.tableColumnResolver(sourceName).forEach(column=>{this.addSelectValueAsUnique(column,new ColumnReference([sourceName],column))})}return}else if(source.datasource instanceof SubQuerySource){let sourceName=source.getAliasName();new _SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(source.datasource.query).forEach(item=>{this.addSelectValueAsUnique(item.name,new ColumnReference(sourceName?[sourceName]:null,item.name))});return}else if(source.datasource instanceof ParenSource)return this.visit(source.datasource.source)}visitFromClause(clause){clause&&this.processFromClause(clause,!0)}addSelectValueAsUnique(name,value){this.selectValues.some(item=>item.name===name)||this.selectValues.push({name,value})}};var ReferenceDefinition=class extends SqlComponent{static{this.kind=Symbol("ReferenceDefinition")}constructor(params){super(),this.targetTable=params.targetTable,this.columns=params.columns?[...params.columns]:null,this.matchType=params.matchType??null,this.onDelete=params.onDelete??null,this.onUpdate=params.onUpdate??null,this.deferrable=params.deferrable??null,this.initially=params.initially??null}},ColumnConstraintDefinition=class extends SqlComponent{static{this.kind=Symbol("ColumnConstraintDefinition")}constructor(params){super(),this.kind=params.kind,this.constraintName=params.constraintName,this.defaultValue=params.defaultValue,this.checkExpression=params.checkExpression,this.reference=params.reference,this.rawClause=params.rawClause}},TableConstraintDefinition=class extends SqlComponent{static{this.kind=Symbol("TableConstraintDefinition")}constructor(params){super(),this.kind=params.kind,this.constraintName=params.constraintName,this.columns=params.columns?[...params.columns]:null,this.reference=params.reference,this.checkExpression=params.checkExpression,this.rawClause=params.rawClause,this.deferrable=params.deferrable??null,this.initially=params.initially??null}},TableColumnDefinition=class extends SqlComponent{static{this.kind=Symbol("TableColumnDefinition")}constructor(params){super(),this.name=params.name,this.dataType=params.dataType,this.constraints=params.constraints?[...params.constraints]:[]}},CreateTableQuery=class extends SqlComponent{static{this.kind=Symbol("CreateTableQuery")}constructor(params){super(),this.tableName=new IdentifierString(params.tableName),this.namespaces=params.namespaces?[...params.namespaces]:null,this.isTemporary=params.isTemporary??!1,this.ifNotExists=params.ifNotExists??!1,this.columns=params.columns?[...params.columns]:[],this.tableConstraints=params.tableConstraints?[...params.tableConstraints]:[],this.tableOptions=params.tableOptions??null,this.asSelectQuery=params.asSelectQuery,this.withDataOption=params.withDataOption??null}getSelectQuery(){let selectItems;this.asSelectQuery?selectItems=new SelectValueCollector().collect(this.asSelectQuery).map(val=>new SelectItem(val.value,val.name)):this.columns.length>0?selectItems=this.columns.map(column=>new SelectItem(new ColumnReference(null,column.name),column.name.name)):selectItems=[new SelectItem(new RawString("*"))];let qualifiedName=this.namespaces&&this.namespaces.length>0?[...this.namespaces,this.tableName.name].join("."):this.tableName.name;return new SimpleSelectQuery({selectClause:new SelectClause(selectItems),fromClause:new FromClause(new SourceExpression(new TableSource(null,qualifiedName),null),null)})}getCountQuery(){let qualifiedName=this.namespaces&&this.namespaces.length>0?[...this.namespaces,this.tableName.name].join("."):this.tableName.name;return new SimpleSelectQuery({selectClause:new SelectClause([new SelectItem(new FunctionCall(null,"count",new ColumnReference(null,"*"),null))]),fromClause:new FromClause(new SourceExpression(new TableSource(null,qualifiedName),null),null)})}};var MergeAction=class extends SqlComponent{static{this.kind=Symbol("MergeAction")}},MergeUpdateAction=class extends MergeAction{static{this.kind=Symbol("MergeUpdateAction")}constructor(setClause,whereClause){super(),this.setClause=setClause instanceof SetClause?setClause:new SetClause(setClause),this.whereClause=whereClause??null}},MergeDeleteAction=class extends MergeAction{static{this.kind=Symbol("MergeDeleteAction")}constructor(whereClause){super(),this.whereClause=whereClause??null}},MergeInsertAction=class extends MergeAction{static{this.kind=Symbol("MergeInsertAction")}constructor(params){super(),this.columns=params.columns?params.columns.map(col=>typeof col=="string"?new IdentifierString(col):col):null,this.values=params.values??null,this.defaultValues=params.defaultValues??!1,this.valuesLeadingComments=params.valuesLeadingComments?[...params.valuesLeadingComments]:null}addValuesLeadingComments(comments){if(!(!comments||comments.length===0)){this.valuesLeadingComments||(this.valuesLeadingComments=[]);for(let comment of comments)this.valuesLeadingComments.includes(comment)||this.valuesLeadingComments.push(comment)}}getValuesLeadingComments(){return this.valuesLeadingComments?[...this.valuesLeadingComments]:[]}},MergeDoNothingAction=class extends MergeAction{static{this.kind=Symbol("MergeDoNothingAction")}},MergeWhenClause=class extends SqlComponent{static{this.kind=Symbol("MergeWhenClause")}constructor(matchType,action,condition,options){super(),this.matchType=matchType,this.action=action,this.condition=condition??null,this.thenLeadingComments=options?.thenLeadingComments?[...options.thenLeadingComments]:null}addThenLeadingComments(comments){if(!(!comments||comments.length===0)){this.thenLeadingComments||(this.thenLeadingComments=[]);for(let comment of comments)this.thenLeadingComments.includes(comment)||this.thenLeadingComments.push(comment)}}getThenLeadingComments(){return this.thenLeadingComments?[...this.thenLeadingComments]:[]}},MergeQuery=class extends SqlComponent{static{this.kind=Symbol("MergeQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.target=params.target,this.source=params.source,this.onCondition=params.onCondition,this.whenClauses=params.whenClauses}};var DropTableStatement=class extends SqlComponent{static{this.kind=Symbol("DropTableStatement")}constructor(params){super(),this.tables=params.tables.map(table=>new QualifiedName(table.namespaces,table.name)),this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},DropIndexStatement=class extends SqlComponent{static{this.kind=Symbol("DropIndexStatement")}constructor(params){super(),this.indexNames=params.indexNames.map(index=>new QualifiedName(index.namespaces,index.name)),this.ifExists=params.ifExists??!1,this.concurrently=params.concurrently??!1,this.behavior=params.behavior??null}},IndexColumnDefinition=class extends SqlComponent{static{this.kind=Symbol("IndexColumnDefinition")}constructor(params){super(),this.expression=params.expression,this.sortOrder=params.sortOrder??null,this.nullsOrder=params.nullsOrder??null,this.collation=params.collation??null,this.operatorClass=params.operatorClass??null}},CreateIndexStatement=class extends SqlComponent{static{this.kind=Symbol("CreateIndexStatement")}constructor(params){super(),this.unique=params.unique??!1,this.concurrently=params.concurrently??!1,this.ifNotExists=params.ifNotExists??!1,this.indexName=new QualifiedName(params.indexName.namespaces,params.indexName.name),this.tableName=new QualifiedName(params.tableName.namespaces,params.tableName.name),this.usingMethod=params.usingMethod??null,this.columns=params.columns.map(col=>new IndexColumnDefinition({expression:col.expression,sortOrder:col.sortOrder,nullsOrder:col.nullsOrder,collation:col.collation??null,operatorClass:col.operatorClass??null})),this.include=params.include?[...params.include]:null,this.where=params.where,this.withOptions=params.withOptions??null,this.tablespace=params.tablespace??null}},AlterTableAddConstraint=class extends SqlComponent{static{this.kind=Symbol("AlterTableAddConstraint")}constructor(params){super(),this.constraint=params.constraint,this.ifNotExists=params.ifNotExists??!1,this.notValid=params.notValid??!1}},AlterTableDropConstraint=class extends SqlComponent{static{this.kind=Symbol("AlterTableDropConstraint")}constructor(params){super(),this.constraintName=params.constraintName,this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},AlterTableDropColumn=class extends SqlComponent{static{this.kind=Symbol("AlterTableDropColumn")}constructor(params){super(),this.columnName=params.columnName,this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},AlterTableStatement=class extends SqlComponent{static{this.kind=Symbol("AlterTableStatement")}constructor(params){super(),this.table=new QualifiedName(params.table.namespaces,params.table.name),this.only=params.only??!1,this.ifExists=params.ifExists??!1,this.actions=params.actions.map(action=>action)}},DropConstraintStatement=class extends SqlComponent{static{this.kind=Symbol("DropConstraintStatement")}constructor(params){super(),this.constraintName=params.constraintName,this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}};var PRESETS={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"}},SqlPrintTokenParser=class _SqlPrintTokenParser{constructor(options){this.handlers=new Map;this.index=1;this.joinConditionContexts=[];options?.preset&&(options={...options.preset,...options}),this.parameterDecorator=new ParameterDecorator({prefix:typeof options?.parameterSymbol=="string"?options.parameterSymbol:options?.parameterSymbol?.start??":",suffix:typeof options?.parameterSymbol=="object"?options.parameterSymbol.end:"",style:options?.parameterStyle??"named"}),this.identifierDecorator=new IdentifierDecorator({start:options?.identifierEscape?.start??'"',end:options?.identifierEscape?.end??'"'}),this.castStyle=options?.castStyle??"standard",this.constraintStyle=options?.constraintStyle??"postgres",this.normalizeJoinConditionOrder=options?.joinConditionOrderByDeclaration??!1,this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(QualifiedName.kind,expr=>this.visitQualifiedName(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(WindowFrameBoundStatic.kind,expr=>this.visitWindowFrameBoundStatic(expr)),this.handlers.set(WindowFrameBoundaryValue.kind,expr=>this.visitWindowFrameBoundaryValue(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(Distinct.kind,expr=>this.visitDistinct(expr)),this.handlers.set(DistinctOn.kind,expr=>this.visitDistinctOn(expr)),this.handlers.set(HintClause.kind,expr=>this.visitHintClause(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(SourceAliasExpression.kind,expr=>this.visitSourceAliasExpression(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(WindowsClause.kind,expr=>this.visitWindowClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.visitOffsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(FetchExpression.kind,expr=>this.visitFetchExpression(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleQuery(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(InsertClause.kind,expr=>this.visitInsertClause(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(UpdateClause.kind,expr=>this.visitUpdateClause(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(DeleteClause.kind,expr=>this.visitDeleteClause(expr)),this.handlers.set(UsingClause.kind,expr=>this.visitUsingClause(expr)),this.handlers.set(SetClause.kind,expr=>this.visitSetClause(expr)),this.handlers.set(SetClauseItem.kind,expr=>this.visitSetClauseItem(expr)),this.handlers.set(ReturningClause.kind,expr=>this.visitReturningClause(expr)),this.handlers.set(CreateTableQuery.kind,expr=>this.visitCreateTableQuery(expr)),this.handlers.set(TableColumnDefinition.kind,expr=>this.visitTableColumnDefinition(expr)),this.handlers.set(ColumnConstraintDefinition.kind,expr=>this.visitColumnConstraintDefinition(expr)),this.handlers.set(TableConstraintDefinition.kind,expr=>this.visitTableConstraintDefinition(expr)),this.handlers.set(ReferenceDefinition.kind,expr=>this.visitReferenceDefinition(expr)),this.handlers.set(CreateIndexStatement.kind,expr=>this.visitCreateIndexStatement(expr)),this.handlers.set(IndexColumnDefinition.kind,expr=>this.visitIndexColumnDefinition(expr)),this.handlers.set(DropTableStatement.kind,expr=>this.visitDropTableStatement(expr)),this.handlers.set(DropIndexStatement.kind,expr=>this.visitDropIndexStatement(expr)),this.handlers.set(AlterTableStatement.kind,expr=>this.visitAlterTableStatement(expr)),this.handlers.set(AlterTableAddConstraint.kind,expr=>this.visitAlterTableAddConstraint(expr)),this.handlers.set(AlterTableDropConstraint.kind,expr=>this.visitAlterTableDropConstraint(expr)),this.handlers.set(AlterTableDropColumn.kind,expr=>this.visitAlterTableDropColumn(expr)),this.handlers.set(DropConstraintStatement.kind,expr=>this.visitDropConstraintStatement(expr)),this.handlers.set(MergeQuery.kind,expr=>this.visitMergeQuery(expr)),this.handlers.set(MergeWhenClause.kind,expr=>this.visitMergeWhenClause(expr)),this.handlers.set(MergeUpdateAction.kind,expr=>this.visitMergeUpdateAction(expr)),this.handlers.set(MergeDeleteAction.kind,expr=>this.visitMergeDeleteAction(expr)),this.handlers.set(MergeInsertAction.kind,expr=>this.visitMergeInsertAction(expr)),this.handlers.set(MergeDoNothingAction.kind,expr=>this.visitMergeDoNothingAction(expr))}static{this.SPACE_TOKEN=new SqlPrintToken(10," ")}static{this.COMMA_TOKEN=new SqlPrintToken(3,",")}static{this.ARGUMENT_SPLIT_COMMA_TOKEN=new SqlPrintToken(11,",")}static{this.PAREN_OPEN_TOKEN=new SqlPrintToken(4,"(")}static{this.PAREN_CLOSE_TOKEN=new SqlPrintToken(4,")")}static{this.DOT_TOKEN=new SqlPrintToken(8,".")}static{this._selfHandlingComponentTypes=null}static getSelfHandlingComponentTypes(){return this._selfHandlingComponentTypes||(this._selfHandlingComponentTypes=new Set([SimpleSelectQuery.kind,SelectItem.kind,CaseKeyValuePair.kind,SwitchCaseArgument.kind,ColumnReference.kind,LiteralValue.kind,ParameterExpression.kind,TableSource.kind,SourceAliasExpression.kind,TypeValue.kind,FunctionCall.kind,IdentifierString.kind,QualifiedName.kind])),this._selfHandlingComponentTypes}visitBinarySelectQuery(arg){let token=new SqlPrintToken(0,"");if(arg.positionedComments&&arg.positionedComments.length>0)this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null;else if(arg.headerComments&&arg.headerComments.length>0){if(this.shouldMergeHeaderComments(arg.headerComments)){let mergedHeaderComment=this.createHeaderMultiLineCommentBlock(arg.headerComments);token.innerTokens.push(mergedHeaderComment)}else{let headerCommentBlocks=this.createCommentBlocks(arg.headerComments,!0);token.innerTokens.push(...headerCommentBlocks)}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}return token.innerTokens.push(this.visit(arg.left)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.operator.value,"BinarySelectQueryOperator")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.right)),token}static commaSpaceTokens(){return[_SqlPrintTokenParser.COMMA_TOKEN,_SqlPrintTokenParser.SPACE_TOKEN]}static argumentCommaSpaceTokens(){return[_SqlPrintTokenParser.ARGUMENT_SPLIT_COMMA_TOKEN,_SqlPrintTokenParser.SPACE_TOKEN]}visitQualifiedName(arg){let token=new SqlPrintToken(0,"","QualifiedName");if(arg.namespaces)for(let i=0;i<arg.namespaces.length;i++)token.innerTokens.push(arg.namespaces[i].accept(this)),token.innerTokens.push(_SqlPrintTokenParser.DOT_TOKEN);let originalNameComments=arg.name.positionedComments,originalNameLegacyComments=arg.name.comments;arg.name.positionedComments=null,arg.name.comments=null;let nameToken=arg.name.accept(this);return token.innerTokens.push(nameToken),arg.name.positionedComments=originalNameComments,arg.name.comments=originalNameLegacyComments,(this.hasPositionedComments(arg.name)||this.hasLegacyComments(arg.name))&&this.addComponentComments(token,arg.name),this.addComponentComments(token,arg),token}visitPartitionByClause(arg){let token=new SqlPrintToken(1,"partition by","PartitionByClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.value)),token}visitOrderByClause(arg){let token=new SqlPrintToken(1,"order by","OrderByClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.order.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.order[i]));return token}visitOrderByItem(arg){let token=new SqlPrintToken(0,"","OrderByItem");return token.innerTokens.push(this.visit(arg.value)),arg.sortDirection&&arg.sortDirection!=="asc"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"desc"))),arg.nullsPosition&&(arg.nullsPosition==="first"?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"nulls first"))):arg.nullsPosition==="last"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"nulls last")))),token}parse(arg){this.index=1;let token=this.visit(arg),paramsRaw=ParameterCollector.collect(arg).sort((a,b)=>(a.index??0)-(b.index??0)),style=this.parameterDecorator.style;if(style==="named"){let paramsObj={};for(let p of paramsRaw){let key=p.name.value;if(paramsObj.hasOwnProperty(key)){if(paramsObj[key]!==p.value)throw new Error(`Duplicate parameter name '${key}' with different values detected during query composition.`);continue}paramsObj[key]=p.value}return{token,params:paramsObj}}else if(style==="indexed"){let paramsArr=paramsRaw.map(p=>p.value);return{token,params:paramsArr}}else if(style==="anonymous"){let paramsArr=paramsRaw.map(p=>p.value);return{token,params:paramsArr}}return{token,params:[]}}componentHandlesOwnComments(component){return"handlesOwnComments"in component&&typeof component.handlesOwnComments=="function"?component.handlesOwnComments():_SqlPrintTokenParser.getSelfHandlingComponentTypes().has(component.getKind())}visit(arg){let handler=this.handlers.get(arg.getKind());if(handler){let token=handler(arg);return this.componentHandlesOwnComments(arg)||this.addComponentComments(token,arg),token}throw new Error(`[SqlPrintTokenParser] No handler for kind: ${arg.getKind().toString()}`)}hasPositionedComments(component){return(component.positionedComments?.length??0)>0}hasLegacyComments(component){return(component.comments?.length??0)>0}addComponentComments(token,component){this.hasPositionedComments(component)?this.addPositionedCommentsToToken(token,component):this.hasLegacyComments(component)&&this.addCommentsToToken(token,component.comments)}addPositionedCommentsToToken(token,component){if(!this.hasPositionedComments(component))return;let beforeComments=component.getPositionedComments("before");if(beforeComments.length>0){let commentBlocks=this.createCommentBlocks(beforeComments);for(let i=commentBlocks.length-1;i>=0;i--)token.innerTokens.unshift(commentBlocks[i])}let afterComments=component.getPositionedComments("after");if(afterComments.length>0){let commentBlocks=this.createCommentBlocks(afterComments);for(let commentBlock of commentBlocks)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(commentBlock)}let componentsWithDuplicationIssues=["CaseExpression","SwitchCaseArgument","CaseKeyValuePair","SelectClause","LiteralValue","IdentifierString","DistinctOn","SourceAliasExpression","SimpleSelectQuery","WhereClause"];token.containerType&&componentsWithDuplicationIssues.includes(token.containerType)&&(component.positionedComments=null)}addCommentsToToken(token,comments){if(!comments?.length)return;let commentBlocks=this.createCommentBlocks(comments);this.insertCommentBlocksWithSpacing(token,commentBlocks)}createInlineCommentSequence(comments){let commentTokens=[];for(let i=0;i<comments.length;i++){let comment=comments[i];if(comment.trim()){let commentToken=new SqlPrintToken(6,this.formatComment(comment));if(commentTokens.push(commentToken),i<comments.length-1){let spaceToken=new SqlPrintToken(10," ");commentTokens.push(spaceToken)}}}return commentTokens}createCommentBlocks(comments,isHeaderComment=!1){let commentBlocks=[];for(let comment of comments){let trimmed=comment.trim(),isSeparatorLine=/^[-=_+*#]+$/.test(trimmed);(trimmed||isSeparatorLine||comment==="")&&commentBlocks.push(this.createSingleCommentBlock(comment,isHeaderComment))}return commentBlocks}shouldMergeComment(trimmed){return!(!/^[-=_+*#]+$/.test(trimmed)&&trimmed.startsWith("--")||trimmed.startsWith("/*")&&trimmed.endsWith("*/")&&(!trimmed.slice(2,-2).trim()||trimmed.includes(`
14
- `)))}createSingleCommentBlock(comment,isHeaderComment=!1){let commentBlock=new SqlPrintToken(0,"","CommentBlock");isHeaderComment&&commentBlock.markAsHeaderComment();let commentToken=new SqlPrintToken(6,this.formatComment(comment));commentBlock.innerTokens.push(commentToken);let commentNewlineToken=new SqlPrintToken(12,"");commentBlock.innerTokens.push(commentNewlineToken);let spaceToken=new SqlPrintToken(10," ");return commentBlock.innerTokens.push(spaceToken),commentBlock}formatComment(comment){let trimmed=comment.trim();return trimmed?/^[-=_+*#]+$/.test(trimmed)?this.formatBlockComment(trimmed):trimmed.startsWith("--")?this.formatLineComment(trimmed.slice(2)):trimmed.startsWith("/*")&&trimmed.endsWith("*/")?this.formatBlockComment(trimmed):this.formatBlockComment(trimmed):"/* */"}insertCommentBlocksWithSpacing(token,commentBlocks){if(token.containerType==="SelectItem"){token.innerTokens.length>0&&token.innerTokens[token.innerTokens.length-1].type!==10&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(...commentBlocks);return}if(token.containerType==="SelectClause"){token.innerTokens.unshift(_SqlPrintTokenParser.SPACE_TOKEN,...commentBlocks);return}if(token.containerType==="IdentifierString"){token.innerTokens.length>0&&token.innerTokens[token.innerTokens.length-1].type!==10&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(...commentBlocks);return}if(token.innerTokens.unshift(...commentBlocks),this.shouldAddSeparatorSpace(token.containerType)){let separatorSpace=new SqlPrintToken(10," ");token.innerTokens.splice(commentBlocks.length,0,separatorSpace),token.innerTokens.length>commentBlocks.length+1&&token.innerTokens[commentBlocks.length+1].type===10&&token.innerTokens.splice(commentBlocks.length+1,1)}else token.innerTokens.length>commentBlocks.length&&token.innerTokens[commentBlocks.length].type===10&&token.innerTokens.splice(commentBlocks.length,1)}addPositionedCommentsToParenExpression(token,component){if(!component.positionedComments)return;let beforeComments=component.getPositionedComments("before");if(beforeComments.length>0){let commentBlocks=this.createCommentBlocks(beforeComments),insertIndex=1;for(let commentBlock of commentBlocks)token.innerTokens.splice(insertIndex,0,commentBlock),insertIndex++}let afterComments=component.getPositionedComments("after");if(afterComments.length>0){let commentBlocks=this.createCommentBlocks(afterComments),insertIndex=token.innerTokens.length;for(let commentBlock of commentBlocks)token.innerTokens.splice(insertIndex-1,0,commentBlock)}}shouldAddSeparatorSpace(containerType){return this.isClauseLevelContainer(containerType)}isClauseLevelContainer(containerType){switch(containerType){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(comment){let hasDelimiters=comment.startsWith("/*")&&comment.endsWith("*/"),rawContent=hasDelimiters?comment.slice(2,-2):comment,lines=this.escapeCommentDelimiters(rawContent).replace(/\r?\n/g,`
13
+ ${context}`;return new _ParseError(message,index,context)}};function extractLexemeComments(lexeme){let before=[],after=[];if(!lexeme)return{before,after};if(lexeme.positionedComments&&lexeme.positionedComments.length>0)for(let positioned of lexeme.positionedComments)!positioned.comments||positioned.comments.length===0||(positioned.position==="before"?before.push(...positioned.comments):positioned.position==="after"&&after.push(...positioned.comments));else lexeme.comments&&lexeme.comments.length>0&&before.push(...lexeme.comments);return{before,after}}var FunctionExpressionParser=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(lexemes,index){let idx=index;if(idx+1<lexemes.length&&lexemes[idx+1].type&512){idx++;let arg=ValueParser.parseArgument(512,1024,lexemes,idx);return idx=arg.newIndex,{value:new ArrayExpression(arg.value),newIndex:idx}}else if(idx+1<lexemes.length&&lexemes[idx+1].type&4){idx++,idx++;let arg=SelectQueryParser.parseFromLexeme(lexemes,idx);return idx=arg.newIndex,idx++,{value:new ArrayQueryExpression(arg.value),newIndex:idx}}throw new Error(`Invalid ARRAY syntax at index ${idx}, expected ARRAY[... or ARRAY(...)`)}static parseFromLexeme(lexemes,index){let idx=index,current=lexemes[idx];return current.value==="array"?this.parseArrayExpression(lexemes,idx):current.value==="substring"||current.value==="overlay"?this.parseKeywordFunction(lexemes,idx,[{key:"from",required:!1},{key:"for",required:!1}]):current.value==="cast"?this.parseKeywordFunction(lexemes,idx,[{key:"as",required:!0}]):current.value==="trim"?this.parseKeywordFunction(lexemes,idx,[{key:"from",required:!1}]):this.parseFunctionCall(lexemes,idx)}static tryParseBinaryExpression(lexemes,index,left,allowAndOperator=!0,allowOrOperator=!0){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&2){let operator=lexemes[idx].value.toLowerCase();if(!allowAndOperator&&operator==="and"||!allowOrOperator&&operator==="or")return null;if(idx++,operator==="between")return this.parseBetweenExpression(lexemes,idx,left,!1);if(operator==="not between")return this.parseBetweenExpression(lexemes,idx,left,!0);if(operator==="::"){let typeValue=this.parseTypeValue(lexemes,idx);return idx=typeValue.newIndex,{value:new CastExpression(left,typeValue.value),newIndex:idx}}let rightResult=ValueParser.parseFromLexeme(lexemes,idx);return idx=rightResult.newIndex,{value:new BinaryExpression(left,operator,rightResult.value),newIndex:idx}}return null}static parseBetweenExpression(lexemes,index,value,negated){let idx=index,lower=ValueParser.parseFromLexeme(lexemes,idx,!1);if(idx=lower.newIndex,idx<lexemes.length&&lexemes[idx].type&2&&lexemes[idx].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${idx}`);idx++;let upper=this.parseBetweenUpperBound(lexemes,idx);return idx=upper.newIndex,{value:new BetweenExpression(value,lower.value,upper.value,negated),newIndex:idx}}static parseBetweenUpperBound(lexemes,index){return ValueParser.parseFromLexeme(lexemes,index,!1,!1)}static parseFunctionCall(lexemes,index){let idx=index,fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx),namespaces=fullNameResult.namespaces,name=fullNameResult.name;if(idx=fullNameResult.newIndex,idx<lexemes.length&&lexemes[idx].type&4){let functionName=name.name.toLowerCase(),arg,closingComments=null,internalOrderBy=null;if(this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY.has(functionName)){let result=this.parseAggregateArguments(lexemes,idx);arg={value:result.arguments,newIndex:result.newIndex},internalOrderBy=result.orderByClause,closingComments=result.closingComments}else{let argWithComments=this.parseArgumentWithComments(lexemes,idx);arg={value:argWithComments.value,newIndex:argWithComments.newIndex},closingComments=argWithComments.closingComments}idx=arg.newIndex;let withinGroup=null;if(idx<lexemes.length&&lexemes[idx].value==="within group"){let withinGroupResult=this.parseWithinGroupClause(lexemes,idx);withinGroup=withinGroupResult.value,idx=withinGroupResult.newIndex}let withOrdinality=!1;if(idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++),idx<lexemes.length&&lexemes[idx].value==="over"){let over=OverExpressionParser.parseFromLexeme(lexemes,idx);idx=over.newIndex;let value=new FunctionCall(namespaces,name.name,arg.value,over.value,withinGroup,withOrdinality,internalOrderBy);return closingComments&&closingComments.length>0&&value.addPositionedComments("after",closingComments),{value,newIndex:idx}}else{let value=new FunctionCall(namespaces,name.name,arg.value,null,withinGroup,withOrdinality,internalOrderBy);return closingComments&&closingComments.length>0&&value.addPositionedComments("after",closingComments),{value,newIndex:idx}}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Expected opening parenthesis after function name '${name.name}'.`)}static parseKeywordFunction(lexemes,index,keywords2){let idx=index,fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx),namespaces=fullNameResult.namespaces,name=fullNameResult.name;if(idx=fullNameResult.newIndex,idx<lexemes.length&&lexemes[idx].type&4){idx++;let input=ValueParser.parseFromLexeme(lexemes,idx),arg=input.value;if(idx=input.newIndex,idx<lexemes.length&&lexemes[idx].type&16)return this.parseFunctionCall(lexemes,index);for(let{key,required}of keywords2)if(idx<lexemes.length&&lexemes[idx].type&128&&lexemes[idx].value===key)if(idx++,idx<lexemes.length&&lexemes[idx].type&8192){let typeValue=this.parseTypeValue(lexemes,idx);arg=new BinaryExpression(arg,key,typeValue.value),idx=typeValue.newIndex}else{let right=ValueParser.parseFromLexeme(lexemes,idx);arg=new BinaryExpression(arg,key,right.value),idx=right.newIndex}else if(required)throw ParseError.fromUnparsedLexemes(lexemes,idx,`Keyword '${key}' is required for ${name.name} function.`);if(idx<lexemes.length&&lexemes[idx].type&8){idx++;let withinGroup=null;if(idx<lexemes.length&&lexemes[idx].value==="within group"){let withinGroupResult=this.parseWithinGroupClause(lexemes,idx);withinGroup=withinGroupResult.value,idx=withinGroupResult.newIndex}let withOrdinality=!1;if(idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++),idx<lexemes.length&&lexemes[idx].value==="over"){idx++;let over=OverExpressionParser.parseFromLexeme(lexemes,idx);return idx=over.newIndex,{value:new FunctionCall(namespaces,name.name,arg,over.value,withinGroup,withOrdinality,null),newIndex:idx}}else return{value:new FunctionCall(namespaces,name.name,arg,null,withinGroup,withOrdinality,null),newIndex:idx}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Missing closing parenthesis for function '${name.name}'.`)}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Missing opening parenthesis for function '${name.name}'.`)}static parseTypeValue(lexemes,index){let idx=index,{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,idx<lexemes.length&&lexemes[idx].type&4){let arg=ValueParser.parseArgument(4,8,lexemes,idx);idx=arg.newIndex;let value=new TypeValue(namespaces,new RawString(name.name),arg.value);return arg.value.positionedComments&&(value.positionedComments=arg.value.positionedComments),arg.value.comments,{value,newIndex:idx}}else return{value:new TypeValue(namespaces,new RawString(name.name)),newIndex:idx}}static parseWithinGroupClause(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].value!=="within group")throw new Error(`Expected 'WITHIN GROUP' at index ${idx}`);if(idx++,idx>=lexemes.length||!(lexemes[idx].type&4))throw new Error(`Expected '(' after 'WITHIN GROUP' at index ${idx}`);idx++;let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);if(idx=orderByResult.newIndex,idx>=lexemes.length||!(lexemes[idx].type&8))throw new Error(`Expected ')' after WITHIN GROUP ORDER BY clause at index ${idx}`);return idx++,{value:orderByResult.value,newIndex:idx}}static parseAggregateArguments(lexemes,index){let idx=index,args=[],orderByClause=null;if(idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected opening parenthesis.");if(idx++,idx<lexemes.length&&lexemes[idx].type&8){let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{arguments:new ValueList([]),orderByClause:null,closingComments:closingComments2,newIndex:idx}}if(idx<lexemes.length&&lexemes[idx].value==="*"){let wildcard=new ColumnReference(null,"*");if(idx++,idx<lexemes.length&&lexemes[idx].type&8){let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{arguments:wildcard,orderByClause:null,closingComments:closingComments2,newIndex:idx}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis after wildcard '*'.")}let firstArg=ValueParser.parseFromLexeme(lexemes,idx);for(idx=firstArg.newIndex,args.push(firstArg.value);idx<lexemes.length&&(lexemes[idx].type&16||lexemes[idx].value==="order by");){if(lexemes[idx].value==="order by"){let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);idx=orderByResult.newIndex,orderByClause=orderByResult.value;break}if(lexemes[idx].type&16){if(idx++,idx<lexemes.length&&lexemes[idx].value==="order by"){let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);idx=orderByResult.newIndex,orderByClause=orderByResult.value;break}let argResult=ValueParser.parseFromLexeme(lexemes,idx);idx=argResult.newIndex,args.push(argResult.value)}}if(idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis.");let closingComments=this.getClosingComments(lexemes[idx]);return idx++,{arguments:args.length===1?args[0]:new ValueList(args),orderByClause,closingComments,newIndex:idx}}static parseArgumentWithComments(lexemes,index){let idx=index;if(idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected opening parenthesis.");let openParenToken=lexemes[idx];idx++;let args=[];if(idx<lexemes.length&&lexemes[idx].type&8){let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{value:new ValueList([]),closingComments:closingComments2,newIndex:idx}}if(idx<lexemes.length&&lexemes[idx].value==="*"){let wildcard=new ColumnReference(null,"*");if(idx++,idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis after wildcard '*'.");let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{value:wildcard,closingComments:closingComments2,newIndex:idx}}let result=ValueParser.parseFromLexeme(lexemes,idx);if(idx=result.newIndex,openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let afterComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){let beforeComments=afterComments.map(pc=>({position:"before",comments:pc.comments}));result.value.positionedComments=[...beforeComments,...result.value.positionedComments||[]],result.value,"qualifiedName"in result.value&&result.value.qualifiedName&&"name"in result.value.qualifiedName&&result.value.qualifiedName.name&&(result.value.qualifiedName.name.positionedComments=null,result.value.qualifiedName.name)}}for(args.push(result.value);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let argResult=ValueParser.parseFromLexeme(lexemes,idx);idx=argResult.newIndex,args.push(argResult.value)}if(idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis.");let closingComments=this.getClosingComments(lexemes[idx]);return idx++,{value:args.length===1?args[0]:new ValueList(args),closingComments,newIndex:idx}}static getClosingComments(lexeme){if(!lexeme)return null;let commentInfo=extractLexemeComments(lexeme);return commentInfo.after.length>0?commentInfo.after:commentInfo.before.length>0?commentInfo.before:null}};var OperatorPrecedence=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(operator){let precedence=this.precedenceMap[operator.toLowerCase()];return precedence!==void 0?precedence:0}static hasHigherOrEqualPrecedence(operator1,operator2){return this.getPrecedence(operator1)>=this.getPrecedence(operator2)}static isLogicalOperator(operator){let op=operator.toLowerCase();return op==="and"||op==="or"}static isBetweenOperator(operator){let op=operator.toLowerCase();return op==="between"||op==="not between"}static isComparisonOperator(operator){let lowerOp=operator.toLowerCase();return["=","!=","<>","<",">","<=",">=","like","ilike","similar to","in","not in","->","->>","#>","#>>","@>","<@","?","?|","?&","~","~*","!~","!~*","rlike","regexp"].includes(lowerOp)}};var ValueParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw ParseError.fromUnparsedLexemes(lexemes,result.newIndex,"[ValueParser]");return result.value}static parseFromLexeme(lexemes,index,allowAndOperator=!0,allowOrOperator=!0){return this.parseExpressionWithPrecedence(lexemes,index,0,allowAndOperator,allowOrOperator)}static parseExpressionWithPrecedence(lexemes,index,minPrecedence,allowAndOperator=!0,allowOrOperator=!0){let idx=index,comment=lexemes[idx].comments,positionedComments=lexemes[idx].positionedComments,left=this.parseItem(lexemes,idx);positionedComments&&positionedComments.length>0&&!left.value.positionedComments?left.value.positionedComments=positionedComments:left.value.comments===null&&comment&&comment.length>0&&(left.value.comments=comment),idx=left.newIndex;let result=left.value,arrayAccessResult=this.parseArrayAccess(lexemes,idx,result);for(result=arrayAccessResult.value,idx=arrayAccessResult.newIndex;idx<lexemes.length&&lexemes[idx].type&2;){let operatorToken=lexemes[idx],operator=operatorToken.value;if(!allowAndOperator&&operator.toLowerCase()==="and"||!allowOrOperator&&operator.toLowerCase()==="or")break;let precedence=OperatorPrecedence.getPrecedence(operator);if(precedence<minPrecedence)break;if(idx++,OperatorPrecedence.isBetweenOperator(operator)){let betweenResult=FunctionExpressionParser.parseBetweenExpression(lexemes,idx,result,operator.toLowerCase().includes("not"));result=betweenResult.value,idx=betweenResult.newIndex;continue}if(operator==="::"){let typeValue=FunctionExpressionParser.parseTypeValue(lexemes,idx);result=new CastExpression(result,typeValue.value),idx=typeValue.newIndex;continue}let nextMinPrecedence=precedence+1,rightResult=this.parseExpressionWithPrecedence(lexemes,idx,nextMinPrecedence,allowAndOperator,allowOrOperator);idx=rightResult.newIndex;let binaryExpr=new BinaryExpression(result,operator,rightResult.value);operatorToken.comments&&operatorToken.comments.length>0&&(binaryExpr.operator.comments=operatorToken.comments),operatorToken.positionedComments&&operatorToken.positionedComments.length>0&&(binaryExpr.operator.positionedComments=operatorToken.positionedComments),result=binaryExpr}return{value:result,newIndex:idx}}static transferPositionedComments(lexeme,value){lexeme.positionedComments&&lexeme.positionedComments.length>0&&!value.positionedComments?value.positionedComments=lexeme.positionedComments:value.comments===null&&lexeme.comments&&lexeme.comments.length>0&&(value.comments=lexeme.comments)}static parseItem(lexemes,index){let idx=index;if(idx>=lexemes.length)throw new Error(`Unexpected end of lexemes at index ${index}`);let current=lexemes[idx];if(current.type&64&&current.type&2&&current.type&8192){if(idx+1<lexemes.length&&lexemes[idx+1].type&4)if(this.isTypeConstructor(lexemes,idx+1,current.value)){let result=FunctionExpressionParser.parseTypeValue(lexemes,idx);return this.transferPositionedComments(current,result.value),{value:result.value,newIndex:result.newIndex}}else{let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}let first=IdentifierParser.parseFromLexeme(lexemes,idx);if(first.newIndex>=lexemes.length)return this.transferPositionedComments(current,first.value),first;if(lexemes[first.newIndex].type&1){let literalIndex=first.newIndex,literalLexeme=lexemes[literalIndex],second=LiteralParser.parseFromLexeme(lexemes,literalIndex);this.transferPositionedComments(literalLexeme,second.value);let result=new UnaryExpression(lexemes[idx].value,second.value);return this.transferPositionedComments(current,result),{value:result,newIndex:second.newIndex}}return this.transferPositionedComments(current,first.value),first}else if(current.type&64){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(lexemes[newIndex-1].type&2048){let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(lexemes[newIndex-1].type&8192)if(newIndex<lexemes.length&&lexemes[newIndex].type&4)if(this.isTypeConstructor(lexemes,newIndex,name.name)){let result=FunctionExpressionParser.parseTypeValue(lexemes,idx);return this.transferPositionedComments(current,result.value),{value:result.value,newIndex:result.newIndex}}else{let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else{let value2=new TypeValue(namespaces,name);return this.transferPositionedComments(current,value2),{value:value2,newIndex}}let value=new ColumnReference(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}else if(current.type&1){let result=LiteralParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&4){let result=ParenExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&2048){let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&2){let result=UnaryExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&256){let result=ParameterExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&4096){let result=StringSpecifierExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&128){let result=CommandExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&512){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx),value=new ColumnReference(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}else if(current.type&8192){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(newIndex<lexemes.length&&lexemes[newIndex].type&4)if(this.isTypeConstructor(lexemes,newIndex,name.name)){let result=FunctionExpressionParser.parseTypeValue(lexemes,idx);return this.transferPositionedComments(current,result.value),{value:result.value,newIndex:result.newIndex}}else{let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else{let value=new TypeValue(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}}throw ParseError.fromUnparsedLexemes(lexemes,idx,"[ValueParser] Invalid lexeme.")}static parseArgument(openToken,closeToken,lexemes,index){let idx=index,args=[];if(idx<lexemes.length&&lexemes[idx].type===openToken){let openParenToken=lexemes[idx];if(idx++,idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,{value:new ValueList([]),newIndex:idx};if(idx<lexemes.length&&lexemes[idx].value==="*"){let wildcard=new ColumnReference(null,"*");if(openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let beforeComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");beforeComments.length>0&&(wildcard.positionedComments=beforeComments.map(pc=>({position:"before",comments:pc.comments})))}else openParenToken.comments&&openParenToken.comments.length>0&&(wildcard.comments=openParenToken.comments);if(idx++,idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,{value:wildcard,newIndex:idx};throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis after wildcard '*'.")}let result=this.parseFromLexeme(lexemes,idx);if(idx=result.newIndex,openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let afterComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){let beforeComments=afterComments.map(pc=>({position:"before",comments:pc.comments}));result.value.positionedComments?result.value.positionedComments=[...beforeComments,...result.value.positionedComments]:result.value.positionedComments=beforeComments}}else openParenToken.comments&&openParenToken.comments.length>0&&(result.value.comments?result.value.comments=openParenToken.comments.concat(result.value.comments):result.value.comments=openParenToken.comments);for(args.push(result.value);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let argResult=this.parseFromLexeme(lexemes,idx);idx=argResult.newIndex,args.push(argResult.value)}if(idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,args.length===1?{value:args[0],newIndex:idx}:{value:new ValueList(args),newIndex:idx};throw ParseError.fromUnparsedLexemes(lexemes,idx,"Missing closing parenthesis.")}throw ParseError.fromUnparsedLexemes(lexemes,index,"Expected opening parenthesis.")}static parseArrayAccess(lexemes,index,baseExpression){let idx=index,result=baseExpression;for(;idx<lexemes.length&&lexemes[idx].type&512&&!this.isSqlServerBracketIdentifier(lexemes,idx);){if(idx++,idx>=lexemes.length)throw new Error(`Expected array index or slice after '[' at index ${idx-1}`);if(lexemes[idx].type&1024)throw new Error(`Empty array access brackets not supported at index ${idx}`);let startExpr=null,isSlice=!1;if(lexemes[idx].type&2&&lexemes[idx].value===":")isSlice=!0,idx++;else{let colonPrecedence=OperatorPrecedence.getPrecedence(":"),firstResult=this.parseExpressionWithPrecedence(lexemes,idx,colonPrecedence+1);startExpr=firstResult.value,idx=firstResult.newIndex,idx<lexemes.length&&lexemes[idx].type&2&&lexemes[idx].value===":"&&(isSlice=!0,idx++)}if(isSlice){let endExpr=null;if(idx<lexemes.length&&!(lexemes[idx].type&1024)){let colonPrecedence=OperatorPrecedence.getPrecedence(":"),endResult=this.parseExpressionWithPrecedence(lexemes,idx,colonPrecedence+1);endExpr=endResult.value,idx=endResult.newIndex}if(idx>=lexemes.length||!(lexemes[idx].type&1024))throw new Error(`Expected ']' after array slice at index ${idx}`);idx++,result=new ArraySliceExpression(result,startExpr,endExpr)}else{if(!startExpr){let indexResult=this.parseFromLexeme(lexemes,idx);startExpr=indexResult.value,idx=indexResult.newIndex}if(idx>=lexemes.length||!(lexemes[idx].type&1024))throw new Error(`Expected ']' after array index at index ${idx}`);idx++,result=new ArrayIndexExpression(result,startExpr)}}return{value:result,newIndex:idx}}static isSqlServerBracketIdentifier(lexemes,bracketIndex){let idx=bracketIndex+1;if(idx>=lexemes.length)return!1;for(;idx<lexemes.length&&!(lexemes[idx].type&1024);){let token=lexemes[idx];if(token.type&64||token.type&2&&token.value==="."){idx++;continue}return!1}if(idx>=lexemes.length)return!1;let closingBracketIndex=idx;if(closingBracketIndex+1<lexemes.length){let nextToken=lexemes[closingBracketIndex+1];if(nextToken.type&2&&nextToken.value===".")return!0}idx=bracketIndex+1;let hasOnlyIdentifiersAndDots=!0;for(;idx<closingBracketIndex;){let token=lexemes[idx];if(!(token.type&64||token.type&2&&token.value===".")){hasOnlyIdentifiersAndDots=!1;break}idx++}return hasOnlyIdentifiersAndDots}static isTypeConstructor(lexemes,openParenIndex,typeName){let alwaysTypeConstructors=["NUMERIC","DECIMAL","VARCHAR","CHAR","CHARACTER","TIMESTAMP","TIME","INTERVAL"],upperTypeName=typeName.toUpperCase();if(alwaysTypeConstructors.includes(upperTypeName))return!0;if(upperTypeName==="DATE"){let firstArgIndex=openParenIndex+1;if(firstArgIndex<lexemes.length){let firstArg=lexemes[firstArgIndex];return!(firstArg.type&1&&typeof firstArg.value=="string"&&isNaN(Number(firstArg.value)))}}return!1}};var CTECollector=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}getCommonTables(){return this.commonTables}reset(){this.commonTables=[],this.visitedNodes.clear()}collect(query){return this.visit(query),this.getCommonTables()}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}let kindSymbol=arg.getKind()?.toString()||"unknown",constructor=arg.constructor?.name||"unknown";throw new Error(`[CTECollector] No handler for ${constructor} with kind ${kindSymbol}.`)}visitSimpleSelectQuery(query){if(query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.orderByClause&&query.orderByClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.limitClause&&query.limitClause.accept(this),query.forClause&&query.forClause.accept(this),query.selectClause.accept(this),query.withClause&&query.withClause.accept(this)}visitBinarySelectQuery(query){query.left.accept(this),query.right.accept(this)}visitValuesQuery(query){for(let tuple of query.tuples)tuple.accept(this)}visitWithClause(withClause){for(let i=0;i<withClause.tables.length;i++)withClause.tables[i].accept(this)}visitCommonTable(commonTable){commonTable.query.accept(this),this.commonTables.push(commonTable)}visitSelectClause(clause){for(let item of clause.items)item.accept(this)}visitSelectItem(item){item.value.accept(this)}visitFromClause(fromClause){if(fromClause.source.accept(this),fromClause.joins)for(let join of fromClause.joins)join.accept(this)}visitSourceExpression(source){source.datasource.accept(this)}visitTableSource(source){}visitFunctionSource(source){source.argument&&source.argument.accept(this)}visitParenSource(source){source.source.accept(this)}visitSubQuerySource(subQuery){subQuery.query.accept(this)}visitInlineQuery(inlineQuery){inlineQuery.selectQuery.accept(this)}visitJoinClause(joinClause){joinClause.source.accept(this),joinClause.condition&&joinClause.condition.accept(this)}visitJoinOnClause(joinOn){joinOn.condition.accept(this)}visitJoinUsingClause(joinUsing){joinUsing.condition.accept(this)}visitWhereClause(whereClause){whereClause.condition.accept(this)}visitGroupByClause(clause){for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition.accept(this)}visitOrderByClause(clause){for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitLimitClause(clause){clause.value.accept(this)}visitForClause(clause){}visitOrderByItem(item){item.value.accept(this)}visitParenExpression(expr){expr.expression.accept(this)}visitBinaryExpression(expr){expr.left.accept(this),expr.right.accept(this)}visitUnaryExpression(expr){expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase.accept(this)}visitSwitchCaseArgument(switchCase){for(let caseItem of switchCase.cases)caseItem.accept(this);switchCase.elseValue&&switchCase.elseValue.accept(this)}visitCaseKeyValuePair(pair){pair.key.accept(this),pair.value.accept(this)}visitBetweenExpression(expr){expr.expression.accept(this),expr.lower.accept(this),expr.upper.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this)}visitArrayExpression(expr){expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitTupleExpression(expr){for(let value of expr.values)value.accept(this)}visitCastExpression(expr){expr.input.accept(this),expr.castType.accept(this)}visitTypeValue(expr){expr.argument&&expr.argument.accept(this)}visitWindowFrameExpression(expr){expr.partition&&expr.partition.accept(this),expr.order&&expr.order.accept(this),expr.frameSpec&&expr.frameSpec.accept(this)}visitWindowFrameSpec(spec){}visitIdentifierString(ident){}visitRawString(raw){}visitColumnReference(column){}visitParameterExpression(param){}visitLiteralValue(value){}visitPartitionByClause(partitionBy){}visitValueList(valueList){for(let value of valueList.values)value.accept(this)}visitStringSpecifierExpression(expr){}};var CTEDisabler=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}reset(){this.visitedNodes.clear()}execute(arg){return this.reset(),this.visit(arg)}visit(arg){if(!this.isRootVisit)return this.visitNode(arg);this.reset(),this.isRootVisit=!1;try{return this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return arg;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler)return handler(arg);let kindSymbol=arg.getKind()?.toString()||"unknown",constructor=arg.constructor?.name||"unknown";throw new Error(`[CTEDisabler] No handler for ${constructor} with kind ${kindSymbol}.`)}visitSimpleSelectQuery(arg){return arg.withClause&&arg.withClause.tables.forEach(table=>{this.visit(table.query)}),arg.withClause=null,arg.selectClause=this.visit(arg.selectClause),arg.fromClause=arg.fromClause?this.visit(arg.fromClause):null,arg.whereClause=arg.whereClause?this.visit(arg.whereClause):null,arg.groupByClause=arg.groupByClause?this.visit(arg.groupByClause):null,arg.havingClause=arg.havingClause?this.visit(arg.havingClause):null,arg.orderByClause=arg.orderByClause?this.visit(arg.orderByClause):null,arg.windowClause&&(arg.windowClause=new WindowsClause(arg.windowClause.windows.map(w=>this.visit(w)))),arg.limitClause=arg.limitClause?this.visit(arg.limitClause):null,arg.forClause=arg.forClause?this.visit(arg.forClause):null,arg}visitBinarySelectQuery(query){return query.left=this.visit(query.left),query.right=this.visit(query.right),query}visitValuesQuery(query){let newTuples=query.tuples.map(tuple=>this.visit(tuple));return new ValuesQuery(newTuples)}visitSelectClause(clause){let newItems=clause.items.map(item=>this.visit(item));return new SelectClause(newItems,clause.distinct)}visitFromClause(clause){let newSource=this.visit(clause.source),newJoins=clause.joins?clause.joins.map(join=>this.visit(join)):null;return new FromClause(newSource,newJoins)}visitSubQuerySource(subQuery){let newQuery=this.visit(subQuery.query);return new SubQuerySource(newQuery)}visitInlineQuery(inlineQuery){let newQuery=this.visit(inlineQuery.selectQuery);return new InlineQuery(newQuery)}visitJoinClause(joinClause){let newSource=this.visit(joinClause.source),newCondition=joinClause.condition?this.visit(joinClause.condition):null;return new JoinClause(joinClause.joinType.value,newSource,newCondition,joinClause.lateral)}visitJoinOnClause(joinOn){let newCondition=this.visit(joinOn.condition);return new JoinOnClause(newCondition)}visitJoinUsingClause(joinUsing){let newCondition=this.visit(joinUsing.condition);return new JoinUsingClause(newCondition)}visitWhereClause(whereClause){let newCondition=this.visit(whereClause.condition);return new WhereClause(newCondition)}visitGroupByClause(clause){let newGrouping=clause.grouping.map(item=>this.visit(item));return new GroupByClause(newGrouping)}visitHavingClause(clause){let newCondition=this.visit(clause.condition);return new HavingClause(newCondition)}visitOrderByClause(clause){let newOrder=clause.order.map(item=>this.visit(item));return new OrderByClause(newOrder)}visitWindowFrameClause(clause){let newExpression=this.visit(clause.expression);return new WindowFrameClause(clause.name.name,newExpression)}visitLimitClause(clause){let newLimit=this.visit(clause.value);return new LimitClause(newLimit)}visitForClause(clause){return new ForClause(clause.lockMode)}visitParenExpression(expr){let newExpression=this.visit(expr.expression);return new ParenExpression(newExpression)}visitBinaryExpression(expr){let newLeft=this.visit(expr.left),newRight=this.visit(expr.right);return new BinaryExpression(newLeft,expr.operator.value,newRight)}visitUnaryExpression(expr){let newExpression=this.visit(expr.expression);return new UnaryExpression(expr.operator.value,newExpression)}visitCaseExpression(expr){let newCondition=expr.condition?this.visit(expr.condition):null,newSwitchCase=this.visit(expr.switchCase);return new CaseExpression(newCondition,newSwitchCase)}visitSwitchCaseArgument(switchCase){let newCases=switchCase.cases.map(caseItem=>this.visit(caseItem)),newElseValue=switchCase.elseValue?this.visit(switchCase.elseValue):null;return new SwitchCaseArgument(newCases,newElseValue)}visitCaseKeyValuePair(pair){let newKey=this.visit(pair.key),newValue=this.visit(pair.value);return new CaseKeyValuePair(newKey,newValue)}visitBetweenExpression(expr){let newExpression=this.visit(expr.expression),newLower=this.visit(expr.lower),newUpper=this.visit(expr.upper);return new BetweenExpression(newExpression,newLower,newUpper,expr.negated)}visitFunctionCall(func){let newArgument=func.argument?this.visit(func.argument):null,newOver=func.over?this.visit(func.over):null;return new FunctionCall(func.namespaces,func.name,newArgument,newOver)}visitArrayExpression(expr){let newExpression=this.visit(expr.expression);return new ArrayExpression(newExpression)}visitArrayQueryExpression(expr){let newQuery=this.visit(expr.query);return new ArrayQueryExpression(newQuery)}visitTupleExpression(expr){let newValues=expr.values.map(value=>this.visit(value));return new TupleExpression(newValues)}visitCastExpression(expr){let newInput=this.visit(expr.input),newCastType=this.visit(expr.castType);return new CastExpression(newInput,newCastType)}visitTypeValue(typeValue){let newArgument=typeValue.argument?this.visit(typeValue.argument):null;return new TypeValue(typeValue.namespaces,typeValue.name,newArgument)}visitSelectItem(item){let newValue=this.visit(item.value);return new SelectItem(newValue,item.identifier?.name)}visitIdentifierString(ident){return ident}visitRawString(raw){return raw}visitColumnReference(column){return column}visitSourceExpression(source){let newSource=this.visit(source.datasource),newAlias=source.aliasExpression;return new SourceExpression(newSource,newAlias)}visitTableSource(source){return source}visitParenSource(source){let newSource=this.visit(source.source);return new ParenSource(newSource)}visitParameterExpression(param){return param}visitWindowFrameExpression(expr){let newPartition=expr.partition?this.visit(expr.partition):null,newOrder=expr.order?this.visit(expr.order):null,newFrameSpec=expr.frameSpec?this.visit(expr.frameSpec):null;return new WindowFrameExpression(newPartition,newOrder,newFrameSpec)}visitWindowFrameSpec(spec){return spec}visitLiteralValue(value){return value}visitOrderByItem(item){let newValue=this.visit(item.value);return new OrderByItem(newValue,item.sortDirection,item.nullsPosition)}visitValueList(valueList){let newValues=valueList.values.map(value=>this.visit(value));return new ValueList(newValues)}visitArraySliceExpression(expr){return expr}visitArrayIndexExpression(expr){return expr}visitStringSpecifierExpression(expr){return expr}visitPartitionByClause(clause){let newValue=this.visit(clause.value);return new PartitionByClause(newValue)}};var TableSourceCollector=class{constructor(selectableOnly=!0){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.cteNames=new Set;this.isRootVisit=!0;this.selectableOnly=selectableOnly,this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),selectableOnly||(this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.visitOffsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)))}getTableSources(){return this.tableSources}reset(){this.tableSources=[],this.tableNameMap.clear(),this.visitedNodes.clear(),this.cteNames.clear()}getTableIdentifier(source){return source.qualifiedName.namespaces&&source.qualifiedName.namespaces.length>0?source.qualifiedName.namespaces.map(ns=>ns.name).join(".")+"."+(source.qualifiedName.name instanceof RawString?source.qualifiedName.name.value:source.qualifiedName.name.name):source.qualifiedName.name instanceof RawString?source.qualifiedName.name.value:source.qualifiedName.name.name}collect(query){return this.visit(query),this.getTableSources()}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.selectableOnly||this.collectCTEs(arg),this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}}collectCTEs(query){let cteCollector=new CTECollector;cteCollector.visit(query);let commonTables=cteCollector.getCommonTables();for(let cte of commonTables)this.cteNames.add(cte.aliasExpression.table.name)}visitSimpleSelectQuery(query){if(query.fromClause&&query.fromClause.accept(this),!this.selectableOnly){if(query.withClause&&query.withClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.orderByClause&&query.orderByClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.limitClause&&query.limitClause.accept(this),query.offsetClause&&query.offsetClause.accept(this),query.fetchClause&&query.fetchClause.accept(this),query.forClause&&query.forClause.accept(this),query.selectClause.accept(this)}}visitBinarySelectQuery(query){query.left.accept(this),query.right.accept(this)}visitValuesQuery(query){if(!this.selectableOnly)for(let tuple of query.tuples)tuple.accept(this)}visitWithClause(withClause){if(!this.selectableOnly)for(let table of withClause.tables)table.accept(this)}visitCommonTable(commonTable){this.selectableOnly||commonTable.query.accept(this)}visitFromClause(fromClause){if(fromClause.source.accept(this),fromClause.joins)for(let join of fromClause.joins)join.accept(this)}visitSourceExpression(source){source.datasource.accept(this)}visitTableSource(source){let identifier=this.getTableIdentifier(source);!this.tableNameMap.has(identifier)&&!this.isCTETable(source.table.name)&&(this.tableNameMap.set(identifier,!0),this.tableSources.push(source))}visitFunctionSource(source){source.argument&&this.visitValueComponent(source.argument)}visitValueComponent(value){value.accept(this)}isCTETable(tableName){return this.cteNames.has(tableName)}visitParenSource(source){source.source.accept(this)}visitSubQuerySource(subQuery){this.selectableOnly||subQuery.query.accept(this)}visitInlineQuery(inlineQuery){this.selectableOnly||inlineQuery.selectQuery.accept(this)}visitJoinClause(joinClause){joinClause.source.accept(this),!this.selectableOnly&&joinClause.condition&&joinClause.condition.accept(this)}visitJoinOnClause(joinOn){this.selectableOnly||joinOn.condition.accept(this)}visitJoinUsingClause(joinUsing){this.selectableOnly||joinUsing.condition.accept(this)}visitWhereClause(whereClause){whereClause.condition.accept(this)}visitGroupByClause(clause){for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition.accept(this)}visitOrderByClause(clause){for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitLimitClause(clause){clause.value.accept(this)}visitOffsetClause(clause){clause.value.accept(this)}visitFetchClause(clause){clause.expression.accept(this)}visitForClause(_clause){}visitOrderByItem(item){item.value.accept(this)}visitSelectClause(clause){for(let item of clause.items)item.accept(this)}visitSelectItem(item){item.value.accept(this)}visitParenExpression(expr){expr.expression.accept(this)}visitBinaryExpression(expr){expr.left.accept(this),expr.right.accept(this)}visitUnaryExpression(expr){expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase.accept(this)}visitSwitchCaseArgument(switchCase){for(let caseItem of switchCase.cases)caseItem.accept(this);switchCase.elseValue&&switchCase.elseValue.accept(this)}visitCaseKeyValuePair(pair){pair.key.accept(this),pair.value.accept(this)}visitBetweenExpression(expr){expr.expression.accept(this),expr.lower.accept(this),expr.upper.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this)}visitArrayExpression(expr){expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitTupleExpression(expr){for(let value of expr.values)value.accept(this)}visitCastExpression(expr){expr.input.accept(this),expr.castType.accept(this)}visitValueList(valueList){for(let value of valueList.values)value.accept(this)}visitStringSpecifierExpression(_expr){}};var HintClause=class extends SqlComponent{static{this.kind=Symbol("HintClause")}constructor(hintContent){super(),this.hintContent=hintContent}getFullHint(){return"/*+ "+this.hintContent+" */"}static isHintClause(value){let trimmed=value.trim();return trimmed.length>=5&&trimmed.substring(0,3)==="/*+"&&trimmed.substring(trimmed.length-2)==="*/"}static extractHintContent(hintClause){let trimmed=hintClause.trim();if(!this.isHintClause(trimmed))throw new Error("Not a valid hint clause: "+hintClause);return trimmed.slice(3,-2).trim()}};var SqlPrintToken=class{constructor(type,text="",containerType=""){this.innerTokens=[];this.type=type,this.text=text,this.containerType=containerType}markAsHeaderComment(){if(this.containerType!=="CommentBlock")throw new Error("Header comment flag must only be applied to CommentBlock containers.");this.isHeaderComment=!0}};var ParameterCollector=class{static collect(node){let result=[];function walk(n){if(!(!n||typeof n!="object")){n.constructor&&n.constructor.kind===ParameterExpression.kind&&result.push(n);for(let key of Object.keys(n)){let v=n[key];Array.isArray(v)?v.forEach(walk):v&&typeof v=="object"&&v.constructor&&v.constructor.kind&&walk(v)}}}return walk(node),result}};var IdentifierDecorator=class{constructor(identifierEscape){this.start=identifierEscape?.start??'"',this.end=identifierEscape?.end??'"'}decorate(text){return text=this.start+text+this.end,text}};var ParameterDecorator=class{constructor(options){this.prefix=options?.prefix??":",this.suffix=options?.suffix??"",this.style=options?.style??"named"}decorate(text,index){let paramText="";return this.style==="anonymous"?paramText=this.prefix:this.style==="indexed"?paramText=this.prefix+index:this.style==="named"&&(paramText=this.prefix+text+this.suffix),text=paramText,text}};var UpdateQuery=class extends SqlComponent{static{this.kind=Symbol("UpdateQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.updateClause=params.updateClause,this.setClause=params.setClause instanceof SetClause?params.setClause:new SetClause(params.setClause),this.whereClause=params.whereClause??null,this.fromClause=params.fromClause??null,this.returningClause=params.returning??null}};var DeleteQuery=class extends SqlComponent{static{this.kind=Symbol("DeleteQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.deleteClause=params.deleteClause,this.usingClause=params.usingClause??null,this.whereClause=params.whereClause??null,this.returningClause=params.returning??null}};var SelectValueCollector=class _SelectValueCollector{constructor(tableColumnResolver=null,initialCommonTables=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=tableColumnResolver??null,this.commonTableCollector=new CTECollector,this.commonTables=[],this.initialCommonTables=initialCommonTables,this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr))}getValues(){return this.selectValues}reset(){this.selectValues=[],this.visitedNodes.clear(),this.initialCommonTables?this.commonTables=this.initialCommonTables:this.commonTables=[]}collect(arg){this.visit(arg);let items=this.getValues();return this.reset(),items}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}}visitSimpleSelectQuery(query){this.commonTables.length===0&&this.initialCommonTables===null&&(this.commonTables=this.commonTableCollector.collect(query)),query.selectClause&&query.selectClause.accept(this);let wildcards=this.selectValues.filter(item=>item.name==="*");if(wildcards.length===0)return;if(this.selectValues.some(item=>item.value instanceof ColumnReference&&item.value.namespaces===null)){query.fromClause&&this.processFromClause(query.fromClause,!0),this.selectValues=this.selectValues.filter(item=>item.name!=="*");return}let wildSourceNames=wildcards.filter(item=>item.value instanceof ColumnReference&&item.value.namespaces).map(item=>item.value.getNamespace());if(query.fromClause){let fromSourceName=query.fromClause.getSourceAliasName();if(fromSourceName&&wildSourceNames.includes(fromSourceName)&&this.processFromClause(query.fromClause,!1),query.fromClause.joins)for(let join of query.fromClause.joins){let joinSourceName=join.getSourceAliasName();joinSourceName&&wildSourceNames.includes(joinSourceName)&&this.processJoinClause(join)}}this.selectValues=this.selectValues.filter(item=>item.name!=="*")}processFromClause(clause,joinCascade){if(clause){let fromSourceName=clause.getSourceAliasName();if(this.processSourceExpression(fromSourceName,clause.source),clause.joins&&joinCascade)for(let join of clause.joins)this.processJoinClause(join)}}processJoinClause(clause){let sourceName=clause.getSourceAliasName();this.processSourceExpression(sourceName,clause.source)}processSourceExpression(sourceName,source){let commonTable=this.commonTables.find(item=>item.aliasExpression.table.name===sourceName);if(commonTable){let innerCommonTables=this.commonTables.filter(item=>item.aliasExpression.table.name!==sourceName);new _SelectValueCollector(this.tableColumnResolver,innerCommonTables).collect(commonTable.query).forEach(item=>{this.addSelectValueAsUnique(item.name,new ColumnReference(sourceName?[sourceName]:null,item.name))})}else new _SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(source).forEach(item=>{this.addSelectValueAsUnique(item.name,new ColumnReference(sourceName?[sourceName]:null,item.name))})}visitSelectClause(clause){for(let item of clause.items)this.processSelectItem(item)}processSelectItem(item){if(item.identifier)this.addSelectValueAsUnique(item.identifier.name,item.value);else if(item.value instanceof ColumnReference){let columnName=item.value.column.name;columnName==="*"?this.selectValues.push({name:columnName,value:item.value}):this.addSelectValueAsUnique(columnName,item.value)}}visitSourceExpression(source){if(source.aliasExpression&&source.aliasExpression.columns){let sourceName=source.getAliasName();source.aliasExpression.columns.forEach(column=>{this.addSelectValueAsUnique(column.name,new ColumnReference(sourceName?[sourceName]:null,column.name))});return}else if(source.datasource instanceof TableSource){if(this.tableColumnResolver){let sourceName=source.datasource.getSourceName();this.tableColumnResolver(sourceName).forEach(column=>{this.addSelectValueAsUnique(column,new ColumnReference([sourceName],column))})}return}else if(source.datasource instanceof SubQuerySource){let sourceName=source.getAliasName();new _SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(source.datasource.query).forEach(item=>{this.addSelectValueAsUnique(item.name,new ColumnReference(sourceName?[sourceName]:null,item.name))});return}else if(source.datasource instanceof ParenSource)return this.visit(source.datasource.source)}visitFromClause(clause){clause&&this.processFromClause(clause,!0)}addSelectValueAsUnique(name,value){this.selectValues.some(item=>item.name===name)||this.selectValues.push({name,value})}};var ReferenceDefinition=class extends SqlComponent{static{this.kind=Symbol("ReferenceDefinition")}constructor(params){super(),this.targetTable=params.targetTable,this.columns=params.columns?[...params.columns]:null,this.matchType=params.matchType??null,this.onDelete=params.onDelete??null,this.onUpdate=params.onUpdate??null,this.deferrable=params.deferrable??null,this.initially=params.initially??null}},ColumnConstraintDefinition=class extends SqlComponent{static{this.kind=Symbol("ColumnConstraintDefinition")}constructor(params){super(),this.kind=params.kind,this.constraintName=params.constraintName,this.defaultValue=params.defaultValue,this.checkExpression=params.checkExpression,this.reference=params.reference,this.rawClause=params.rawClause}},TableConstraintDefinition=class extends SqlComponent{static{this.kind=Symbol("TableConstraintDefinition")}constructor(params){super(),this.kind=params.kind,this.constraintName=params.constraintName,this.columns=params.columns?[...params.columns]:null,this.reference=params.reference,this.checkExpression=params.checkExpression,this.rawClause=params.rawClause,this.deferrable=params.deferrable??null,this.initially=params.initially??null}},TableColumnDefinition=class extends SqlComponent{static{this.kind=Symbol("TableColumnDefinition")}constructor(params){super(),this.name=params.name,this.dataType=params.dataType,this.constraints=params.constraints?[...params.constraints]:[]}},CreateTableQuery=class extends SqlComponent{static{this.kind=Symbol("CreateTableQuery")}constructor(params){super(),this.tableName=new IdentifierString(params.tableName),this.namespaces=params.namespaces?[...params.namespaces]:null,this.isTemporary=params.isTemporary??!1,this.ifNotExists=params.ifNotExists??!1,this.columns=params.columns?[...params.columns]:[],this.tableConstraints=params.tableConstraints?[...params.tableConstraints]:[],this.tableOptions=params.tableOptions??null,this.asSelectQuery=params.asSelectQuery,this.withDataOption=params.withDataOption??null}getSelectQuery(){let selectItems;this.asSelectQuery?selectItems=new SelectValueCollector().collect(this.asSelectQuery).map(val=>new SelectItem(val.value,val.name)):this.columns.length>0?selectItems=this.columns.map(column=>new SelectItem(new ColumnReference(null,column.name),column.name.name)):selectItems=[new SelectItem(new RawString("*"))];let qualifiedName=this.namespaces&&this.namespaces.length>0?[...this.namespaces,this.tableName.name].join("."):this.tableName.name;return new SimpleSelectQuery({selectClause:new SelectClause(selectItems),fromClause:new FromClause(new SourceExpression(new TableSource(null,qualifiedName),null),null)})}getCountQuery(){let qualifiedName=this.namespaces&&this.namespaces.length>0?[...this.namespaces,this.tableName.name].join("."):this.tableName.name;return new SimpleSelectQuery({selectClause:new SelectClause([new SelectItem(new FunctionCall(null,"count",new ColumnReference(null,"*"),null))]),fromClause:new FromClause(new SourceExpression(new TableSource(null,qualifiedName),null),null)})}};var MergeAction=class extends SqlComponent{static{this.kind=Symbol("MergeAction")}},MergeUpdateAction=class extends MergeAction{static{this.kind=Symbol("MergeUpdateAction")}constructor(setClause,whereClause){super(),this.setClause=setClause instanceof SetClause?setClause:new SetClause(setClause),this.whereClause=whereClause??null}},MergeDeleteAction=class extends MergeAction{static{this.kind=Symbol("MergeDeleteAction")}constructor(whereClause){super(),this.whereClause=whereClause??null}},MergeInsertAction=class extends MergeAction{static{this.kind=Symbol("MergeInsertAction")}constructor(params){super(),this.columns=params.columns?params.columns.map(col=>typeof col=="string"?new IdentifierString(col):col):null,this.values=params.values??null,this.defaultValues=params.defaultValues??!1,this.valuesLeadingComments=params.valuesLeadingComments?[...params.valuesLeadingComments]:null}addValuesLeadingComments(comments){if(!(!comments||comments.length===0)){this.valuesLeadingComments||(this.valuesLeadingComments=[]);for(let comment of comments)this.valuesLeadingComments.includes(comment)||this.valuesLeadingComments.push(comment)}}getValuesLeadingComments(){return this.valuesLeadingComments?[...this.valuesLeadingComments]:[]}},MergeDoNothingAction=class extends MergeAction{static{this.kind=Symbol("MergeDoNothingAction")}},MergeWhenClause=class extends SqlComponent{static{this.kind=Symbol("MergeWhenClause")}constructor(matchType,action,condition,options){super(),this.matchType=matchType,this.action=action,this.condition=condition??null,this.thenLeadingComments=options?.thenLeadingComments?[...options.thenLeadingComments]:null}addThenLeadingComments(comments){if(!(!comments||comments.length===0)){this.thenLeadingComments||(this.thenLeadingComments=[]);for(let comment of comments)this.thenLeadingComments.includes(comment)||this.thenLeadingComments.push(comment)}}getThenLeadingComments(){return this.thenLeadingComments?[...this.thenLeadingComments]:[]}},MergeQuery=class extends SqlComponent{static{this.kind=Symbol("MergeQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.target=params.target,this.source=params.source,this.onCondition=params.onCondition,this.whenClauses=params.whenClauses}};function cloneIdentifierWithComments(identifier){let clone=new IdentifierString(identifier.name);return identifier.positionedComments?clone.positionedComments=identifier.positionedComments.map(entry=>({position:entry.position,comments:[...entry.comments]})):identifier.comments&&identifier.comments.length>0&&(clone.comments=[...identifier.comments]),clone}var DropTableStatement=class extends SqlComponent{static{this.kind=Symbol("DropTableStatement")}constructor(params){super(),this.tables=params.tables.map(table=>new QualifiedName(table.namespaces,table.name)),this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},DropIndexStatement=class extends SqlComponent{static{this.kind=Symbol("DropIndexStatement")}constructor(params){super(),this.indexNames=params.indexNames.map(index=>new QualifiedName(index.namespaces,index.name)),this.ifExists=params.ifExists??!1,this.concurrently=params.concurrently??!1,this.behavior=params.behavior??null}},IndexColumnDefinition=class extends SqlComponent{static{this.kind=Symbol("IndexColumnDefinition")}constructor(params){super(),this.expression=params.expression,this.sortOrder=params.sortOrder??null,this.nullsOrder=params.nullsOrder??null,this.collation=params.collation??null,this.operatorClass=params.operatorClass??null}},CreateIndexStatement=class extends SqlComponent{static{this.kind=Symbol("CreateIndexStatement")}constructor(params){super(),this.unique=params.unique??!1,this.concurrently=params.concurrently??!1,this.ifNotExists=params.ifNotExists??!1,this.indexName=new QualifiedName(params.indexName.namespaces,params.indexName.name),this.tableName=new QualifiedName(params.tableName.namespaces,params.tableName.name),this.usingMethod=params.usingMethod??null,this.columns=params.columns.map(col=>new IndexColumnDefinition({expression:col.expression,sortOrder:col.sortOrder,nullsOrder:col.nullsOrder,collation:col.collation??null,operatorClass:col.operatorClass??null})),this.include=params.include?[...params.include]:null,this.where=params.where,this.withOptions=params.withOptions??null,this.tablespace=params.tablespace??null}},AlterTableAddConstraint=class extends SqlComponent{static{this.kind=Symbol("AlterTableAddConstraint")}constructor(params){super(),this.constraint=params.constraint,this.ifNotExists=params.ifNotExists??!1,this.notValid=params.notValid??!1}},AlterTableDropConstraint=class extends SqlComponent{static{this.kind=Symbol("AlterTableDropConstraint")}constructor(params){super(),this.constraintName=params.constraintName,this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},AlterTableDropColumn=class extends SqlComponent{static{this.kind=Symbol("AlterTableDropColumn")}constructor(params){super(),this.columnName=params.columnName,this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},AlterTableStatement=class extends SqlComponent{static{this.kind=Symbol("AlterTableStatement")}constructor(params){super(),this.table=new QualifiedName(params.table.namespaces,params.table.name),this.only=params.only??!1,this.ifExists=params.ifExists??!1,this.actions=params.actions.map(action=>action)}},DropConstraintStatement=class extends SqlComponent{static{this.kind=Symbol("DropConstraintStatement")}constructor(params){super(),this.constraintName=params.constraintName,this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},ExplainOption=class extends SqlComponent{static{this.kind=Symbol("ExplainOption")}constructor(params){super(),this.name=cloneIdentifierWithComments(params.name),this.value=params.value??null}},ExplainStatement=class extends SqlComponent{static{this.kind=Symbol("ExplainStatement")}constructor(params){super(),this.options=params.options?params.options.map(option=>new ExplainOption(option)):null,this.statement=params.statement}},AnalyzeStatement=class extends SqlComponent{static{this.kind=Symbol("AnalyzeStatement")}constructor(params){super(),this.verbose=params?.verbose??!1,this.target=params?.target?new QualifiedName(params.target.namespaces,params.target.name):null,params?.columns?this.columns=params.columns.map(cloneIdentifierWithComments):this.columns=null}};var PRESETS={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"}},SqlPrintTokenParser=class _SqlPrintTokenParser{constructor(options){this.handlers=new Map;this.index=1;this.joinConditionContexts=[];options?.preset&&(options={...options.preset,...options}),this.parameterDecorator=new ParameterDecorator({prefix:typeof options?.parameterSymbol=="string"?options.parameterSymbol:options?.parameterSymbol?.start??":",suffix:typeof options?.parameterSymbol=="object"?options.parameterSymbol.end:"",style:options?.parameterStyle??"named"}),this.identifierDecorator=new IdentifierDecorator({start:options?.identifierEscape?.start??'"',end:options?.identifierEscape?.end??'"'}),this.castStyle=options?.castStyle??"standard",this.constraintStyle=options?.constraintStyle??"postgres",this.normalizeJoinConditionOrder=options?.joinConditionOrderByDeclaration??!1,this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(QualifiedName.kind,expr=>this.visitQualifiedName(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(WindowFrameBoundStatic.kind,expr=>this.visitWindowFrameBoundStatic(expr)),this.handlers.set(WindowFrameBoundaryValue.kind,expr=>this.visitWindowFrameBoundaryValue(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(Distinct.kind,expr=>this.visitDistinct(expr)),this.handlers.set(DistinctOn.kind,expr=>this.visitDistinctOn(expr)),this.handlers.set(HintClause.kind,expr=>this.visitHintClause(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(SourceAliasExpression.kind,expr=>this.visitSourceAliasExpression(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(WindowsClause.kind,expr=>this.visitWindowClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.visitOffsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(FetchExpression.kind,expr=>this.visitFetchExpression(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleQuery(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(InsertClause.kind,expr=>this.visitInsertClause(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(UpdateClause.kind,expr=>this.visitUpdateClause(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(DeleteClause.kind,expr=>this.visitDeleteClause(expr)),this.handlers.set(UsingClause.kind,expr=>this.visitUsingClause(expr)),this.handlers.set(SetClause.kind,expr=>this.visitSetClause(expr)),this.handlers.set(SetClauseItem.kind,expr=>this.visitSetClauseItem(expr)),this.handlers.set(ReturningClause.kind,expr=>this.visitReturningClause(expr)),this.handlers.set(CreateTableQuery.kind,expr=>this.visitCreateTableQuery(expr)),this.handlers.set(TableColumnDefinition.kind,expr=>this.visitTableColumnDefinition(expr)),this.handlers.set(ColumnConstraintDefinition.kind,expr=>this.visitColumnConstraintDefinition(expr)),this.handlers.set(TableConstraintDefinition.kind,expr=>this.visitTableConstraintDefinition(expr)),this.handlers.set(ReferenceDefinition.kind,expr=>this.visitReferenceDefinition(expr)),this.handlers.set(CreateIndexStatement.kind,expr=>this.visitCreateIndexStatement(expr)),this.handlers.set(IndexColumnDefinition.kind,expr=>this.visitIndexColumnDefinition(expr)),this.handlers.set(DropTableStatement.kind,expr=>this.visitDropTableStatement(expr)),this.handlers.set(DropIndexStatement.kind,expr=>this.visitDropIndexStatement(expr)),this.handlers.set(AlterTableStatement.kind,expr=>this.visitAlterTableStatement(expr)),this.handlers.set(AlterTableAddConstraint.kind,expr=>this.visitAlterTableAddConstraint(expr)),this.handlers.set(AlterTableDropConstraint.kind,expr=>this.visitAlterTableDropConstraint(expr)),this.handlers.set(AlterTableDropColumn.kind,expr=>this.visitAlterTableDropColumn(expr)),this.handlers.set(DropConstraintStatement.kind,expr=>this.visitDropConstraintStatement(expr)),this.handlers.set(ExplainStatement.kind,expr=>this.visitExplainStatement(expr)),this.handlers.set(AnalyzeStatement.kind,expr=>this.visitAnalyzeStatement(expr)),this.handlers.set(MergeQuery.kind,expr=>this.visitMergeQuery(expr)),this.handlers.set(MergeWhenClause.kind,expr=>this.visitMergeWhenClause(expr)),this.handlers.set(MergeUpdateAction.kind,expr=>this.visitMergeUpdateAction(expr)),this.handlers.set(MergeDeleteAction.kind,expr=>this.visitMergeDeleteAction(expr)),this.handlers.set(MergeInsertAction.kind,expr=>this.visitMergeInsertAction(expr)),this.handlers.set(MergeDoNothingAction.kind,expr=>this.visitMergeDoNothingAction(expr))}static{this.SPACE_TOKEN=new SqlPrintToken(10," ")}static{this.COMMA_TOKEN=new SqlPrintToken(3,",")}static{this.ARGUMENT_SPLIT_COMMA_TOKEN=new SqlPrintToken(11,",")}static{this.PAREN_OPEN_TOKEN=new SqlPrintToken(4,"(")}static{this.PAREN_CLOSE_TOKEN=new SqlPrintToken(4,")")}static{this.DOT_TOKEN=new SqlPrintToken(8,".")}static{this._selfHandlingComponentTypes=null}static getSelfHandlingComponentTypes(){return this._selfHandlingComponentTypes||(this._selfHandlingComponentTypes=new Set([SimpleSelectQuery.kind,SelectItem.kind,CaseKeyValuePair.kind,SwitchCaseArgument.kind,ColumnReference.kind,LiteralValue.kind,ParameterExpression.kind,TableSource.kind,SourceAliasExpression.kind,TypeValue.kind,FunctionCall.kind,IdentifierString.kind,QualifiedName.kind])),this._selfHandlingComponentTypes}visitBinarySelectQuery(arg){let token=new SqlPrintToken(0,"");if(arg.positionedComments&&arg.positionedComments.length>0)this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null;else if(arg.headerComments&&arg.headerComments.length>0){if(this.shouldMergeHeaderComments(arg.headerComments)){let mergedHeaderComment=this.createHeaderMultiLineCommentBlock(arg.headerComments);token.innerTokens.push(mergedHeaderComment)}else{let headerCommentBlocks=this.createCommentBlocks(arg.headerComments,!0);token.innerTokens.push(...headerCommentBlocks)}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}return token.innerTokens.push(this.visit(arg.left)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.operator.value,"BinarySelectQueryOperator")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.right)),token}static commaSpaceTokens(){return[_SqlPrintTokenParser.COMMA_TOKEN,_SqlPrintTokenParser.SPACE_TOKEN]}static argumentCommaSpaceTokens(){return[_SqlPrintTokenParser.ARGUMENT_SPLIT_COMMA_TOKEN,_SqlPrintTokenParser.SPACE_TOKEN]}visitQualifiedName(arg){let token=new SqlPrintToken(0,"","QualifiedName");if(arg.namespaces)for(let i=0;i<arg.namespaces.length;i++)token.innerTokens.push(arg.namespaces[i].accept(this)),token.innerTokens.push(_SqlPrintTokenParser.DOT_TOKEN);let originalNameComments=arg.name.positionedComments,originalNameLegacyComments=arg.name.comments;arg.name.positionedComments=null,arg.name.comments=null;let nameToken=arg.name.accept(this);return token.innerTokens.push(nameToken),arg.name.positionedComments=originalNameComments,arg.name.comments=originalNameLegacyComments,(this.hasPositionedComments(arg.name)||this.hasLegacyComments(arg.name))&&this.addComponentComments(token,arg.name),this.addComponentComments(token,arg),token}visitPartitionByClause(arg){let token=new SqlPrintToken(1,"partition by","PartitionByClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.value)),token}visitOrderByClause(arg){let token=new SqlPrintToken(1,"order by","OrderByClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.order.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.order[i]));return token}visitOrderByItem(arg){let token=new SqlPrintToken(0,"","OrderByItem");return token.innerTokens.push(this.visit(arg.value)),arg.sortDirection&&arg.sortDirection!=="asc"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"desc"))),arg.nullsPosition&&(arg.nullsPosition==="first"?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"nulls first"))):arg.nullsPosition==="last"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"nulls last")))),token}parse(arg){this.index=1;let token=this.visit(arg),paramsRaw=ParameterCollector.collect(arg).sort((a,b)=>(a.index??0)-(b.index??0)),style=this.parameterDecorator.style;if(style==="named"){let paramsObj={};for(let p of paramsRaw){let key=p.name.value;if(paramsObj.hasOwnProperty(key)){if(paramsObj[key]!==p.value)throw new Error(`Duplicate parameter name '${key}' with different values detected during query composition.`);continue}paramsObj[key]=p.value}return{token,params:paramsObj}}else if(style==="indexed"){let paramsArr=paramsRaw.map(p=>p.value);return{token,params:paramsArr}}else if(style==="anonymous"){let paramsArr=paramsRaw.map(p=>p.value);return{token,params:paramsArr}}return{token,params:[]}}componentHandlesOwnComments(component){return"handlesOwnComments"in component&&typeof component.handlesOwnComments=="function"?component.handlesOwnComments():_SqlPrintTokenParser.getSelfHandlingComponentTypes().has(component.getKind())}visit(arg){let handler=this.handlers.get(arg.getKind());if(handler){let token=handler(arg);return this.componentHandlesOwnComments(arg)||this.addComponentComments(token,arg),token}throw new Error(`[SqlPrintTokenParser] No handler for kind: ${arg.getKind().toString()}`)}hasPositionedComments(component){return(component.positionedComments?.length??0)>0}hasLegacyComments(component){return(component.comments?.length??0)>0}addComponentComments(token,component){this.hasPositionedComments(component)?this.addPositionedCommentsToToken(token,component):this.hasLegacyComments(component)&&this.addCommentsToToken(token,component.comments)}addPositionedCommentsToToken(token,component){if(!this.hasPositionedComments(component))return;let beforeComments=component.getPositionedComments("before");if(beforeComments.length>0){let commentBlocks=this.createCommentBlocks(beforeComments);for(let i=commentBlocks.length-1;i>=0;i--)token.innerTokens.unshift(commentBlocks[i])}let afterComments=component.getPositionedComments("after");if(afterComments.length>0){let commentBlocks=this.createCommentBlocks(afterComments);for(let commentBlock of commentBlocks)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(commentBlock)}let componentsWithDuplicationIssues=["CaseExpression","SwitchCaseArgument","CaseKeyValuePair","SelectClause","LiteralValue","IdentifierString","DistinctOn","SourceAliasExpression","SimpleSelectQuery","WhereClause"];token.containerType&&componentsWithDuplicationIssues.includes(token.containerType)&&(component.positionedComments=null)}addCommentsToToken(token,comments){if(!comments?.length)return;let commentBlocks=this.createCommentBlocks(comments);this.insertCommentBlocksWithSpacing(token,commentBlocks)}createInlineCommentSequence(comments){let commentTokens=[];for(let i=0;i<comments.length;i++){let comment=comments[i];if(comment.trim()){let commentToken=new SqlPrintToken(6,this.formatComment(comment));if(commentTokens.push(commentToken),i<comments.length-1){let spaceToken=new SqlPrintToken(10," ");commentTokens.push(spaceToken)}}}return commentTokens}createCommentBlocks(comments,isHeaderComment=!1){let commentBlocks=[];for(let comment of comments){let trimmed=comment.trim(),isSeparatorLine=/^[-=_+*#]+$/.test(trimmed);(trimmed||isSeparatorLine||comment==="")&&commentBlocks.push(this.createSingleCommentBlock(comment,isHeaderComment))}return commentBlocks}shouldMergeComment(trimmed){return!(!/^[-=_+*#]+$/.test(trimmed)&&trimmed.startsWith("--")||trimmed.startsWith("/*")&&trimmed.endsWith("*/")&&(!trimmed.slice(2,-2).trim()||trimmed.includes(`
14
+ `)))}createSingleCommentBlock(comment,isHeaderComment=!1){let commentBlock=new SqlPrintToken(0,"","CommentBlock");isHeaderComment&&commentBlock.markAsHeaderComment();let commentToken=new SqlPrintToken(6,this.formatComment(comment));commentBlock.innerTokens.push(commentToken);let commentNewlineToken=new SqlPrintToken(12,"");commentBlock.innerTokens.push(commentNewlineToken);let spaceToken=new SqlPrintToken(10," ");return commentBlock.innerTokens.push(spaceToken),commentBlock}formatComment(comment){let trimmed=comment.trim();return trimmed?/^[-=_+*#]+$/.test(trimmed)?this.formatBlockComment(trimmed):trimmed.startsWith("--")?this.formatLineComment(trimmed.slice(2)):trimmed.startsWith("/*")&&trimmed.endsWith("*/")?this.formatBlockComment(trimmed):this.formatBlockComment(trimmed):"/* */"}insertCommentBlocksWithSpacing(token,commentBlocks){if(token.containerType==="SelectItem"){token.innerTokens.length>0&&token.innerTokens[token.innerTokens.length-1].type!==10&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(...commentBlocks);return}if(token.containerType==="SelectClause"){token.innerTokens.unshift(_SqlPrintTokenParser.SPACE_TOKEN,...commentBlocks);return}if(token.containerType==="IdentifierString"){token.innerTokens.length>0&&token.innerTokens[token.innerTokens.length-1].type!==10&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(...commentBlocks);return}if(token.innerTokens.unshift(...commentBlocks),this.shouldAddSeparatorSpace(token.containerType)){let separatorSpace=new SqlPrintToken(10," ");token.innerTokens.splice(commentBlocks.length,0,separatorSpace),token.innerTokens.length>commentBlocks.length+1&&token.innerTokens[commentBlocks.length+1].type===10&&token.innerTokens.splice(commentBlocks.length+1,1)}else token.innerTokens.length>commentBlocks.length&&token.innerTokens[commentBlocks.length].type===10&&token.innerTokens.splice(commentBlocks.length,1)}addPositionedCommentsToParenExpression(token,component){if(!component.positionedComments)return;let beforeComments=component.getPositionedComments("before");if(beforeComments.length>0){let commentBlocks=this.createCommentBlocks(beforeComments),insertIndex=1;for(let commentBlock of commentBlocks)token.innerTokens.splice(insertIndex,0,commentBlock),insertIndex++}let afterComments=component.getPositionedComments("after");if(afterComments.length>0){let commentBlocks=this.createCommentBlocks(afterComments),insertIndex=token.innerTokens.length-1+1;for(let commentBlock of commentBlocks)token.innerTokens.splice(insertIndex,0,_SqlPrintTokenParser.SPACE_TOKEN,commentBlock),insertIndex+=2}}shouldAddSeparatorSpace(containerType){return this.isClauseLevelContainer(containerType)}isClauseLevelContainer(containerType){switch(containerType){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(comment){let hasDelimiters=comment.startsWith("/*")&&comment.endsWith("*/"),rawContent=hasDelimiters?comment.slice(2,-2):comment,lines=this.escapeCommentDelimiters(rawContent).replace(/\r?\n/g,`
15
15
  `).split(`
16
16
  `).map(line=>line.replace(/\s+/g," ").trim()).filter(line=>line.length>0);if(lines.length===0)return"/* */";let isSeparatorLine=lines.length===1&&/^[-=_+*#]+$/.test(lines[0]);return hasDelimiters?isSeparatorLine||lines.length===1?`/* ${lines[0]} */`:`/*
17
17
  ${lines.map(line=>` ${line}`).join(`
18
18
  `)}
19
- */`:isSeparatorLine?`/* ${lines[0]} */`:`/* ${lines.join(" ")} */`}shouldMergeHeaderComments(comments){return comments.length<=1?!1:comments.some(comment=>{let trimmed=comment.trim();return/^[-=_+*#]{3,}$/.test(trimmed)||trimmed.startsWith("- ")||trimmed.startsWith("* ")})}createHeaderMultiLineCommentBlock(headerComments){let commentBlock=new SqlPrintToken(0,"","CommentBlock");if(commentBlock.markAsHeaderComment(),headerComments.length===0){let commentToken=new SqlPrintToken(6,"/* */");commentBlock.innerTokens.push(commentToken)}else{let openToken=new SqlPrintToken(6,"/*");commentBlock.innerTokens.push(openToken),commentBlock.innerTokens.push(new SqlPrintToken(12,""));for(let line of headerComments){let sanitized=this.escapeCommentDelimiters(line),lineToken=new SqlPrintToken(6,` ${sanitized}`);commentBlock.innerTokens.push(lineToken),commentBlock.innerTokens.push(new SqlPrintToken(12,""))}let closeToken=new SqlPrintToken(6,"*/");commentBlock.innerTokens.push(closeToken)}return commentBlock.innerTokens.push(new SqlPrintToken(12,"")),commentBlock.innerTokens.push(new SqlPrintToken(10," ")),commentBlock}formatLineComment(content){let sanitized=this.sanitizeLineCommentContent(content);return sanitized?`-- ${sanitized}`:"--"}sanitizeLineCommentContent(content){let sanitized=this.escapeCommentDelimiters(content).replace(/\r?\n/g," ").replace(/\u2028|\u2029/g," ").replace(/\s+/g," ").trim();return sanitized.startsWith("--")&&(sanitized=sanitized.slice(2).trimStart()),sanitized}escapeCommentDelimiters(content){return content.replace(/\/\*/g,"\\/\\*").replace(/\*\//g,"*\\/")}visitValueList(arg){let token=new SqlPrintToken(0,"","ValueList");for(let i=0;i<arg.values.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.argumentCommaSpaceTokens()),token.innerTokens.push(this.visit(arg.values[i]));return token}visitColumnReference(arg){let token=new SqlPrintToken(0,"","ColumnReference");return token.innerTokens.push(arg.qualifiedName.accept(this)),this.addComponentComments(token,arg),token}visitFunctionCall(arg){let token=new SqlPrintToken(0,"","FunctionCall");if(token.innerTokens.push(arg.qualifiedName.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),arg.argument&&token.innerTokens.push(this.visit(arg.argument)),arg.internalOrderBy&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.internalOrderBy))),arg.comments&&arg.comments.length>0){let closingParenToken=new SqlPrintToken(4,")");this.addCommentsToToken(closingParenToken,arg.comments),token.innerTokens.push(closingParenToken),arg.comments=null}else token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN);return arg.withOrdinality&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"with ordinality"))),arg.over&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"over")),arg.over instanceof IdentifierString?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.over.accept(this))):(token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.over)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN))),this.addComponentComments(token,arg),token}visitUnaryExpression(arg){let token=new SqlPrintToken(0,"","UnaryExpression");return token.innerTokens.push(this.visit(arg.operator)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.expression)),token}visitBinaryExpression(arg){let token=new SqlPrintToken(0,"","BinaryExpression");token.innerTokens.push(this.visit(arg.left)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let operatorToken=this.visit(arg.operator),operatorLower=operatorToken.text.toLowerCase();return(operatorLower==="and"||operatorLower==="or")&&(operatorToken.type=5),token.innerTokens.push(operatorToken),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.right)),token}visitLiteralValue(arg){let text;arg.value===null?text="null":arg.isStringLiteral?text=`'${arg.value.replace(/'/g,"''")}'`:typeof arg.value=="string"?text=arg.value:text=arg.value.toString();let token=new SqlPrintToken(2,text,"LiteralValue");return arg.positionedComments&&arg.positionedComments.length>0?(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null):arg.comments&&arg.comments.length>0&&this.addCommentsToToken(token,arg.comments),token}visitParameterExpression(arg){arg.index=this.index;let text=this.parameterDecorator.decorate(arg.name.value,arg.index),token=new SqlPrintToken(7,text);return this.addComponentComments(token,arg),this.index++,token}visitSwitchCaseArgument(arg){let token=new SqlPrintToken(0,"","SwitchCaseArgument");this.addComponentComments(token,arg);for(let kv of arg.cases)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(kv.accept(this));if(arg.elseValue)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.createElseToken(arg.elseValue,arg.comments));else if(arg.comments&&arg.comments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(arg.comments);token.innerTokens.push(...commentTokens)}return token}createElseToken(elseValue,switchCaseComments){let elseToken=new SqlPrintToken(0,"","ElseClause");if(elseToken.innerTokens.push(new SqlPrintToken(1,"else")),switchCaseComments&&switchCaseComments.length>0){elseToken.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(switchCaseComments);elseToken.innerTokens.push(...commentTokens)}elseToken.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let elseValueContainer=new SqlPrintToken(0,"","CaseElseValue");return elseValueContainer.innerTokens.push(this.visit(elseValue)),elseToken.innerTokens.push(elseValueContainer),elseToken}visitCaseKeyValuePair(arg){let token=new SqlPrintToken(0,"","CaseKeyValuePair");if(arg.positionedComments&&arg.positionedComments.length>0&&(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null),token.innerTokens.push(new SqlPrintToken(1,"when")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.key)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"then")),arg.comments&&arg.comments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(arg.comments);token.innerTokens.push(...commentTokens)}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let thenValueContainer=new SqlPrintToken(0,"","CaseThenValue");return thenValueContainer.innerTokens.push(this.visit(arg.value)),token.innerTokens.push(thenValueContainer),token}visitRawString(arg){return new SqlPrintToken(2,arg.value,"RawString")}visitIdentifierString(arg){let text=arg.name==="*"?arg.name:this.identifierDecorator.decorate(arg.name);if(arg.positionedComments&&arg.positionedComments.length>0){let token2=new SqlPrintToken(0,"","IdentifierString");this.addPositionedCommentsToToken(token2,arg),arg.positionedComments=null;let valueToken=new SqlPrintToken(2,text);return token2.innerTokens.push(valueToken),token2}if(arg.comments&&arg.comments.length>0){let token2=new SqlPrintToken(0,"","IdentifierString"),valueToken=new SqlPrintToken(2,text);return token2.innerTokens.push(valueToken),this.addComponentComments(token2,arg),token2}return new SqlPrintToken(2,text,"IdentifierString")}visitParenExpression(arg){let token=new SqlPrintToken(0,"","ParenExpression"),hasOwnComments=arg.positionedComments&&arg.positionedComments.length>0,hasInnerComments=arg.expression.positionedComments&&arg.expression.positionedComments.length>0,innerBeforeComments=[],innerAfterComments=[];if(hasInnerComments&&(innerBeforeComments=arg.expression.getPositionedComments("before"),innerAfterComments=arg.expression.getPositionedComments("after"),arg.expression.positionedComments=null),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.expression)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),innerBeforeComments.length>0){let commentBlocks=this.createCommentBlocks(innerBeforeComments),insertIndex=1;for(let commentBlock of commentBlocks)token.innerTokens.splice(insertIndex,0,commentBlock),insertIndex++}if(innerAfterComments.length>0){let commentBlocks=this.createCommentBlocks(innerAfterComments),insertIndex=token.innerTokens.length;for(let commentBlock of commentBlocks)token.innerTokens.splice(insertIndex-1,0,commentBlock)}return hasOwnComments&&(this.addPositionedCommentsToParenExpression(token,arg),arg.positionedComments=null),token}visitCastExpression(arg){let token=new SqlPrintToken(0,"","CastExpression");return this.castStyle==="postgres"?(token.innerTokens.push(this.visit(arg.input)),token.innerTokens.push(new SqlPrintToken(5,"::")),token.innerTokens.push(this.visit(arg.castType)),token):(token.innerTokens.push(new SqlPrintToken(1,"cast")),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.input)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.castType)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token)}visitCaseExpression(arg){let token=new SqlPrintToken(0,"","CaseExpression");arg.positionedComments&&arg.positionedComments.length>0&&(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null);let promotedComments=[],trailingSwitchComments=this.extractSwitchAfterComments(arg.switchCase),conditionToken=null;arg.condition&&(conditionToken=this.visit(arg.condition),promotedComments.push(...this.collectCaseLeadingCommentBlocks(conditionToken)));let switchToken=this.visit(arg.switchCase);if(promotedComments.push(...this.collectCaseLeadingCommentsFromSwitch(switchToken)),promotedComments.length>0&&token.innerTokens.push(...promotedComments),token.innerTokens.push(new SqlPrintToken(1,"case")),conditionToken&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(conditionToken)),token.innerTokens.push(switchToken),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"end")),trailingSwitchComments.length>0){token.innerTokens.push(new SqlPrintToken(12,""));let trailingBlocks=this.createCommentBlocks(trailingSwitchComments);token.innerTokens.push(...trailingBlocks)}return token}extractSwitchAfterComments(arg){if(!arg.positionedComments||arg.positionedComments.length===0)return[];let trailing=[],retained=[];for(let entry of arg.positionedComments)entry.position==="after"?trailing.push(...entry.comments):retained.push(entry);return arg.positionedComments=retained.length>0?retained:null,trailing}collectCaseLeadingCommentsFromSwitch(token){if(!token.innerTokens||token.innerTokens.length===0)return[];let pairToken=token.innerTokens.find(child=>child.containerType==="CaseKeyValuePair");if(!pairToken)return[];let keyToken=this.findCaseKeyToken(pairToken);return keyToken?this.collectCaseLeadingCommentBlocks(keyToken):[]}findCaseKeyToken(pairToken){for(let child of pairToken.innerTokens)if(child.containerType!=="CommentBlock"&&child.type!==10&&child.type!==1&&child.containerType!=="CaseThenValue")return child}collectCaseLeadingCommentBlocks(token){if(!token.innerTokens||token.innerTokens.length===0)return[];let collected=[];return this.collectCaseLeadingCommentBlocksRecursive(token,collected,new Set,0),collected}collectCaseLeadingCommentBlocksRecursive(token,collected,seen,depth){if(!token.innerTokens||token.innerTokens.length===0)return;let removedAny=!1;for(;token.innerTokens.length>0;){let first=token.innerTokens[0];if(first.containerType==="CommentBlock"){token.innerTokens.shift();let signature=this.commentBlockSignature(first);depth>0&&seen.has(signature)||(collected.push(first),seen.add(signature)),removedAny=!0;continue}if(!removedAny&&first.type===10)return;break}if(!token.innerTokens||token.innerTokens.length===0)return;let firstChild=token.innerTokens[0];this.isTransparentCaseWrapper(firstChild)&&this.collectCaseLeadingCommentBlocksRecursive(firstChild,collected,seen,depth+1)}isTransparentCaseWrapper(token){return token?["ColumnReference","QualifiedName","IdentifierString","RawString","LiteralValue","ParenExpression","UnaryExpression"].includes(token.containerType):!1}commentBlockSignature(commentBlock){return!commentBlock.innerTokens||commentBlock.innerTokens.length===0?"":commentBlock.innerTokens.filter(inner=>inner.text!=="").map(inner=>inner.text).join("|")}visitArrayExpression(arg){let token=new SqlPrintToken(0,"","ArrayExpression");return token.innerTokens.push(new SqlPrintToken(1,"array")),token.innerTokens.push(new SqlPrintToken(4,"[")),token.innerTokens.push(this.visit(arg.expression)),token.innerTokens.push(new SqlPrintToken(4,"]")),token}visitArrayQueryExpression(arg){let token=new SqlPrintToken(0,"","ArrayExpression");return token.innerTokens.push(new SqlPrintToken(1,"array")),token.innerTokens.push(new SqlPrintToken(4,"(")),token.innerTokens.push(this.visit(arg.query)),token.innerTokens.push(new SqlPrintToken(4,")")),token}visitArraySliceExpression(arg){let token=new SqlPrintToken(0,"","ArrayExpression");return token.innerTokens.push(this.visit(arg.array)),token.innerTokens.push(new SqlPrintToken(4,"[")),arg.startIndex&&token.innerTokens.push(this.visit(arg.startIndex)),token.innerTokens.push(new SqlPrintToken(5,":")),arg.endIndex&&token.innerTokens.push(this.visit(arg.endIndex)),token.innerTokens.push(new SqlPrintToken(4,"]")),token}visitArrayIndexExpression(arg){let token=new SqlPrintToken(0,"","ArrayExpression");return token.innerTokens.push(this.visit(arg.array)),token.innerTokens.push(new SqlPrintToken(4,"[")),token.innerTokens.push(this.visit(arg.index)),token.innerTokens.push(new SqlPrintToken(4,"]")),token}visitBetweenExpression(arg){let token=new SqlPrintToken(0,"","BetweenExpression");return token.innerTokens.push(this.visit(arg.expression)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.negated&&(token.innerTokens.push(new SqlPrintToken(1,"not")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)),token.innerTokens.push(new SqlPrintToken(1,"between")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.lower)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"and")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.upper)),token}visitStringSpecifierExpression(arg){let specifier=arg.specifier.accept(this).text,value=arg.value.accept(this).text;return new SqlPrintToken(2,specifier+value,"StringSpecifierExpression")}visitTypeValue(arg){let token=new SqlPrintToken(0,"","TypeValue");return this.addComponentComments(token,arg),token.innerTokens.push(arg.qualifiedName.accept(this)),arg.argument&&(token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.argument)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)),token}visitTupleExpression(arg){let token=new SqlPrintToken(0,"","TupleExpression"),requiresMultiline=this.tupleRequiresMultiline(arg);token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);for(let i=0;i<arg.values.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.argumentCommaSpaceTokens()),token.innerTokens.push(this.visit(arg.values[i]));return requiresMultiline&&token.innerTokens.push(new SqlPrintToken(12,"","TupleExpression")),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}tupleRequiresMultiline(tuple){for(let value of tuple.values)if(this.hasInlineComments(value))return!0;return!1}hasInlineComments(component){return this.hasLeadingComments(component)?!0:component instanceof TupleExpression?this.tupleRequiresMultiline(component):!1}hasLeadingComments(component){let before=(component.positionedComments??[]).find(pc=>pc.position==="before");return!!(before&&before.comments.some(comment=>comment.trim().length>0))}visitWindowFrameExpression(arg){let token=new SqlPrintToken(0,"","WindowFrameExpression"),first=!0;return arg.partition&&(token.innerTokens.push(this.visit(arg.partition)),first=!1),arg.order&&(first?first=!1:token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.order))),arg.frameSpec&&(first?first=!1:token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.frameSpec))),token}visitWindowFrameSpec(arg){let token=new SqlPrintToken(0,"","WindowFrameSpec");return token.innerTokens.push(new SqlPrintToken(1,arg.frameType)),arg.endBound===null?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.startBound.accept(this))):(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"between")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.startBound.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"and")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.endBound.accept(this))),token}visitWindowFrameBoundaryValue(arg){let token=new SqlPrintToken(0,"","WindowFrameBoundaryValue");return token.innerTokens.push(arg.value.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.isFollowing?"following":"preceding")),token}visitWindowFrameBoundStatic(arg){return new SqlPrintToken(1,arg.bound)}visitSelectItem(arg){let token=new SqlPrintToken(0,"","SelectItem"),originalSelectItemPositionedComments=arg.positionedComments,originalValuePositionedComments=arg.value.positionedComments;arg.value.positionedComments=null;let beforeComments=arg.getPositionedComments("before"),afterComments=arg.getPositionedComments("after"),isParenExpression=arg.value instanceof ParenExpression;if(beforeComments.length>0){let commentTokens=this.createInlineCommentSequence(beforeComments);token.innerTokens.push(...commentTokens),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}if(token.innerTokens.push(this.visit(arg.value)),afterComments.length>0&&!isParenExpression){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(afterComments);token.innerTokens.push(...commentTokens)}if(arg.positionedComments=originalSelectItemPositionedComments,arg.value.positionedComments=originalValuePositionedComments,!arg.identifier)return token;if(arg.value instanceof ColumnReference){let defaultName=arg.value.column.name;if(arg.identifier.name===defaultName)return token}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let asKeywordPositionedComments="asKeywordPositionedComments"in arg?arg.asKeywordPositionedComments:null;if(asKeywordPositionedComments){let beforeComments2=asKeywordPositionedComments.filter(pc=>pc.position==="before");if(beforeComments2.length>0)for(let posComment of beforeComments2){let commentTokens=this.createInlineCommentSequence(posComment.comments);token.innerTokens.push(...commentTokens),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}}if(token.innerTokens.push(new SqlPrintToken(1,"as")),asKeywordPositionedComments){let afterComments2=asKeywordPositionedComments.filter(pc=>pc.position==="after");if(afterComments2.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let posComment of afterComments2){let commentTokens=this.createInlineCommentSequence(posComment.comments);token.innerTokens.push(...commentTokens)}}}let asKeywordComments="asKeywordComments"in arg?arg.asKeywordComments:null;if(asKeywordComments&&asKeywordComments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(asKeywordComments);token.innerTokens.push(...commentTokens)}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let identifierToken=this.visit(arg.identifier);token.innerTokens.push(identifierToken);let aliasPositionedComments="aliasPositionedComments"in arg?arg.aliasPositionedComments:null;if(aliasPositionedComments){let afterComments2=aliasPositionedComments.filter(pc=>pc.position==="after");if(afterComments2.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let posComment of afterComments2){let commentTokens=this.createInlineCommentSequence(posComment.comments);token.innerTokens.push(...commentTokens)}}}let aliasComments=arg.aliasComments;if(aliasComments&&aliasComments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(aliasComments);token.innerTokens.push(...commentTokens)}return token}visitSelectClause(arg){let token=new SqlPrintToken(1,"select","SelectClause");arg.positionedComments&&arg.positionedComments.length>0&&(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null);let selectKeywordText="select";for(let hint of arg.hints)selectKeywordText+=" "+this.visit(hint).text;if(arg.distinct){let distinctToken=arg.distinct.accept(this);if(distinctToken.innerTokens&&distinctToken.innerTokens.length>0){let distinctText=distinctToken.text;for(let innerToken of distinctToken.innerTokens)distinctText+=this.flattenTokenText(innerToken);selectKeywordText+=" "+distinctText}else selectKeywordText+=" "+distinctToken.text}token.text=selectKeywordText,token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.items.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.items[i]));return token}flattenTokenText(token){let result=token.text;if(token.innerTokens)for(let innerToken of token.innerTokens)result+=this.flattenTokenText(innerToken);return result}visitHintClause(arg){return new SqlPrintToken(2,arg.getFullHint())}visitDistinct(arg){let token=new SqlPrintToken(1,"distinct");return arg.positionedComments&&arg.positionedComments.length>0&&(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null),token}visitDistinctOn(arg){let token=new SqlPrintToken(0,"","DistinctOn");return token.innerTokens.push(new SqlPrintToken(1,"distinct on")),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(arg.value.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}visitTableSource(arg){let fullName="";Array.isArray(arg.namespaces)&&arg.namespaces.length>0&&(fullName=arg.namespaces.map(ns=>ns.accept(this).text).join(".")+"."),fullName+=arg.table.accept(this).text;let token=new SqlPrintToken(2,fullName);return this.addComponentComments(token,arg),arg.identifier&&(arg.identifier.name,arg.table.name),token}visitSourceExpression(arg){let token=new SqlPrintToken(0,"","SourceExpression");if(token.innerTokens.push(arg.datasource.accept(this)),!arg.aliasExpression)return token;if(arg.datasource instanceof TableSource){let defaultName=arg.datasource.table.name;return arg.aliasExpression.table.name===defaultName||(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.aliasExpression.accept(this))),token}else return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.aliasExpression.accept(this)),token}visitFromClause(arg){let contextPushed=!1;if(this.normalizeJoinConditionOrder){let aliasOrder=this.buildJoinAliasOrder(arg);aliasOrder.size>0&&(this.joinConditionContexts.push({aliasOrder}),contextPushed=!0)}try{let token=new SqlPrintToken(1,"from","FromClause");if(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.source)),arg.joins)for(let i=0;i<arg.joins.length;i++)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.joins[i]));return token}finally{contextPushed&&this.joinConditionContexts.pop()}}visitJoinClause(arg){let token=new SqlPrintToken(0,"","JoinClause"),joinKeywordPositionedComments=arg.joinKeywordPositionedComments;if(joinKeywordPositionedComments){let beforeComments=joinKeywordPositionedComments.filter(pc=>pc.position==="before");if(beforeComments.length>0)for(let posComment of beforeComments){let commentTokens=this.createInlineCommentSequence(posComment.comments);token.innerTokens.push(...commentTokens),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}}if(token.innerTokens.push(new SqlPrintToken(1,arg.joinType.value)),joinKeywordPositionedComments){let afterComments=joinKeywordPositionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let posComment of afterComments){let commentTokens=this.createInlineCommentSequence(posComment.comments);token.innerTokens.push(...commentTokens)}}}let joinKeywordComments=arg.joinKeywordComments;if(joinKeywordComments&&joinKeywordComments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(joinKeywordComments);token.innerTokens.push(...commentTokens)}return arg.lateral&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"lateral"))),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.source)),arg.condition&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.condition))),token}visitJoinOnClause(arg){if(this.normalizeJoinConditionOrder){let aliasOrder=this.getCurrentJoinAliasOrder();aliasOrder&&this.normalizeJoinConditionValue(arg.condition,aliasOrder)}let token=new SqlPrintToken(0,"","JoinOnClause");return token.innerTokens.push(new SqlPrintToken(1,"on")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.condition)),token}getCurrentJoinAliasOrder(){return this.joinConditionContexts.length===0?null:this.joinConditionContexts[this.joinConditionContexts.length-1].aliasOrder}buildJoinAliasOrder(fromClause){let aliasOrder=new Map,nextIndex=0,registerSource=source=>{let identifiers=this.collectSourceIdentifiers(source);if(identifiers.length!==0){for(let identifier of identifiers){let key=identifier.toLowerCase();aliasOrder.has(key)||aliasOrder.set(key,nextIndex)}nextIndex++}};if(registerSource(fromClause.source),fromClause.joins)for(let joinClause of fromClause.joins)registerSource(joinClause.source);return aliasOrder}collectSourceIdentifiers(source){let identifiers=[],aliasName=source.getAliasName();if(aliasName&&identifiers.push(aliasName),source.datasource instanceof TableSource){let tableComponent=source.datasource.table.name;identifiers.push(tableComponent);let fullName=source.datasource.getSourceName();fullName&&fullName!==tableComponent&&identifiers.push(fullName)}return identifiers}normalizeJoinConditionValue(condition,aliasOrder){let kind=condition.getKind();if(kind===ParenExpression.kind){let paren=condition;this.normalizeJoinConditionValue(paren.expression,aliasOrder);return}if(kind===BinaryExpression.kind){let binary=condition;this.normalizeJoinConditionValue(binary.left,aliasOrder),this.normalizeJoinConditionValue(binary.right,aliasOrder),this.normalizeBinaryEquality(binary,aliasOrder)}}normalizeBinaryEquality(binary,aliasOrder){if(binary.operator.value.toLowerCase()!=="=")return;let leftOwner=this.resolveColumnOwner(binary.left),rightOwner=this.resolveColumnOwner(binary.right);if(!leftOwner||!rightOwner||leftOwner===rightOwner)return;let leftOrder=aliasOrder.get(leftOwner),rightOrder=aliasOrder.get(rightOwner);if(!(leftOrder===void 0||rightOrder===void 0)&&leftOrder>rightOrder){let originalLeft=binary.left;binary.left=binary.right,binary.right=originalLeft}}resolveColumnOwner(value){let kind=value.getKind();if(kind===ColumnReference.kind){let namespace=value.getNamespace();return namespace?(namespace.includes(".")?namespace.split(".").pop()??"":namespace).toLowerCase():null}return kind===ParenExpression.kind?this.resolveColumnOwner(value.expression):null}visitJoinUsingClause(arg){let token=new SqlPrintToken(0,"","JoinUsingClause");return token.innerTokens.push(new SqlPrintToken(1,"using")),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.condition)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}visitFunctionSource(arg){let token=new SqlPrintToken(0,"","FunctionSource");return token.innerTokens.push(arg.qualifiedName.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),arg.argument&&token.innerTokens.push(this.visit(arg.argument)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}visitSourceAliasExpression(arg){let token=new SqlPrintToken(0,"","SourceAliasExpression");if(token.innerTokens.push(this.visit(arg.table)),arg.columns){token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);for(let i=0;i<arg.columns.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.argumentCommaSpaceTokens()),token.innerTokens.push(this.visit(arg.columns[i]));token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return arg.positionedComments&&arg.positionedComments.length>0?(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null):arg.comments&&arg.comments.length>0&&this.addCommentsToToken(token,arg.comments),token}visitWhereClause(arg){let token=new SqlPrintToken(1,"where","WhereClause");return this.addComponentComments(token,arg),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.condition)),token}visitGroupByClause(arg){let token=new SqlPrintToken(1,"group by","GroupByClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.grouping.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.grouping[i]));return token}visitHavingClause(arg){let token=new SqlPrintToken(1,"having","HavingClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.condition)),token}visitWindowClause(arg){let token=new SqlPrintToken(1,"window","WindowClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.windows.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.windows[i]));return token}visitWindowFrameClause(arg){let token=new SqlPrintToken(0,"","WindowFrameClause");return token.innerTokens.push(arg.name.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.expression)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}visitLimitClause(arg){let token=new SqlPrintToken(1,"limit","LimitClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.value)),token}visitOffsetClause(arg){let token=new SqlPrintToken(1,"offset","OffsetClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.value)),token}visitFetchClause(arg){let token=new SqlPrintToken(1,"fetch","FetchClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.expression)),token}visitFetchExpression(arg){let token=new SqlPrintToken(0,"","FetchExpression");return token.innerTokens.push(new SqlPrintToken(1,arg.type)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.count.accept(this)),arg.unit&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.unit))),token}visitForClause(arg){let token=new SqlPrintToken(1,"for","ForClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.lockMode)),token}visitWithClause(arg){let token=new SqlPrintToken(1,"with","WithClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.recursive&&(token.innerTokens.push(new SqlPrintToken(1,"recursive")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN));for(let i=0;i<arg.tables.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(arg.tables[i].accept(this));return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),this.addComponentComments(token,arg),token}visitCommonTable(arg){let token=new SqlPrintToken(0,"","CommonTable");arg.positionedComments&&arg.positionedComments.length>0?(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null):arg.comments&&arg.comments.length>0&&this.addCommentsToToken(token,arg.comments),token.innerTokens.push(arg.aliasExpression.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.materialized!==null&&(arg.materialized?token.innerTokens.push(new SqlPrintToken(1,"materialized")):token.innerTokens.push(new SqlPrintToken(1,"not materialized")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let query=new SqlPrintToken(0,"","SubQuerySource");return query.innerTokens.push(arg.query.accept(this)),token.innerTokens.push(query),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}visitSimpleQuery(arg){let token=new SqlPrintToken(0,"","SimpleSelectQuery");if(arg.headerComments&&arg.headerComments.length>0){if(this.shouldMergeHeaderComments(arg.headerComments)){let mergedHeaderComment=this.createHeaderMultiLineCommentBlock(arg.headerComments);token.innerTokens.push(mergedHeaderComment)}else{let headerCommentBlocks=this.createCommentBlocks(arg.headerComments,!0);token.innerTokens.push(...headerCommentBlocks)}arg.withClause&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}if(arg.positionedComments&&arg.positionedComments.length>0&&(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null),arg.withClause&&token.innerTokens.push(arg.withClause.accept(this)),arg.comments&&arg.comments.length>0){let commentBlocks=this.createCommentBlocks(arg.comments);token.innerTokens.push(...commentBlocks),arg.selectClause&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}return token.innerTokens.push(arg.selectClause.accept(this)),arg.fromClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.fromClause.accept(this)),arg.whereClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.whereClause.accept(this))),arg.groupByClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.groupByClause.accept(this))),arg.havingClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.havingClause.accept(this))),arg.orderByClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.orderByClause.accept(this))),arg.windowClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.windowClause.accept(this))),arg.limitClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.limitClause.accept(this))),arg.offsetClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.offsetClause.accept(this))),arg.fetchClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.fetchClause.accept(this))),arg.forClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.forClause.accept(this)))),token}visitSubQuerySource(arg){let token=new SqlPrintToken(0,"");token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let subQuery=new SqlPrintToken(0,"","SubQuerySource");return subQuery.innerTokens.push(arg.query.accept(this)),token.innerTokens.push(subQuery),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}visitValuesQuery(arg){let token=new SqlPrintToken(1,"values","ValuesQuery");if(arg.headerComments&&arg.headerComments.length>0)if(this.shouldMergeHeaderComments(arg.headerComments)){let mergedHeaderComment=this.createHeaderMultiLineCommentBlock(arg.headerComments);token.innerTokens.push(mergedHeaderComment),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}else{let headerCommentBlocks=this.createCommentBlocks(arg.headerComments,!0);for(let commentBlock of headerCommentBlocks)token.innerTokens.push(commentBlock),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let values=new SqlPrintToken(0,"","Values");for(let i=0;i<arg.tuples.length;i++)i>0&&values.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),values.innerTokens.push(arg.tuples[i].accept(this));return token.innerTokens.push(values),this.addCommentsToToken(token,arg.comments),token}visitInlineQuery(arg){let token=new SqlPrintToken(0,"");token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let queryToken=new SqlPrintToken(0,"","InlineQuery");if(queryToken.innerTokens.push(arg.selectQuery.accept(this)),token.innerTokens.push(queryToken),arg.comments&&arg.comments.length>0){let closingParenToken=new SqlPrintToken(4,")");this.addCommentsToToken(closingParenToken,arg.comments),token.innerTokens.push(closingParenToken),arg.comments=null}else token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN);return token}visitInsertQuery(arg){let token=new SqlPrintToken(0,"","InsertQuery");return arg.withClause&&token.innerTokens.push(arg.withClause.accept(this)),token.innerTokens.push(this.visit(arg.insertClause)),arg.selectQuery&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.selectQuery))),arg.returningClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.returningClause.accept(this))),token}visitInsertClause(arg){let token=new SqlPrintToken(0,"","InsertClause");if(token.innerTokens.push(new SqlPrintToken(1,"insert into")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.source.accept(this)),arg.columns&&arg.columns.length>0){token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);for(let i=0;i<arg.columns.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(arg.columns[i].accept(this));token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return token}visitDeleteQuery(arg){let token=new SqlPrintToken(0,"","DeleteQuery");return arg.withClause&&token.innerTokens.push(arg.withClause.accept(this)),token.innerTokens.push(arg.deleteClause.accept(this)),arg.usingClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.usingClause.accept(this))),arg.whereClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.whereClause.accept(this))),arg.returningClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.returningClause.accept(this))),token}visitDeleteClause(arg){let token=new SqlPrintToken(1,"delete from","DeleteClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.source.accept(this)),token}visitUsingClause(arg){let token=new SqlPrintToken(1,"using","UsingClause");if(arg.sources.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.sources.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.sources[i]))}return token}visitMergeQuery(arg){let token=new SqlPrintToken(0,"","MergeQuery");arg.withClause&&token.innerTokens.push(arg.withClause.accept(this)),token.innerTokens.push(new SqlPrintToken(1,"merge into")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.target.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"using")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.source.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let onClauseToken=new SqlPrintToken(0,"","JoinOnClause");onClauseToken.innerTokens.push(new SqlPrintToken(1,"on")),onClauseToken.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),onClauseToken.innerTokens.push(arg.onCondition.accept(this)),token.innerTokens.push(onClauseToken);for(let clause of arg.whenClauses)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.accept(this));return token}visitMergeWhenClause(arg){let token=new SqlPrintToken(0,"","MergeWhenClause");token.innerTokens.push(new SqlPrintToken(1,this.mergeMatchTypeToKeyword(arg.matchType))),arg.condition&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"and")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.condition.accept(this)));let thenLeadingComments=arg.getThenLeadingComments(),thenKeywordToken=new SqlPrintToken(1,"then");if(thenLeadingComments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentBlocks=this.createCommentBlocks(thenLeadingComments);token.innerTokens.push(...commentBlocks),token.innerTokens.push(thenKeywordToken)}else token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(thenKeywordToken);return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.action.accept(this)),token}visitMergeUpdateAction(arg){let token=new SqlPrintToken(0,"","MergeUpdateAction");return token.innerTokens.push(new SqlPrintToken(1,"update")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.setClause.accept(this)),arg.whereClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.whereClause.accept(this))),token}visitMergeDeleteAction(arg){let token=new SqlPrintToken(0,"","MergeDeleteAction");return token.innerTokens.push(new SqlPrintToken(1,"delete")),arg.whereClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.whereClause.accept(this))),token}visitMergeInsertAction(arg){let token=new SqlPrintToken(0,"","MergeInsertAction");if(token.innerTokens.push(new SqlPrintToken(1,"insert")),arg.columns&&arg.columns.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);for(let i=0;i<arg.columns.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(arg.columns[i].accept(this));token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}if(arg.defaultValues)return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"default values")),token;if(arg.values){let leadingValuesComments=arg.getValuesLeadingComments();if(leadingValuesComments.length>0){token.innerTokens.push(new SqlPrintToken(12,""));let commentBlocks=this.createCommentBlocks(leadingValuesComments);token.innerTokens.push(...commentBlocks)}else token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let valuesKeywordToken=new SqlPrintToken(1,"values");token.innerTokens.push(valuesKeywordToken),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(arg.values.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return token}visitMergeDoNothingAction(_){return new SqlPrintToken(1,"do nothing","MergeDoNothingAction")}mergeMatchTypeToKeyword(matchType){switch(matchType){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(arg){let token=new SqlPrintToken(0,"","UpdateQuery");return arg.withClause&&token.innerTokens.push(arg.withClause.accept(this)),token.innerTokens.push(arg.updateClause.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.setClause.accept(this)),arg.fromClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.fromClause.accept(this))),arg.whereClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.whereClause.accept(this))),arg.returningClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.returningClause.accept(this))),token}visitUpdateClause(arg){let token=new SqlPrintToken(1,"update","UpdateClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.source.accept(this)),token}visitSetClause(arg){let token=new SqlPrintToken(1,"set","SetClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.items.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.items[i]));return token}visitSetClauseItem(arg){let token=new SqlPrintToken(0,"","SetClauseItem");return token.innerTokens.push(arg.column.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(5,"=")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.value.accept(this)),token}visitReturningClause(arg){let token=new SqlPrintToken(1,"returning","ReturningClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.columns.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.columns[i]));return token}visitCreateTableQuery(arg){let baseKeyword=arg.isTemporary?"create temporary table":"create table",keywordText=arg.ifNotExists?`${baseKeyword} if not exists`:baseKeyword,token=new SqlPrintToken(1,keywordText,"CreateTableQuery");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let qualifiedName=new QualifiedName(arg.namespaces??null,arg.tableName);token.innerTokens.push(qualifiedName.accept(this));let definitionEntries=[...arg.columns,...arg.tableConstraints];if(definitionEntries.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let definitionToken=new SqlPrintToken(0,"","CreateTableDefinition");for(let i=0;i<definitionEntries.length;i++)i>0&&definitionToken.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),definitionToken.innerTokens.push(definitionEntries[i].accept(this));token.innerTokens.push(definitionToken),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return arg.tableOptions&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.tableOptions.accept(this))),arg.asSelectQuery&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.asSelectQuery.accept(this))),arg.withDataOption&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"with")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.withDataOption==="with-no-data"&&(token.innerTokens.push(new SqlPrintToken(1,"no")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)),token.innerTokens.push(new SqlPrintToken(1,"data"))),token}visitTableColumnDefinition(arg){let token=new SqlPrintToken(0,"","TableColumnDefinition");token.innerTokens.push(arg.name.accept(this)),arg.dataType&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.dataType.accept(this)));for(let constraint of arg.constraints)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(constraint.accept(this));return token}visitColumnConstraintDefinition(arg){let token=new SqlPrintToken(0,"","ColumnConstraintDefinition");arg.constraintName&&(token.innerTokens.push(new SqlPrintToken(1,"constraint")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this)));let appendKeyword=text=>{token.innerTokens.length>0&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,text))},appendComponent=component=>{token.innerTokens.length>0&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(component.accept(this))};switch(arg.kind){case"not-null":appendKeyword("not null");break;case"null":appendKeyword("null");break;case"default":appendKeyword("default"),arg.defaultValue&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.defaultValue.accept(this)));break;case"primary-key":appendKeyword("primary key");break;case"unique":appendKeyword("unique");break;case"references":arg.reference&&appendComponent(arg.reference);break;case"check":arg.checkExpression&&(appendKeyword("check"),token.innerTokens.push(this.wrapWithParenExpression(arg.checkExpression)));break;case"generated-always-identity":case"generated-by-default-identity":case"raw":arg.rawClause&&appendComponent(arg.rawClause);break}return token}visitTableConstraintDefinition(arg){let token=new SqlPrintToken(0,"","TableConstraintDefinition"),appendKeyword=text=>{token.innerTokens.length>0&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,text))},appendComponent=component=>{token.innerTokens.length>0&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(component.accept(this))},appendColumns=columns=>{if(!columns||columns.length===0)return;token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let listToken=new SqlPrintToken(0,"","ValueList");for(let i=0;i<columns.length;i++)i>0&&listToken.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),listToken.innerTokens.push(columns[i].accept(this));token.innerTokens.push(listToken),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)},useMysqlConstraintStyle=this.constraintStyle==="mysql",inlineNameKinds=new Set(["primary-key","unique","foreign-key"]),shouldInlineConstraintName=useMysqlConstraintStyle&&!!arg.constraintName&&inlineNameKinds.has(arg.kind);switch(arg.constraintName&&!shouldInlineConstraintName&&(appendKeyword("constraint"),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this))),arg.kind){case"primary-key":appendKeyword("primary key"),shouldInlineConstraintName&&arg.constraintName&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this))),appendColumns(arg.columns??[]);break;case"unique":useMysqlConstraintStyle?(appendKeyword("unique key"),shouldInlineConstraintName&&arg.constraintName&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this)))):appendKeyword("unique"),appendColumns(arg.columns??[]);break;case"foreign-key":appendKeyword("foreign key"),shouldInlineConstraintName&&arg.constraintName&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this))),appendColumns(arg.columns??[]),arg.reference&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.reference.accept(this)));break;case"check":arg.checkExpression&&(appendKeyword("check"),token.innerTokens.push(this.wrapWithParenExpression(arg.checkExpression)));break;case"raw":arg.rawClause&&appendComponent(arg.rawClause);break}return token}wrapWithParenExpression(expression){if(expression instanceof ParenExpression)return this.visit(expression);let synthetic=new ParenExpression(expression);return this.visit(synthetic)}visitReferenceDefinition(arg){let token=new SqlPrintToken(0,"","ReferenceDefinition");if(token.innerTokens.push(new SqlPrintToken(1,"references")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.targetTable.accept(this)),arg.columns&&arg.columns.length>0){token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let columnList=new SqlPrintToken(0,"","ValueList");for(let i=0;i<arg.columns.length;i++)i>0&&columnList.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),columnList.innerTokens.push(arg.columns[i].accept(this));token.innerTokens.push(columnList),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return arg.matchType&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,`match ${arg.matchType}`))),arg.onDelete&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"on delete")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.onDelete))),arg.onUpdate&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"on update")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.onUpdate))),arg.deferrable==="deferrable"?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"deferrable"))):arg.deferrable==="not deferrable"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"not deferrable"))),arg.initially==="immediate"?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"initially immediate"))):arg.initially==="deferred"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"initially deferred"))),token}visitCreateIndexStatement(arg){let keywordParts=["create"];arg.unique&&keywordParts.push("unique"),keywordParts.push("index"),arg.concurrently&&keywordParts.push("concurrently"),arg.ifNotExists&&keywordParts.push("if not exists");let token=new SqlPrintToken(1,keywordParts.join(" "),"CreateIndexStatement");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.indexName.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"on")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.tableName.accept(this)),arg.usingMethod&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"using")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.usingMethod.accept(this))),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let columnList=new SqlPrintToken(0,"","IndexColumnList");for(let i=0;i<arg.columns.length;i++)i>0&&columnList.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),columnList.innerTokens.push(arg.columns[i].accept(this));if(token.innerTokens.push(columnList),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),arg.include&&arg.include.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"include")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let includeList=new SqlPrintToken(0,"","ValueList");for(let i=0;i<arg.include.length;i++)i>0&&includeList.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),includeList.innerTokens.push(arg.include[i].accept(this));token.innerTokens.push(includeList),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return arg.withOptions&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.withOptions.accept(this))),arg.tablespace&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"tablespace")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.tablespace.accept(this))),arg.where&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"where")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.where))),token}visitIndexColumnDefinition(arg){let token=new SqlPrintToken(0,"","IndexColumnDefinition");return token.innerTokens.push(this.visit(arg.expression)),arg.collation&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"collate")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.collation.accept(this))),arg.operatorClass&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.operatorClass.accept(this))),arg.sortOrder&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.sortOrder))),arg.nullsOrder&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,`nulls ${arg.nullsOrder}`))),token}visitDropTableStatement(arg){let keyword=arg.ifExists?"drop table if exists":"drop table",token=new SqlPrintToken(1,keyword,"DropTableStatement");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let tableList=new SqlPrintToken(0,"","ValueList");for(let i=0;i<arg.tables.length;i++)i>0&&tableList.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),tableList.innerTokens.push(arg.tables[i].accept(this));return token.innerTokens.push(tableList),arg.behavior&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.behavior))),token}visitDropIndexStatement(arg){let keywordParts=["drop","index"];arg.concurrently&&keywordParts.push("concurrently"),arg.ifExists&&keywordParts.push("if exists");let token=new SqlPrintToken(1,keywordParts.join(" "),"DropIndexStatement");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let indexList=new SqlPrintToken(0,"","ValueList");for(let i=0;i<arg.indexNames.length;i++)i>0&&indexList.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),indexList.innerTokens.push(arg.indexNames[i].accept(this));return token.innerTokens.push(indexList),arg.behavior&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.behavior))),token}visitAlterTableStatement(arg){let keywordParts=["alter","table"];arg.ifExists&&keywordParts.push("if exists"),arg.only&&keywordParts.push("only");let token=new SqlPrintToken(1,keywordParts.join(" "),"AlterTableStatement");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.table.accept(this));for(let i=0;i<arg.actions.length;i++)i===0||token.innerTokens.push(_SqlPrintTokenParser.COMMA_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.actions[i].accept(this));return token}visitAlterTableAddConstraint(arg){let keyword=arg.ifNotExists?"add if not exists":"add",token=new SqlPrintToken(0,"","AlterTableAddConstraint");return token.innerTokens.push(new SqlPrintToken(1,keyword)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraint.accept(this)),arg.notValid&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"not valid"))),token}visitAlterTableDropConstraint(arg){let keyword="drop constraint";arg.ifExists&&(keyword+=" if exists");let token=new SqlPrintToken(0,"","AlterTableDropConstraint");return token.innerTokens.push(new SqlPrintToken(1,keyword)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this)),arg.behavior&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.behavior))),token}visitAlterTableDropColumn(arg){let keyword="drop column";arg.ifExists&&(keyword+=" if exists");let token=new SqlPrintToken(0,"","AlterTableDropColumn");return token.innerTokens.push(new SqlPrintToken(1,keyword)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.columnName.accept(this)),arg.behavior&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.behavior))),token}visitDropConstraintStatement(arg){let keyword="drop constraint";arg.ifExists&&(keyword+=" if exists");let token=new SqlPrintToken(1,keyword,"DropConstraintStatement");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this)),arg.behavior&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.behavior))),token}};var LinePrinter=class{constructor(indentChar=" ",indentSize=0,newline=`\r
19
+ */`:isSeparatorLine?`/* ${lines[0]} */`:`/* ${lines.join(" ")} */`}shouldMergeHeaderComments(comments){return comments.length<=1?!1:comments.some(comment=>{let trimmed=comment.trim();return/^[-=_+*#]{3,}$/.test(trimmed)||trimmed.startsWith("- ")||trimmed.startsWith("* ")})}createHeaderMultiLineCommentBlock(headerComments){let commentBlock=new SqlPrintToken(0,"","CommentBlock");if(commentBlock.markAsHeaderComment(),headerComments.length===0){let commentToken=new SqlPrintToken(6,"/* */");commentBlock.innerTokens.push(commentToken)}else{let openToken=new SqlPrintToken(6,"/*");commentBlock.innerTokens.push(openToken),commentBlock.innerTokens.push(new SqlPrintToken(12,""));for(let line of headerComments){let sanitized=this.escapeCommentDelimiters(line),lineToken=new SqlPrintToken(6,` ${sanitized}`);commentBlock.innerTokens.push(lineToken),commentBlock.innerTokens.push(new SqlPrintToken(12,""))}let closeToken=new SqlPrintToken(6,"*/");commentBlock.innerTokens.push(closeToken)}return commentBlock.innerTokens.push(new SqlPrintToken(12,"")),commentBlock.innerTokens.push(new SqlPrintToken(10," ")),commentBlock}formatLineComment(content){let sanitized=this.sanitizeLineCommentContent(content);return sanitized?`-- ${sanitized}`:"--"}sanitizeLineCommentContent(content){let sanitized=this.escapeCommentDelimiters(content).replace(/\r?\n/g," ").replace(/\u2028|\u2029/g," ").replace(/\s+/g," ").trim();return sanitized.startsWith("--")&&(sanitized=sanitized.slice(2).trimStart()),sanitized}escapeCommentDelimiters(content){return content.replace(/\/\*/g,"\\/\\*").replace(/\*\//g,"*\\/")}visitValueList(arg){let token=new SqlPrintToken(0,"","ValueList");for(let i=0;i<arg.values.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.argumentCommaSpaceTokens()),token.innerTokens.push(this.visit(arg.values[i]));return token}visitColumnReference(arg){let token=new SqlPrintToken(0,"","ColumnReference");return token.innerTokens.push(arg.qualifiedName.accept(this)),this.addComponentComments(token,arg),token}visitFunctionCall(arg){let token=new SqlPrintToken(0,"","FunctionCall");if(token.innerTokens.push(arg.qualifiedName.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),arg.argument&&token.innerTokens.push(this.visit(arg.argument)),arg.internalOrderBy&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.internalOrderBy))),arg.comments&&arg.comments.length>0){let closingParenToken=new SqlPrintToken(4,")");this.addCommentsToToken(closingParenToken,arg.comments),token.innerTokens.push(closingParenToken),arg.comments=null}else token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN);return arg.withOrdinality&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"with ordinality"))),arg.over&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"over")),arg.over instanceof IdentifierString?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.over.accept(this))):(token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.over)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN))),this.addComponentComments(token,arg),token}visitUnaryExpression(arg){let token=new SqlPrintToken(0,"","UnaryExpression");return token.innerTokens.push(this.visit(arg.operator)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.expression)),token}visitBinaryExpression(arg){let token=new SqlPrintToken(0,"","BinaryExpression");token.innerTokens.push(this.visit(arg.left)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let operatorToken=this.visit(arg.operator),operatorLower=operatorToken.text.toLowerCase();return(operatorLower==="and"||operatorLower==="or")&&(operatorToken.type=5),token.innerTokens.push(operatorToken),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.right)),token}visitLiteralValue(arg){let text;arg.value===null?text="null":arg.isStringLiteral?text=`'${arg.value.replace(/'/g,"''")}'`:typeof arg.value=="string"?text=arg.value:text=arg.value.toString();let token=new SqlPrintToken(2,text,"LiteralValue");return arg.positionedComments&&arg.positionedComments.length>0?(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null):arg.comments&&arg.comments.length>0&&this.addCommentsToToken(token,arg.comments),token}visitParameterExpression(arg){arg.index=this.index;let text=this.parameterDecorator.decorate(arg.name.value,arg.index),token=new SqlPrintToken(7,text);return this.addComponentComments(token,arg),this.index++,token}visitSwitchCaseArgument(arg){let token=new SqlPrintToken(0,"","SwitchCaseArgument");this.addComponentComments(token,arg);for(let kv of arg.cases)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(kv.accept(this));if(arg.elseValue)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.createElseToken(arg.elseValue,arg.comments));else if(arg.comments&&arg.comments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(arg.comments);token.innerTokens.push(...commentTokens)}return token}createElseToken(elseValue,switchCaseComments){let elseToken=new SqlPrintToken(0,"","ElseClause");if(elseToken.innerTokens.push(new SqlPrintToken(1,"else")),switchCaseComments&&switchCaseComments.length>0){elseToken.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(switchCaseComments);elseToken.innerTokens.push(...commentTokens)}elseToken.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let elseValueContainer=new SqlPrintToken(0,"","CaseElseValue");return elseValueContainer.innerTokens.push(this.visit(elseValue)),elseToken.innerTokens.push(elseValueContainer),elseToken}visitCaseKeyValuePair(arg){let token=new SqlPrintToken(0,"","CaseKeyValuePair");if(arg.positionedComments&&arg.positionedComments.length>0&&(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null),token.innerTokens.push(new SqlPrintToken(1,"when")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.key)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"then")),arg.comments&&arg.comments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(arg.comments);token.innerTokens.push(...commentTokens)}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let thenValueContainer=new SqlPrintToken(0,"","CaseThenValue");return thenValueContainer.innerTokens.push(this.visit(arg.value)),token.innerTokens.push(thenValueContainer),token}visitRawString(arg){return new SqlPrintToken(2,arg.value,"RawString")}visitIdentifierString(arg){let text=arg.name==="*"?arg.name:this.identifierDecorator.decorate(arg.name);if(arg.positionedComments&&arg.positionedComments.length>0){let token2=new SqlPrintToken(0,"","IdentifierString");this.addPositionedCommentsToToken(token2,arg),arg.positionedComments=null;let valueToken=new SqlPrintToken(2,text);return token2.innerTokens.push(valueToken),token2}if(arg.comments&&arg.comments.length>0){let token2=new SqlPrintToken(0,"","IdentifierString"),valueToken=new SqlPrintToken(2,text);return token2.innerTokens.push(valueToken),this.addComponentComments(token2,arg),token2}return new SqlPrintToken(2,text,"IdentifierString")}visitParenExpression(arg){let token=new SqlPrintToken(0,"","ParenExpression"),hasOwnComments=arg.positionedComments&&arg.positionedComments.length>0,hasInnerComments=arg.expression.positionedComments&&arg.expression.positionedComments.length>0,innerBeforeComments=[],innerAfterComments=[];if(hasInnerComments&&(innerBeforeComments=arg.expression.getPositionedComments("before"),innerAfterComments=arg.expression.getPositionedComments("after"),arg.expression.positionedComments=null),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.expression)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),innerBeforeComments.length>0){let commentBlocks=this.createCommentBlocks(innerBeforeComments),insertIndex=1;for(let commentBlock of commentBlocks)token.innerTokens.splice(insertIndex,0,commentBlock),insertIndex++}if(innerAfterComments.length>0){let commentBlocks=this.createCommentBlocks(innerAfterComments),insertIndex=token.innerTokens.length;for(let commentBlock of commentBlocks)token.innerTokens.splice(insertIndex-1,0,commentBlock)}return hasOwnComments&&(this.addPositionedCommentsToParenExpression(token,arg),arg.positionedComments=null),token}visitCastExpression(arg){let token=new SqlPrintToken(0,"","CastExpression");return this.castStyle==="postgres"?(token.innerTokens.push(this.visit(arg.input)),token.innerTokens.push(new SqlPrintToken(5,"::")),token.innerTokens.push(this.visit(arg.castType)),token):(token.innerTokens.push(new SqlPrintToken(1,"cast")),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.input)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.castType)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token)}visitCaseExpression(arg){let token=new SqlPrintToken(0,"","CaseExpression");arg.positionedComments&&arg.positionedComments.length>0&&(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null);let promotedComments=[],trailingSwitchComments=this.extractSwitchAfterComments(arg.switchCase),conditionToken=null;arg.condition&&(conditionToken=this.visit(arg.condition),promotedComments.push(...this.collectCaseLeadingCommentBlocks(conditionToken)));let switchToken=this.visit(arg.switchCase);if(promotedComments.push(...this.collectCaseLeadingCommentsFromSwitch(switchToken)),promotedComments.length>0&&token.innerTokens.push(...promotedComments),token.innerTokens.push(new SqlPrintToken(1,"case")),conditionToken&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(conditionToken)),token.innerTokens.push(switchToken),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"end")),trailingSwitchComments.length>0){token.innerTokens.push(new SqlPrintToken(12,""));let trailingBlocks=this.createCommentBlocks(trailingSwitchComments);token.innerTokens.push(...trailingBlocks)}return token}extractSwitchAfterComments(arg){if(!arg.positionedComments||arg.positionedComments.length===0)return[];let trailing=[],retained=[];for(let entry of arg.positionedComments)entry.position==="after"?trailing.push(...entry.comments):retained.push(entry);return arg.positionedComments=retained.length>0?retained:null,trailing}collectCaseLeadingCommentsFromSwitch(token){if(!token.innerTokens||token.innerTokens.length===0)return[];let pairToken=token.innerTokens.find(child=>child.containerType==="CaseKeyValuePair");if(!pairToken)return[];let keyToken=this.findCaseKeyToken(pairToken);return keyToken?this.collectCaseLeadingCommentBlocks(keyToken):[]}findCaseKeyToken(pairToken){for(let child of pairToken.innerTokens)if(child.containerType!=="CommentBlock"&&child.type!==10&&child.type!==1&&child.containerType!=="CaseThenValue")return child}collectCaseLeadingCommentBlocks(token){if(!token.innerTokens||token.innerTokens.length===0)return[];let collected=[];return this.collectCaseLeadingCommentBlocksRecursive(token,collected,new Set,0),collected}collectCaseLeadingCommentBlocksRecursive(token,collected,seen,depth){if(!token.innerTokens||token.innerTokens.length===0)return;let removedAny=!1;for(;token.innerTokens.length>0;){let first=token.innerTokens[0];if(first.containerType==="CommentBlock"){token.innerTokens.shift();let signature=this.commentBlockSignature(first);depth>0&&seen.has(signature)||(collected.push(first),seen.add(signature)),removedAny=!0;continue}if(!removedAny&&first.type===10)return;break}if(!token.innerTokens||token.innerTokens.length===0)return;let firstChild=token.innerTokens[0];this.isTransparentCaseWrapper(firstChild)&&this.collectCaseLeadingCommentBlocksRecursive(firstChild,collected,seen,depth+1)}isTransparentCaseWrapper(token){return token?["ColumnReference","QualifiedName","IdentifierString","RawString","LiteralValue","ParenExpression","UnaryExpression"].includes(token.containerType):!1}commentBlockSignature(commentBlock){return!commentBlock.innerTokens||commentBlock.innerTokens.length===0?"":commentBlock.innerTokens.filter(inner=>inner.text!=="").map(inner=>inner.text).join("|")}visitArrayExpression(arg){let token=new SqlPrintToken(0,"","ArrayExpression");return token.innerTokens.push(new SqlPrintToken(1,"array")),token.innerTokens.push(new SqlPrintToken(4,"[")),token.innerTokens.push(this.visit(arg.expression)),token.innerTokens.push(new SqlPrintToken(4,"]")),token}visitArrayQueryExpression(arg){let token=new SqlPrintToken(0,"","ArrayExpression");return token.innerTokens.push(new SqlPrintToken(1,"array")),token.innerTokens.push(new SqlPrintToken(4,"(")),token.innerTokens.push(this.visit(arg.query)),token.innerTokens.push(new SqlPrintToken(4,")")),token}visitArraySliceExpression(arg){let token=new SqlPrintToken(0,"","ArrayExpression");return token.innerTokens.push(this.visit(arg.array)),token.innerTokens.push(new SqlPrintToken(4,"[")),arg.startIndex&&token.innerTokens.push(this.visit(arg.startIndex)),token.innerTokens.push(new SqlPrintToken(5,":")),arg.endIndex&&token.innerTokens.push(this.visit(arg.endIndex)),token.innerTokens.push(new SqlPrintToken(4,"]")),token}visitArrayIndexExpression(arg){let token=new SqlPrintToken(0,"","ArrayExpression");return token.innerTokens.push(this.visit(arg.array)),token.innerTokens.push(new SqlPrintToken(4,"[")),token.innerTokens.push(this.visit(arg.index)),token.innerTokens.push(new SqlPrintToken(4,"]")),token}visitBetweenExpression(arg){let token=new SqlPrintToken(0,"","BetweenExpression");return token.innerTokens.push(this.visit(arg.expression)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.negated&&(token.innerTokens.push(new SqlPrintToken(1,"not")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)),token.innerTokens.push(new SqlPrintToken(1,"between")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.lower)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"and")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.upper)),token}visitStringSpecifierExpression(arg){let specifier=arg.specifier.accept(this).text,value=arg.value.accept(this).text;return new SqlPrintToken(2,specifier+value,"StringSpecifierExpression")}visitTypeValue(arg){let token=new SqlPrintToken(0,"","TypeValue");return this.addComponentComments(token,arg),token.innerTokens.push(arg.qualifiedName.accept(this)),arg.argument&&(token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.argument)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)),token}visitTupleExpression(arg){let token=new SqlPrintToken(0,"","TupleExpression"),requiresMultiline=this.tupleRequiresMultiline(arg);token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);for(let i=0;i<arg.values.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.argumentCommaSpaceTokens()),token.innerTokens.push(this.visit(arg.values[i]));return requiresMultiline&&token.innerTokens.push(new SqlPrintToken(12,"","TupleExpression")),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}tupleRequiresMultiline(tuple){for(let value of tuple.values)if(this.hasInlineComments(value))return!0;return!1}hasInlineComments(component){return this.hasLeadingComments(component)?!0:component instanceof TupleExpression?this.tupleRequiresMultiline(component):!1}hasLeadingComments(component){let before=(component.positionedComments??[]).find(pc=>pc.position==="before");return!!(before&&before.comments.some(comment=>comment.trim().length>0))}visitWindowFrameExpression(arg){let token=new SqlPrintToken(0,"","WindowFrameExpression"),first=!0;return arg.partition&&(token.innerTokens.push(this.visit(arg.partition)),first=!1),arg.order&&(first?first=!1:token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.order))),arg.frameSpec&&(first?first=!1:token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.frameSpec))),token}visitWindowFrameSpec(arg){let token=new SqlPrintToken(0,"","WindowFrameSpec");return token.innerTokens.push(new SqlPrintToken(1,arg.frameType)),arg.endBound===null?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.startBound.accept(this))):(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"between")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.startBound.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"and")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.endBound.accept(this))),token}visitWindowFrameBoundaryValue(arg){let token=new SqlPrintToken(0,"","WindowFrameBoundaryValue");return token.innerTokens.push(arg.value.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.isFollowing?"following":"preceding")),token}visitWindowFrameBoundStatic(arg){return new SqlPrintToken(1,arg.bound)}visitSelectItem(arg){let token=new SqlPrintToken(0,"","SelectItem"),originalSelectItemPositionedComments=arg.positionedComments,originalValuePositionedComments=arg.value.positionedComments,isParenExpression=arg.value instanceof ParenExpression;isParenExpression||(arg.value.positionedComments=null);let beforeComments=arg.getPositionedComments("before"),afterComments=arg.getPositionedComments("after");if(beforeComments.length>0){let commentTokens=this.createInlineCommentSequence(beforeComments);token.innerTokens.push(...commentTokens),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}if(token.innerTokens.push(this.visit(arg.value)),afterComments.length>0&&!isParenExpression){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(afterComments);token.innerTokens.push(...commentTokens)}if(arg.positionedComments=originalSelectItemPositionedComments,arg.value.positionedComments=originalValuePositionedComments,!arg.identifier)return token;if(arg.value instanceof ColumnReference){let defaultName=arg.value.column.name;if(arg.identifier.name===defaultName)return token}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let asKeywordPositionedComments="asKeywordPositionedComments"in arg?arg.asKeywordPositionedComments:null;if(asKeywordPositionedComments){let beforeComments2=asKeywordPositionedComments.filter(pc=>pc.position==="before");if(beforeComments2.length>0)for(let posComment of beforeComments2){let commentTokens=this.createInlineCommentSequence(posComment.comments);token.innerTokens.push(...commentTokens),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}}if(token.innerTokens.push(new SqlPrintToken(1,"as")),asKeywordPositionedComments){let afterComments2=asKeywordPositionedComments.filter(pc=>pc.position==="after");if(afterComments2.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let posComment of afterComments2){let commentTokens=this.createInlineCommentSequence(posComment.comments);token.innerTokens.push(...commentTokens)}}}let asKeywordComments="asKeywordComments"in arg?arg.asKeywordComments:null;if(asKeywordComments&&asKeywordComments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(asKeywordComments);token.innerTokens.push(...commentTokens)}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let identifierToken=this.visit(arg.identifier);token.innerTokens.push(identifierToken);let aliasPositionedComments="aliasPositionedComments"in arg?arg.aliasPositionedComments:null;if(aliasPositionedComments){let afterComments2=aliasPositionedComments.filter(pc=>pc.position==="after");if(afterComments2.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let posComment of afterComments2){let commentTokens=this.createInlineCommentSequence(posComment.comments);token.innerTokens.push(...commentTokens)}}}let aliasComments=arg.aliasComments;if(aliasComments&&aliasComments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(aliasComments);token.innerTokens.push(...commentTokens)}return token}visitSelectClause(arg){let token=new SqlPrintToken(1,"select","SelectClause");arg.positionedComments&&arg.positionedComments.length>0&&(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null);let selectKeywordText="select";for(let hint of arg.hints)selectKeywordText+=" "+this.visit(hint).text;if(arg.distinct){let distinctToken=arg.distinct.accept(this);if(distinctToken.innerTokens&&distinctToken.innerTokens.length>0){let distinctText=distinctToken.text;for(let innerToken of distinctToken.innerTokens)distinctText+=this.flattenTokenText(innerToken);selectKeywordText+=" "+distinctText}else selectKeywordText+=" "+distinctToken.text}token.text=selectKeywordText,token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.items.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.items[i]));return token}flattenTokenText(token){let result=token.text;if(token.innerTokens)for(let innerToken of token.innerTokens)result+=this.flattenTokenText(innerToken);return result}visitHintClause(arg){return new SqlPrintToken(2,arg.getFullHint())}visitDistinct(arg){let token=new SqlPrintToken(1,"distinct");return arg.positionedComments&&arg.positionedComments.length>0&&(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null),token}visitDistinctOn(arg){let token=new SqlPrintToken(0,"","DistinctOn");return token.innerTokens.push(new SqlPrintToken(1,"distinct on")),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(arg.value.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}visitTableSource(arg){let fullName="";Array.isArray(arg.namespaces)&&arg.namespaces.length>0&&(fullName=arg.namespaces.map(ns=>ns.accept(this).text).join(".")+"."),fullName+=arg.table.accept(this).text;let token=new SqlPrintToken(2,fullName);return this.addComponentComments(token,arg),arg.identifier&&(arg.identifier.name,arg.table.name),token}visitSourceExpression(arg){let token=new SqlPrintToken(0,"","SourceExpression");if(token.innerTokens.push(arg.datasource.accept(this)),!arg.aliasExpression)return token;if(arg.datasource instanceof TableSource){let defaultName=arg.datasource.table.name;return arg.aliasExpression.table.name===defaultName||(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.aliasExpression.accept(this))),token}else return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.aliasExpression.accept(this)),token}visitFromClause(arg){let contextPushed=!1;if(this.normalizeJoinConditionOrder){let aliasOrder=this.buildJoinAliasOrder(arg);aliasOrder.size>0&&(this.joinConditionContexts.push({aliasOrder}),contextPushed=!0)}try{let token=new SqlPrintToken(1,"from","FromClause");if(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.source)),arg.joins)for(let i=0;i<arg.joins.length;i++)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.joins[i]));return token}finally{contextPushed&&this.joinConditionContexts.pop()}}visitJoinClause(arg){let token=new SqlPrintToken(0,"","JoinClause"),joinKeywordPositionedComments=arg.joinKeywordPositionedComments;if(joinKeywordPositionedComments){let beforeComments=joinKeywordPositionedComments.filter(pc=>pc.position==="before");if(beforeComments.length>0)for(let posComment of beforeComments){let commentTokens=this.createInlineCommentSequence(posComment.comments);token.innerTokens.push(...commentTokens),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}}if(token.innerTokens.push(new SqlPrintToken(1,arg.joinType.value)),joinKeywordPositionedComments){let afterComments=joinKeywordPositionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let posComment of afterComments){let commentTokens=this.createInlineCommentSequence(posComment.comments);token.innerTokens.push(...commentTokens)}}}let joinKeywordComments=arg.joinKeywordComments;if(joinKeywordComments&&joinKeywordComments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(joinKeywordComments);token.innerTokens.push(...commentTokens)}return arg.lateral&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"lateral"))),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.source)),arg.condition&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.condition))),token}visitJoinOnClause(arg){if(this.normalizeJoinConditionOrder){let aliasOrder=this.getCurrentJoinAliasOrder();aliasOrder&&this.normalizeJoinConditionValue(arg.condition,aliasOrder)}let token=new SqlPrintToken(0,"","JoinOnClause");return token.innerTokens.push(new SqlPrintToken(1,"on")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.condition)),token}getCurrentJoinAliasOrder(){return this.joinConditionContexts.length===0?null:this.joinConditionContexts[this.joinConditionContexts.length-1].aliasOrder}buildJoinAliasOrder(fromClause){let aliasOrder=new Map,nextIndex=0,registerSource=source=>{let identifiers=this.collectSourceIdentifiers(source);if(identifiers.length!==0){for(let identifier of identifiers){let key=identifier.toLowerCase();aliasOrder.has(key)||aliasOrder.set(key,nextIndex)}nextIndex++}};if(registerSource(fromClause.source),fromClause.joins)for(let joinClause of fromClause.joins)registerSource(joinClause.source);return aliasOrder}collectSourceIdentifiers(source){let identifiers=[],aliasName=source.getAliasName();if(aliasName&&identifiers.push(aliasName),source.datasource instanceof TableSource){let tableComponent=source.datasource.table.name;identifiers.push(tableComponent);let fullName=source.datasource.getSourceName();fullName&&fullName!==tableComponent&&identifiers.push(fullName)}return identifiers}normalizeJoinConditionValue(condition,aliasOrder){let kind=condition.getKind();if(kind===ParenExpression.kind){let paren=condition;this.normalizeJoinConditionValue(paren.expression,aliasOrder);return}if(kind===BinaryExpression.kind){let binary=condition;this.normalizeJoinConditionValue(binary.left,aliasOrder),this.normalizeJoinConditionValue(binary.right,aliasOrder),this.normalizeBinaryEquality(binary,aliasOrder)}}normalizeBinaryEquality(binary,aliasOrder){if(binary.operator.value.toLowerCase()!=="=")return;let leftOwner=this.resolveColumnOwner(binary.left),rightOwner=this.resolveColumnOwner(binary.right);if(!leftOwner||!rightOwner||leftOwner===rightOwner)return;let leftOrder=aliasOrder.get(leftOwner),rightOrder=aliasOrder.get(rightOwner);if(!(leftOrder===void 0||rightOrder===void 0)&&leftOrder>rightOrder){let originalLeft=binary.left;binary.left=binary.right,binary.right=originalLeft}}resolveColumnOwner(value){let kind=value.getKind();if(kind===ColumnReference.kind){let namespace=value.getNamespace();return namespace?(namespace.includes(".")?namespace.split(".").pop()??"":namespace).toLowerCase():null}return kind===ParenExpression.kind?this.resolveColumnOwner(value.expression):null}visitJoinUsingClause(arg){let token=new SqlPrintToken(0,"","JoinUsingClause");return token.innerTokens.push(new SqlPrintToken(1,"using")),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.condition)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}visitFunctionSource(arg){let token=new SqlPrintToken(0,"","FunctionSource");return token.innerTokens.push(arg.qualifiedName.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),arg.argument&&token.innerTokens.push(this.visit(arg.argument)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}visitSourceAliasExpression(arg){let token=new SqlPrintToken(0,"","SourceAliasExpression");if(token.innerTokens.push(this.visit(arg.table)),arg.columns){token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);for(let i=0;i<arg.columns.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.argumentCommaSpaceTokens()),token.innerTokens.push(this.visit(arg.columns[i]));token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return arg.positionedComments&&arg.positionedComments.length>0?(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null):arg.comments&&arg.comments.length>0&&this.addCommentsToToken(token,arg.comments),token}visitWhereClause(arg){let token=new SqlPrintToken(1,"where","WhereClause");return this.addComponentComments(token,arg),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.condition)),token}visitGroupByClause(arg){let token=new SqlPrintToken(1,"group by","GroupByClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.grouping.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.grouping[i]));return token}visitHavingClause(arg){let token=new SqlPrintToken(1,"having","HavingClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.condition)),token}visitWindowClause(arg){let token=new SqlPrintToken(1,"window","WindowClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.windows.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.windows[i]));return token}visitWindowFrameClause(arg){let token=new SqlPrintToken(0,"","WindowFrameClause");return token.innerTokens.push(arg.name.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.expression)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}visitLimitClause(arg){let token=new SqlPrintToken(1,"limit","LimitClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.value)),token}visitOffsetClause(arg){let token=new SqlPrintToken(1,"offset","OffsetClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.value)),token}visitFetchClause(arg){let token=new SqlPrintToken(1,"fetch","FetchClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.expression)),token}visitFetchExpression(arg){let token=new SqlPrintToken(0,"","FetchExpression");return token.innerTokens.push(new SqlPrintToken(1,arg.type)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.count.accept(this)),arg.unit&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.unit))),token}visitForClause(arg){let token=new SqlPrintToken(1,"for","ForClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.lockMode)),token}visitWithClause(arg){let token=new SqlPrintToken(1,"with","WithClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.recursive&&(token.innerTokens.push(new SqlPrintToken(1,"recursive")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN));for(let i=0;i<arg.tables.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(arg.tables[i].accept(this));return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),this.addComponentComments(token,arg),token}visitCommonTable(arg){let token=new SqlPrintToken(0,"","CommonTable");arg.positionedComments&&arg.positionedComments.length>0?(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null):arg.comments&&arg.comments.length>0&&this.addCommentsToToken(token,arg.comments),token.innerTokens.push(arg.aliasExpression.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.materialized!==null&&(arg.materialized?token.innerTokens.push(new SqlPrintToken(1,"materialized")):token.innerTokens.push(new SqlPrintToken(1,"not materialized")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let query=new SqlPrintToken(0,"","SubQuerySource");return query.innerTokens.push(arg.query.accept(this)),token.innerTokens.push(query),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}visitSimpleQuery(arg){let token=new SqlPrintToken(0,"","SimpleSelectQuery");if(arg.headerComments&&arg.headerComments.length>0){if(this.shouldMergeHeaderComments(arg.headerComments)){let mergedHeaderComment=this.createHeaderMultiLineCommentBlock(arg.headerComments);token.innerTokens.push(mergedHeaderComment)}else{let headerCommentBlocks=this.createCommentBlocks(arg.headerComments,!0);token.innerTokens.push(...headerCommentBlocks)}arg.withClause&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}if(arg.positionedComments&&arg.positionedComments.length>0&&(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null),arg.withClause&&token.innerTokens.push(arg.withClause.accept(this)),arg.comments&&arg.comments.length>0){let commentBlocks=this.createCommentBlocks(arg.comments);token.innerTokens.push(...commentBlocks),arg.selectClause&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}return token.innerTokens.push(arg.selectClause.accept(this)),arg.fromClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.fromClause.accept(this)),arg.whereClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.whereClause.accept(this))),arg.groupByClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.groupByClause.accept(this))),arg.havingClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.havingClause.accept(this))),arg.orderByClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.orderByClause.accept(this))),arg.windowClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.windowClause.accept(this))),arg.limitClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.limitClause.accept(this))),arg.offsetClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.offsetClause.accept(this))),arg.fetchClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.fetchClause.accept(this))),arg.forClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.forClause.accept(this)))),token}visitSubQuerySource(arg){let token=new SqlPrintToken(0,"");token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let subQuery=new SqlPrintToken(0,"","SubQuerySource");return subQuery.innerTokens.push(arg.query.accept(this)),token.innerTokens.push(subQuery),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}visitValuesQuery(arg){let token=new SqlPrintToken(1,"values","ValuesQuery");if(arg.headerComments&&arg.headerComments.length>0)if(this.shouldMergeHeaderComments(arg.headerComments)){let mergedHeaderComment=this.createHeaderMultiLineCommentBlock(arg.headerComments);token.innerTokens.push(mergedHeaderComment),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}else{let headerCommentBlocks=this.createCommentBlocks(arg.headerComments,!0);for(let commentBlock of headerCommentBlocks)token.innerTokens.push(commentBlock),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let values=new SqlPrintToken(0,"","Values");for(let i=0;i<arg.tuples.length;i++)i>0&&values.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),values.innerTokens.push(arg.tuples[i].accept(this));return token.innerTokens.push(values),this.addCommentsToToken(token,arg.comments),token}visitInlineQuery(arg){let token=new SqlPrintToken(0,"");token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let queryToken=new SqlPrintToken(0,"","InlineQuery");if(queryToken.innerTokens.push(arg.selectQuery.accept(this)),token.innerTokens.push(queryToken),arg.comments&&arg.comments.length>0){let closingParenToken=new SqlPrintToken(4,")");this.addCommentsToToken(closingParenToken,arg.comments),token.innerTokens.push(closingParenToken),arg.comments=null}else token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN);return token}visitInsertQuery(arg){let token=new SqlPrintToken(0,"","InsertQuery");return arg.withClause&&token.innerTokens.push(arg.withClause.accept(this)),token.innerTokens.push(this.visit(arg.insertClause)),arg.selectQuery&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.selectQuery))),arg.returningClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.returningClause.accept(this))),token}visitInsertClause(arg){let token=new SqlPrintToken(0,"","InsertClause");if(token.innerTokens.push(new SqlPrintToken(1,"insert into")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.source.accept(this)),arg.columns&&arg.columns.length>0){token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);for(let i=0;i<arg.columns.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(arg.columns[i].accept(this));token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return token}visitDeleteQuery(arg){let token=new SqlPrintToken(0,"","DeleteQuery");return arg.withClause&&token.innerTokens.push(arg.withClause.accept(this)),token.innerTokens.push(arg.deleteClause.accept(this)),arg.usingClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.usingClause.accept(this))),arg.whereClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.whereClause.accept(this))),arg.returningClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.returningClause.accept(this))),token}visitDeleteClause(arg){let token=new SqlPrintToken(1,"delete from","DeleteClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.source.accept(this)),token}visitUsingClause(arg){let token=new SqlPrintToken(1,"using","UsingClause");if(arg.sources.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.sources.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.sources[i]))}return token}visitMergeQuery(arg){let token=new SqlPrintToken(0,"","MergeQuery");arg.withClause&&token.innerTokens.push(arg.withClause.accept(this)),token.innerTokens.push(new SqlPrintToken(1,"merge into")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.target.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"using")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.source.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let onClauseToken=new SqlPrintToken(0,"","JoinOnClause");onClauseToken.innerTokens.push(new SqlPrintToken(1,"on")),onClauseToken.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),onClauseToken.innerTokens.push(arg.onCondition.accept(this)),token.innerTokens.push(onClauseToken);for(let clause of arg.whenClauses)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.accept(this));return token}visitMergeWhenClause(arg){let token=new SqlPrintToken(0,"","MergeWhenClause");token.innerTokens.push(new SqlPrintToken(1,this.mergeMatchTypeToKeyword(arg.matchType))),arg.condition&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"and")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.condition.accept(this)));let thenLeadingComments=arg.getThenLeadingComments(),thenKeywordToken=new SqlPrintToken(1,"then");if(thenLeadingComments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentBlocks=this.createCommentBlocks(thenLeadingComments);token.innerTokens.push(...commentBlocks),token.innerTokens.push(thenKeywordToken)}else token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(thenKeywordToken);return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.action.accept(this)),token}visitMergeUpdateAction(arg){let token=new SqlPrintToken(0,"","MergeUpdateAction");return token.innerTokens.push(new SqlPrintToken(1,"update")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.setClause.accept(this)),arg.whereClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.whereClause.accept(this))),token}visitMergeDeleteAction(arg){let token=new SqlPrintToken(0,"","MergeDeleteAction");return token.innerTokens.push(new SqlPrintToken(1,"delete")),arg.whereClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.whereClause.accept(this))),token}visitMergeInsertAction(arg){let token=new SqlPrintToken(0,"","MergeInsertAction");if(token.innerTokens.push(new SqlPrintToken(1,"insert")),arg.columns&&arg.columns.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);for(let i=0;i<arg.columns.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(arg.columns[i].accept(this));token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}if(arg.defaultValues)return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"default values")),token;if(arg.values){let leadingValuesComments=arg.getValuesLeadingComments();if(leadingValuesComments.length>0){token.innerTokens.push(new SqlPrintToken(12,""));let commentBlocks=this.createCommentBlocks(leadingValuesComments);token.innerTokens.push(...commentBlocks)}else token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let valuesKeywordToken=new SqlPrintToken(1,"values");token.innerTokens.push(valuesKeywordToken),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(arg.values.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return token}visitMergeDoNothingAction(_){return new SqlPrintToken(1,"do nothing","MergeDoNothingAction")}mergeMatchTypeToKeyword(matchType){switch(matchType){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(arg){let token=new SqlPrintToken(0,"","UpdateQuery");return arg.withClause&&token.innerTokens.push(arg.withClause.accept(this)),token.innerTokens.push(arg.updateClause.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.setClause.accept(this)),arg.fromClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.fromClause.accept(this))),arg.whereClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.whereClause.accept(this))),arg.returningClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.returningClause.accept(this))),token}visitUpdateClause(arg){let token=new SqlPrintToken(1,"update","UpdateClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.source.accept(this)),token}visitSetClause(arg){let token=new SqlPrintToken(1,"set","SetClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.items.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.items[i]));return token}visitSetClauseItem(arg){let token=new SqlPrintToken(0,"","SetClauseItem");return token.innerTokens.push(arg.column.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(5,"=")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.value.accept(this)),token}visitReturningClause(arg){let token=new SqlPrintToken(1,"returning","ReturningClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.columns.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.columns[i]));return token}visitCreateTableQuery(arg){let baseKeyword=arg.isTemporary?"create temporary table":"create table",keywordText=arg.ifNotExists?`${baseKeyword} if not exists`:baseKeyword,token=new SqlPrintToken(1,keywordText,"CreateTableQuery");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let qualifiedName=new QualifiedName(arg.namespaces??null,arg.tableName);token.innerTokens.push(qualifiedName.accept(this));let definitionEntries=[...arg.columns,...arg.tableConstraints];if(definitionEntries.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let definitionToken=new SqlPrintToken(0,"","CreateTableDefinition");for(let i=0;i<definitionEntries.length;i++)i>0&&definitionToken.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),definitionToken.innerTokens.push(definitionEntries[i].accept(this));token.innerTokens.push(definitionToken),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return arg.tableOptions&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.tableOptions.accept(this))),arg.asSelectQuery&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.asSelectQuery.accept(this))),arg.withDataOption&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"with")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.withDataOption==="with-no-data"&&(token.innerTokens.push(new SqlPrintToken(1,"no")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)),token.innerTokens.push(new SqlPrintToken(1,"data"))),token}visitTableColumnDefinition(arg){let token=new SqlPrintToken(0,"","TableColumnDefinition");token.innerTokens.push(arg.name.accept(this)),arg.dataType&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.dataType.accept(this)));for(let constraint of arg.constraints)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(constraint.accept(this));return token}visitColumnConstraintDefinition(arg){let token=new SqlPrintToken(0,"","ColumnConstraintDefinition");arg.constraintName&&(token.innerTokens.push(new SqlPrintToken(1,"constraint")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this)));let appendKeyword=text=>{token.innerTokens.length>0&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,text))},appendComponent=component=>{token.innerTokens.length>0&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(component.accept(this))};switch(arg.kind){case"not-null":appendKeyword("not null");break;case"null":appendKeyword("null");break;case"default":appendKeyword("default"),arg.defaultValue&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.defaultValue.accept(this)));break;case"primary-key":appendKeyword("primary key");break;case"unique":appendKeyword("unique");break;case"references":arg.reference&&appendComponent(arg.reference);break;case"check":arg.checkExpression&&(appendKeyword("check"),token.innerTokens.push(this.wrapWithParenExpression(arg.checkExpression)));break;case"generated-always-identity":case"generated-by-default-identity":case"raw":arg.rawClause&&appendComponent(arg.rawClause);break}return token}visitTableConstraintDefinition(arg){let token=new SqlPrintToken(0,"","TableConstraintDefinition"),appendKeyword=text=>{token.innerTokens.length>0&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,text))},appendComponent=component=>{token.innerTokens.length>0&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(component.accept(this))},appendColumns=columns=>{if(!columns||columns.length===0)return;token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let listToken=new SqlPrintToken(0,"","ValueList");for(let i=0;i<columns.length;i++)i>0&&listToken.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),listToken.innerTokens.push(columns[i].accept(this));token.innerTokens.push(listToken),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)},useMysqlConstraintStyle=this.constraintStyle==="mysql",inlineNameKinds=new Set(["primary-key","unique","foreign-key"]),shouldInlineConstraintName=useMysqlConstraintStyle&&!!arg.constraintName&&inlineNameKinds.has(arg.kind);switch(arg.constraintName&&!shouldInlineConstraintName&&(appendKeyword("constraint"),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this))),arg.kind){case"primary-key":appendKeyword("primary key"),shouldInlineConstraintName&&arg.constraintName&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this))),appendColumns(arg.columns??[]);break;case"unique":useMysqlConstraintStyle?(appendKeyword("unique key"),shouldInlineConstraintName&&arg.constraintName&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this)))):appendKeyword("unique"),appendColumns(arg.columns??[]);break;case"foreign-key":appendKeyword("foreign key"),shouldInlineConstraintName&&arg.constraintName&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this))),appendColumns(arg.columns??[]),arg.reference&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.reference.accept(this)));break;case"check":arg.checkExpression&&(appendKeyword("check"),token.innerTokens.push(this.wrapWithParenExpression(arg.checkExpression)));break;case"raw":arg.rawClause&&appendComponent(arg.rawClause);break}return token}wrapWithParenExpression(expression){if(expression instanceof ParenExpression)return this.visit(expression);let synthetic=new ParenExpression(expression);return this.visit(synthetic)}visitReferenceDefinition(arg){let token=new SqlPrintToken(0,"","ReferenceDefinition");if(token.innerTokens.push(new SqlPrintToken(1,"references")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.targetTable.accept(this)),arg.columns&&arg.columns.length>0){token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let columnList=new SqlPrintToken(0,"","ValueList");for(let i=0;i<arg.columns.length;i++)i>0&&columnList.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),columnList.innerTokens.push(arg.columns[i].accept(this));token.innerTokens.push(columnList),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return arg.matchType&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,`match ${arg.matchType}`))),arg.onDelete&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"on delete")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.onDelete))),arg.onUpdate&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"on update")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.onUpdate))),arg.deferrable==="deferrable"?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"deferrable"))):arg.deferrable==="not deferrable"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"not deferrable"))),arg.initially==="immediate"?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"initially immediate"))):arg.initially==="deferred"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"initially deferred"))),token}visitCreateIndexStatement(arg){let keywordParts=["create"];arg.unique&&keywordParts.push("unique"),keywordParts.push("index"),arg.concurrently&&keywordParts.push("concurrently"),arg.ifNotExists&&keywordParts.push("if not exists");let token=new SqlPrintToken(1,keywordParts.join(" "),"CreateIndexStatement");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.indexName.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"on")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.tableName.accept(this)),arg.usingMethod&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"using")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.usingMethod.accept(this))),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let columnList=new SqlPrintToken(0,"","IndexColumnList");for(let i=0;i<arg.columns.length;i++)i>0&&columnList.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),columnList.innerTokens.push(arg.columns[i].accept(this));if(token.innerTokens.push(columnList),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),arg.include&&arg.include.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"include")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);let includeList=new SqlPrintToken(0,"","ValueList");for(let i=0;i<arg.include.length;i++)i>0&&includeList.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),includeList.innerTokens.push(arg.include[i].accept(this));token.innerTokens.push(includeList),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return arg.withOptions&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.withOptions.accept(this))),arg.tablespace&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"tablespace")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.tablespace.accept(this))),arg.where&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"where")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.where))),token}visitIndexColumnDefinition(arg){let token=new SqlPrintToken(0,"","IndexColumnDefinition");return token.innerTokens.push(this.visit(arg.expression)),arg.collation&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"collate")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.collation.accept(this))),arg.operatorClass&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.operatorClass.accept(this))),arg.sortOrder&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.sortOrder))),arg.nullsOrder&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,`nulls ${arg.nullsOrder}`))),token}visitDropTableStatement(arg){let keyword=arg.ifExists?"drop table if exists":"drop table",token=new SqlPrintToken(1,keyword,"DropTableStatement");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let tableList=new SqlPrintToken(0,"","ValueList");for(let i=0;i<arg.tables.length;i++)i>0&&tableList.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),tableList.innerTokens.push(arg.tables[i].accept(this));return token.innerTokens.push(tableList),arg.behavior&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.behavior))),token}visitDropIndexStatement(arg){let keywordParts=["drop","index"];arg.concurrently&&keywordParts.push("concurrently"),arg.ifExists&&keywordParts.push("if exists");let token=new SqlPrintToken(1,keywordParts.join(" "),"DropIndexStatement");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let indexList=new SqlPrintToken(0,"","ValueList");for(let i=0;i<arg.indexNames.length;i++)i>0&&indexList.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),indexList.innerTokens.push(arg.indexNames[i].accept(this));return token.innerTokens.push(indexList),arg.behavior&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.behavior))),token}visitAlterTableStatement(arg){let keywordParts=["alter","table"];arg.ifExists&&keywordParts.push("if exists"),arg.only&&keywordParts.push("only");let token=new SqlPrintToken(1,keywordParts.join(" "),"AlterTableStatement");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.table.accept(this));for(let i=0;i<arg.actions.length;i++)i===0||token.innerTokens.push(_SqlPrintTokenParser.COMMA_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.actions[i].accept(this));return token}visitAlterTableAddConstraint(arg){let keyword=arg.ifNotExists?"add if not exists":"add",token=new SqlPrintToken(0,"","AlterTableAddConstraint");return token.innerTokens.push(new SqlPrintToken(1,keyword)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraint.accept(this)),arg.notValid&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"not valid"))),token}visitAlterTableDropConstraint(arg){let keyword="drop constraint";arg.ifExists&&(keyword+=" if exists");let token=new SqlPrintToken(0,"","AlterTableDropConstraint");return token.innerTokens.push(new SqlPrintToken(1,keyword)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this)),arg.behavior&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.behavior))),token}visitAlterTableDropColumn(arg){let keyword="drop column";arg.ifExists&&(keyword+=" if exists");let token=new SqlPrintToken(0,"","AlterTableDropColumn");return token.innerTokens.push(new SqlPrintToken(1,keyword)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.columnName.accept(this)),arg.behavior&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.behavior))),token}visitDropConstraintStatement(arg){let keyword="drop constraint";arg.ifExists&&(keyword+=" if exists");let token=new SqlPrintToken(1,keyword,"DropConstraintStatement");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.constraintName.accept(this)),arg.behavior&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.behavior))),token}visitExplainStatement(arg){let token=new SqlPrintToken(0,"","ExplainStatement");token.innerTokens.push(new SqlPrintToken(1,"explain"));let inlineFlags=[],optionList=[];if(arg.options)for(let option of arg.options)this.isExplainLegacyFlag(option)&&this.isExplainBooleanTrue(option.value)?inlineFlags.push(option):optionList.push(option);for(let flag of inlineFlags)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,flag.name.name.toLowerCase()));if(optionList.length>0){token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);for(let i=0;i<optionList.length;i++)i>0&&(token.innerTokens.push(_SqlPrintTokenParser.COMMA_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)),token.innerTokens.push(this.renderExplainOption(optionList[i]));token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.statement.accept(this)),token}visitAnalyzeStatement(arg){let keywordParts=["analyze"];arg.verbose&&keywordParts.push("verbose");let token=new SqlPrintToken(1,keywordParts.join(" "),"AnalyzeStatement");if(arg.target&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.renderQualifiedNameInline(arg.target)),arg.columns&&arg.columns.length>0)){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);for(let i=0;i<arg.columns.length;i++)i>0&&(token.innerTokens.push(_SqlPrintTokenParser.COMMA_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)),token.innerTokens.push(this.renderIdentifierInline(arg.columns[i]));token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)}return token}renderExplainOption(option){let token=new SqlPrintToken(0,"","ExplainOption");return token.innerTokens.push(new SqlPrintToken(1,option.name.name.toLowerCase())),option.value&&!this.isExplainBooleanTrue(option.value)&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(option.value.accept(this))),token}isExplainLegacyFlag(option){let name=option.name.name.toLowerCase();return name==="analyze"||name==="verbose"}isExplainBooleanTrue(value){if(!value)return!1;if(value instanceof RawString){let normalized=value.value.toLowerCase();return normalized==="true"||normalized==="t"||normalized==="on"||normalized==="yes"||normalized==="1"}if(value instanceof LiteralValue){if(typeof value.value=="boolean")return value.value;if(typeof value.value=="number")return value.value!==0;if(typeof value.value=="string"){let normalized=value.value.toLowerCase();return normalized==="true"||normalized==="t"||normalized==="on"||normalized==="yes"||normalized==="1"}}return!1}renderQualifiedNameInline(arg){let parts=[];if(arg.namespaces&&arg.namespaces.length>0)for(let ns of arg.namespaces)parts.push(this.renderIdentifierText(ns));return parts.push(this.renderIdentifierText(arg.name)),new SqlPrintToken(2,parts.join("."),"QualifiedName")}renderIdentifierInline(component){return new SqlPrintToken(2,this.renderIdentifierText(component),"IdentifierString")}renderIdentifierText(component){return component instanceof IdentifierString?component.name==="*"?component.name:this.identifierDecorator.decorate(component.name):component.value}};var LinePrinter=class{constructor(indentChar=" ",indentSize=0,newline=`\r
20
20
  `,commaBreak="none"){this.indentChar=indentChar,this.indentSize=indentSize,this.newline=newline,this.commaBreak=commaBreak,this.lines=[],this.appendNewline(0)}print(){let result="";for(let line of this.lines)line.text!==""&&(result+=this.indent(line.level)+line.text);return result.trimEnd()}indent(level){return this.indentChar.repeat(this.indentSize*level)}appendNewline(level){if(this.lines.length>0){let current=this.lines[this.lines.length-1];current.text!==""&&(current.text=current.text.trimEnd()+this.newline)}this.lines.push(new PrintLine(level,""))}appendText(text){if(this.cleanupLine(text)){let previousLine=this.lines[this.lines.length-1];previousLine.text=previousLine.text.trimEnd()+text;return}let workLine=this.getCurrentLine();text===" "&&workLine.text===""||(workLine.text+=text)}trimTrailingWhitespaceFromPreviousLine(){if(this.lines.length<2)return;let previousLine=this.lines[this.lines.length-2],newlineMatch=previousLine.text.match(/(\r?\n)$/),trailingNewline=newlineMatch?newlineMatch[1]:"",content=trailingNewline?previousLine.text.slice(0,-trailingNewline.length):previousLine.text;previousLine.text=content.replace(/[ \t]+$/,"")+trailingNewline}cleanupLine(text){let workLine=this.getCurrentLine();if(text===","&&workLine.text.trim()===""&&this.lines.length>1&&(this.commaBreak==="after"||this.commaBreak==="none")){let previousIndex=this.lines.length-2;for(;previousIndex>=0&&this.lines[previousIndex].text.trim()==="";)this.lines.splice(previousIndex,1),previousIndex--;if(previousIndex<0)return!1;let previousLine=this.lines[previousIndex];return this.lineHasTrailingComment(previousLine.text)?!1:(this.lines.pop(),!0)}return!1}lineHasTrailingComment(text){return text.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}},PrintLine=class{constructor(level,text){this.level=level,this.text=text}};var INDENT_CHAR_MAP={space:" ",tab:" "},NEWLINE_MAP={lf:`
21
21
  `,crlf:`\r
22
- `,cr:"\r"},IDENTIFIER_ESCAPE_MAP={quote:{start:'"',end:'"'},backtick:{start:"`",end:"`"},bracket:{start:"[",end:"]"},none:{start:"",end:""}};function resolveIndentCharOption(option){if(option===void 0)return;let normalized=typeof option=="string"?option.toLowerCase():option;return typeof normalized=="string"&&Object.prototype.hasOwnProperty.call(INDENT_CHAR_MAP,normalized)?INDENT_CHAR_MAP[normalized]:option}function resolveNewlineOption(option){if(option===void 0)return;let normalized=typeof option=="string"?option.toLowerCase():option;return typeof normalized=="string"&&Object.prototype.hasOwnProperty.call(NEWLINE_MAP,normalized)?NEWLINE_MAP[normalized]:option}function resolveIdentifierEscapeOption(option){if(option===void 0)return;if(typeof option=="string"){let normalized=option.toLowerCase();if(!Object.prototype.hasOwnProperty.call(IDENTIFIER_ESCAPE_MAP,normalized))throw new Error(`Unknown identifierEscape option: ${option}`);let mapped=IDENTIFIER_ESCAPE_MAP[normalized];return{start:mapped.start,end:mapped.end}}let start=option.start??"",end=option.end??"";return{start,end}}var OnelineFormattingHelper=class{constructor(options){this.options=options}shouldFormatContainer(token,shouldIndentNested){switch(token.containerType){case"ParenExpression":return this.options.parenthesesOneLine&&!shouldIndentNested;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(parentContainerType){return this.options.insertColumnsOneLine?parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction":!1}shouldInsertJoinNewline(insideWithClause){return!(insideWithClause&&this.options.withClauseStyle==="full-oneline")}resolveCommaBreak(parentContainerType,commaBreak,cteCommaBreak,valuesCommaBreak){return parentContainerType==="WithClause"?cteCommaBreak:parentContainerType==="Values"?valuesCommaBreak:this.isInsertClauseOneline(parentContainerType)?"none":commaBreak}shouldSkipInsertClauseSpace(parentContainerType,nextToken,currentLineText){if(!(parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction"))return!1;if(nextToken&&nextToken.type===4&&nextToken.text==="(")return!0;if(!this.options.insertColumnsOneLine)return!1;let lastChar=currentLineText.slice(-1);return lastChar==="("||lastChar===" "||lastChar===""}shouldSkipCommentBlockSpace(parentContainerType,insideWithClause){return parentContainerType==="CommentBlock"&&insideWithClause&&this.options.withClauseStyle==="full-oneline"}formatInsertClauseToken(text,parentContainerType,currentLineText,ensureTrailingSpace){if(!this.isInsertClauseOneline(parentContainerType))return{handled:!1};if(text==="")return{handled:!0};let leadingWhitespace=text.match(/^\s+/)?.[0]??"",trimmed=leadingWhitespace?text.slice(leadingWhitespace.length):text;if(trimmed==="")return{handled:!0};if(leadingWhitespace){let lastChar=currentLineText.slice(-1);lastChar!=="("&&lastChar!==" "&&lastChar!==""&&ensureTrailingSpace()}return{handled:!0,text:trimmed}}};var CREATE_TABLE_SINGLE_PAREN_KEYWORDS=new Set(["unique","check","key","index"]),CREATE_TABLE_MULTI_PAREN_KEYWORDS=new Set(["primary key","foreign key","unique key"]),CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER=new Set(["references"]),SqlPrinter=class _SqlPrinter{constructor(options){this.insideWithClause=!1;this.mergeWhenPredicateDepth=0;this.pendingLineCommentBreak=null;this.smartCommentBlockBuilder=null;let resolvedIndentChar=resolveIndentCharOption(options?.indentChar),resolvedNewline=resolveNewlineOption(options?.newline);this.indentChar=resolvedIndentChar??"",this.indentSize=options?.indentSize??0,this.newline=resolvedNewline??" ",this.commaBreak=options?.commaBreak??"none",this.cteCommaBreak=options?.cteCommaBreak??this.commaBreak,this.valuesCommaBreak=options?.valuesCommaBreak??this.commaBreak,this.andBreak=options?.andBreak??"none",this.orBreak=options?.orBreak??"none",this.keywordCase=options?.keywordCase??"none",this.commentExportMode=this.resolveCommentExportMode(options?.exportComment),this.withClauseStyle=options?.withClauseStyle??"standard",this.commentStyle=options?.commentStyle??"block",this.parenthesesOneLine=options?.parenthesesOneLine??!1,this.betweenOneLine=options?.betweenOneLine??!1,this.valuesOneLine=options?.valuesOneLine??!1,this.joinOneLine=options?.joinOneLine??!1,this.caseOneLine=options?.caseOneLine??!1,this.subqueryOneLine=options?.subqueryOneLine??!1,this.indentNestedParentheses=options?.indentNestedParentheses??!1,this.insertColumnsOneLine=options?.insertColumnsOneLine??!1,this.whenOneLine=options?.whenOneLine??!1;let onelineOptions={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 OnelineFormattingHelper(onelineOptions),this.linePrinter=new LinePrinter(this.indentChar,this.indentSize,this.newline,this.commaBreak),this.indentIncrementContainers=new Set(options?.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","SetClause"])}print(token,level=0){return this.linePrinter=new LinePrinter(this.indentChar,this.indentSize,this.newline,this.commaBreak),this.insideWithClause=!1,this.pendingLineCommentBreak=null,this.smartCommentBlockBuilder=null,this.linePrinter.lines.length>0&&level!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=level),this.appendToken(token,level,void 0,0,!1),this.linePrinter.print()}resolveCommentExportMode(option){return option===void 0?"none":option===!0?"full":option===!1?"none":option}rendersInlineComments(){return this.commentExportMode==="full"}shouldRenderComment(token,context){if(context?.forceRender)return this.commentExportMode!=="none";switch(this.commentExportMode){case"full":return!0;case"none":return!1;case"header-only":return token.isHeaderComment===!0;case"top-header-only":return token.isHeaderComment===!0&&!!context?.isTopLevelContainer;default:return!1}}appendToken(token,level,parentContainerType,caseContextDepth=0,indentParentActive=!1,commentContext){let wasInsideWithClause=this.insideWithClause;if(token.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"&&(this.insideWithClause=!0),this.shouldSkipToken(token))return;let containerIsTopLevel=parentContainerType===void 0,leadingCommentCount=0,leadingCommentContexts=[];if(token.innerTokens&&token.innerTokens.length>0)for(;leadingCommentCount<token.innerTokens.length;){let leadingCandidate=token.innerTokens[leadingCommentCount];if(leadingCandidate.containerType!=="CommentBlock")break;let context={position:"leading",isTopLevelContainer:containerIsTopLevel},shouldRender=this.shouldRenderComment(leadingCandidate,context);leadingCommentContexts.push({token:leadingCandidate,context,shouldRender}),leadingCommentCount++}let hasRenderableLeadingComment=leadingCommentContexts.some(item=>item.shouldRender),leadingCommentIndentLevel=hasRenderableLeadingComment?this.getLeadingCommentIndentLevel(parentContainerType,level):null;hasRenderableLeadingComment&&!this.isOnelineMode()&&this.shouldAddNewlineBeforeLeadingComments(parentContainerType)&&this.linePrinter.getCurrentLine().text.trim().length>0&&this.linePrinter.appendNewline(leadingCommentIndentLevel??level);for(let leading of leadingCommentContexts)leading.shouldRender&&this.appendToken(leading.token,leadingCommentIndentLevel??level,token.containerType,caseContextDepth,indentParentActive,leading.context);if(this.smartCommentBlockBuilder&&token.containerType!=="CommentBlock"&&token.type!==12&&this.flushSmartCommentBlockBuilder(),this.pendingLineCommentBreak!==null){this.isOnelineMode()||this.linePrinter.appendNewline(this.pendingLineCommentBreak);let shouldSkipToken=token.type===12;if(this.pendingLineCommentBreak=null,shouldSkipToken)return}let effectiveCommentContext=commentContext??{position:"inline",isTopLevelContainer:containerIsTopLevel};if(token.containerType==="CommentBlock"){if(!this.shouldRenderComment(token,effectiveCommentContext))return;let commentLevel=this.getCommentBaseIndentLevel(level,parentContainerType);this.handleCommentBlockContainer(token,commentLevel,effectiveCommentContext);return}let current=this.linePrinter.getCurrentLine(),nextCaseContextDepth=this.isCaseContext(token.containerType)?caseContextDepth+1:caseContextDepth,shouldIndentNested=this.shouldIndentNestedParentheses(token);if(token.type===1)this.handleKeywordToken(token,level,parentContainerType,caseContextDepth);else if(token.type===3)this.handleCommaToken(token,level,parentContainerType);else if(token.type===4)this.handleParenthesisToken(token,level,indentParentActive,parentContainerType);else if(token.type===5&&token.text.toLowerCase()==="and")this.handleAndOperatorToken(token,level,parentContainerType,caseContextDepth);else if(token.type===5&&token.text.toLowerCase()==="or")this.handleOrOperatorToken(token,level,parentContainerType,caseContextDepth);else if(token.containerType==="JoinClause")this.handleJoinClauseToken(token,level);else if(token.type===6){if(this.shouldRenderComment(token,effectiveCommentContext)){let commentLevel=this.getCommentBaseIndentLevel(level,parentContainerType);this.printCommentToken(token.text,commentLevel,parentContainerType)}}else if(token.type===10)this.handleSpaceToken(token,parentContainerType);else if(token.type===12){if(this.whenOneLine&&parentContainerType==="MergeWhenClause")return;let commentLevel=this.getCommentBaseIndentLevel(level,parentContainerType);this.handleCommentNewlineToken(token,commentLevel)}else if(token.containerType==="CommonTable"&&this.withClauseStyle==="cte-oneline"){this.handleCteOnelineToken(token,level);return}else if(this.shouldFormatContainerAsOneline(token,shouldIndentNested)){this.handleOnelineToken(token,level);return}else this.tryAppendInsertClauseTokenText(token.text,parentContainerType)||this.linePrinter.appendText(token.text);if(token.keywordTokens&&token.keywordTokens.length>0)for(let i=0;i<token.keywordTokens.length;i++){let keywordToken=token.keywordTokens[i];this.appendToken(keywordToken,level,token.containerType,nextCaseContextDepth,indentParentActive)}let innerLevel=level,increasedIndent=!1,shouldIncreaseIndent=this.indentIncrementContainers.has(token.containerType)||shouldIndentNested,delayIndentNewline=shouldIndentNested&&token.containerType==="ParenExpression",isAlterTableStatement=token.containerType==="AlterTableStatement",deferAlterTableIndent=!1;if(!this.isOnelineMode()&&shouldIncreaseIndent&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline"))if(delayIndentNewline)innerLevel=level+1,increasedIndent=!0;else if(current.text!=="")if(isAlterTableStatement)innerLevel=level+1,increasedIndent=!0,deferAlterTableIndent=!0;else{let targetIndentLevel=level+1;token.containerType==="SetClause"&&parentContainerType==="MergeUpdateAction"&&(targetIndentLevel=level+2),this.shouldAlignCreateTableSelect(token.containerType,parentContainerType)?(innerLevel=level,increasedIndent=!1,this.linePrinter.appendNewline(level)):(innerLevel=targetIndentLevel,increasedIndent=!0,this.linePrinter.appendNewline(innerLevel))}else token.containerType==="SetClause"&&(innerLevel=parentContainerType==="MergeUpdateAction"?level+2:level+1,increasedIndent=!0,current.level=innerLevel);let isMergeWhenClause=this.whenOneLine&&token.containerType==="MergeWhenClause",mergePredicateActive=isMergeWhenClause,alterTableTableRendered=!1,alterTableIndentInserted=!1;for(let i=leadingCommentCount;i<token.innerTokens.length;i++){let child=token.innerTokens[i],nextChild=token.innerTokens[i+1],previousEntry=this.findPreviousSignificantToken(token.innerTokens,i),previousChild=previousEntry?.token,priorChild=(previousEntry?this.findPreviousSignificantToken(token.innerTokens,previousEntry.index):void 0)?.token,childIsAction=this.isMergeActionContainer(child),nextIsAction=this.isMergeActionContainer(nextChild),inMergePredicate=mergePredicateActive&&!childIsAction;if(isAlterTableStatement){if(child.containerType==="QualifiedName")alterTableTableRendered=!0;else if(deferAlterTableIndent&&alterTableTableRendered&&!alterTableIndentInserted&&(this.isOnelineMode()||this.linePrinter.appendNewline(innerLevel),alterTableIndentInserted=!0,deferAlterTableIndent=!1,!this.isOnelineMode()&&child.type===10))continue}if(child.type===10){if(this.shouldConvertSpaceToClauseBreak(token.containerType,nextChild)){if(!this.isOnelineMode()){let clauseBreakIndent=this.getClauseBreakIndentLevel(token.containerType,innerLevel);this.linePrinter.appendNewline(clauseBreakIndent)}isMergeWhenClause&&nextIsAction&&(mergePredicateActive=!1);continue}this.handleSpaceToken(child,token.containerType,nextChild,previousChild,priorChild);continue}let childIndentParentActive=token.containerType==="ParenExpression"?shouldIndentNested:indentParentActive;inMergePredicate&&this.mergeWhenPredicateDepth++;let childCommentContext=child.containerType==="CommentBlock"?{position:"inline",isTopLevelContainer:containerIsTopLevel}:void 0;this.appendToken(child,innerLevel,token.containerType,nextCaseContextDepth,childIndentParentActive,childCommentContext),inMergePredicate&&this.mergeWhenPredicateDepth--,childIsAction&&isMergeWhenClause&&(mergePredicateActive=!1)}if(this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder(),token.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"){this.insideWithClause=!1,this.linePrinter.appendNewline(level);return}increasedIndent&&shouldIncreaseIndent&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&!delayIndentNewline&&this.linePrinter.appendNewline(level)}isCaseContext(containerType){switch(containerType){case"CaseExpression":case"CaseKeyValuePair":case"CaseThenValue":case"CaseElseValue":case"SwitchCaseArgument":return!0;default:return!1}}shouldSkipToken(token){return token.type===12?!1:(!token.innerTokens||token.innerTokens.length===0)&&token.text===""}applyKeywordCase(text){return this.keywordCase==="upper"?text.toUpperCase():this.keywordCase==="lower"?text.toLowerCase():text}handleKeywordToken(token,level,parentContainerType,caseContextDepth=0){let lower=token.text.toLowerCase();if(lower==="and"&&(this.andBreak!=="none"||this.whenOneLine&&parentContainerType==="MergeWhenClause")){this.handleAndOperatorToken(token,level,parentContainerType,caseContextDepth);return}else if(lower==="or"&&(this.orBreak!=="none"||this.whenOneLine&&parentContainerType==="MergeWhenClause")){this.handleOrOperatorToken(token,level,parentContainerType,caseContextDepth);return}let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}this.ensureSpaceBeforeKeyword(),this.linePrinter.appendText(text)}ensureSpaceBeforeKeyword(){let currentLine=this.linePrinter.getCurrentLine();currentLine.text===""||currentLine.text[currentLine.text.length-1]==="("||this.ensureTrailingSpace()}ensureTrailingSpace(){let currentLine=this.linePrinter.getCurrentLine();currentLine.text!==""&&(currentLine.text.endsWith(" ")||(currentLine.text+=" "),currentLine.text=currentLine.text.replace(/\s+$/," "))}tryAppendInsertClauseTokenText(text,parentContainerType){let currentLineText=this.linePrinter.getCurrentLine().text,result=this.onelineHelper.formatInsertClauseToken(text,parentContainerType,currentLineText,()=>this.ensureTrailingSpace());return result.handled?(result.text&&this.linePrinter.appendText(result.text),!0):!1}handleCommaToken(token,level,parentContainerType){let text=token.text,isWithinWithClause=parentContainerType==="WithClause",effectiveCommaBreak=this.onelineHelper.resolveCommaBreak(parentContainerType,this.commaBreak,this.cteCommaBreak,this.valuesCommaBreak);if(parentContainerType==="SetClause"&&(effectiveCommaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline")this.linePrinter.appendText(text);else if(this.withClauseStyle==="cte-oneline"&&isWithinWithClause)this.linePrinter.appendText(text),this.linePrinter.appendNewline(level);else if(effectiveCommaBreak==="before"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="before"&&(this.linePrinter.commaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||(this.linePrinter.appendNewline(level),this.newline===" "&&this.linePrinter.trimTrailingWhitespaceFromPreviousLine(),parentContainerType==="InsertClause"&&(this.linePrinter.getCurrentLine().level=level+1)),this.linePrinter.appendText(text),previousCommaBreak!=="before"&&(this.linePrinter.commaBreak=previousCommaBreak)}else if(effectiveCommaBreak==="after"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="after"&&(this.linePrinter.commaBreak="after"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),previousCommaBreak!=="after"&&(this.linePrinter.commaBreak=previousCommaBreak)}else if(effectiveCommaBreak==="none"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="none"&&(this.linePrinter.commaBreak="none"),this.linePrinter.appendText(text),this.onelineHelper.isInsertClauseOneline(parentContainerType)&&this.ensureTrailingSpace(),previousCommaBreak!=="none"&&(this.linePrinter.commaBreak=previousCommaBreak)}else this.linePrinter.appendText(text)}handleAndOperatorToken(token,level,parentContainerType,caseContextDepth=0){let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}if(this.whenOneLine&&(parentContainerType==="MergeWhenClause"||this.mergeWhenPredicateDepth>0)){this.linePrinter.appendText(text);return}this.andBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text)):this.andBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level)):this.linePrinter.appendText(text)}handleParenthesisToken(token,level,indentParentActive,parentContainerType){if(token.text==="("){if(this.linePrinter.appendText(token.text),(parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction")&&this.insertColumnsOneLine)return;this.isOnelineMode()||(this.shouldBreakAfterOpeningParen(parentContainerType)?this.linePrinter.appendNewline(level+1):indentParentActive&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&this.linePrinter.appendNewline(level));return}if(token.text===")"&&!this.isOnelineMode()){if(this.shouldBreakBeforeClosingParen(parentContainerType)){this.linePrinter.appendNewline(Math.max(level,0)),this.linePrinter.appendText(token.text);return}if(indentParentActive&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")){let closingLevel=Math.max(level-1,0);this.linePrinter.appendNewline(closingLevel)}}this.linePrinter.appendText(token.text)}handleOrOperatorToken(token,level,parentContainerType,caseContextDepth=0){let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}if(this.whenOneLine&&(parentContainerType==="MergeWhenClause"||this.mergeWhenPredicateDepth>0)){this.linePrinter.appendText(text);return}this.orBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text)):this.orBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level)):this.linePrinter.appendText(text)}shouldIndentNestedParentheses(token){return!this.indentNestedParentheses||token.containerType!=="ParenExpression"?!1:token.innerTokens.some(child=>this.containsParenExpression(child))}containsParenExpression(token){if(token.containerType==="ParenExpression")return!0;for(let child of token.innerTokens)if(this.containsParenExpression(child))return!0;return!1}handleJoinClauseToken(token,level){let text=this.applyKeywordCase(token.text);this.onelineHelper.shouldInsertJoinNewline(this.insideWithClause)&&this.linePrinter.appendNewline(level),this.linePrinter.appendText(text)}shouldFormatContainerAsOneline(token,shouldIndentNested){return this.onelineHelper.shouldFormatContainer(token,shouldIndentNested)}isInsertClauseOneline(parentContainerType){return this.onelineHelper.isInsertClauseOneline(parentContainerType)}handleSpaceToken(token,parentContainerType,nextToken,previousToken,priorToken){this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder();let currentLineText=this.linePrinter.getCurrentLine().text;if(!this.onelineHelper.shouldSkipInsertClauseSpace(parentContainerType,nextToken,currentLineText)){if(this.onelineHelper.shouldSkipCommentBlockSpace(parentContainerType,this.insideWithClause)){let currentLine=this.linePrinter.getCurrentLine();currentLine.text!==""&&!currentLine.text.endsWith(" ")&&this.linePrinter.appendText(" ");return}this.shouldSkipSpaceBeforeParenthesis(parentContainerType,nextToken,previousToken,priorToken)||this.linePrinter.appendText(token.text)}}findPreviousSignificantToken(tokens,index){for(let i=index-1;i>=0;i--){let candidate=tokens[i];if(!(candidate.type===10||candidate.type===12)&&!(candidate.type===6&&!this.rendersInlineComments()))return{token:candidate,index:i}}}shouldSkipSpaceBeforeParenthesis(parentContainerType,nextToken,previousToken,priorToken){return!nextToken||nextToken.type!==4||nextToken.text!=="("||!parentContainerType||!this.isCreateTableSpacingContext(parentContainerType)||!previousToken?!1:!!(this.isCreateTableNameToken(previousToken,parentContainerType)||this.isCreateTableConstraintKeyword(previousToken,parentContainerType)||priorToken&&this.isCreateTableConstraintKeyword(priorToken,parentContainerType)&&this.isIdentifierAttachedToConstraint(previousToken,priorToken,parentContainerType))}shouldAlignCreateTableSelect(containerType,parentContainerType){return containerType==="SimpleSelectQuery"&&parentContainerType==="CreateTableQuery"}isCreateTableSpacingContext(parentContainerType){switch(parentContainerType){case"CreateTableQuery":case"CreateTableDefinition":case"TableConstraintDefinition":case"ColumnConstraintDefinition":case"ReferenceDefinition":return!0;default:return!1}}isCreateTableNameToken(previousToken,parentContainerType){return parentContainerType!=="CreateTableQuery"?!1:previousToken.containerType==="QualifiedName"}isCreateTableConstraintKeyword(token,parentContainerType){if(token.type!==1)return!1;let text=token.text.toLowerCase();return parentContainerType==="ReferenceDefinition"?CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER.has(text):!!(CREATE_TABLE_SINGLE_PAREN_KEYWORDS.has(text)||CREATE_TABLE_MULTI_PAREN_KEYWORDS.has(text))}isIdentifierAttachedToConstraint(token,keywordToken,parentContainerType){if(!token)return!1;if(parentContainerType==="ReferenceDefinition")return token.containerType==="QualifiedName"&&CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER.has(keywordToken.text.toLowerCase());if(parentContainerType==="TableConstraintDefinition"||parentContainerType==="ColumnConstraintDefinition"){let normalized=keywordToken.text.toLowerCase();if(CREATE_TABLE_SINGLE_PAREN_KEYWORDS.has(normalized)||CREATE_TABLE_MULTI_PAREN_KEYWORDS.has(normalized))return token.containerType==="IdentifierString"}return!1}printCommentToken(text,level,parentContainerType){let trimmed=text.trim();if(trimmed&&!(this.commentStyle==="smart"&&parentContainerType==="CommentBlock"&&this.handleSmartCommentBlockToken(text,trimmed,level)))if(this.commentStyle==="smart"){let normalized=this.normalizeCommentForSmart(trimmed);if(normalized.lines.length>1||normalized.forceBlock){let blockText=this.buildBlockComment(normalized.lines,level);this.linePrinter.appendText(blockText)}else{let content=normalized.lines[0],lineText=content?`-- ${content}`:"--";if(parentContainerType==="CommentBlock")this.linePrinter.appendText(lineText),this.pendingLineCommentBreak=this.resolveCommentIndentLevel(level,parentContainerType);else{this.linePrinter.appendText(lineText);let effectiveLevel=this.resolveCommentIndentLevel(level,parentContainerType);this.linePrinter.appendNewline(effectiveLevel)}}}else{if(trimmed.startsWith("/*")&&trimmed.endsWith("*/"))if(/\r?\n/.test(trimmed)){let newlineReplacement=this.isOnelineMode()?" ":typeof this.newline=="string"?this.newline:`
22
+ `,cr:"\r"},IDENTIFIER_ESCAPE_MAP={quote:{start:'"',end:'"'},backtick:{start:"`",end:"`"},bracket:{start:"[",end:"]"},none:{start:"",end:""}};function resolveIndentCharOption(option){if(option===void 0)return;let normalized=typeof option=="string"?option.toLowerCase():option;return typeof normalized=="string"&&Object.prototype.hasOwnProperty.call(INDENT_CHAR_MAP,normalized)?INDENT_CHAR_MAP[normalized]:option}function resolveNewlineOption(option){if(option===void 0)return;let normalized=typeof option=="string"?option.toLowerCase():option;return typeof normalized=="string"&&Object.prototype.hasOwnProperty.call(NEWLINE_MAP,normalized)?NEWLINE_MAP[normalized]:option}function resolveIdentifierEscapeOption(option){if(option===void 0)return;if(typeof option=="string"){let normalized=option.toLowerCase();if(!Object.prototype.hasOwnProperty.call(IDENTIFIER_ESCAPE_MAP,normalized))throw new Error(`Unknown identifierEscape option: ${option}`);let mapped=IDENTIFIER_ESCAPE_MAP[normalized];return{start:mapped.start,end:mapped.end}}let start=option.start??"",end=option.end??"";return{start,end}}var OnelineFormattingHelper=class{constructor(options){this.options=options}shouldFormatContainer(token,shouldIndentNested){switch(token.containerType){case"ParenExpression":return this.options.parenthesesOneLine&&!shouldIndentNested;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(parentContainerType){return this.options.insertColumnsOneLine?parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction":!1}shouldInsertJoinNewline(insideWithClause){return!(insideWithClause&&this.options.withClauseStyle==="full-oneline")}resolveCommaBreak(parentContainerType,commaBreak,cteCommaBreak,valuesCommaBreak){return parentContainerType==="WithClause"?cteCommaBreak:parentContainerType==="AnalyzeStatement"||parentContainerType==="ExplainStatement"?"none":parentContainerType==="Values"?valuesCommaBreak:this.isInsertClauseOneline(parentContainerType)?"none":commaBreak}shouldSkipInsertClauseSpace(parentContainerType,nextToken,currentLineText){if(!(parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction"))return!1;if(nextToken&&nextToken.type===4&&nextToken.text==="(")return!0;if(!this.options.insertColumnsOneLine)return!1;let lastChar=currentLineText.slice(-1);return lastChar==="("||lastChar===" "||lastChar===""}shouldSkipCommentBlockSpace(parentContainerType,insideWithClause){return parentContainerType==="CommentBlock"&&insideWithClause&&this.options.withClauseStyle==="full-oneline"}formatInsertClauseToken(text,parentContainerType,currentLineText,ensureTrailingSpace){if(!this.isInsertClauseOneline(parentContainerType))return{handled:!1};if(text==="")return{handled:!0};let leadingWhitespace=text.match(/^\s+/)?.[0]??"",trimmed=leadingWhitespace?text.slice(leadingWhitespace.length):text;if(trimmed==="")return{handled:!0};if(leadingWhitespace){let lastChar=currentLineText.slice(-1);lastChar!=="("&&lastChar!==" "&&lastChar!==""&&ensureTrailingSpace()}return{handled:!0,text:trimmed}}};var CREATE_TABLE_SINGLE_PAREN_KEYWORDS=new Set(["unique","check","key","index"]),CREATE_TABLE_MULTI_PAREN_KEYWORDS=new Set(["primary key","foreign key","unique key"]),CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER=new Set(["references"]),SqlPrinter=class _SqlPrinter{constructor(options){this.insideWithClause=!1;this.mergeWhenPredicateDepth=0;this.pendingLineCommentBreak=null;this.smartCommentBlockBuilder=null;let resolvedIndentChar=resolveIndentCharOption(options?.indentChar),resolvedNewline=resolveNewlineOption(options?.newline);this.indentChar=resolvedIndentChar??"",this.indentSize=options?.indentSize??0,this.newline=resolvedNewline??" ",this.commaBreak=options?.commaBreak??"none",this.cteCommaBreak=options?.cteCommaBreak??this.commaBreak,this.valuesCommaBreak=options?.valuesCommaBreak??this.commaBreak,this.andBreak=options?.andBreak??"none",this.orBreak=options?.orBreak??"none",this.keywordCase=options?.keywordCase??"none",this.commentExportMode=this.resolveCommentExportMode(options?.exportComment),this.withClauseStyle=options?.withClauseStyle??"standard",this.commentStyle=options?.commentStyle??"block",this.parenthesesOneLine=options?.parenthesesOneLine??!1,this.betweenOneLine=options?.betweenOneLine??!1,this.valuesOneLine=options?.valuesOneLine??!1,this.joinOneLine=options?.joinOneLine??!1,this.caseOneLine=options?.caseOneLine??!1,this.subqueryOneLine=options?.subqueryOneLine??!1,this.indentNestedParentheses=options?.indentNestedParentheses??!1,this.insertColumnsOneLine=options?.insertColumnsOneLine??!1,this.whenOneLine=options?.whenOneLine??!1;let onelineOptions={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 OnelineFormattingHelper(onelineOptions),this.linePrinter=new LinePrinter(this.indentChar,this.indentSize,this.newline,this.commaBreak),this.indentIncrementContainers=new Set(options?.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","SetClause"])}print(token,level=0){return this.linePrinter=new LinePrinter(this.indentChar,this.indentSize,this.newline,this.commaBreak),this.insideWithClause=!1,this.pendingLineCommentBreak=null,this.smartCommentBlockBuilder=null,this.linePrinter.lines.length>0&&level!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=level),this.appendToken(token,level,void 0,0,!1),this.linePrinter.print()}resolveCommentExportMode(option){return option===void 0?"none":option===!0?"full":option===!1?"none":option}rendersInlineComments(){return this.commentExportMode==="full"}shouldRenderComment(token,context){if(context?.forceRender)return this.commentExportMode!=="none";switch(this.commentExportMode){case"full":return!0;case"none":return!1;case"header-only":return token.isHeaderComment===!0;case"top-header-only":return token.isHeaderComment===!0&&!!context?.isTopLevelContainer;default:return!1}}appendToken(token,level,parentContainerType,caseContextDepth=0,indentParentActive=!1,commentContext){let wasInsideWithClause=this.insideWithClause;if(token.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"&&(this.insideWithClause=!0),this.shouldSkipToken(token))return;let containerIsTopLevel=parentContainerType===void 0,leadingCommentCount=0,leadingCommentContexts=[];if(token.innerTokens&&token.innerTokens.length>0)for(;leadingCommentCount<token.innerTokens.length;){let leadingCandidate=token.innerTokens[leadingCommentCount];if(leadingCandidate.containerType!=="CommentBlock")break;let context={position:"leading",isTopLevelContainer:containerIsTopLevel},shouldRender=this.shouldRenderComment(leadingCandidate,context);leadingCommentContexts.push({token:leadingCandidate,context,shouldRender}),leadingCommentCount++}let hasRenderableLeadingComment=leadingCommentContexts.some(item=>item.shouldRender),leadingCommentIndentLevel=hasRenderableLeadingComment?this.getLeadingCommentIndentLevel(parentContainerType,level):null;hasRenderableLeadingComment&&!this.isOnelineMode()&&this.shouldAddNewlineBeforeLeadingComments(parentContainerType)&&this.linePrinter.getCurrentLine().text.trim().length>0&&this.linePrinter.appendNewline(leadingCommentIndentLevel??level);for(let leading of leadingCommentContexts)leading.shouldRender&&this.appendToken(leading.token,leadingCommentIndentLevel??level,token.containerType,caseContextDepth,indentParentActive,leading.context);if(this.smartCommentBlockBuilder&&token.containerType!=="CommentBlock"&&token.type!==12&&this.flushSmartCommentBlockBuilder(),this.pendingLineCommentBreak!==null){this.isOnelineMode()||this.linePrinter.appendNewline(this.pendingLineCommentBreak);let shouldSkipToken=token.type===12;if(this.pendingLineCommentBreak=null,shouldSkipToken)return}let effectiveCommentContext=commentContext??{position:"inline",isTopLevelContainer:containerIsTopLevel};if(token.containerType==="CommentBlock"){if(!this.shouldRenderComment(token,effectiveCommentContext))return;let commentLevel=this.getCommentBaseIndentLevel(level,parentContainerType);this.handleCommentBlockContainer(token,commentLevel,effectiveCommentContext);return}let current=this.linePrinter.getCurrentLine(),nextCaseContextDepth=this.isCaseContext(token.containerType)?caseContextDepth+1:caseContextDepth,shouldIndentNested=this.shouldIndentNestedParentheses(token);if(token.type===1)this.handleKeywordToken(token,level,parentContainerType,caseContextDepth);else if(token.type===3)this.handleCommaToken(token,level,parentContainerType);else if(token.type===4)this.handleParenthesisToken(token,level,indentParentActive,parentContainerType);else if(token.type===5&&token.text.toLowerCase()==="and")this.handleAndOperatorToken(token,level,parentContainerType,caseContextDepth);else if(token.type===5&&token.text.toLowerCase()==="or")this.handleOrOperatorToken(token,level,parentContainerType,caseContextDepth);else if(token.containerType==="JoinClause")this.handleJoinClauseToken(token,level);else if(token.type===6){if(this.shouldRenderComment(token,effectiveCommentContext)){let commentLevel=this.getCommentBaseIndentLevel(level,parentContainerType);this.printCommentToken(token.text,commentLevel,parentContainerType)}}else if(token.type===10)this.handleSpaceToken(token,parentContainerType);else if(token.type===12){if(this.whenOneLine&&parentContainerType==="MergeWhenClause")return;let commentLevel=this.getCommentBaseIndentLevel(level,parentContainerType);this.handleCommentNewlineToken(token,commentLevel)}else if(token.containerType==="CommonTable"&&this.withClauseStyle==="cte-oneline"){this.handleCteOnelineToken(token,level);return}else if(this.shouldFormatContainerAsOneline(token,shouldIndentNested)){this.handleOnelineToken(token,level);return}else this.tryAppendInsertClauseTokenText(token.text,parentContainerType)||this.linePrinter.appendText(token.text);if(token.keywordTokens&&token.keywordTokens.length>0)for(let i=0;i<token.keywordTokens.length;i++){let keywordToken=token.keywordTokens[i];this.appendToken(keywordToken,level,token.containerType,nextCaseContextDepth,indentParentActive)}let innerLevel=level,increasedIndent=!1,shouldIncreaseIndent=this.indentIncrementContainers.has(token.containerType)||shouldIndentNested,delayIndentNewline=shouldIndentNested&&token.containerType==="ParenExpression",isAlterTableStatement=token.containerType==="AlterTableStatement",deferAlterTableIndent=!1;if(this.shouldAlignExplainStatementChild(parentContainerType,token.containerType))!this.isOnelineMode()&&current.text!==""&&this.linePrinter.appendNewline(level),innerLevel=level,increasedIndent=!1;else if(!this.isOnelineMode()&&shouldIncreaseIndent&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline"))if(delayIndentNewline)innerLevel=level+1,increasedIndent=!0;else if(current.text!=="")if(isAlterTableStatement)innerLevel=level+1,increasedIndent=!0,deferAlterTableIndent=!0;else{let targetIndentLevel=level+1;token.containerType==="SetClause"&&parentContainerType==="MergeUpdateAction"&&(targetIndentLevel=level+2),this.shouldAlignCreateTableSelect(token.containerType,parentContainerType)?(innerLevel=level,increasedIndent=!1,this.linePrinter.appendNewline(level)):(innerLevel=targetIndentLevel,increasedIndent=!0,this.linePrinter.appendNewline(innerLevel))}else token.containerType==="SetClause"&&(innerLevel=parentContainerType==="MergeUpdateAction"?level+2:level+1,increasedIndent=!0,current.level=innerLevel);let isMergeWhenClause=this.whenOneLine&&token.containerType==="MergeWhenClause",mergePredicateActive=isMergeWhenClause,alterTableTableRendered=!1,alterTableIndentInserted=!1;for(let i=leadingCommentCount;i<token.innerTokens.length;i++){let child=token.innerTokens[i],nextChild=token.innerTokens[i+1],previousEntry=this.findPreviousSignificantToken(token.innerTokens,i),previousChild=previousEntry?.token,priorChild=(previousEntry?this.findPreviousSignificantToken(token.innerTokens,previousEntry.index):void 0)?.token,childIsAction=this.isMergeActionContainer(child),nextIsAction=this.isMergeActionContainer(nextChild),inMergePredicate=mergePredicateActive&&!childIsAction;if(isAlterTableStatement){if(child.containerType==="QualifiedName")alterTableTableRendered=!0;else if(deferAlterTableIndent&&alterTableTableRendered&&!alterTableIndentInserted&&(this.isOnelineMode()||this.linePrinter.appendNewline(innerLevel),alterTableIndentInserted=!0,deferAlterTableIndent=!1,!this.isOnelineMode()&&child.type===10))continue}if(child.type===10){if(this.shouldConvertSpaceToClauseBreak(token.containerType,nextChild)){if(!this.isOnelineMode()){let clauseBreakIndent=this.getClauseBreakIndentLevel(token.containerType,innerLevel);this.linePrinter.appendNewline(clauseBreakIndent)}isMergeWhenClause&&nextIsAction&&(mergePredicateActive=!1);continue}this.handleSpaceToken(child,token.containerType,nextChild,previousChild,priorChild);continue}let childIndentParentActive=token.containerType==="ParenExpression"?shouldIndentNested:indentParentActive;inMergePredicate&&this.mergeWhenPredicateDepth++;let childCommentContext=child.containerType==="CommentBlock"?{position:"inline",isTopLevelContainer:containerIsTopLevel}:void 0;this.appendToken(child,innerLevel,token.containerType,nextCaseContextDepth,childIndentParentActive,childCommentContext),inMergePredicate&&this.mergeWhenPredicateDepth--,childIsAction&&isMergeWhenClause&&(mergePredicateActive=!1)}if(this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder(),token.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"){this.insideWithClause=!1,this.linePrinter.appendNewline(level);return}increasedIndent&&shouldIncreaseIndent&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&!delayIndentNewline&&this.linePrinter.appendNewline(level)}shouldAlignExplainStatementChild(parentType,childType){if(parentType!=="ExplainStatement")return!1;switch(childType){case"SimpleSelectQuery":case"InsertQuery":case"UpdateQuery":case"DeleteQuery":case"MergeQuery":return!0;default:return!1}}isCaseContext(containerType){switch(containerType){case"CaseExpression":case"CaseKeyValuePair":case"CaseThenValue":case"CaseElseValue":case"SwitchCaseArgument":return!0;default:return!1}}shouldSkipToken(token){return token.type===12?!1:(!token.innerTokens||token.innerTokens.length===0)&&token.text===""}applyKeywordCase(text){return this.keywordCase==="upper"?text.toUpperCase():this.keywordCase==="lower"?text.toLowerCase():text}handleKeywordToken(token,level,parentContainerType,caseContextDepth=0){let lower=token.text.toLowerCase();if(lower==="and"&&(this.andBreak!=="none"||this.whenOneLine&&parentContainerType==="MergeWhenClause")){this.handleAndOperatorToken(token,level,parentContainerType,caseContextDepth);return}else if(lower==="or"&&(this.orBreak!=="none"||this.whenOneLine&&parentContainerType==="MergeWhenClause")){this.handleOrOperatorToken(token,level,parentContainerType,caseContextDepth);return}let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}this.ensureSpaceBeforeKeyword(),this.linePrinter.appendText(text)}ensureSpaceBeforeKeyword(){let currentLine=this.linePrinter.getCurrentLine();currentLine.text===""||currentLine.text[currentLine.text.length-1]==="("||this.ensureTrailingSpace()}ensureTrailingSpace(){let currentLine=this.linePrinter.getCurrentLine();currentLine.text!==""&&(currentLine.text.endsWith(" ")||(currentLine.text+=" "),currentLine.text=currentLine.text.replace(/\s+$/," "))}tryAppendInsertClauseTokenText(text,parentContainerType){let currentLineText=this.linePrinter.getCurrentLine().text,result=this.onelineHelper.formatInsertClauseToken(text,parentContainerType,currentLineText,()=>this.ensureTrailingSpace());return result.handled?(result.text&&this.linePrinter.appendText(result.text),!0):!1}handleCommaToken(token,level,parentContainerType){let text=token.text,isWithinWithClause=parentContainerType==="WithClause",effectiveCommaBreak=this.onelineHelper.resolveCommaBreak(parentContainerType,this.commaBreak,this.cteCommaBreak,this.valuesCommaBreak);if(parentContainerType==="SetClause"&&(effectiveCommaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline")this.linePrinter.appendText(text);else if(this.withClauseStyle==="cte-oneline"&&isWithinWithClause)this.linePrinter.appendText(text),this.linePrinter.appendNewline(level);else if(effectiveCommaBreak==="before"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="before"&&(this.linePrinter.commaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||(this.linePrinter.appendNewline(level),this.newline===" "&&this.linePrinter.trimTrailingWhitespaceFromPreviousLine(),parentContainerType==="InsertClause"&&(this.linePrinter.getCurrentLine().level=level+1)),this.linePrinter.appendText(text),previousCommaBreak!=="before"&&(this.linePrinter.commaBreak=previousCommaBreak)}else if(effectiveCommaBreak==="after"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="after"&&(this.linePrinter.commaBreak="after"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),previousCommaBreak!=="after"&&(this.linePrinter.commaBreak=previousCommaBreak)}else if(effectiveCommaBreak==="none"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="none"&&(this.linePrinter.commaBreak="none"),this.linePrinter.appendText(text),this.onelineHelper.isInsertClauseOneline(parentContainerType)&&this.ensureTrailingSpace(),previousCommaBreak!=="none"&&(this.linePrinter.commaBreak=previousCommaBreak)}else this.linePrinter.appendText(text)}handleAndOperatorToken(token,level,parentContainerType,caseContextDepth=0){let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}if(this.whenOneLine&&(parentContainerType==="MergeWhenClause"||this.mergeWhenPredicateDepth>0)){this.linePrinter.appendText(text);return}this.andBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text)):this.andBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level)):this.linePrinter.appendText(text)}handleParenthesisToken(token,level,indentParentActive,parentContainerType){if(token.text==="("){if(this.linePrinter.appendText(token.text),(parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction")&&this.insertColumnsOneLine)return;this.isOnelineMode()||(this.shouldBreakAfterOpeningParen(parentContainerType)?this.linePrinter.appendNewline(level+1):indentParentActive&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&this.linePrinter.appendNewline(level));return}if(token.text===")"&&!this.isOnelineMode()){if(this.shouldBreakBeforeClosingParen(parentContainerType)){this.linePrinter.appendNewline(Math.max(level,0)),this.linePrinter.appendText(token.text);return}if(indentParentActive&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")){let closingLevel=Math.max(level-1,0);this.linePrinter.appendNewline(closingLevel)}}this.linePrinter.appendText(token.text)}handleOrOperatorToken(token,level,parentContainerType,caseContextDepth=0){let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}if(this.whenOneLine&&(parentContainerType==="MergeWhenClause"||this.mergeWhenPredicateDepth>0)){this.linePrinter.appendText(text);return}this.orBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text)):this.orBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level)):this.linePrinter.appendText(text)}shouldIndentNestedParentheses(token){return!this.indentNestedParentheses||token.containerType!=="ParenExpression"?!1:token.innerTokens.some(child=>this.containsParenExpression(child))}containsParenExpression(token){if(token.containerType==="ParenExpression")return!0;for(let child of token.innerTokens)if(this.containsParenExpression(child))return!0;return!1}handleJoinClauseToken(token,level){let text=this.applyKeywordCase(token.text);this.onelineHelper.shouldInsertJoinNewline(this.insideWithClause)&&this.linePrinter.appendNewline(level),this.linePrinter.appendText(text)}shouldFormatContainerAsOneline(token,shouldIndentNested){return this.onelineHelper.shouldFormatContainer(token,shouldIndentNested)}isInsertClauseOneline(parentContainerType){return this.onelineHelper.isInsertClauseOneline(parentContainerType)}handleSpaceToken(token,parentContainerType,nextToken,previousToken,priorToken){this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder();let currentLineText=this.linePrinter.getCurrentLine().text;if(!this.onelineHelper.shouldSkipInsertClauseSpace(parentContainerType,nextToken,currentLineText)){if(this.onelineHelper.shouldSkipCommentBlockSpace(parentContainerType,this.insideWithClause)){let currentLine=this.linePrinter.getCurrentLine();currentLine.text!==""&&!currentLine.text.endsWith(" ")&&this.linePrinter.appendText(" ");return}this.shouldSkipSpaceBeforeParenthesis(parentContainerType,nextToken,previousToken,priorToken)||this.linePrinter.appendText(token.text)}}findPreviousSignificantToken(tokens,index){for(let i=index-1;i>=0;i--){let candidate=tokens[i];if(!(candidate.type===10||candidate.type===12)&&!(candidate.type===6&&!this.rendersInlineComments()))return{token:candidate,index:i}}}shouldSkipSpaceBeforeParenthesis(parentContainerType,nextToken,previousToken,priorToken){return!nextToken||nextToken.type!==4||nextToken.text!=="("||!parentContainerType||!this.isCreateTableSpacingContext(parentContainerType)||!previousToken?!1:!!(this.isCreateTableNameToken(previousToken,parentContainerType)||this.isCreateTableConstraintKeyword(previousToken,parentContainerType)||priorToken&&this.isCreateTableConstraintKeyword(priorToken,parentContainerType)&&this.isIdentifierAttachedToConstraint(previousToken,priorToken,parentContainerType))}shouldAlignCreateTableSelect(containerType,parentContainerType){return containerType==="SimpleSelectQuery"&&parentContainerType==="CreateTableQuery"}isCreateTableSpacingContext(parentContainerType){switch(parentContainerType){case"CreateTableQuery":case"CreateTableDefinition":case"TableConstraintDefinition":case"ColumnConstraintDefinition":case"ReferenceDefinition":return!0;default:return!1}}isCreateTableNameToken(previousToken,parentContainerType){return parentContainerType!=="CreateTableQuery"?!1:previousToken.containerType==="QualifiedName"}isCreateTableConstraintKeyword(token,parentContainerType){if(token.type!==1)return!1;let text=token.text.toLowerCase();return parentContainerType==="ReferenceDefinition"?CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER.has(text):!!(CREATE_TABLE_SINGLE_PAREN_KEYWORDS.has(text)||CREATE_TABLE_MULTI_PAREN_KEYWORDS.has(text))}isIdentifierAttachedToConstraint(token,keywordToken,parentContainerType){if(!token)return!1;if(parentContainerType==="ReferenceDefinition")return token.containerType==="QualifiedName"&&CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER.has(keywordToken.text.toLowerCase());if(parentContainerType==="TableConstraintDefinition"||parentContainerType==="ColumnConstraintDefinition"){let normalized=keywordToken.text.toLowerCase();if(CREATE_TABLE_SINGLE_PAREN_KEYWORDS.has(normalized)||CREATE_TABLE_MULTI_PAREN_KEYWORDS.has(normalized))return token.containerType==="IdentifierString"}return!1}printCommentToken(text,level,parentContainerType){let trimmed=text.trim();if(trimmed&&!(this.commentStyle==="smart"&&parentContainerType==="CommentBlock"&&this.handleSmartCommentBlockToken(text,trimmed,level)))if(this.commentStyle==="smart"){let normalized=this.normalizeCommentForSmart(trimmed);if(normalized.lines.length>1||normalized.forceBlock){let blockText=this.buildBlockComment(normalized.lines,level);this.linePrinter.appendText(blockText)}else{let content=normalized.lines[0],lineText=content?`-- ${content}`:"--";if(parentContainerType==="CommentBlock")this.linePrinter.appendText(lineText),this.pendingLineCommentBreak=this.resolveCommentIndentLevel(level,parentContainerType);else{this.linePrinter.appendText(lineText);let effectiveLevel=this.resolveCommentIndentLevel(level,parentContainerType);this.linePrinter.appendNewline(effectiveLevel)}}}else{if(trimmed.startsWith("/*")&&trimmed.endsWith("*/"))if(/\r?\n/.test(trimmed)){let newlineReplacement=this.isOnelineMode()?" ":typeof this.newline=="string"?this.newline:`
23
23
  `,normalized=trimmed.replace(/\r?\n/g,newlineReplacement);this.linePrinter.appendText(normalized)}else this.linePrinter.appendText(trimmed);else this.linePrinter.appendText(trimmed);if(trimmed.startsWith("--"))if(parentContainerType==="CommentBlock")this.pendingLineCommentBreak=this.resolveCommentIndentLevel(level,parentContainerType);else{let effectiveLevel=this.resolveCommentIndentLevel(level,parentContainerType);this.linePrinter.appendNewline(effectiveLevel)}}}handleSmartCommentBlockToken(raw,trimmed,level){if(!this.smartCommentBlockBuilder){if(trimmed==="/*")return this.smartCommentBlockBuilder={lines:[],level,mode:"block"},!0;let lineContent=this.extractLineCommentContent(trimmed);return lineContent!==null?(this.smartCommentBlockBuilder={lines:[lineContent],level,mode:"line"},!0):!1}if(this.smartCommentBlockBuilder.mode==="block"){if(trimmed==="*/"){let{lines,level:blockLevel}=this.smartCommentBlockBuilder,blockText=this.buildBlockComment(lines,blockLevel);return this.linePrinter.appendText(blockText),this.pendingLineCommentBreak=blockLevel,this.smartCommentBlockBuilder=null,!0}return this.smartCommentBlockBuilder.lines.push(this.normalizeSmartBlockLine(raw)),!0}let content=this.extractLineCommentContent(trimmed);return content!==null?(this.smartCommentBlockBuilder.lines.push(content),!0):(this.flushSmartCommentBlockBuilder(),!1)}handleCommentBlockContainer(token,level,context){if(this.commentStyle!=="smart"){let rawLines=this.extractRawCommentBlockLines(token);if(rawLines.length>0){let normalizedBlocks=rawLines.map(line=>`/* ${line} */`).join(" "),hasTrailingSpace=token.innerTokens?.some(child=>child.type===10&&child.text.includes(" "));this.linePrinter.appendText(hasTrailingSpace?`${normalizedBlocks} `:normalizedBlocks);return}for(let child of token.innerTokens){let childContext={position:context.position,isTopLevelContainer:context.isTopLevelContainer,forceRender:!0};this.appendToken(child,level,token.containerType,0,!1,childContext)}return}let lines=this.collectCommentBlockLines(token);if(lines.length===0&&!this.smartCommentBlockBuilder){this.smartCommentBlockBuilder={lines:[""],level,mode:"line"};return}!this.smartCommentBlockBuilder||this.smartCommentBlockBuilder.mode!=="line"?this.smartCommentBlockBuilder={lines:[...lines],level,mode:"line"}:this.smartCommentBlockBuilder.lines.push(...lines)}normalizeSmartBlockLine(raw){let line=raw.replace(/\s+$/g,"");return line?(line.startsWith(" ")&&(line=line.slice(2)),line.startsWith("* ")?line.slice(2):line==="*"?"":line.startsWith("*")?line.slice(1):line):""}extractLineCommentContent(trimmed){return trimmed.startsWith("--")?trimmed.slice(2).trimStart():trimmed.startsWith("/*")&&trimmed.endsWith("*/")?trimmed.slice(2,-2).trim():null}flushSmartCommentBlockBuilder(){if(!this.smartCommentBlockBuilder)return;let{lines,level,mode}=this.smartCommentBlockBuilder;if(mode==="line"){if(lines.filter(line=>line.trim()!=="").length>1){let blockText=this.buildBlockComment(lines,level);this.linePrinter.appendText(blockText)}else{let content=lines[0]??"",lineText=content?`-- ${content}`:"--";this.linePrinter.appendText(lineText)}this.isOnelineMode()||this.linePrinter.appendNewline(level),this.pendingLineCommentBreak=null}this.smartCommentBlockBuilder=null}collectCommentBlockLines(token){let lines=[],collectingBlock=!1;for(let child of token.innerTokens??[])if(child.type===6){let trimmed=child.text.trim();if(trimmed==="/*"){collectingBlock=!0;continue}if(trimmed==="*/"){collectingBlock=!1;continue}if(collectingBlock){lines.push(this.normalizeSmartBlockLine(child.text));continue}let content=this.extractLineCommentContent(trimmed);content!==null&&lines.push(content)}return lines}extractRawCommentBlockLines(token){let lines=[],collectingBlock=!1;for(let child of token.innerTokens??[])if(child.type===6){let trimmed=child.text.trim();if(trimmed==="/*"){collectingBlock=!0;continue}if(trimmed==="*/"){collectingBlock=!1;continue}if(collectingBlock){trimmed.length>0&&lines.push(trimmed);continue}}return lines}normalizeCommentForSmart(text){let trimmed=text.trim(),source=trimmed,forceBlock=!1;if(trimmed.startsWith("--"))source=trimmed.slice(2);else if(trimmed.startsWith("/*")&&trimmed.endsWith("*/")){let inner=trimmed.slice(2,-2);inner.replace(/\r?\n/g,`
24
24
  `).includes(`
25
25
  `)?(forceBlock=!0,source=inner):(source=inner,source.trim()||(source=trimmed))}let rawSegments=this.escapeCommentDelimiters(source).replace(/\r?\n/g,`
26
26
  `).split(`
27
27
  `),processedLines=[],processedRaw=[];for(let segment of rawSegments){let rawTrimmed=segment.trim(),sanitized=this.sanitizeCommentLine(segment);sanitized.length>0&&(processedLines.push(sanitized),processedRaw.push(rawTrimmed))}let lines=processedLines;if(lines.length===0&&(lines=[""]),!forceBlock&&lines.length===1&&!lines[0]&&trimmed.startsWith("/*")&&trimmed.endsWith("*/")){let escapedFull=this.escapeCommentDelimiters(trimmed);lines=[this.sanitizeCommentLine(escapedFull)]}return!forceBlock&&lines.length>1&&(forceBlock=!0),lines=lines.map((line,index)=>{if(/^[-=_+*#]+$/.test(line)){let normalizedRaw=(processedRaw[index]??line).replace(/\s+/g,"");if(normalizedRaw.length>=line.length)return normalizedRaw}return line}),{lines,forceBlock}}buildBlockComment(lines,level){if(lines.length<=1){let content=lines[0]??"";return content?`/* ${content} */`:"/* */"}let newline=this.newline===" "?`
28
- `:this.newline,currentLevel=this.linePrinter.getCurrentLine()?.level??level,baseIndent=this.getIndentString(currentLevel),innerIndent=baseIndent+" ",body=lines.map(line=>`${innerIndent}${line}`).join(newline),closing=`${baseIndent}*/`;return`/*${newline}${body}${newline}${closing}`}getIndentString(level){return level<=0?"":this.indentSize<=0?" ".repeat(level):(typeof this.indentChar=="string"?this.indentChar:"").repeat(this.indentSize*level)}sanitizeCommentLine(content){let sanitized=content;return sanitized=sanitized.replace(/\u2028|\u2029/g," "),sanitized=sanitized.replace(/\s+/g," ").trim(),sanitized}escapeCommentDelimiters(content){return content.replace(/\/\*/g,"\\/\\*").replace(/\*\//g,"*\\/")}getCommentBaseIndentLevel(level,parentContainerType){if(!parentContainerType)return level;let clauseAlignedLevel=this.getClauseBreakIndentLevel(parentContainerType,level);return Math.max(level,clauseAlignedLevel)}resolveCommentIndentLevel(level,parentContainerType){let baseLevel=this.getCommentBaseIndentLevel(level,parentContainerType),currentLevel=this.linePrinter.getCurrentLine().level??baseLevel;return Math.max(baseLevel,currentLevel)}handleCommentNewlineToken(token,level){if(!this.smartCommentBlockBuilder){if(this.pendingLineCommentBreak!==null){this.linePrinter.appendNewline(this.pendingLineCommentBreak),this.pendingLineCommentBreak=null;return}this.shouldSkipCommentNewline()||this.isOnelineMode()||this.linePrinter.appendNewline(level)}}shouldSkipCommentNewline(){return this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.withClauseStyle==="cte-oneline"}shouldAddNewlineBeforeLeadingComments(parentType){return parentType?parentType==="TupleExpression"?!0:parentType==="InsertClause"||parentType==="MergeInsertAction"?!this.insertColumnsOneLine:parentType==="SetClause"||parentType==="SelectClause":!1}getLeadingCommentIndentLevel(parentType,currentLevel){return parentType==="TupleExpression"||parentType==="InsertClause"||parentType==="MergeInsertAction"||parentType==="SelectClause"||parentType==="SetClause"?currentLevel+1:currentLevel}isOnelineMode(){return this.newline===" "}handleCteOnelineToken(token,level){let onelineResult=this.createCteOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);cleanedResult=cleanedResult.replace(/\(\s+/g,"(").replace(/\s+\)/g," )"),this.linePrinter.appendText(cleanedResult.trim())}createCteOnelinePrinter(){return new _SqlPrinter({indentChar:"",indentSize:0,newline:" ",commaBreak:this.commaBreak,cteCommaBreak:this.cteCommaBreak,valuesCommaBreak:this.valuesCommaBreak,andBreak:this.andBreak,orBreak:this.orBreak,keywordCase:this.keywordCase,exportComment:"none",withClauseStyle:"standard",indentNestedParentheses:!1,insertColumnsOneLine:this.insertColumnsOneLine})}handleOnelineToken(token,level){let onelineResult=this.createOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);this.linePrinter.appendText(cleanedResult)}getClauseBreakIndentLevel(parentType,level){if(!parentType)return level;switch(parentType){case"MergeWhenClause":return level+1;case"MergeUpdateAction":case"MergeDeleteAction":case"MergeInsertAction":return level+1;default:return level}}isMergeActionContainer(token){if(!token)return!1;switch(token.containerType){case"MergeUpdateAction":case"MergeDeleteAction":case"MergeInsertAction":case"MergeDoNothingAction":return!0;default:return!1}}shouldBreakAfterOpeningParen(parentType){return parentType&&(parentType==="InsertClause"||parentType==="MergeInsertAction")?!this.isInsertClauseOneline(parentType):!1}shouldBreakBeforeClosingParen(parentType){return parentType&&(parentType==="InsertClause"||parentType==="MergeInsertAction")?!this.isInsertClauseOneline(parentType):!1}shouldConvertSpaceToClauseBreak(parentType,nextToken){if(!parentType||!nextToken)return!1;let nextKeyword=nextToken.type===1?nextToken.text.toLowerCase():null,nextContainer=nextToken.containerType;return!!(parentType==="MergeQuery"&&(nextKeyword==="using"||nextContainer==="MergeWhenClause")||parentType==="MergeWhenClause"&&(nextContainer==="MergeUpdateAction"||nextContainer==="MergeDeleteAction"||nextContainer==="MergeInsertAction"||nextContainer==="MergeDoNothingAction")||parentType==="UpdateQuery"&&(nextKeyword==="set"||nextKeyword==="from"||nextKeyword==="where"||nextKeyword==="returning")||parentType==="InsertQuery"&&(nextKeyword==="returning"||nextKeyword&&(nextKeyword.startsWith("select")||nextKeyword.startsWith("values"))||nextContainer==="ValuesQuery"||nextContainer==="SimpleSelectQuery"||nextContainer==="InsertClause")||parentType==="DeleteQuery"&&(nextKeyword==="using"||nextKeyword==="where"||nextKeyword==="returning")||(parentType==="MergeUpdateAction"||parentType==="MergeDeleteAction")&&nextKeyword==="where"||parentType==="MergeInsertAction"&&nextKeyword&&(nextKeyword.startsWith("values")||nextKeyword==="default values"))}createOnelinePrinter(){return new _SqlPrinter({indentChar:"",indentSize:0,newline:" ",commaBreak:"none",cteCommaBreak:this.cteCommaBreak,valuesCommaBreak:"none",andBreak:"none",orBreak:"none",keywordCase:this.keywordCase,exportComment:this.commentExportMode,commentStyle:this.commentStyle,withClauseStyle:"standard",parenthesesOneLine:!1,betweenOneLine:!1,valuesOneLine:!1,joinOneLine:!1,caseOneLine:!1,subqueryOneLine:!1,indentNestedParentheses:!1,insertColumnsOneLine:this.insertColumnsOneLine})}cleanDuplicateSpaces(text){return text.replace(/\s{2,}/g," ")}};var VALID_PRESETS=["mysql","postgres","sqlserver","sqlite"],SqlFormatter=class{constructor(options={}){let presetConfig=options.preset?PRESETS[options.preset]:void 0;if(options.preset&&!presetConfig)throw new Error(`Invalid preset: ${options.preset}`);let resolvedIdentifierEscape=resolveIdentifierEscapeOption(options.identifierEscape??presetConfig?.identifierEscape),parserOptions={...presetConfig,identifierEscape:resolvedIdentifierEscape??presetConfig?.identifierEscape,parameterSymbol:options.parameterSymbol??presetConfig?.parameterSymbol,parameterStyle:options.parameterStyle??presetConfig?.parameterStyle,castStyle:options.castStyle??presetConfig?.castStyle,joinConditionOrderByDeclaration:options.joinConditionOrderByDeclaration},constraintStyle=options.constraintStyle??presetConfig?.constraintStyle??"postgres",parserConfig={...parserOptions,constraintStyle};this.parser=new SqlPrintTokenParser({...parserConfig});let normalizedExportComment=options.exportComment===!0?"full":options.exportComment===!1?"none":options.exportComment,printerOptions={...options,exportComment:normalizedExportComment,parenthesesOneLine:options.parenthesesOneLine,betweenOneLine:options.betweenOneLine,valuesOneLine:options.valuesOneLine,joinOneLine:options.joinOneLine,caseOneLine:options.caseOneLine,subqueryOneLine:options.subqueryOneLine,indentNestedParentheses:options.indentNestedParentheses};this.printer=new SqlPrinter(printerOptions)}format(sql){let{token,params}=this.parser.parse(sql);return{formattedSql:this.printer.print(token),params}}};var Formatter=class{constructor(){this.sqlFormatter=new SqlFormatter({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(arg,config=null){return config&&(this.sqlFormatter=new SqlFormatter(config)),this.sqlFormatter.format(arg).formattedSql}formatWithParameters(arg,config=null){config&&(this.sqlFormatter=new SqlFormatter(config));let result=this.sqlFormatter.format(arg);return{sql:result.formattedSql,params:result.params}}visit(arg){return this.format(arg)}};var CTEBuilder=class{constructor(){this.sourceCollector=new TableSourceCollector(!0),this.cteCollector=new CTECollector,this.formatter=new Formatter}build(commonTables){if(commonTables.length===0)return new WithClause(!1,commonTables);let resolvedTables=this.resolveDuplicateNames(commonTables),{tableMap,recursiveCTEs,dependencies}=this.buildDependencyGraph(resolvedTables),sortedTables=this.sortCommonTables(resolvedTables,tableMap,recursiveCTEs,dependencies);return new WithClause(recursiveCTEs.size>0,sortedTables)}resolveDuplicateNames(commonTables){let ctesByName=new Map;for(let table of commonTables){let tableName=table.aliasExpression.table.name;ctesByName.has(tableName)||ctesByName.set(tableName,[]),ctesByName.get(tableName).push(table)}let resolvedTables=[];for(let[name,tables]of Array.from(ctesByName.entries())){if(tables.length===1){resolvedTables.push(tables[0]);continue}let definitions=tables.map(table=>this.formatter.format(table.query));if(new Set(definitions).size===1)resolvedTables.push(tables[0]);else throw new Error(`CTE name conflict detected: '${name}' has multiple different definitions`)}return resolvedTables}buildDependencyGraph(tables){let tableMap=new Map;for(let table of tables)tableMap.set(table.aliasExpression.table.name,table);let recursiveCTEs=new Set,dependencies=new Map,referencedBy=new Map;for(let table of tables){let tableName=table.aliasExpression.table.name,referencedTables=this.sourceCollector.collect(table.query);for(let referencedTable of referencedTables)if(referencedTable.table.name===tableName){recursiveCTEs.add(tableName);break}dependencies.has(tableName)||dependencies.set(tableName,new Set);let referencedCTEs=this.cteCollector.collect(table.query);for(let referencedCTE of referencedCTEs){let referencedName=referencedCTE.aliasExpression.table.name;tableMap.has(referencedName)&&(dependencies.get(tableName).add(referencedName),referencedBy.has(referencedName)||referencedBy.set(referencedName,new Set),referencedBy.get(referencedName).add(tableName))}}return{tableMap,recursiveCTEs,dependencies}}sortCommonTables(tables,tableMap,recursiveCTEs,dependencies){let recursiveResult=[],nonRecursiveResult=[],visited=new Set,visiting=new Set,visit=tableName=>{if(visited.has(tableName))return;if(visiting.has(tableName))throw new Error(`Circular reference detected in CTE: ${tableName}`);visiting.add(tableName);let deps=dependencies.get(tableName)||new Set;for(let dep of Array.from(deps))visit(dep);visiting.delete(tableName),visited.add(tableName),recursiveCTEs.has(tableName)?recursiveResult.push(tableMap.get(tableName)):nonRecursiveResult.push(tableMap.get(tableName))};for(let table of tables){let tableName=table.aliasExpression.table.name;visited.has(tableName)||visit(tableName)}return[...recursiveResult,...nonRecursiveResult]}};var CTEInjector=class{constructor(){this.nameConflictResolver=new CTEBuilder,this.cteCollector=new CTECollector}inject(query,commonTables){if(commonTables.length===0)return query;commonTables.push(...this.cteCollector.collect(query));let resolvedWithCaluse=this.nameConflictResolver.build(commonTables);if(query instanceof SimpleSelectQuery)return this.injectIntoSimpleQuery(query,resolvedWithCaluse);if(query instanceof BinarySelectQuery)return this.injectIntoBinaryQuery(query,resolvedWithCaluse);throw new Error("Unsupported query type")}injectIntoSimpleQuery(query,withClause){if(query.withClause)throw new Error("The query already has a WITH clause. Please remove it before injecting new CTEs.");return query.withClause=withClause,query}injectIntoBinaryQuery(query,withClause){if(query.left instanceof SimpleSelectQuery)return this.injectIntoSimpleQuery(query.left,withClause),query;if(query.left instanceof BinarySelectQuery)return this.injectIntoBinaryQuery(query.left,withClause),query;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var CTENormalizer=class{constructor(){}static normalize(query){let allCommonTables=new CTECollector().collect(query);return allCommonTables.length===0?query:(new CTEDisabler().execute(query),new CTEInjector().inject(query,allCommonTables))}};var DuplicateDetectionMode=(DuplicateDetectionMode2=>(DuplicateDetectionMode2.ColumnNameOnly="columnNameOnly",DuplicateDetectionMode2.FullName="fullName",DuplicateDetectionMode2))(DuplicateDetectionMode||{}),SelectableColumnCollector=class _SelectableColumnCollector{constructor(tableColumnResolver,includeWildCard=!1,duplicateDetection="columnNameOnly",options){this.selectValues=[];this.visitedNodes=new Set;this.uniqueKeys=new Set;this.isRootVisit=!0;this.tableColumnResolver=null;this.commonTables=[];this.initializeProperties(tableColumnResolver,includeWildCard,duplicateDetection,options),this.initializeHandlers()}initializeProperties(tableColumnResolver,includeWildCard,duplicateDetection,options){this.tableColumnResolver=tableColumnResolver??null,this.includeWildCard=includeWildCard,this.commonTableCollector=new CTECollector,this.commonTables=[],this.duplicateDetection=duplicateDetection,this.options=options||{}}initializeHandlers(){this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.initializeClauseHandlers(),this.initializeValueComponentHandlers()}initializeClauseHandlers(){this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.offsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr))}initializeValueComponentHandlers(){this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}getValues(){return this.selectValues}collect(arg){if(!arg)throw new Error("Input argument cannot be null or undefined");this.visit(arg);let items=this.getValues();return this.reset(),items}reset(){this.selectValues=[],this.visitedNodes.clear(),this.uniqueKeys.clear(),this.commonTables=[]}addSelectValueAsUnique(name,value){let key=this.generateUniqueKey(name,value);this.uniqueKeys.has(key)||(this.uniqueKeys.add(key),this.selectValues.push({name,value}))}generateUniqueKey(name,value){if(this.duplicateDetection==="columnNameOnly")return this.normalizeColumnName(name);{let tableName="";value&&typeof value.getNamespace=="function"&&(tableName=value.getNamespace()||"");let fullName=tableName?tableName+"."+name:name;return this.normalizeColumnName(fullName)}}normalizeColumnName(name){if(typeof name!="string")throw new Error("Column name must be a string");return this.options.ignoreCaseAndUnderscore?name.toLowerCase().replace(/_/g,""):name}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}if(!(arg instanceof SimpleSelectQuery||arg instanceof BinarySelectQuery))throw new Error("Root visit requires a SimpleSelectQuery or BinarySelectQuery.");this.reset(),this.isRootVisit=!1,this.commonTables=this.commonTableCollector.collect(arg);try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(!this.visitedNodes.has(arg)){this.visitedNodes.add(arg);try{let handler=this.handlers.get(arg.getKind());handler&&handler(arg)}catch(error){let errorMessage=error instanceof Error?error.message:String(error);throw new Error(`Error processing SQL component of type ${arg.getKind().toString()}: ${errorMessage}`)}}}visitSimpleSelectQuery(query){if(query.selectClause&&query.selectClause.accept(this),query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.orderByClause&&query.orderByClause.accept(this),query.limitClause&&query.limitClause.accept(this),query.offsetClause&&query.offsetClause.accept(this),query.fetchClause&&query.fetchClause.accept(this),query.forClause&&query.forClause.accept(this)}visitBinarySelectQuery(query){query.left instanceof SimpleSelectQuery?this.visitSimpleSelectQuery(query.left):query.left instanceof BinarySelectQuery&&this.visitBinarySelectQuery(query.left),query.right instanceof SimpleSelectQuery?this.visitSimpleSelectQuery(query.right):query.right instanceof BinarySelectQuery&&this.visitBinarySelectQuery(query.right)}visitSelectClause(clause){for(let item of clause.items)if(item.identifier)this.addSelectValueAsUnique(item.identifier.name,item.value);else if(item.value instanceof ColumnReference){let columnName=item.value.column.name;columnName!=="*"?this.addSelectValueAsUnique(columnName,item.value):this.includeWildCard&&this.addSelectValueAsUnique(columnName,item.value)}else item.value.accept(this)}visitFromClause(clause){let sourceValues=new SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(clause);for(let item of sourceValues)this.addSelectValueAsUnique(item.name,item.value);if(this.options.upstream&&this.collectUpstreamColumns(clause),clause.joins)for(let join of clause.joins)join.condition&&join.condition.accept(this)}visitWhereClause(clause){clause.condition&&clause.condition.accept(this)}visitGroupByClause(clause){if(clause.grouping)for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition&&clause.condition.accept(this)}visitOrderByClause(clause){if(clause.order)for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitWindowFrameExpression(expr){expr.partition&&expr.partition.accept(this),expr.order&&expr.order.accept(this),expr.frameSpec&&expr.frameSpec.accept(this)}visitLimitClause(clause){clause.value&&clause.value.accept(this)}offsetClause(clause){clause.value&&clause.value.accept(this)}visitFetchClause(clause){clause.expression&&clause.expression.accept(this)}visitJoinOnClause(joinOnClause){joinOnClause.condition&&joinOnClause.condition.accept(this)}visitJoinUsingClause(joinUsingClause){joinUsingClause.condition&&joinUsingClause.condition.accept(this)}visitColumnReference(columnRef){if(columnRef.column.name!=="*")this.addSelectValueAsUnique(columnRef.column.name,columnRef);else if(this.includeWildCard)this.addSelectValueAsUnique(columnRef.column.name,columnRef);else return}visitBinaryExpression(expr){expr.left&&expr.left.accept(this),expr.right&&expr.right.accept(this)}visitUnaryExpression(expr){expr.expression&&expr.expression.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this),func.withinGroup&&func.withinGroup.accept(this),func.internalOrderBy&&func.internalOrderBy.accept(this)}visitInlineQuery(inlineQuery){inlineQuery.selectQuery&&this.visitNode(inlineQuery.selectQuery)}visitParenExpression(expr){expr.expression&&expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase&&expr.switchCase.accept(this)}visitCastExpression(expr){expr.input&&expr.input.accept(this)}visitBetweenExpression(expr){expr.expression&&expr.expression.accept(this),expr.lower&&expr.lower.accept(this),expr.upper&&expr.upper.accept(this)}visitArrayExpression(expr){expr.expression&&expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitArraySliceExpression(expr){expr.array&&expr.array.accept(this),expr.startIndex&&expr.startIndex.accept(this),expr.endIndex&&expr.endIndex.accept(this)}visitArrayIndexExpression(expr){expr.array&&expr.array.accept(this),expr.index&&expr.index.accept(this)}visitValueList(expr){if(expr.values&&Array.isArray(expr.values))for(let value of expr.values)value&&value.accept(this)}visitPartitionByClause(clause){clause.value.accept(this)}collectUpstreamColumns(clause){if(this.collectAllAvailableCTEColumns(),this.collectUpstreamColumnsFromSource(clause.source),clause.joins)for(let join of clause.joins)this.collectUpstreamColumnsFromSource(join.source)}collectUpstreamColumnsFromSource(source){if(source.datasource instanceof TableSource){let cteTable=this.findCTEByName(source.datasource.table.name);cteTable?this.collectUpstreamColumnsFromCTE(cteTable):this.collectUpstreamColumnsFromTable(source.datasource)}else source.datasource instanceof SubQuerySource?this.collectUpstreamColumnsFromSubquery(source.datasource):source.datasource instanceof ParenSource&&this.collectUpstreamColumnsFromSource(new SourceExpression(source.datasource.source,null))}collectUpstreamColumnsFromTable(tableSource){if(this.tableColumnResolver){let tableName=tableSource.table.name,columns=this.tableColumnResolver(tableName);for(let columnName of columns){let columnRef=new ColumnReference(tableSource.table.name,columnName);this.addSelectValueAsUnique(columnName,columnRef)}}}collectUpstreamColumnsFromSubquery(subquerySource){if(subquerySource.query instanceof SimpleSelectQuery){let subqueryColumns=new _SelectableColumnCollector(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!0}).collect(subquerySource.query);for(let item of subqueryColumns)this.addSelectValueAsUnique(item.name,item.value)}}collectUpstreamColumnsFromCTE(cteTable){if(cteTable.query instanceof SimpleSelectQuery){let cteColumns=new _SelectableColumnCollector(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!1}).collect(cteTable.query);for(let item of cteColumns)item.name!=="*"&&this.addSelectValueAsUnique(item.name,item.value)}}collectAllAvailableCTEColumns(){for(let cte of this.commonTables)this.collectUpstreamColumnsFromCTE(cte)}findCTEByName(name){return this.commonTables.find(cte=>cte.getSourceAliasName()===name)||null}};var SourceParser=class _SourceParser{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The source component is complete but there are additional tokens.`);return result.value}static parseTableSourceFromLexemes(lexemes,index){let fullNameResult=FullNameParser.parseFromLexeme(lexemes,index);return this.parseTableSource(fullNameResult)}static parseFromLexeme(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&4)return this.parseParenSource(lexemes,idx);let fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx);return fullNameResult.lastTokenType&2048?_SourceParser.parseFunctionSource(lexemes,fullNameResult):_SourceParser.parseTableSource(fullNameResult)}static parseTableSource(fullNameResult){let{namespaces,name,newIndex}=fullNameResult,value=new TableSource(namespaces,name.name);return name.positionedComments&&name.positionedComments.length>0?value.positionedComments=name.positionedComments:name.comments&&name.comments.length>0&&(value.comments=name.comments),{value,newIndex}}static parseFunctionSource(lexemes,fullNameResult){let idx=fullNameResult.newIndex,{namespaces,name}=fullNameResult,argument=ValueParser.parseArgument(4,8,lexemes,idx);idx=argument.newIndex;let functionName=name.name;return{value:new FunctionSource({namespaces,name:functionName},argument.value),newIndex:idx}}static parseParenSource(lexemes,index){let idx=index,openParenToken=lexemes[idx];if(idx++,idx>=lexemes.length)throw new Error(`Syntax error: Unexpected end of input at position ${idx}. Expected a subquery or nested expression after opening parenthesis.`);let keyword=lexemes[idx].value;if(keyword==="select"||keyword==="values"||keyword==="with"){let result=this.parseSubQuerySource(lexemes,idx,openParenToken);if(idx=result.newIndex,idx<lexemes.length&&lexemes[idx].type==8)idx++;else throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:result.value,newIndex:idx}}else if(lexemes[idx].type==4){let result=this.parseParenSource(lexemes,idx);if(idx=result.newIndex,idx<lexemes.length&&lexemes[idx].type==8)idx++;else throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:result.value,newIndex:idx}}throw new Error(`Syntax error at position ${idx}: Expected 'SELECT' keyword, 'VALUES' keyword, or opening parenthesis '(' but found "${lexemes[idx].value}".`)}static parseSubQuerySource(lexemes,index,openParenToken){let idx=index,{value:selectQuery,newIndex}=SelectQueryParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,openParenToken&&openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let afterComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){let beforeComments=afterComments.map(pc=>({position:"before",comments:pc.comments}));selectQuery.positionedComments?selectQuery.positionedComments=[...beforeComments,...selectQuery.positionedComments]:selectQuery.positionedComments=beforeComments,selectQuery.comments&&(selectQuery.comments=null)}}return{value:new SubQuerySource(selectQuery),newIndex:idx}}};var DuplicateCTEError=class extends Error{constructor(cteName){super(`CTE '${cteName}' already exists in the query`);this.cteName=cteName;this.name="DuplicateCTEError"}},InvalidCTENameError=class extends Error{constructor(cteName,reason){super(`Invalid CTE name '${cteName}': ${reason}`);this.cteName=cteName;this.name="InvalidCTENameError"}},CTENotFoundError=class extends Error{constructor(cteName){super(`CTE '${cteName}' not found in the query`);this.cteName=cteName;this.name="CTENotFoundError"}};var UpstreamSelectQueryFinder=class{constructor(tableColumnResolver,options){this.options=options||{},this.tableColumnResolver=tableColumnResolver,this.columnCollector=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0})}find(query,columnNames){let namesArray=typeof columnNames=="string"?[columnNames]:columnNames,ctes=new CTECollector().collect(query),cteMap=new Map;for(let cte of ctes)cteMap.set(cte.getSourceAliasName(),cte);return this.findUpstream(query,namesArray,cteMap)}handleTableSource(src,columnNames,cteMap){let cte=cteMap.get(src.table.name);if(cte){let nextCteMap=new Map(cteMap);nextCteMap.delete(src.table.name);let result=this.findUpstream(cte.query,columnNames,nextCteMap);return result.length===0?null:result}return null}handleSubQuerySource(src,columnNames,cteMap){let result=this.findUpstream(src.query,columnNames,cteMap);return result.length===0?null:result}processFromClauseBranches(fromClause,columnNames,cteMap){let sources=fromClause.getSources();if(sources.length===0)return null;let allBranchResults=[],allBranchesOk=!0,validBranchCount=0;for(let sourceExpr of sources){let src=sourceExpr.datasource,branchResult=null;if(src instanceof TableSource)branchResult=this.handleTableSource(src,columnNames,cteMap),validBranchCount++;else if(src instanceof SubQuerySource)branchResult=this.handleSubQuerySource(src,columnNames,cteMap),validBranchCount++;else{if(src instanceof ValuesQuery)continue;allBranchesOk=!1;break}if(branchResult===null){allBranchesOk=!1;break}allBranchResults.push(branchResult)}return allBranchesOk&&allBranchResults.length===validBranchCount?allBranchResults.flat():null}findUpstream(query,columnNames,cteMap){if(query instanceof SimpleSelectQuery){let fromClause=query.fromClause;if(fromClause){let branchResult=this.processFromClauseBranches(fromClause,columnNames,cteMap);if(branchResult&&branchResult.length>0)return branchResult}let columns=this.columnCollector.collect(query).map(col=>col.name),cteColumns=this.collectCTEColumns(query,cteMap),allColumns=[...columns,...cteColumns],normalize=s=>this.options.ignoreCaseAndUnderscore?s.toLowerCase().replace(/_/g,""):s;return columnNames.every(name=>allColumns.some(col=>normalize(col)===normalize(name)))?[query]:[]}else if(query instanceof BinarySelectQuery){let left=this.findUpstream(query.left,columnNames,cteMap),right=this.findUpstream(query.right,columnNames,cteMap);return[...left,...right]}return[]}collectCTEColumns(query,cteMap){let cteColumns=[];if(query.withClause)for(let cte of query.withClause.tables){let columns=this.collectColumnsFromSelectQuery(cte.query);cteColumns.push(...columns)}return cteColumns}collectColumnsFromSelectQuery(query){if(query instanceof SimpleSelectQuery)try{return this.columnCollector.collect(query).map(col=>col.name)}catch(error){return console.warn("Failed to collect columns from SimpleSelectQuery:",error),[]}else if(query instanceof BinarySelectQuery)return this.collectColumnsFromSelectQuery(query.left);return[]}};var SourceAliasExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(idx<lexemes.length&&(lexemes[idx].type&64||lexemes[idx].type&2048)){let aliasToken=lexemes[idx],table=aliasToken.value;if(idx++,idx<lexemes.length&&lexemes[idx].type&4){let columns=[];for(idx++;idx<lexemes.length&&lexemes[idx].type&64&&(columns.push(lexemes[idx].value),idx++,idx<lexemes.length&&lexemes[idx].type&16);)idx++;if(lexemes[idx].type&8)idx++;else throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis ')' for column alias list. Each opening parenthesis must have a matching closing parenthesis.`);if(columns.length===0)throw new Error(`Syntax error at position ${index}: No column aliases found. Column alias declarations must contain at least one column name.`);let sourceAlias2=new SourceAliasExpression(table,columns);return aliasToken.positionedComments&&aliasToken.positionedComments.length>0&&(sourceAlias2.positionedComments=aliasToken.positionedComments),{value:sourceAlias2,newIndex:idx}}let sourceAlias=new SourceAliasExpression(table,null);return aliasToken.positionedComments&&aliasToken.positionedComments.length>0&&(sourceAlias.positionedComments=aliasToken.positionedComments),{value:sourceAlias,newIndex:idx}}throw new Error(`Syntax error at position ${index}: Expected an identifier for table alias but found "${lexemes[index]?.value||"end of input"}".`)}};var SourceExpressionParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The source expression is complete but there are additional tokens.`);return result.value}static parseTableSourceFromLexemes(lexemes,index){let result=SourceParser.parseTableSourceFromLexemes(lexemes,index);return{value:new SourceExpression(result.value,null),newIndex:result.newIndex}}static parseFromLexeme(lexemes,index){let idx=index,sourceResult=SourceParser.parseFromLexeme(lexemes,idx);if(idx=sourceResult.newIndex,idx<lexemes.length){if(lexemes[idx].value==="as"){idx++;let aliasResult=SourceAliasExpressionParser.parseFromLexeme(lexemes,idx);return idx=aliasResult.newIndex,{value:new SourceExpression(sourceResult.value,aliasResult.value),newIndex:idx}}if(idx<lexemes.length&&this.isTokenTypeAliasCandidate(lexemes[idx].type)){let aliasResult=SourceAliasExpressionParser.parseFromLexeme(lexemes,idx);return idx=aliasResult.newIndex,{value:new SourceExpression(sourceResult.value,aliasResult.value),newIndex:idx}}}return{value:new SourceExpression(sourceResult.value,null),newIndex:idx}}static isTokenTypeAliasCandidate(type){return(type&64)!==0||(type&2048)!==0}};var ParameterHelper=class{static set(query,name,value){let params=ParameterCollector.collect(query),found=!1;for(let p of params)p.name.value===name&&(p.value=value,found=!0);if(!found)throw new Error(`Parameter '${name}' not found in query.`)}};var ValuesQuery=class extends SqlComponent{constructor(tuples,columnAliases=null){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.tuples=tuples,this.columnAliases=columnAliases}static{this.kind=Symbol("ValuesQuery")}toSimpleQuery(){return QueryBuilder.buildSimpleQuery(this)}toInsertQuery(options){return this.toSimpleQuery().toInsertQuery(options)}toUpdateQuery(options){return this.toSimpleQuery().toUpdateQuery(options)}toDeleteQuery(options){return this.toSimpleQuery().toDeleteQuery(options)}toMergeQuery(options){return this.toSimpleQuery().toMergeQuery(options)}setParameter(name,value){return ParameterHelper.set(this,name,value),this}};var BinarySelectQuery=class _BinarySelectQuery extends SqlComponent{constructor(left,operator,right){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.left=left,this.operator=new RawString(operator),this.right=right}static{this.kind=Symbol("BinarySelectQuery")}union(query){return this.appendSelectQuery("union",query)}unionAll(query){return this.appendSelectQuery("union all",query)}intersect(query){return this.appendSelectQuery("intersect",query)}intersectAll(query){return this.appendSelectQuery("intersect all",query)}except(query){return this.appendSelectQuery("except",query)}exceptAll(query){return this.appendSelectQuery("except all",query)}appendSelectQuery(operator,query){return this.left=new _BinarySelectQuery(this.left,this.operator.value,this.right),this.operator=new RawString(operator),this.right=query,CTENormalizer.normalize(this),this}unionRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.union(parsedQuery)}unionAllRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.unionAll(parsedQuery)}intersectRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.intersect(parsedQuery)}intersectAllRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.intersectAll(parsedQuery)}exceptRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.except(parsedQuery)}exceptAllRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.exceptAll(parsedQuery)}toInsertQuery(options){return this.toSimpleQuery().toInsertQuery(options)}toUpdateQuery(options){return this.toSimpleQuery().toUpdateQuery(options)}toDeleteQuery(options){return this.toSimpleQuery().toDeleteQuery(options)}toMergeQuery(options){return this.toSimpleQuery().toMergeQuery(options)}toSource(alias="subq"){return new SourceExpression(new SubQuerySource(this),new SourceAliasExpression(alias,null))}setParameter(name,value){return ParameterHelper.set(this,name,value),this}toSimpleQuery(){return QueryBuilder.buildSimpleQuery(this)}};var InsertQuerySelectValuesConverter=class{static toSelectUnion(insertQuery){let valuesQuery=insertQuery.selectQuery;if(!(valuesQuery instanceof ValuesQuery))throw new Error("InsertQuery selectQuery is not a VALUES query.");if(!valuesQuery.tuples.length)throw new Error("VALUES query does not contain any tuples.");let columns=insertQuery.insertClause.columns;if(!columns||columns.length===0)throw new Error("Cannot convert to SELECT form without explicit column list.");let columnNames=columns.map(col=>col.name),selectQueries=valuesQuery.tuples.map(tuple=>{if(tuple.values.length!==columnNames.length)throw new Error("Tuple value count does not match column count.");let items=columnNames.map((name,idx)=>new SelectItem(tuple.values[idx],name)),selectClause=new SelectClause(items);return new SimpleSelectQuery({selectClause})}),combined=selectQueries[0];for(let i=1;i<selectQueries.length;i++)if(combined instanceof SimpleSelectQuery)combined=combined.toUnionAll(selectQueries[i]);else if(combined instanceof BinarySelectQuery)combined.appendSelectQuery("union all",selectQueries[i]);else throw new Error("Unsupported SelectQuery type during UNION ALL construction.");return new InsertQuery({withClause:insertQuery.withClause,insertClause:insertQuery.insertClause,selectQuery:combined,returning:insertQuery.returningClause})}static toValues(insertQuery){let columns=insertQuery.insertClause.columns;if(!columns||columns.length===0)throw new Error("Cannot convert to VALUES form without explicit column list.");if(!insertQuery.selectQuery)throw new Error("InsertQuery does not have a selectQuery to convert.");let columnNames=columns.map(col=>col.name),simpleQueries=this.flattenSelectQueries(insertQuery.selectQuery);if(!simpleQueries.length)throw new Error("No SELECT components found to convert.");let tuples=simpleQueries.map(query=>{if(query.fromClause||query.whereClause&&query.whereClause.condition)throw new Error("SELECT queries with FROM or WHERE clauses cannot be converted to VALUES.");let valueMap=new Map;for(let item of query.selectClause.items){let identifier=item.identifier?.name??null;if(!identifier)throw new Error("Each SELECT item must have an alias matching target columns.");valueMap.has(identifier)||valueMap.set(identifier,item.value)}let rowValues=columnNames.map(name=>{let value=valueMap.get(name);if(!value)throw new Error(`Column '${name}' is not provided by the SELECT query.`);return value});return new TupleExpression(rowValues)}),valuesQuery=new ValuesQuery(tuples,columnNames);return new InsertQuery({withClause:insertQuery.withClause,insertClause:insertQuery.insertClause,selectQuery:valuesQuery,returning:insertQuery.returningClause})}static flattenSelectQueries(selectQuery){if(selectQuery instanceof SimpleSelectQuery)return[selectQuery];if(selectQuery instanceof BinarySelectQuery)return[...this.flattenSelectQueries(selectQuery.left),...this.flattenSelectQueries(selectQuery.right)];throw new Error("Unsupported SelectQuery subtype for conversion.")}};var QueryBuilder=class _QueryBuilder{static buildBinaryQuery(queries,operator){if(!queries||queries.length===0)throw new Error("No queries provided to combine.");if(queries.length===1)throw new Error("At least two queries are required to create a BinarySelectQuery.");let wrap=q=>q instanceof ValuesQuery?_QueryBuilder.buildSimpleQuery(q):q,result=new BinarySelectQuery(wrap(queries[0]),operator,wrap(queries[1]));CTENormalizer.normalize(result);for(let i=2;i<queries.length;i++)result.appendSelectQuery(operator,wrap(queries[i]));return result}constructor(){}static buildSimpleQuery(query){if(query instanceof SimpleSelectQuery)return query;if(query instanceof BinarySelectQuery)return _QueryBuilder.buildSimpleBinaryQuery(query);if(query instanceof ValuesQuery)return _QueryBuilder.buildSimpleValuesQuery(query);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(query){let extractedOrderBy=_QueryBuilder.extractAndRemoveOrderByFromBinaryQuery(query),subQuerySource=new SubQuerySource(query),sourceExpr=new SourceExpression(subQuerySource,new SourceAliasExpression("bq",null)),fromClause=new FromClause(sourceExpr,null),selectClause=_QueryBuilder.createSelectAllClause(),q=new SimpleSelectQuery({selectClause,fromClause,orderByClause:extractedOrderBy});return CTENormalizer.normalize(q)}static extractAndRemoveOrderByFromBinaryQuery(query){return _QueryBuilder.findAndRemoveRightmostOrderBy(query)}static findAndRemoveRightmostOrderBy(query){if(query instanceof BinarySelectQuery){let rightOrderBy=_QueryBuilder.findAndRemoveRightmostOrderBy(query.right);return rightOrderBy||_QueryBuilder.findAndRemoveRightmostOrderBy(query.left)}else if(query instanceof SimpleSelectQuery){let orderBy=query.orderByClause;if(orderBy)return query.orderByClause=null,orderBy}return null}static buildSimpleValuesQuery(query){let columnCount=query.tuples.length>0?query.tuples[0].values.length:0;if(query.tuples.length===0)throw new Error("Empty VALUES clause cannot be converted to a SimpleSelectQuery");if(!query.columnAliases)throw new Error("Column aliases are required to convert a VALUES clause to SimpleSelectQuery. Please specify column aliases.");if(query.columnAliases.length!==columnCount)throw new Error(`The number of column aliases (${query.columnAliases.length}) does not match the number of columns in the first tuple (${columnCount}).`);let subQuerySource=new SubQuerySource(query),sourceExpr=new SourceExpression(subQuerySource,new SourceAliasExpression("vq",query.columnAliases)),fromClause=new FromClause(sourceExpr,null),selectItems=query.columnAliases.map(name=>new SelectItem(new ColumnReference("vq",name),name)),selectClause=new SelectClause(selectItems,null);return new SimpleSelectQuery({selectClause,fromClause})}static createSelectAllClause(){let columnRef=new ColumnReference(null,"*"),selectItem=new SelectItem(columnRef,"*");return new SelectClause([selectItem],null)}static buildCreateTableQuery(query,tableName,isTemporary=!1,ifNotExists=!1){return new CreateTableQuery({tableName,isTemporary,ifNotExists,asSelectQuery:query})}static buildInsertQuery(selectQuery,targetOrOptions,explicitColumns){let options=_QueryBuilder.normalizeInsertOptions(targetOrOptions,explicitColumns),columnNames=_QueryBuilder.prepareInsertColumns(selectQuery,options.columns??null),withClause=_QueryBuilder.extractWithClause(selectQuery),sourceExpr=SourceExpressionParser.parse(options.target);return new InsertQuery({withClause:withClause??void 0,insertClause:new InsertClause(sourceExpr,columnNames),selectQuery})}static convertInsertValuesToSelect(insertQuery){return InsertQuerySelectValuesConverter.toSelectUnion(insertQuery)}static convertInsertSelectToValues(insertQuery){return InsertQuerySelectValuesConverter.toValues(insertQuery)}static buildUpdateQuery(selectQuery,selectSourceOrOptions,updateTableExprRaw,primaryKeys){let options=_QueryBuilder.normalizeUpdateOptions(selectSourceOrOptions,updateTableExprRaw,primaryKeys),updateColumns=_QueryBuilder.prepareUpdateColumns(selectQuery,options.primaryKeys,options.columns??null),updateClause=new UpdateClause(SourceExpressionParser.parse(options.target)),targetAlias=updateClause.getSourceAliasName();if(!targetAlias)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let withClause=_QueryBuilder.extractWithClause(selectQuery),setItems=updateColumns.map(column=>new SetClauseItem(column,_QueryBuilder.toColumnReference(options.sourceAlias,column)));if(setItems.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 setClause=new SetClause(setItems),fromClause=new FromClause(selectQuery.toSource(options.sourceAlias),null),whereClause=new WhereClause(_QueryBuilder.buildEqualityPredicate(targetAlias,options.sourceAlias,options.primaryKeys));return new UpdateQuery({updateClause,setClause,fromClause,whereClause,withClause:withClause??void 0})}static buildDeleteQuery(selectQuery,options){let normalized=_QueryBuilder.normalizeDeleteOptions(options),predicateColumns=_QueryBuilder.prepareDeleteColumns(selectQuery,normalized.primaryKeys,normalized.columns??null),deleteClause=new DeleteClause(SourceExpressionParser.parse(normalized.target)),targetAlias=deleteClause.getSourceAliasName();if(!targetAlias)throw new Error("Source expression does not have an alias. Please provide an alias for the delete target.");let withClause=_QueryBuilder.extractWithClause(selectQuery),predicate=_QueryBuilder.buildEqualityPredicate(targetAlias,normalized.sourceAlias,predicateColumns),sourceExpression=selectQuery.toSource(normalized.sourceAlias),existsSelectClause=new SelectClause([new SelectItem(new LiteralValue(1))]),existsSubquery=new SimpleSelectQuery({selectClause:existsSelectClause,fromClause:new FromClause(sourceExpression,null),whereClause:new WhereClause(predicate)}),whereClause=new WhereClause(new UnaryExpression("exists",new InlineQuery(existsSubquery)));return new DeleteQuery({deleteClause,whereClause,withClause:withClause??void 0})}static buildMergeQuery(selectQuery,options){let normalized=_QueryBuilder.normalizeMergeOptions(options),mergeColumnPlan=_QueryBuilder.prepareMergeColumns(selectQuery,normalized.primaryKeys,normalized.updateColumns??null,normalized.insertColumns??null,normalized.matchedAction??"update",normalized.notMatchedAction??"insert"),targetExpression=SourceExpressionParser.parse(normalized.target),targetAlias=targetExpression.getAliasName();if(!targetAlias)throw new Error("Source expression does not have an alias. Please provide an alias for the merge target.");let withClause=_QueryBuilder.extractWithClause(selectQuery),onCondition=_QueryBuilder.buildEqualityPredicate(targetAlias,normalized.sourceAlias,normalized.primaryKeys),sourceExpression=selectQuery.toSource(normalized.sourceAlias),whenClauses=[],matchedAction=normalized.matchedAction??"update";if(matchedAction==="update"){if(mergeColumnPlan.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 setItems=mergeColumnPlan.updateColumns.map(column=>new SetClauseItem(column,_QueryBuilder.toColumnReference(normalized.sourceAlias,column)));whenClauses.push(new MergeWhenClause("matched",new MergeUpdateAction(new SetClause(setItems))))}else matchedAction==="delete"?whenClauses.push(new MergeWhenClause("matched",new MergeDeleteAction)):matchedAction==="doNothing"&&whenClauses.push(new MergeWhenClause("matched",new MergeDoNothingAction));let notMatchedAction=normalized.notMatchedAction??"insert";if(notMatchedAction==="insert"){if(mergeColumnPlan.insertColumns.length===0)throw new Error("Unable to infer MERGE insert columns. Provide insertColumns explicitly.");let insertValues=new ValueList(mergeColumnPlan.insertColumns.map(column=>_QueryBuilder.toColumnReference(normalized.sourceAlias,column)));whenClauses.push(new MergeWhenClause("not_matched",new MergeInsertAction({columns:mergeColumnPlan.insertColumns,values:insertValues})))}else notMatchedAction==="doNothing"&&whenClauses.push(new MergeWhenClause("not_matched",new MergeDoNothingAction));let notMatchedBySourceAction=normalized.notMatchedBySourceAction??"doNothing";if(notMatchedBySourceAction==="delete"?whenClauses.push(new MergeWhenClause("not_matched_by_source",new MergeDeleteAction)):notMatchedBySourceAction==="doNothing"&&whenClauses.push(new MergeWhenClause("not_matched_by_source",new MergeDoNothingAction)),whenClauses.length===0)throw new Error("At least one MERGE action must be generated. Adjust the merge conversion options.");return new MergeQuery({withClause:withClause??void 0,target:targetExpression,source:sourceExpression,onCondition,whenClauses})}static normalizeInsertOptions(targetOrOptions,explicitColumns){return typeof targetOrOptions=="string"?{target:targetOrOptions,columns:explicitColumns}:explicitColumns&&explicitColumns.length>0?{...targetOrOptions,columns:explicitColumns}:{...targetOrOptions}}static normalizeUpdateOptions(selectSourceOrOptions,updateTableExprRaw,primaryKeys){if(typeof selectSourceOrOptions=="string"){if(!updateTableExprRaw)throw new Error("updateTableExprRaw is required when using the legacy buildUpdateQuery signature.");if(primaryKeys===void 0)throw new Error("primaryKeys are required when using the legacy buildUpdateQuery signature.");return{target:updateTableExprRaw,primaryKeys:_QueryBuilder.normalizeColumnArray(primaryKeys),sourceAlias:selectSourceOrOptions}}return{target:selectSourceOrOptions.target,primaryKeys:_QueryBuilder.normalizeColumnArray(selectSourceOrOptions.primaryKeys),sourceAlias:selectSourceOrOptions.sourceAlias??"src",columns:selectSourceOrOptions.columns}}static normalizeDeleteOptions(options){return{...options,primaryKeys:_QueryBuilder.normalizeColumnArray(options.primaryKeys),sourceAlias:options.sourceAlias??"src"}}static normalizeMergeOptions(options){return{...options,primaryKeys:_QueryBuilder.normalizeColumnArray(options.primaryKeys),sourceAlias:options.sourceAlias??"src"}}static normalizeColumnArray(columns){let normalized=(Array.isArray(columns)?columns:[columns]).map(col=>col.trim()).filter(col=>col.length>0);if(!normalized.length)throw new Error("At least one column must be specified.");return normalized}static collectSelectItems(selectQuery){return new SelectValueCollector().collect(selectQuery)}static collectSelectColumnNames(selectQuery){let items=_QueryBuilder.collectSelectItems(selectQuery),names=[];for(let item of items){if(!item.name||item.name==="*")throw new Error("Columns cannot be inferred from the selectQuery. Make sure you are not using wildcards or unnamed columns.");names.includes(item.name)||names.push(item.name)}if(!names.length)throw new Error("Unable to determine any column names from selectQuery.");return names}static ensurePrimaryKeys(selectColumns,primaryKeys){let available=new Set(selectColumns);for(let pk of primaryKeys)if(!available.has(pk))throw new Error(`Primary key column '${pk}' is not present in selectQuery select list.`)}static prepareInsertColumns(selectQuery,optionColumns){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);if(optionColumns&&optionColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(optionColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>!selectColumns.includes(name));if(missing.length>0)throw new Error(`Columns specified in conversion options were not found in selectQuery select list: [${missing.join(", ")}].`);return _QueryBuilder.rebuildSelectClause(selectQuery,uniqueNormalized),_QueryBuilder.ensureSelectClauseSize(selectQuery,uniqueNormalized.length),uniqueNormalized}return _QueryBuilder.ensureSelectClauseSize(selectQuery,selectColumns.length),selectColumns}static prepareUpdateColumns(selectQuery,primaryKeys,explicitColumns){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);_QueryBuilder.ensurePrimaryKeys(selectColumns,primaryKeys);let primaryKeySet=new Set(primaryKeys),updateCandidates=selectColumns.filter(name=>!primaryKeySet.has(name)),updateColumnsOrdered;if(explicitColumns&&explicitColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>primaryKeySet.has(name)||!updateCandidates.includes(name));if(missing.length>0)throw new Error(`Provided update columns were not found in selectQuery output or are primary keys: [${missing.join(", ")}].`);updateColumnsOrdered=uniqueNormalized}else updateColumnsOrdered=Array.from(new Set(updateCandidates));let desiredOrder=Array.from(new Set([...primaryKeys,...updateColumnsOrdered]));return _QueryBuilder.rebuildSelectClause(selectQuery,desiredOrder),_QueryBuilder.ensureSelectClauseSize(selectQuery,desiredOrder.length),updateColumnsOrdered}static prepareDeleteColumns(selectQuery,primaryKeys,explicitColumns){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);_QueryBuilder.ensurePrimaryKeys(selectColumns,primaryKeys);let primaryKeySet=new Set(primaryKeys),matchColumns=[];if(explicitColumns&&explicitColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitColumns),preferred=new Set(normalized);matchColumns=selectColumns.filter(name=>preferred.has(name)&&!primaryKeySet.has(name))}let requiredColumns=new Set;primaryKeys.forEach(key=>requiredColumns.add(key)),matchColumns.forEach(col=>requiredColumns.add(col));let desiredOrder=selectColumns.filter(name=>requiredColumns.has(name));return _QueryBuilder.rebuildSelectClause(selectQuery,desiredOrder),_QueryBuilder.ensureSelectClauseSize(selectQuery,desiredOrder.length),desiredOrder}static prepareMergeColumns(selectQuery,primaryKeys,explicitUpdateColumns,explicitInsertColumns,matchedAction,notMatchedAction){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);_QueryBuilder.ensurePrimaryKeys(selectColumns,primaryKeys);let primaryKeySet=new Set(primaryKeys),updateColumnsOrdered=[];if(matchedAction==="update"){let candidates=selectColumns.filter(name=>!primaryKeySet.has(name));if(explicitUpdateColumns&&explicitUpdateColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitUpdateColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>primaryKeySet.has(name)||!candidates.includes(name));if(missing.length>0)throw new Error(`Provided update columns were not found in selectQuery output or are primary keys: [${missing.join(", ")}].`);updateColumnsOrdered=uniqueNormalized}else updateColumnsOrdered=Array.from(new Set(candidates))}let insertColumnsOrdered=[];if(notMatchedAction==="insert")if(explicitInsertColumns&&explicitInsertColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitInsertColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>!selectColumns.includes(name));if(missing.length>0)throw new Error(`Provided insert columns were not found in selectQuery output: [${missing.join(", ")}].`);insertColumnsOrdered=uniqueNormalized}else insertColumnsOrdered=Array.from(new Set(selectColumns));let desiredOrder=Array.from(new Set([...primaryKeys,...updateColumnsOrdered,...insertColumnsOrdered,...selectColumns])).filter(name=>selectColumns.includes(name));return _QueryBuilder.rebuildSelectClause(selectQuery,desiredOrder),_QueryBuilder.ensureSelectClauseSize(selectQuery,desiredOrder.length),{updateColumns:matchedAction==="update"?updateColumnsOrdered:[],insertColumns:notMatchedAction==="insert"?insertColumnsOrdered:[]}}static rebuildSelectClause(selectQuery,desiredColumns){let itemMap=new Map;for(let item of selectQuery.selectClause.items){let name=_QueryBuilder.getSelectItemName(item);name&&(itemMap.has(name)||itemMap.set(name,item))}let rebuiltItems=[],seen=new Set;for(let column of desiredColumns){if(seen.has(column))continue;let item=itemMap.get(column);if(!item)throw new Error(`Column '${column}' not found in select clause.`);rebuiltItems.push(item),seen.add(column)}if(!rebuiltItems.length)throw new Error("Unable to rebuild select clause with the requested columns.");selectQuery.selectClause.items=rebuiltItems}static getSelectItemName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}static ensureSelectClauseSize(selectQuery,expected){if(selectQuery.selectClause.items.length!==expected)throw new Error(`Select clause column count (${selectQuery.selectClause.items.length}) does not match expected count (${expected}).`)}static extractWithClause(selectQuery){let collected=new CTECollector().collect(selectQuery);return collected.length===0?null:(new CTEDisabler().execute(selectQuery),new WithClause(!1,collected))}static buildEqualityPredicate(leftAlias,rightAlias,columns){let uniqueColumns=_QueryBuilder.mergeUniqueColumns(columns);if(!uniqueColumns.length)throw new Error("At least one column is required to build a comparison predicate.");let predicate=null;for(let column of uniqueColumns){let comparison=new BinaryExpression(_QueryBuilder.toColumnReference(leftAlias,column),"=",_QueryBuilder.toColumnReference(rightAlias,column));predicate=predicate?new BinaryExpression(predicate,"and",comparison):comparison}return predicate}static toColumnReference(alias,column){return new ColumnReference(alias,column)}static mergeUniqueColumns(columns){let seen=new Set,result=[];for(let column of columns)seen.has(column)||(seen.add(column),result.push(column));return result}};var SimpleSelectQuery=class extends SqlComponent{constructor(params){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.cteNameCache=new Set;this.withClause=params.withClause??null,this.selectClause=params.selectClause,this.fromClause=params.fromClause??null,this.whereClause=params.whereClause??null,this.groupByClause=params.groupByClause??null,this.havingClause=params.havingClause??null,this.orderByClause=params.orderByClause??null,this.windowClause=params.windowClause??null,this.limitClause=params.limitClause??null,this.offsetClause=params.offsetClause??null,this.fetchClause=params.fetchClause??null,this.forClause=params.forClause??null,this.initializeCTECache()}static{this.kind=Symbol("SelectQuery")}initializeCTECache(){if(this.cteNameCache.clear(),this.withClause?.tables)for(let table of this.withClause.tables)this.cteNameCache.add(table.aliasExpression.table.name)}toUnion(rightQuery){return this.toBinaryQuery("union",rightQuery)}toUnionAll(rightQuery){return this.toBinaryQuery("union all",rightQuery)}toInsertQuery(options){return QueryBuilder.buildInsertQuery(this,options)}toUpdateQuery(options){return QueryBuilder.buildUpdateQuery(this,options)}toDeleteQuery(options){return QueryBuilder.buildDeleteQuery(this,options)}toMergeQuery(options){return QueryBuilder.buildMergeQuery(this,options)}toIntersect(rightQuery){return this.toBinaryQuery("intersect",rightQuery)}toIntersectAll(rightQuery){return this.toBinaryQuery("intersect all",rightQuery)}toExcept(rightQuery){return this.toBinaryQuery("except",rightQuery)}toExceptAll(rightQuery){return this.toBinaryQuery("except all",rightQuery)}toBinaryQuery(operator,rightQuery){return QueryBuilder.buildBinaryQuery([this,rightQuery],operator)}appendWhereRaw(rawCondition){let parsedCondition=ValueParser.parse(rawCondition);this.appendWhere(parsedCondition)}appendWhere(condition){this.whereClause?this.whereClause.condition=new BinaryExpression(this.whereClause.condition,"and",condition):this.whereClause=new WhereClause(condition)}appendHavingRaw(rawCondition){let parsedCondition=ValueParser.parse(rawCondition);this.appendHaving(parsedCondition)}appendHaving(condition){this.havingClause?this.havingClause.condition=new BinaryExpression(this.havingClause.condition,"and",condition):this.havingClause=new HavingClause(condition)}innerJoinRaw(joinSourceRawText,alias,columns,resolver=null){this.joinSourceRaw("inner join",joinSourceRawText,alias,columns,resolver)}leftJoinRaw(joinSourceRawText,alias,columns,resolver=null){this.joinSourceRaw("left join",joinSourceRawText,alias,columns,resolver)}rightJoinRaw(joinSourceRawText,alias,columns,resolver=null){this.joinSourceRaw("right join",joinSourceRawText,alias,columns,resolver)}innerJoin(sourceExpr,columns,resolver=null){this.joinSource("inner join",sourceExpr,columns,resolver)}leftJoin(sourceExpr,columns,resolver=null){this.joinSource("left join",sourceExpr,columns,resolver)}rightJoin(sourceExpr,columns,resolver=null){this.joinSource("right join",sourceExpr,columns,resolver)}joinSourceRaw(joinType,joinSourceRawText,alias,columns,resolver=null){let tableSource=SourceParser.parse(joinSourceRawText),sourceExpr=new SourceExpression(tableSource,new SourceAliasExpression(alias,null));this.joinSource(joinType,sourceExpr,columns,resolver)}joinSource(joinType,sourceExpr,columns,resolver=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let columnsArr=Array.isArray(columns)?columns:[columns],valueSets=new SelectableColumnCollector(resolver).collect(this),joinCondition=null,count=0,sourceAlias=sourceExpr.getAliasName();if(!sourceAlias)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let valueSet of valueSets)if(columnsArr.some(col=>col==valueSet.name)){let expr=new BinaryExpression(valueSet.value,"=",new ColumnReference([sourceAlias],valueSet.name));joinCondition?joinCondition=new BinaryExpression(joinCondition,"and",expr):joinCondition=expr,count++}if(!joinCondition||count!==columnsArr.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${columnsArr.join(", ")}`);let joinOnClause=new JoinOnClause(joinCondition),joinClause=new JoinClause(joinType,sourceExpr,joinOnClause,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(joinClause):this.fromClause.joins=[joinClause]),CTENormalizer.normalize(this)}toSource(alias){if(!alias||alias.trim()==="")throw new Error("Alias is required for toSource(). Please specify a non-empty alias name.");return new SourceExpression(new SubQuerySource(this),new SourceAliasExpression(alias,null))}appendWith(commonTable){let tables=Array.isArray(commonTable)?commonTable:[commonTable];this.withClause?this.withClause.tables.push(...tables):this.withClause=new WithClause(!1,tables),CTENormalizer.normalize(this)}appendWithRaw(rawText,alias){let query=SelectQueryParser.parse(rawText),commonTable=new CommonTable(query,alias,null);this.appendWith(commonTable)}overrideSelectItemExpr(columnName,fn){let items=this.selectClause.items.filter(item2=>item2.identifier?.name===columnName);if(items.length===0)throw new Error(`Column ${columnName} not found in the query`);if(items.length>1)throw new Error(`Duplicate column name ${columnName} found in the query`);let item=items[0],exprSql=new Formatter().visit(item.value),newValue=fn(exprSql);item.value=ValueParser.parse(newValue)}appendWhereExpr(columnName,exprBuilder,options){if(options&&options.upstream){let queries=new UpstreamSelectQueryFinder().find(this,[columnName]),collector=new SelectableColumnCollector,formatter=new Formatter;for(let q of queries){let exprs=collector.collect(q).filter(item=>item.name===columnName).map(item=>item.value);if(exprs.length!==1)throw new Error(`Expected exactly one expression for column '${columnName}'`);let exprStr=formatter.format(exprs[0]);q.appendWhereRaw(exprBuilder(exprStr))}}else{let collector=new SelectableColumnCollector,formatter=new Formatter,exprs=collector.collect(this).filter(item=>item.name===columnName).map(item=>item.value);if(exprs.length!==1)throw new Error(`Expected exactly one expression for column '${columnName}'`);let exprStr=formatter.format(exprs[0]);this.appendWhereRaw(exprBuilder(exprStr))}}setParameter(name,value){return ParameterHelper.set(this,name,value),this}toSimpleQuery(){return this}addCTE(name,query,options){if(!name||name.trim()==="")throw new InvalidCTENameError(name,"name cannot be empty or whitespace-only");if(this.hasCTE(name))throw new DuplicateCTEError(name);let materialized=options?.materialized??null,commonTable=new CommonTable(query,name,materialized);return this.appendWith(commonTable),this.cteNameCache.add(name),this}removeCTE(name){if(!this.hasCTE(name))throw new CTENotFoundError(name);return this.withClause&&(this.withClause.tables=this.withClause.tables.filter(table=>table.aliasExpression.table.name!==name),this.withClause.tables.length===0&&(this.withClause=null)),this.cteNameCache.delete(name),this}hasCTE(name){return this.cteNameCache.has(name)}getCTENames(){return this.withClause?.tables.map(table=>table.aliasExpression.table.name)??[]}replaceCTE(name,query,options){if(!name||name.trim()==="")throw new InvalidCTENameError(name,"name cannot be empty or whitespace-only");this.hasCTE(name)&&this.removeCTE(name);let materialized=options?.materialized??null,commonTable=new CommonTable(query,name,materialized);return this.appendWith(commonTable),this.cteNameCache.add(name),this}};var SelectClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The SELECT clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,distinct=null,selectTokenComments=idx<lexemes.length?lexemes[idx].comments:null;if(lexemes[idx].value!=="select")throw new Error(`Syntax error at position ${idx}: Expected 'SELECT' keyword but found "${lexemes[idx].value}". SELECT clauses must start with the SELECT keyword.`);idx++;let hints=[];for(;idx<lexemes.length&&HintClause.isHintClause(lexemes[idx].value);){let hintContent=HintClause.extractHintContent(lexemes[idx].value);hints.push(new HintClause(hintContent)),idx++}if(idx<lexemes.length&&lexemes[idx].value==="distinct")idx++,distinct=new Distinct;else if(idx<lexemes.length&&lexemes[idx].value==="distinct on"){idx++;let argument=ValueParser.parseArgument(4,8,lexemes,idx);distinct=new DistinctOn(argument.value),idx=argument.newIndex}let items=[],item=SelectItemParser.parseItem(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=SelectItemParser.parseItem(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No select items found. The SELECT clause requires at least one expression to select.`);return{value:new SelectClause(items,distinct,hints),newIndex:idx}}},SelectItemParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseItem(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The select item is complete but there are additional tokens.`);return result.value}static parseItem(lexemes,index){let idx=index,valueTokenComments=this.extractValueTokenComments(lexemes,idx),parsedValue=ValueParser.parseFromLexeme(lexemes,idx),value=parsedValue.value;idx=parsedValue.newIndex;let{asComments,newIndex:asIndex}=this.parseAsKeyword(lexemes,idx);if(idx=asIndex,idx<lexemes.length&&lexemes[idx].type&64){let alias=lexemes[idx].value,aliasComments=lexemes[idx].comments,aliasPositionedComments=lexemes[idx].positionedComments;idx++;let selectItem2=new SelectItem(value,alias);return this.applyValueTokenComments(selectItem2,valueTokenComments),this.applyAsKeywordComments(selectItem2,asComments),this.applyAliasComments(selectItem2,aliasComments,aliasPositionedComments),{value:selectItem2,newIndex:idx}}else if(value instanceof ColumnReference&&value.column.name!=="*"){let selectItem2=new SelectItem(value,value.column.name);return this.applyValueTokenComments(selectItem2,valueTokenComments),this.applyAsKeywordComments(selectItem2,asComments),{value:selectItem2,newIndex:idx}}let selectItem=new SelectItem(value);return this.applyValueTokenComments(selectItem,valueTokenComments),this.applyAsKeywordComments(selectItem,asComments),{value:selectItem,newIndex:idx}}static clearPositionedCommentsRecursively(component){!component||typeof component!="object"||("positionedComments"in component&&(component.positionedComments=null),component.left&&this.clearPositionedCommentsRecursively(component.left),component.right&&this.clearPositionedCommentsRecursively(component.right),component.qualifiedName&&this.clearPositionedCommentsRecursively(component.qualifiedName),component.table&&this.clearPositionedCommentsRecursively(component.table),component.name&&this.clearPositionedCommentsRecursively(component.name),component.args&&Array.isArray(component.args)&&component.args.forEach(arg=>{this.clearPositionedCommentsRecursively(arg)}),component.value&&this.clearPositionedCommentsRecursively(component.value))}static extractValueTokenComments(lexemes,index){if(index>=lexemes.length)return{positioned:null,legacy:null};let token=lexemes[index];return{positioned:token.positionedComments&&token.positionedComments.length>0?token.positionedComments:null,legacy:null}}static parseAsKeyword(lexemes,index){if(index>=lexemes.length||lexemes[index].value!=="as")return{asComments:{positioned:null,legacy:null},newIndex:index};let asToken=lexemes[index];return{asComments:{positioned:asToken.positionedComments&&asToken.positionedComments.length>0?asToken.positionedComments:null,legacy:asToken.comments&&asToken.comments.length>0?asToken.comments:null},newIndex:index+1}}static applyValueTokenComments(selectItem,valueTokenComments){if(valueTokenComments.positioned){for(let posComment of valueTokenComments.positioned)selectItem.addPositionedComments(posComment.position,posComment.comments);this.clearValueTokenComments(selectItem)}}static applyAsKeywordComments(selectItem,asComments){asComments.positioned?selectItem.asKeywordPositionedComments=asComments.positioned:asComments.legacy&&(selectItem.asKeywordComments=asComments.legacy)}static applyAliasComments(selectItem,aliasComments,aliasPositionedComments){aliasPositionedComments&&aliasPositionedComments.length>0?selectItem.aliasPositionedComments=aliasPositionedComments:aliasComments&&aliasComments.length>0&&(selectItem.aliasComments=aliasComments)}static clearValueTokenComments(selectItem){if("positionedComments"in selectItem.value&&(selectItem.value.positionedComments=null),selectItem.value instanceof ColumnReference){let columnRef=selectItem.value;columnRef.qualifiedName&&columnRef.qualifiedName.name&&(columnRef.qualifiedName.name.positionedComments=null)}selectItem.value instanceof BinaryExpression&&this.clearPositionedCommentsRecursively(selectItem.value)}};var JoinOnClauseParser=class{static tryParse(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].value==="on"){idx++;let condition=ValueParser.parseFromLexeme(lexemes,idx);return idx=condition.newIndex,{value:new JoinOnClause(condition.value),newIndex:idx}}return null}};var JoinUsingClauseParser=class{static tryParse(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].value==="using"){idx++;let result=ValueParser.parseArgument(4,8,lexemes,idx),usingColumns=result.value;return idx=result.newIndex,{value:new JoinUsingClause(usingColumns),newIndex:idx}}return null}};var JoinClauseParser=class{static tryParse(lexemes,index){let idx=index,joins=[];for(;this.isJoinCommand(lexemes,idx);){let joinClause=this.parseJoinClause(lexemes,idx);joins.push(joinClause.value),idx=joinClause.newIndex}return joins.length>0?{value:joins,newIndex:idx}:null}static isJoinKeyword(value){return!!joinkeywordParser.parse(value,0)}static parseLateral(lexemes,index){let idx=index;return idx<lexemes.length&&lexemes[idx].value==="lateral"?(idx++,{value:!0,newIndex:idx}):{value:!1,newIndex:idx}}static isJoinCommand(lexemes,index){return index>=lexemes.length?!1:!!(lexemes[index].type&16||this.isJoinKeyword(lexemes[index].value)===!0)}static parseJoinClause(lexemes,index){let idx=index,{joinType,joinComments,newIndex:joinIndex}=this.parseJoinKeyword(lexemes,idx);idx=joinIndex;let lateralResult=this.parseLateral(lexemes,idx),lateral=lateralResult.value;idx=lateralResult.newIndex;let sourceResult=SourceExpressionParser.parseFromLexeme(lexemes,idx);idx=sourceResult.newIndex;let joinClause=this.parseJoinCondition(lexemes,idx,joinType,sourceResult.value,lateral,joinComments);if(joinClause)return joinClause;let naturalJoinClause=new JoinClause(joinType,sourceResult.value,null,lateral);return this.applyJoinComments(naturalJoinClause,joinComments),{value:naturalJoinClause,newIndex:idx}}static parseJoinKeyword(lexemes,index){let joinType=lexemes[index].value===","?"cross join":lexemes[index].value,joinComments=this.extractJoinKeywordComments(lexemes[index]);return{joinType,joinComments,newIndex:index+1}}static extractJoinKeywordComments(token){return{positioned:token.positionedComments&&token.positionedComments.length>0?token.positionedComments:null,legacy:token.comments&&token.comments.length>0?token.comments:null}}static parseJoinCondition(lexemes,index,joinType,sourceValue,lateral,joinComments){if(index>=lexemes.length)return null;let onResult=JoinOnClauseParser.tryParse(lexemes,index);if(onResult){let joinClause=new JoinClause(joinType,sourceValue,onResult.value,lateral);return this.applyJoinComments(joinClause,joinComments),{value:joinClause,newIndex:onResult.newIndex}}let usingResult=JoinUsingClauseParser.tryParse(lexemes,index);if(usingResult){let joinClause=new JoinClause(joinType,sourceValue,usingResult.value,lateral);return this.applyJoinComments(joinClause,joinComments),{value:joinClause,newIndex:usingResult.newIndex}}return null}static applyJoinComments(joinClause,joinComments){joinComments.positioned?joinClause.joinKeywordPositionedComments=joinComments.positioned:joinComments.legacy&&(joinClause.joinKeywordComments=joinComments.legacy)}};var CommentUtils=class{static collectClauseComments(lexemes,currentIndex,keywordValue){if(currentIndex>=lexemes.length||lexemes[currentIndex].value.toLowerCase()!==keywordValue.toLowerCase())return null;let comments=[];lexemes[currentIndex].comments&&comments.push(...lexemes[currentIndex].comments);let checkIndex=currentIndex-1;for(;checkIndex>=0;){let prevToken=lexemes[checkIndex];if(prevToken.comments&&prevToken.comments.length>0){let clauseSpecificComments=prevToken.comments.filter(comment=>{let lowerComment=comment.toLowerCase();return lowerComment.includes(keywordValue.toLowerCase())||lowerComment.includes("\u306E")||lowerComment.includes("\u30B3\u30E1\u30F3\u30C8")});clauseSpecificComments.length>0&&(comments.unshift(...clauseSpecificComments),prevToken.comments=prevToken.comments.filter(c=>!clauseSpecificComments.includes(c)),prevToken.comments.length===0&&(prevToken.comments=null));break}if(this.isSignificantSqlKeyword(prevToken.value))break;checkIndex--}return comments.length>0?comments:null}static isSignificantSqlKeyword(value){return new Set(["select","from","where","group by","having","order by","limit","offset"]).has(value.toLowerCase())}};var FromClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The FROM clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,fromTokenComments=CommentUtils.collectClauseComments(lexemes,idx,"from");if(lexemes[idx].value!=="from")throw new Error(`Syntax error at position ${idx}: Expected 'FROM' keyword but found "${lexemes[idx].value}". FROM clauses must start with the FROM keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FROM' keyword. The FROM clause requires a table reference.");let sourceExpression=SourceExpressionParser.parseFromLexeme(lexemes,idx);idx=sourceExpression.newIndex;let join=JoinClauseParser.tryParse(lexemes,idx);if(idx=join?.newIndex||idx,join!==null){let clause=new FromClause(sourceExpression.value,join.value);return{value:clause,newIndex:idx}}else{let clause=new FromClause(sourceExpression.value,null);return{value:clause,newIndex:idx}}}};var WhereClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The WHERE clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,whereLexeme=lexemes[idx],whereTokenComments=CommentUtils.collectClauseComments(lexemes,idx,"where"),wherePositionedComments=whereLexeme.positionedComments;if(whereLexeme.value!=="where")throw new Error(`Syntax error at position ${idx}: Expected 'WHERE' keyword but found "${lexemes[idx].value}". WHERE clauses must start with the WHERE keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'WHERE' keyword. The WHERE clause requires a condition expression.");let item=ValueParser.parseFromLexeme(lexemes,idx),clause=new WhereClause(item.value);return clause.comments=whereTokenComments,wherePositionedComments&&wherePositionedComments.length>0&&(clause.positionedComments=wherePositionedComments.map(comment=>({position:comment.position,comments:[...comment.comments]}))),{value:clause,newIndex:item.newIndex}}};var GroupByClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The GROUP BY clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="group by")throw new Error(`Syntax error at position ${idx}: Expected 'GROUP BY' keyword but found "${lexemes[idx].value}". GROUP BY clauses must start with the GROUP BY keywords.`);if(idx++,idx>=lexemes.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 items=[],item=this.parseItem(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=this.parseItem(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No grouping expressions found. The GROUP BY clause requires at least one expression to group by.`);return{value:new GroupByClause(items),newIndex:idx}}static parseItem(lexemes,index){let idx=index,parsedValue=ValueParser.parseFromLexeme(lexemes,idx),value=parsedValue.value;return idx=parsedValue.newIndex,{value,newIndex:idx}}};var HavingClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The HAVING clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="having")throw new Error(`Syntax error at position ${idx}: Expected 'HAVING' keyword but found "${lexemes[idx].value}". HAVING clauses must start with the HAVING keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'HAVING' keyword. The HAVING clause requires a condition expression.");let item=ValueParser.parseFromLexeme(lexemes,idx);return{value:new HavingClause(item.value),newIndex:item.newIndex}}};var WindowClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The WINDOW clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="window")throw new Error(`Syntax error at position ${idx}: Expected 'WINDOW' keyword but found "${lexemes[idx].value}". WINDOW clauses must start with the WINDOW keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'WINDOW' keyword. The WINDOW clause requires at least one window definition.");let windows=[];for(;idx<lexemes.length;){if(idx>=lexemes.length||lexemes[idx].type!==64)throw new Error("Syntax error: Expected window name after 'WINDOW' keyword.");let name=lexemes[idx].value;if(idx++,idx>=lexemes.length||lexemes[idx].value!=="as")throw new Error(`Syntax error at position ${idx}: Expected 'AS' keyword after window name.`);idx++;let expr=WindowExpressionParser.parseFromLexeme(lexemes,idx);if(idx=expr.newIndex,windows.push(new WindowFrameClause(name,expr.value)),idx<lexemes.length&&lexemes[idx].type&16)idx++;else break}if(windows.length===0)throw new Error("At least one WINDOW clause is required after WINDOW keyword.");return{value:new WindowsClause(windows),newIndex:idx}}};var LimitClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The LIMIT clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="limit")throw new Error(`Syntax error at position ${idx}: Expected 'LIMIT' keyword but found "${lexemes[idx].value}". LIMIT clauses must start with the LIMIT keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'LIMIT' keyword. The LIMIT clause requires a numeric expression.");let limitItem=ValueParser.parseFromLexeme(lexemes,idx);return idx=limitItem.newIndex,{value:new LimitClause(limitItem.value),newIndex:idx}}};var ForClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The FOR clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value.toLowerCase()!=="for")throw new Error(`Syntax error at position ${idx}: Expected 'FOR' keyword but found "${lexemes[idx].value}". FOR clauses must start with the FOR keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FOR' keyword. The FOR clause requires a lock mode specification.");let lockModeValue=lexemes[idx].value,lockMode;switch(lockModeValue){case"update":lockMode="update",idx++;break;case"share":lockMode="share",idx++;break;case"key share":lockMode="key share",idx++;break;case"no key update":lockMode="no key update",idx++;break;default:throw new Error(`Syntax error at position ${idx}: Invalid lock mode "${lockModeValue}". Valid lock modes are: UPDATE, SHARE, KEY SHARE, NO KEY UPDATE.`)}return{value:new ForClause(lockMode),newIndex:idx}}};var CommonTableParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The CommonTable definition is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,aliasResult=SourceAliasExpressionParser.parseFromLexeme(lexemes,idx);idx=aliasResult.newIndex,this.collectPrecedingComments(lexemes,index,aliasResult),idx=this.parseAsKeyword(lexemes,idx);let{materialized,newIndex:materializedIndex}=this.parseMaterializedFlag(lexemes,idx);idx=materializedIndex;let{selectQuery,trailingComments,newIndex:selectIndex}=this.parseInnerSelectQuery(lexemes,idx);return idx=selectIndex,{value:new CommonTable(selectQuery,aliasResult.value,materialized),newIndex:idx,trailingComments}}static collectPrecedingComments(lexemes,index,aliasResult){if(!aliasResult.value?.table)return;let cteTable=aliasResult.value.table;for(let i=index-1;i>=0;i--){let token=lexemes[i];if(token.value.toLowerCase()==="with"){this.collectWithTokenComments(token,cteTable);break}if(token.type&16||token.value.toLowerCase()==="recursive")break;this.collectTokenComments(token,cteTable)}}static collectWithTokenComments(token,cteTable){let hasPositionedComments=!1;if(token.positionedComments&&token.positionedComments.length>0)for(let posComment of token.positionedComments)posComment.position==="after"&&posComment.comments&&(this.addPositionedComment(cteTable,"before",posComment.comments),hasPositionedComments=!0);!hasPositionedComments&&token.comments&&token.comments.length>0&&this.addPositionedComment(cteTable,"before",token.comments)}static collectTokenComments(token,cteTable){token.comments&&token.comments.length>0&&this.addPositionedComment(cteTable,"before",token.comments),token.positionedComments&&token.positionedComments.length>0&&(cteTable.positionedComments||(cteTable.positionedComments=[]),cteTable.positionedComments.unshift(...token.positionedComments))}static addPositionedComment(cteTable,position,comments){cteTable.positionedComments||(cteTable.positionedComments=[]),cteTable.positionedComments.unshift({position,comments:[...comments]})}static parseAsKeyword(lexemes,index){if(index<lexemes.length&&lexemes[index].value!=="as")throw new Error(`Syntax error at position ${index}: Expected 'AS' keyword after CTE name but found "${lexemes[index].value}".`);return index+1}static parseMaterializedFlag(lexemes,index){if(index>=lexemes.length)return{materialized:null,newIndex:index};let currentValue=lexemes[index].value;return currentValue==="materialized"?{materialized:!0,newIndex:index+1}:currentValue==="not materialized"?{materialized:!1,newIndex:index+1}:{materialized:null,newIndex:index}}static parseInnerSelectQuery(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type!==4)throw new Error(`Syntax error at position ${idx}: Expected '(' after CTE name but found "${lexemes[idx].value}".`);let cteQueryHeaderComments=this.extractComments(lexemes[idx]);idx++;let queryResult=SelectQueryParser.parseFromLexeme(lexemes,idx);if(idx=queryResult.newIndex,cteQueryHeaderComments.length>0&&(queryResult.value.headerComments?queryResult.value.headerComments=[...cteQueryHeaderComments,...queryResult.value.headerComments]:queryResult.value.headerComments=cteQueryHeaderComments),idx<lexemes.length&&lexemes[idx].type!==8)throw new Error(`Syntax error at position ${idx}: Expected ')' after CTE query but found "${lexemes[idx].value}".`);let closingParenComments=this.extractComments(lexemes[idx]);return idx++,{selectQuery:queryResult.value,trailingComments:closingParenComments.length>0?closingParenComments:null,newIndex:idx}}static extractComments(lexeme){let comments=[];if(lexeme.positionedComments)for(let posComment of lexeme.positionedComments)posComment.comments&&comments.push(...posComment.comments);return lexeme.comments&&lexeme.comments.length>0&&comments.push(...lexeme.comments),comments}};var WithClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The WITH clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,headerComments=this.extractWithTokenHeaderComments(lexemes,idx);idx=this.parseWithKeyword(lexemes,idx);let{recursive,newIndex:recursiveIndex}=this.parseRecursiveFlag(lexemes,idx);idx=recursiveIndex;let{tables,trailingComments,newIndex:ctesIndex}=this.parseAllCommonTables(lexemes,idx);idx=ctesIndex;let withClause=new WithClause(recursive,tables);return trailingComments.length>0&&(withClause.trailingComments=trailingComments),{value:withClause,newIndex:idx,headerComments}}static extractWithTokenHeaderComments(lexemes,index){if(index>=lexemes.length)return null;let withToken=lexemes[index],headerComments=null;if(withToken.positionedComments&&withToken.positionedComments.length>0)for(let posComment of withToken.positionedComments)posComment.position==="before"&&posComment.comments&&(headerComments||(headerComments=[]),headerComments.push(...posComment.comments));return!headerComments&&withToken.comments&&withToken.comments.length>0&&(headerComments=[...withToken.comments]),headerComments}static parseWithKeyword(lexemes,index){if(index<lexemes.length&&lexemes[index].value.toLowerCase()==="with")return index+1;throw new Error(`Syntax error at position ${index}: Expected WITH keyword.`)}static parseRecursiveFlag(lexemes,index){let recursive=index<lexemes.length&&lexemes[index].value.toLowerCase()==="recursive";return{recursive,newIndex:recursive?index+1:index}}static parseAllCommonTables(lexemes,index){let idx=index,tables=[],allTrailingComments=[],firstCte=CommonTableParser.parseFromLexeme(lexemes,idx);for(tables.push(firstCte.value),idx=firstCte.newIndex,firstCte.trailingComments&&allTrailingComments.push(...firstCte.trailingComments);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let cteResult=CommonTableParser.parseFromLexeme(lexemes,idx);tables.push(cteResult.value),idx=cteResult.newIndex,cteResult.trailingComments&&allTrailingComments.push(...cteResult.trailingComments)}return{tables,trailingComments:allTrailingComments,newIndex:idx}}};var ValuesQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The VALUES clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(idx>=lexemes.length)throw new Error(`Syntax error at position ${idx}: Expected 'VALUES' keyword but input ended early.`);let valuesLexeme=lexemes[idx];if(valuesLexeme.value.toLowerCase()!=="values")throw new Error(`Syntax error at position ${idx}: Expected 'VALUES' keyword but found "${valuesLexeme.value}". VALUES clauses must start with the VALUES keyword.`);let valuesComments=extractLexemeComments(valuesLexeme);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'VALUES' keyword. The VALUES clause requires at least one tuple expression.");let tuples=[],firstTuple=this.parseTuple(lexemes,idx);for(tuples.push(firstTuple.value),idx=firstTuple.newIndex,valuesComments.after.length>0&&firstTuple.value.addPositionedComments("before",valuesComments.after);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let tuple=this.parseTuple(lexemes,idx);tuples.push(tuple.value),idx=tuple.newIndex}let query=new ValuesQuery(tuples);return valuesComments.before.length>0&&(query.headerComments=valuesComments.before),{value:query,newIndex:idx}}static parseTuple(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].type!==4)throw new Error(`Syntax error at position ${idx}: Expected opening parenthesis but found "${idx<lexemes.length?lexemes[idx].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);let openingComments=extractLexemeComments(lexemes[idx]);idx++;let values=[];if(idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after opening parenthesis in tuple expression.");if(lexemes[idx].type&8){let tuple2=new TupleExpression([]),closingComments2=extractLexemeComments(lexemes[idx]);return idx++,openingComments.before.length>0&&tuple2.addPositionedComments("before",openingComments.before),closingComments2.after.length>0&&tuple2.addPositionedComments("after",closingComments2.after),{value:tuple2,newIndex:idx}}let firstValue=ValueParser.parseFromLexeme(lexemes,idx);for(values.push(firstValue.value),idx=firstValue.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after comma in tuple expression.");let value=ValueParser.parseFromLexeme(lexemes,idx);values.push(value.value),idx=value.newIndex}if(idx>=lexemes.length||lexemes[idx].type!==8)throw new Error(`Syntax error at position ${idx}: Expected closing parenthesis but found "${idx<lexemes.length?lexemes[idx].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);let closingComments=extractLexemeComments(lexemes[idx]);idx++;let tuple=new TupleExpression(values);return openingComments.before.length>0&&tuple.addPositionedComments("before",openingComments.before),openingComments.after.length>0&&values.length>0&&values[0].addPositionedComments("before",openingComments.after),closingComments.before.length>0&&values.length>0&&values[values.length-1].addPositionedComments("after",closingComments.before),closingComments.after.length>0&&tuple.addPositionedComments("after",closingComments.after),{value:tuple,newIndex:idx}}};var FetchClauseParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="fetch")throw new Error(`Syntax error at position ${idx}: Expected 'FETCH' keyword but found "${lexemes[idx].value}".`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH' keyword.");let fetchExprResult=FetchExpressionParser.parseFromLexeme(lexemes,idx),fetchExpr=fetchExprResult.value;return idx=fetchExprResult.newIndex,{value:new FetchClause(fetchExpr),newIndex:idx}}},FetchExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index,type,typeToken=lexemes[idx].value;if(typeToken==="first")type="first";else if(typeToken==="next")type="next";else throw new Error(`Syntax error at position ${idx}: Expected 'FIRST' or 'NEXT' after 'FETCH' but found "${lexemes[idx].value}".`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT'.");let count=null,unit=null;if(lexemes[idx].value==="row only"||lexemes[idx].value==="rows only")return count=new LiteralValue(1),unit="rows only",idx++,{value:new FetchExpression(type,count,unit),newIndex:idx};let countResult=ValueParser.parseFromLexeme(lexemes,idx);if(count=countResult.value,idx=countResult.newIndex,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT <count>'.");if(lexemes[idx].value==="rows only"?(unit="rows only",idx++):lexemes[idx].value==="percent"?(unit="percent",idx++):lexemes[idx].value==="percent with ties"&&(unit="percent with ties",idx++),!unit)throw new Error("Syntax error: Expected 'ROWS ONLY', 'PERCENT', or 'PERCENT WITH TIES' after 'FETCH FIRST|NEXT <count>'.");return{value:new FetchExpression(type,count,unit),newIndex:idx}}};var OffsetClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The OFFSET clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="offset")throw new Error(`Syntax error at position ${idx}: Expected 'OFFSET' keyword but found "${lexemes[idx].value}". OFFSET clauses must start with the OFFSET keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'OFFSET' keyword. The OFFSET clause requires a numeric expression.");let offsetItem=ValueParser.parseFromLexeme(lexemes,idx);return idx=offsetItem.newIndex,idx<lexemes.length&&(lexemes[idx].value==="row"||lexemes[idx].value==="rows")&&idx++,{value:new OffsetClause(offsetItem.value),newIndex:idx}}};var LexemeCursor=class{static{this.SQL_COMMANDS=new Set(["select","from","where","and","or","order","by","group","having","limit","offset","as","on","inner","left","right","join","union","insert","update","delete","into","values","set"])}static findLexemeAtLineColumn(sql,position){let charOffset=this.lineColumnToCharOffset(sql,position);return charOffset===-1?null:this.findLexemeAtPosition(sql,charOffset)}static findLexemeAtPosition(sql,cursorPosition){if(cursorPosition<0||cursorPosition>=sql.length)return null;let lexemes=this.getAllLexemesWithPosition(sql);for(let lexeme of lexemes)if(lexeme.position&&cursorPosition>=lexeme.position.startPosition&&cursorPosition<lexeme.position.endPosition)return lexeme;return null}static getAllLexemesWithPosition(sql){if(!sql?.trim())return[];try{let lexemes=[],position=0;for(;position<sql.length&&(position=this.skipWhitespaceAndComments(sql,position),!(position>=sql.length));){let lexeme=this.parseNextToken(sql,position);lexeme?(lexemes.push(lexeme),position=lexeme.position.endPosition):position++}return lexemes}catch{return[]}}static skipWhitespaceAndComments(sql,position){return StringUtils.readWhiteSpaceAndComment(sql,position).position}static parseNextToken(sql,startPos){let char=sql[startPos];return char==="'"||char==='"'?this.parseStringLiteral(sql,startPos):/[=<>!+\-*/%().*]/.test(char)?this.parseOperator(sql,startPos):char===","?this.createLexeme(16,",",startPos,startPos+1):/[a-zA-Z0-9_]/.test(char)?this.parseWordToken(sql,startPos):null}static parseStringLiteral(sql,startPos){let quote=sql[startPos],position=startPos+1,token=quote;for(;position<sql.length&&sql[position]!==quote;)token+=sql[position++];return position<sql.length&&(token+=sql[position++]),this.createLexeme(1,token,startPos,position)}static parseOperator(sql,startPos){let token=sql[startPos],position=startPos+1;position<sql.length&&/[=<>!]/.test(sql[position])&&/[=<>!]/.test(token)&&(token+=sql[position++]);let tokenType=this.getOperatorTokenType(token);return this.createLexeme(tokenType,token,startPos,position)}static parseWordToken(sql,startPos){let position=startPos,token="";for(;position<sql.length&&/[a-zA-Z0-9_]/.test(sql[position]);)token+=sql[position++];let tokenType=this.getWordTokenType(token,sql,position),value=this.shouldLowercase(tokenType)?token.toLowerCase():token;return this.createLexeme(tokenType,value,startPos,position)}static getOperatorTokenType(token){switch(token){case"(":return 4;case")":return 8;case"*":return 64;default:return 2}}static getWordTokenType(token,sql,position){let lowerToken=token.toLowerCase();if(this.SQL_COMMANDS.has(lowerToken))return 128;let nextNonWhitespacePos=this.skipWhitespaceAndComments(sql,position);return nextNonWhitespacePos<sql.length&&sql[nextNonWhitespacePos]==="("?2048:64}static shouldLowercase(tokenType){return!!(tokenType&128)||!!(tokenType&2)||!!(tokenType&2048)}static createLexeme(type,value,startPos,endPos){return{type,value,comments:null,position:{startPosition:startPos,endPosition:endPos}}}static lineColumnToCharOffset(sql,position){if(position.line<1||position.column<1)return-1;let lines=sql.split(`
28
+ `:this.newline,currentLevel=this.linePrinter.getCurrentLine()?.level??level,baseIndent=this.getIndentString(currentLevel),innerIndent=baseIndent+" ",body=lines.map(line=>`${innerIndent}${line}`).join(newline),closing=`${baseIndent}*/`;return`/*${newline}${body}${newline}${closing}`}getIndentString(level){return level<=0?"":this.indentSize<=0?" ".repeat(level):(typeof this.indentChar=="string"?this.indentChar:"").repeat(this.indentSize*level)}sanitizeCommentLine(content){let sanitized=content;return sanitized=sanitized.replace(/\u2028|\u2029/g," "),sanitized=sanitized.replace(/\s+/g," ").trim(),sanitized}escapeCommentDelimiters(content){return content.replace(/\/\*/g,"\\/\\*").replace(/\*\//g,"*\\/")}getCommentBaseIndentLevel(level,parentContainerType){if(!parentContainerType)return level;let clauseAlignedLevel=this.getClauseBreakIndentLevel(parentContainerType,level);return Math.max(level,clauseAlignedLevel)}resolveCommentIndentLevel(level,parentContainerType){let baseLevel=this.getCommentBaseIndentLevel(level,parentContainerType),currentLevel=this.linePrinter.getCurrentLine().level??baseLevel;return Math.max(baseLevel,currentLevel)}handleCommentNewlineToken(token,level){if(!this.smartCommentBlockBuilder){if(this.pendingLineCommentBreak!==null){this.linePrinter.appendNewline(this.pendingLineCommentBreak),this.pendingLineCommentBreak=null;return}this.shouldSkipCommentNewline()||this.isOnelineMode()||this.linePrinter.appendNewline(level)}}shouldSkipCommentNewline(){return this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.withClauseStyle==="cte-oneline"}shouldAddNewlineBeforeLeadingComments(parentType){return parentType?parentType==="TupleExpression"?!0:parentType==="InsertClause"||parentType==="MergeInsertAction"?!this.insertColumnsOneLine:parentType==="SetClause"||parentType==="SelectClause"||parentType==="ExplainStatement":!1}getLeadingCommentIndentLevel(parentType,currentLevel){return parentType==="TupleExpression"||parentType==="InsertClause"||parentType==="MergeInsertAction"||parentType==="SelectClause"||parentType==="SetClause"?currentLevel+1:currentLevel}isOnelineMode(){return this.newline===" "}handleCteOnelineToken(token,level){let onelineResult=this.createCteOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);cleanedResult=cleanedResult.replace(/\(\s+/g,"(").replace(/\s+\)/g," )"),this.linePrinter.appendText(cleanedResult.trim())}createCteOnelinePrinter(){return new _SqlPrinter({indentChar:"",indentSize:0,newline:" ",commaBreak:this.commaBreak,cteCommaBreak:this.cteCommaBreak,valuesCommaBreak:this.valuesCommaBreak,andBreak:this.andBreak,orBreak:this.orBreak,keywordCase:this.keywordCase,exportComment:"none",withClauseStyle:"standard",indentNestedParentheses:!1,insertColumnsOneLine:this.insertColumnsOneLine})}handleOnelineToken(token,level){let onelineResult=this.createOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);this.linePrinter.appendText(cleanedResult)}getClauseBreakIndentLevel(parentType,level){if(!parentType)return level;switch(parentType){case"MergeWhenClause":return level+1;case"MergeUpdateAction":case"MergeDeleteAction":case"MergeInsertAction":return level+1;default:return level}}isMergeActionContainer(token){if(!token)return!1;switch(token.containerType){case"MergeUpdateAction":case"MergeDeleteAction":case"MergeInsertAction":case"MergeDoNothingAction":return!0;default:return!1}}shouldBreakAfterOpeningParen(parentType){return parentType&&(parentType==="InsertClause"||parentType==="MergeInsertAction")?!this.isInsertClauseOneline(parentType):!1}shouldBreakBeforeClosingParen(parentType){return parentType&&(parentType==="InsertClause"||parentType==="MergeInsertAction")?!this.isInsertClauseOneline(parentType):!1}shouldConvertSpaceToClauseBreak(parentType,nextToken){if(!parentType||!nextToken)return!1;let nextKeyword=nextToken.type===1?nextToken.text.toLowerCase():null,nextContainer=nextToken.containerType;return!!(parentType==="MergeQuery"&&(nextKeyword==="using"||nextContainer==="MergeWhenClause")||parentType==="MergeWhenClause"&&(nextContainer==="MergeUpdateAction"||nextContainer==="MergeDeleteAction"||nextContainer==="MergeInsertAction"||nextContainer==="MergeDoNothingAction")||parentType==="UpdateQuery"&&(nextKeyword==="set"||nextKeyword==="from"||nextKeyword==="where"||nextKeyword==="returning")||parentType==="InsertQuery"&&(nextKeyword==="returning"||nextKeyword&&(nextKeyword.startsWith("select")||nextKeyword.startsWith("values"))||nextContainer==="ValuesQuery"||nextContainer==="SimpleSelectQuery"||nextContainer==="InsertClause")||parentType==="DeleteQuery"&&(nextKeyword==="using"||nextKeyword==="where"||nextKeyword==="returning")||(parentType==="MergeUpdateAction"||parentType==="MergeDeleteAction")&&nextKeyword==="where"||parentType==="MergeInsertAction"&&nextKeyword&&(nextKeyword.startsWith("values")||nextKeyword==="default values"))}createOnelinePrinter(){return new _SqlPrinter({indentChar:"",indentSize:0,newline:" ",commaBreak:"none",cteCommaBreak:this.cteCommaBreak,valuesCommaBreak:"none",andBreak:"none",orBreak:"none",keywordCase:this.keywordCase,exportComment:this.commentExportMode,commentStyle:this.commentStyle,withClauseStyle:"standard",parenthesesOneLine:!1,betweenOneLine:!1,valuesOneLine:!1,joinOneLine:!1,caseOneLine:!1,subqueryOneLine:!1,indentNestedParentheses:!1,insertColumnsOneLine:this.insertColumnsOneLine})}cleanDuplicateSpaces(text){return text.replace(/\s{2,}/g," ")}};var VALID_PRESETS=["mysql","postgres","sqlserver","sqlite"],SqlFormatter=class{constructor(options={}){let presetConfig=options.preset?PRESETS[options.preset]:void 0;if(options.preset&&!presetConfig)throw new Error(`Invalid preset: ${options.preset}`);let resolvedIdentifierEscape=resolveIdentifierEscapeOption(options.identifierEscape??presetConfig?.identifierEscape),parserOptions={...presetConfig,identifierEscape:resolvedIdentifierEscape??presetConfig?.identifierEscape,parameterSymbol:options.parameterSymbol??presetConfig?.parameterSymbol,parameterStyle:options.parameterStyle??presetConfig?.parameterStyle,castStyle:options.castStyle??presetConfig?.castStyle,joinConditionOrderByDeclaration:options.joinConditionOrderByDeclaration},constraintStyle=options.constraintStyle??presetConfig?.constraintStyle??"postgres",parserConfig={...parserOptions,constraintStyle};this.parser=new SqlPrintTokenParser({...parserConfig});let normalizedExportComment=options.exportComment===!0?"full":options.exportComment===!1?"none":options.exportComment,printerOptions={...options,exportComment:normalizedExportComment,parenthesesOneLine:options.parenthesesOneLine,betweenOneLine:options.betweenOneLine,valuesOneLine:options.valuesOneLine,joinOneLine:options.joinOneLine,caseOneLine:options.caseOneLine,subqueryOneLine:options.subqueryOneLine,indentNestedParentheses:options.indentNestedParentheses};this.printer=new SqlPrinter(printerOptions)}format(sql){let{token,params}=this.parser.parse(sql);return{formattedSql:this.printer.print(token),params}}};var Formatter=class{constructor(){this.sqlFormatter=new SqlFormatter({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(arg,config=null){return config&&(this.sqlFormatter=new SqlFormatter(config)),this.sqlFormatter.format(arg).formattedSql}formatWithParameters(arg,config=null){config&&(this.sqlFormatter=new SqlFormatter(config));let result=this.sqlFormatter.format(arg);return{sql:result.formattedSql,params:result.params}}visit(arg){return this.format(arg)}};var CTEBuilder=class{constructor(){this.sourceCollector=new TableSourceCollector(!0),this.cteCollector=new CTECollector,this.formatter=new Formatter}build(commonTables){if(commonTables.length===0)return new WithClause(!1,commonTables);let resolvedTables=this.resolveDuplicateNames(commonTables),{tableMap,recursiveCTEs,dependencies}=this.buildDependencyGraph(resolvedTables),sortedTables=this.sortCommonTables(resolvedTables,tableMap,recursiveCTEs,dependencies);return new WithClause(recursiveCTEs.size>0,sortedTables)}resolveDuplicateNames(commonTables){let ctesByName=new Map;for(let table of commonTables){let tableName=table.aliasExpression.table.name;ctesByName.has(tableName)||ctesByName.set(tableName,[]),ctesByName.get(tableName).push(table)}let resolvedTables=[];for(let[name,tables]of Array.from(ctesByName.entries())){if(tables.length===1){resolvedTables.push(tables[0]);continue}let definitions=tables.map(table=>this.formatter.format(table.query));if(new Set(definitions).size===1)resolvedTables.push(tables[0]);else throw new Error(`CTE name conflict detected: '${name}' has multiple different definitions`)}return resolvedTables}buildDependencyGraph(tables){let tableMap=new Map;for(let table of tables)tableMap.set(table.aliasExpression.table.name,table);let recursiveCTEs=new Set,dependencies=new Map,referencedBy=new Map;for(let table of tables){let tableName=table.aliasExpression.table.name,referencedTables=this.sourceCollector.collect(table.query);for(let referencedTable of referencedTables)if(referencedTable.table.name===tableName){recursiveCTEs.add(tableName);break}dependencies.has(tableName)||dependencies.set(tableName,new Set);let referencedCTEs=this.cteCollector.collect(table.query);for(let referencedCTE of referencedCTEs){let referencedName=referencedCTE.aliasExpression.table.name;tableMap.has(referencedName)&&(dependencies.get(tableName).add(referencedName),referencedBy.has(referencedName)||referencedBy.set(referencedName,new Set),referencedBy.get(referencedName).add(tableName))}}return{tableMap,recursiveCTEs,dependencies}}sortCommonTables(tables,tableMap,recursiveCTEs,dependencies){let recursiveResult=[],nonRecursiveResult=[],visited=new Set,visiting=new Set,visit=tableName=>{if(visited.has(tableName))return;if(visiting.has(tableName))throw new Error(`Circular reference detected in CTE: ${tableName}`);visiting.add(tableName);let deps=dependencies.get(tableName)||new Set;for(let dep of Array.from(deps))visit(dep);visiting.delete(tableName),visited.add(tableName),recursiveCTEs.has(tableName)?recursiveResult.push(tableMap.get(tableName)):nonRecursiveResult.push(tableMap.get(tableName))};for(let table of tables){let tableName=table.aliasExpression.table.name;visited.has(tableName)||visit(tableName)}return[...recursiveResult,...nonRecursiveResult]}};var CTEInjector=class{constructor(){this.nameConflictResolver=new CTEBuilder,this.cteCollector=new CTECollector}inject(query,commonTables){if(commonTables.length===0)return query;commonTables.push(...this.cteCollector.collect(query));let resolvedWithCaluse=this.nameConflictResolver.build(commonTables);if(query instanceof SimpleSelectQuery)return this.injectIntoSimpleQuery(query,resolvedWithCaluse);if(query instanceof BinarySelectQuery)return this.injectIntoBinaryQuery(query,resolvedWithCaluse);throw new Error("Unsupported query type")}injectIntoSimpleQuery(query,withClause){if(query.withClause)throw new Error("The query already has a WITH clause. Please remove it before injecting new CTEs.");return query.withClause=withClause,query}injectIntoBinaryQuery(query,withClause){if(query.left instanceof SimpleSelectQuery)return this.injectIntoSimpleQuery(query.left,withClause),query;if(query.left instanceof BinarySelectQuery)return this.injectIntoBinaryQuery(query.left,withClause),query;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var CTENormalizer=class{constructor(){}static normalize(query){let allCommonTables=new CTECollector().collect(query);return allCommonTables.length===0?query:(new CTEDisabler().execute(query),new CTEInjector().inject(query,allCommonTables))}};var DuplicateDetectionMode=(DuplicateDetectionMode2=>(DuplicateDetectionMode2.ColumnNameOnly="columnNameOnly",DuplicateDetectionMode2.FullName="fullName",DuplicateDetectionMode2))(DuplicateDetectionMode||{}),SelectableColumnCollector=class _SelectableColumnCollector{constructor(tableColumnResolver,includeWildCard=!1,duplicateDetection="columnNameOnly",options){this.selectValues=[];this.visitedNodes=new Set;this.uniqueKeys=new Set;this.isRootVisit=!0;this.tableColumnResolver=null;this.commonTables=[];this.initializeProperties(tableColumnResolver,includeWildCard,duplicateDetection,options),this.initializeHandlers()}initializeProperties(tableColumnResolver,includeWildCard,duplicateDetection,options){this.tableColumnResolver=tableColumnResolver??null,this.includeWildCard=includeWildCard,this.commonTableCollector=new CTECollector,this.commonTables=[],this.duplicateDetection=duplicateDetection,this.options=options||{}}initializeHandlers(){this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.initializeClauseHandlers(),this.initializeValueComponentHandlers()}initializeClauseHandlers(){this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.offsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr))}initializeValueComponentHandlers(){this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}getValues(){return this.selectValues}collect(arg){if(!arg)throw new Error("Input argument cannot be null or undefined");this.visit(arg);let items=this.getValues();return this.reset(),items}reset(){this.selectValues=[],this.visitedNodes.clear(),this.uniqueKeys.clear(),this.commonTables=[]}addSelectValueAsUnique(name,value){let key=this.generateUniqueKey(name,value);this.uniqueKeys.has(key)||(this.uniqueKeys.add(key),this.selectValues.push({name,value}))}generateUniqueKey(name,value){if(this.duplicateDetection==="columnNameOnly")return this.normalizeColumnName(name);{let tableName="";value&&typeof value.getNamespace=="function"&&(tableName=value.getNamespace()||"");let fullName=tableName?tableName+"."+name:name;return this.normalizeColumnName(fullName)}}normalizeColumnName(name){if(typeof name!="string")throw new Error("Column name must be a string");return this.options.ignoreCaseAndUnderscore?name.toLowerCase().replace(/_/g,""):name}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}if(!(arg instanceof SimpleSelectQuery||arg instanceof BinarySelectQuery))throw new Error("Root visit requires a SimpleSelectQuery or BinarySelectQuery.");this.reset(),this.isRootVisit=!1,this.commonTables=this.commonTableCollector.collect(arg);try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(!this.visitedNodes.has(arg)){this.visitedNodes.add(arg);try{let handler=this.handlers.get(arg.getKind());handler&&handler(arg)}catch(error){let errorMessage=error instanceof Error?error.message:String(error);throw new Error(`Error processing SQL component of type ${arg.getKind().toString()}: ${errorMessage}`)}}}visitSimpleSelectQuery(query){if(query.selectClause&&query.selectClause.accept(this),query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.orderByClause&&query.orderByClause.accept(this),query.limitClause&&query.limitClause.accept(this),query.offsetClause&&query.offsetClause.accept(this),query.fetchClause&&query.fetchClause.accept(this),query.forClause&&query.forClause.accept(this)}visitBinarySelectQuery(query){query.left instanceof SimpleSelectQuery?this.visitSimpleSelectQuery(query.left):query.left instanceof BinarySelectQuery&&this.visitBinarySelectQuery(query.left),query.right instanceof SimpleSelectQuery?this.visitSimpleSelectQuery(query.right):query.right instanceof BinarySelectQuery&&this.visitBinarySelectQuery(query.right)}visitSelectClause(clause){for(let item of clause.items)if(item.identifier)this.addSelectValueAsUnique(item.identifier.name,item.value);else if(item.value instanceof ColumnReference){let columnName=item.value.column.name;columnName!=="*"?this.addSelectValueAsUnique(columnName,item.value):this.includeWildCard&&this.addSelectValueAsUnique(columnName,item.value)}else item.value.accept(this)}visitFromClause(clause){let sourceValues=new SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(clause);for(let item of sourceValues)this.addSelectValueAsUnique(item.name,item.value);if(this.options.upstream&&this.collectUpstreamColumns(clause),clause.joins)for(let join of clause.joins)join.condition&&join.condition.accept(this)}visitWhereClause(clause){clause.condition&&clause.condition.accept(this)}visitGroupByClause(clause){if(clause.grouping)for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition&&clause.condition.accept(this)}visitOrderByClause(clause){if(clause.order)for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitWindowFrameExpression(expr){expr.partition&&expr.partition.accept(this),expr.order&&expr.order.accept(this),expr.frameSpec&&expr.frameSpec.accept(this)}visitLimitClause(clause){clause.value&&clause.value.accept(this)}offsetClause(clause){clause.value&&clause.value.accept(this)}visitFetchClause(clause){clause.expression&&clause.expression.accept(this)}visitJoinOnClause(joinOnClause){joinOnClause.condition&&joinOnClause.condition.accept(this)}visitJoinUsingClause(joinUsingClause){joinUsingClause.condition&&joinUsingClause.condition.accept(this)}visitColumnReference(columnRef){if(columnRef.column.name!=="*")this.addSelectValueAsUnique(columnRef.column.name,columnRef);else if(this.includeWildCard)this.addSelectValueAsUnique(columnRef.column.name,columnRef);else return}visitBinaryExpression(expr){expr.left&&expr.left.accept(this),expr.right&&expr.right.accept(this)}visitUnaryExpression(expr){expr.expression&&expr.expression.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this),func.withinGroup&&func.withinGroup.accept(this),func.internalOrderBy&&func.internalOrderBy.accept(this)}visitInlineQuery(inlineQuery){inlineQuery.selectQuery&&this.visitNode(inlineQuery.selectQuery)}visitParenExpression(expr){expr.expression&&expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase&&expr.switchCase.accept(this)}visitCastExpression(expr){expr.input&&expr.input.accept(this)}visitBetweenExpression(expr){expr.expression&&expr.expression.accept(this),expr.lower&&expr.lower.accept(this),expr.upper&&expr.upper.accept(this)}visitArrayExpression(expr){expr.expression&&expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitArraySliceExpression(expr){expr.array&&expr.array.accept(this),expr.startIndex&&expr.startIndex.accept(this),expr.endIndex&&expr.endIndex.accept(this)}visitArrayIndexExpression(expr){expr.array&&expr.array.accept(this),expr.index&&expr.index.accept(this)}visitValueList(expr){if(expr.values&&Array.isArray(expr.values))for(let value of expr.values)value&&value.accept(this)}visitPartitionByClause(clause){clause.value.accept(this)}collectUpstreamColumns(clause){if(this.collectAllAvailableCTEColumns(),this.collectUpstreamColumnsFromSource(clause.source),clause.joins)for(let join of clause.joins)this.collectUpstreamColumnsFromSource(join.source)}collectUpstreamColumnsFromSource(source){if(source.datasource instanceof TableSource){let cteTable=this.findCTEByName(source.datasource.table.name);cteTable?this.collectUpstreamColumnsFromCTE(cteTable):this.collectUpstreamColumnsFromTable(source.datasource)}else source.datasource instanceof SubQuerySource?this.collectUpstreamColumnsFromSubquery(source.datasource):source.datasource instanceof ParenSource&&this.collectUpstreamColumnsFromSource(new SourceExpression(source.datasource.source,null))}collectUpstreamColumnsFromTable(tableSource){if(this.tableColumnResolver){let tableName=tableSource.table.name,columns=this.tableColumnResolver(tableName);for(let columnName of columns){let columnRef=new ColumnReference(tableSource.table.name,columnName);this.addSelectValueAsUnique(columnName,columnRef)}}}collectUpstreamColumnsFromSubquery(subquerySource){if(subquerySource.query instanceof SimpleSelectQuery){let subqueryColumns=new _SelectableColumnCollector(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!0}).collect(subquerySource.query);for(let item of subqueryColumns)this.addSelectValueAsUnique(item.name,item.value)}}collectUpstreamColumnsFromCTE(cteTable){if(cteTable.query instanceof SimpleSelectQuery){let cteColumns=new _SelectableColumnCollector(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!1}).collect(cteTable.query);for(let item of cteColumns)item.name!=="*"&&this.addSelectValueAsUnique(item.name,item.value)}}collectAllAvailableCTEColumns(){for(let cte of this.commonTables)this.collectUpstreamColumnsFromCTE(cte)}findCTEByName(name){return this.commonTables.find(cte=>cte.getSourceAliasName()===name)||null}};var SourceParser=class _SourceParser{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The source component is complete but there are additional tokens.`);return result.value}static parseTableSourceFromLexemes(lexemes,index){let fullNameResult=FullNameParser.parseFromLexeme(lexemes,index);return this.parseTableSource(fullNameResult)}static parseFromLexeme(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&4)return this.parseParenSource(lexemes,idx);let fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx);return fullNameResult.lastTokenType&2048?_SourceParser.parseFunctionSource(lexemes,fullNameResult):_SourceParser.parseTableSource(fullNameResult)}static parseTableSource(fullNameResult){let{namespaces,name,newIndex}=fullNameResult,value=new TableSource(namespaces,name.name);return name.positionedComments&&name.positionedComments.length>0?value.positionedComments=name.positionedComments:name.comments&&name.comments.length>0&&(value.comments=name.comments),{value,newIndex}}static parseFunctionSource(lexemes,fullNameResult){let idx=fullNameResult.newIndex,{namespaces,name}=fullNameResult,argument=ValueParser.parseArgument(4,8,lexemes,idx);idx=argument.newIndex;let functionName=name.name;return{value:new FunctionSource({namespaces,name:functionName},argument.value),newIndex:idx}}static parseParenSource(lexemes,index){let idx=index,openParenToken=lexemes[idx];if(idx++,idx>=lexemes.length)throw new Error(`Syntax error: Unexpected end of input at position ${idx}. Expected a subquery or nested expression after opening parenthesis.`);let keyword=lexemes[idx].value;if(keyword==="select"||keyword==="values"||keyword==="with"){let result=this.parseSubQuerySource(lexemes,idx,openParenToken);if(idx=result.newIndex,idx<lexemes.length&&lexemes[idx].type==8)idx++;else throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:result.value,newIndex:idx}}else if(lexemes[idx].type==4){let result=this.parseParenSource(lexemes,idx);if(idx=result.newIndex,idx<lexemes.length&&lexemes[idx].type==8)idx++;else throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:result.value,newIndex:idx}}throw new Error(`Syntax error at position ${idx}: Expected 'SELECT' keyword, 'VALUES' keyword, or opening parenthesis '(' but found "${lexemes[idx].value}".`)}static parseSubQuerySource(lexemes,index,openParenToken){let idx=index,{value:selectQuery,newIndex}=SelectQueryParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,openParenToken&&openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let afterComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){let beforeComments=afterComments.map(pc=>({position:"before",comments:pc.comments}));selectQuery.positionedComments?selectQuery.positionedComments=[...beforeComments,...selectQuery.positionedComments]:selectQuery.positionedComments=beforeComments,selectQuery.comments&&(selectQuery.comments=null)}}return{value:new SubQuerySource(selectQuery),newIndex:idx}}};var DuplicateCTEError=class extends Error{constructor(cteName){super(`CTE '${cteName}' already exists in the query`);this.cteName=cteName;this.name="DuplicateCTEError"}},InvalidCTENameError=class extends Error{constructor(cteName,reason){super(`Invalid CTE name '${cteName}': ${reason}`);this.cteName=cteName;this.name="InvalidCTENameError"}},CTENotFoundError=class extends Error{constructor(cteName){super(`CTE '${cteName}' not found in the query`);this.cteName=cteName;this.name="CTENotFoundError"}};var UpstreamSelectQueryFinder=class{constructor(tableColumnResolver,options){this.options=options||{},this.tableColumnResolver=tableColumnResolver,this.columnCollector=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0})}find(query,columnNames){let namesArray=typeof columnNames=="string"?[columnNames]:columnNames,ctes=new CTECollector().collect(query),cteMap=new Map;for(let cte of ctes)cteMap.set(cte.getSourceAliasName(),cte);return this.findUpstream(query,namesArray,cteMap)}handleTableSource(src,columnNames,cteMap){let cte=cteMap.get(src.table.name);if(cte){let nextCteMap=new Map(cteMap);nextCteMap.delete(src.table.name);let result=this.findUpstream(cte.query,columnNames,nextCteMap);return result.length===0?null:result}return null}handleSubQuerySource(src,columnNames,cteMap){let result=this.findUpstream(src.query,columnNames,cteMap);return result.length===0?null:result}processFromClauseBranches(fromClause,columnNames,cteMap){let sources=fromClause.getSources();if(sources.length===0)return null;let allBranchResults=[],allBranchesOk=!0,validBranchCount=0;for(let sourceExpr of sources){let src=sourceExpr.datasource,branchResult=null;if(src instanceof TableSource)branchResult=this.handleTableSource(src,columnNames,cteMap),validBranchCount++;else if(src instanceof SubQuerySource)branchResult=this.handleSubQuerySource(src,columnNames,cteMap),validBranchCount++;else{if(src instanceof ValuesQuery)continue;allBranchesOk=!1;break}if(branchResult===null){allBranchesOk=!1;break}allBranchResults.push(branchResult)}return allBranchesOk&&allBranchResults.length===validBranchCount?allBranchResults.flat():null}findUpstream(query,columnNames,cteMap){if(query instanceof SimpleSelectQuery){let fromClause=query.fromClause;if(fromClause){let branchResult=this.processFromClauseBranches(fromClause,columnNames,cteMap);if(branchResult&&branchResult.length>0)return branchResult}let columns=this.columnCollector.collect(query).map(col=>col.name),cteColumns=this.collectCTEColumns(query,cteMap),allColumns=[...columns,...cteColumns],normalize=s=>this.options.ignoreCaseAndUnderscore?s.toLowerCase().replace(/_/g,""):s;return columnNames.every(name=>allColumns.some(col=>normalize(col)===normalize(name)))?[query]:[]}else if(query instanceof BinarySelectQuery){let left=this.findUpstream(query.left,columnNames,cteMap),right=this.findUpstream(query.right,columnNames,cteMap);return[...left,...right]}return[]}collectCTEColumns(query,cteMap){let cteColumns=[];if(query.withClause)for(let cte of query.withClause.tables){let columns=this.collectColumnsFromSelectQuery(cte.query);cteColumns.push(...columns)}return cteColumns}collectColumnsFromSelectQuery(query){if(query instanceof SimpleSelectQuery)try{return this.columnCollector.collect(query).map(col=>col.name)}catch(error){return console.warn("Failed to collect columns from SimpleSelectQuery:",error),[]}else if(query instanceof BinarySelectQuery)return this.collectColumnsFromSelectQuery(query.left);return[]}};var SourceAliasExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(idx<lexemes.length&&(lexemes[idx].type&64||lexemes[idx].type&2048)){let aliasToken=lexemes[idx],table=aliasToken.value;if(idx++,idx<lexemes.length&&lexemes[idx].type&4){let columns=[];for(idx++;idx<lexemes.length&&lexemes[idx].type&64&&(columns.push(lexemes[idx].value),idx++,idx<lexemes.length&&lexemes[idx].type&16);)idx++;if(lexemes[idx].type&8)idx++;else throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis ')' for column alias list. Each opening parenthesis must have a matching closing parenthesis.`);if(columns.length===0)throw new Error(`Syntax error at position ${index}: No column aliases found. Column alias declarations must contain at least one column name.`);let sourceAlias2=new SourceAliasExpression(table,columns);return aliasToken.positionedComments&&aliasToken.positionedComments.length>0&&(sourceAlias2.positionedComments=aliasToken.positionedComments),{value:sourceAlias2,newIndex:idx}}let sourceAlias=new SourceAliasExpression(table,null);return aliasToken.positionedComments&&aliasToken.positionedComments.length>0&&(sourceAlias.positionedComments=aliasToken.positionedComments),{value:sourceAlias,newIndex:idx}}throw new Error(`Syntax error at position ${index}: Expected an identifier for table alias but found "${lexemes[index]?.value||"end of input"}".`)}};var SourceExpressionParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The source expression is complete but there are additional tokens.`);return result.value}static parseTableSourceFromLexemes(lexemes,index){let result=SourceParser.parseTableSourceFromLexemes(lexemes,index);return{value:new SourceExpression(result.value,null),newIndex:result.newIndex}}static parseFromLexeme(lexemes,index){let idx=index,sourceResult=SourceParser.parseFromLexeme(lexemes,idx);if(idx=sourceResult.newIndex,idx<lexemes.length){if(lexemes[idx].value==="as"){idx++;let aliasResult=SourceAliasExpressionParser.parseFromLexeme(lexemes,idx);return idx=aliasResult.newIndex,{value:new SourceExpression(sourceResult.value,aliasResult.value),newIndex:idx}}if(idx<lexemes.length&&this.isTokenTypeAliasCandidate(lexemes[idx].type)){let aliasResult=SourceAliasExpressionParser.parseFromLexeme(lexemes,idx);return idx=aliasResult.newIndex,{value:new SourceExpression(sourceResult.value,aliasResult.value),newIndex:idx}}}return{value:new SourceExpression(sourceResult.value,null),newIndex:idx}}static isTokenTypeAliasCandidate(type){return(type&64)!==0||(type&2048)!==0}};var ParameterHelper=class{static set(query,name,value){let params=ParameterCollector.collect(query),found=!1;for(let p of params)p.name.value===name&&(p.value=value,found=!0);if(!found)throw new Error(`Parameter '${name}' not found in query.`)}};var ValuesQuery=class extends SqlComponent{constructor(tuples,columnAliases=null){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.tuples=tuples,this.columnAliases=columnAliases}static{this.kind=Symbol("ValuesQuery")}toSimpleQuery(){return QueryBuilder.buildSimpleQuery(this)}toInsertQuery(options){return this.toSimpleQuery().toInsertQuery(options)}toUpdateQuery(options){return this.toSimpleQuery().toUpdateQuery(options)}toDeleteQuery(options){return this.toSimpleQuery().toDeleteQuery(options)}toMergeQuery(options){return this.toSimpleQuery().toMergeQuery(options)}setParameter(name,value){return ParameterHelper.set(this,name,value),this}};var BinarySelectQuery=class _BinarySelectQuery extends SqlComponent{constructor(left,operator,right){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.left=left,this.operator=new RawString(operator),this.right=right}static{this.kind=Symbol("BinarySelectQuery")}union(query){return this.appendSelectQuery("union",query)}unionAll(query){return this.appendSelectQuery("union all",query)}intersect(query){return this.appendSelectQuery("intersect",query)}intersectAll(query){return this.appendSelectQuery("intersect all",query)}except(query){return this.appendSelectQuery("except",query)}exceptAll(query){return this.appendSelectQuery("except all",query)}appendSelectQuery(operator,query){return this.left=new _BinarySelectQuery(this.left,this.operator.value,this.right),this.operator=new RawString(operator),this.right=query,CTENormalizer.normalize(this),this}unionRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.union(parsedQuery)}unionAllRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.unionAll(parsedQuery)}intersectRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.intersect(parsedQuery)}intersectAllRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.intersectAll(parsedQuery)}exceptRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.except(parsedQuery)}exceptAllRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.exceptAll(parsedQuery)}toInsertQuery(options){return this.toSimpleQuery().toInsertQuery(options)}toUpdateQuery(options){return this.toSimpleQuery().toUpdateQuery(options)}toDeleteQuery(options){return this.toSimpleQuery().toDeleteQuery(options)}toMergeQuery(options){return this.toSimpleQuery().toMergeQuery(options)}toSource(alias="subq"){return new SourceExpression(new SubQuerySource(this),new SourceAliasExpression(alias,null))}setParameter(name,value){return ParameterHelper.set(this,name,value),this}toSimpleQuery(){return QueryBuilder.buildSimpleQuery(this)}};var InsertQuerySelectValuesConverter=class{static toSelectUnion(insertQuery){let valuesQuery=insertQuery.selectQuery;if(!(valuesQuery instanceof ValuesQuery))throw new Error("InsertQuery selectQuery is not a VALUES query.");if(!valuesQuery.tuples.length)throw new Error("VALUES query does not contain any tuples.");let columns=insertQuery.insertClause.columns;if(!columns||columns.length===0)throw new Error("Cannot convert to SELECT form without explicit column list.");let columnNames=columns.map(col=>col.name),selectQueries=valuesQuery.tuples.map(tuple=>{if(tuple.values.length!==columnNames.length)throw new Error("Tuple value count does not match column count.");let items=columnNames.map((name,idx)=>new SelectItem(tuple.values[idx],name)),selectClause=new SelectClause(items);return new SimpleSelectQuery({selectClause})}),combined=selectQueries[0];for(let i=1;i<selectQueries.length;i++)if(combined instanceof SimpleSelectQuery)combined=combined.toUnionAll(selectQueries[i]);else if(combined instanceof BinarySelectQuery)combined.appendSelectQuery("union all",selectQueries[i]);else throw new Error("Unsupported SelectQuery type during UNION ALL construction.");return new InsertQuery({withClause:insertQuery.withClause,insertClause:insertQuery.insertClause,selectQuery:combined,returning:insertQuery.returningClause})}static toValues(insertQuery){let columns=insertQuery.insertClause.columns;if(!columns||columns.length===0)throw new Error("Cannot convert to VALUES form without explicit column list.");if(!insertQuery.selectQuery)throw new Error("InsertQuery does not have a selectQuery to convert.");let columnNames=columns.map(col=>col.name),simpleQueries=this.flattenSelectQueries(insertQuery.selectQuery);if(!simpleQueries.length)throw new Error("No SELECT components found to convert.");let tuples=simpleQueries.map(query=>{if(query.fromClause||query.whereClause&&query.whereClause.condition)throw new Error("SELECT queries with FROM or WHERE clauses cannot be converted to VALUES.");let valueMap=new Map;for(let item of query.selectClause.items){let identifier=item.identifier?.name??null;if(!identifier)throw new Error("Each SELECT item must have an alias matching target columns.");valueMap.has(identifier)||valueMap.set(identifier,item.value)}let rowValues=columnNames.map(name=>{let value=valueMap.get(name);if(!value)throw new Error(`Column '${name}' is not provided by the SELECT query.`);return value});return new TupleExpression(rowValues)}),valuesQuery=new ValuesQuery(tuples,columnNames);return new InsertQuery({withClause:insertQuery.withClause,insertClause:insertQuery.insertClause,selectQuery:valuesQuery,returning:insertQuery.returningClause})}static flattenSelectQueries(selectQuery){if(selectQuery instanceof SimpleSelectQuery)return[selectQuery];if(selectQuery instanceof BinarySelectQuery)return[...this.flattenSelectQueries(selectQuery.left),...this.flattenSelectQueries(selectQuery.right)];throw new Error("Unsupported SelectQuery subtype for conversion.")}};var QueryBuilder=class _QueryBuilder{static buildBinaryQuery(queries,operator){if(!queries||queries.length===0)throw new Error("No queries provided to combine.");if(queries.length===1)throw new Error("At least two queries are required to create a BinarySelectQuery.");let wrap=q=>q instanceof ValuesQuery?_QueryBuilder.buildSimpleQuery(q):q,result=new BinarySelectQuery(wrap(queries[0]),operator,wrap(queries[1]));CTENormalizer.normalize(result);for(let i=2;i<queries.length;i++)result.appendSelectQuery(operator,wrap(queries[i]));return result}constructor(){}static buildSimpleQuery(query){if(query instanceof SimpleSelectQuery)return query;if(query instanceof BinarySelectQuery)return _QueryBuilder.buildSimpleBinaryQuery(query);if(query instanceof ValuesQuery)return _QueryBuilder.buildSimpleValuesQuery(query);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(query){let extractedOrderBy=_QueryBuilder.extractAndRemoveOrderByFromBinaryQuery(query),subQuerySource=new SubQuerySource(query),sourceExpr=new SourceExpression(subQuerySource,new SourceAliasExpression("bq",null)),fromClause=new FromClause(sourceExpr,null),selectClause=_QueryBuilder.createSelectAllClause(),q=new SimpleSelectQuery({selectClause,fromClause,orderByClause:extractedOrderBy});return CTENormalizer.normalize(q)}static extractAndRemoveOrderByFromBinaryQuery(query){return _QueryBuilder.findAndRemoveRightmostOrderBy(query)}static findAndRemoveRightmostOrderBy(query){if(query instanceof BinarySelectQuery){let rightOrderBy=_QueryBuilder.findAndRemoveRightmostOrderBy(query.right);return rightOrderBy||_QueryBuilder.findAndRemoveRightmostOrderBy(query.left)}else if(query instanceof SimpleSelectQuery){let orderBy=query.orderByClause;if(orderBy)return query.orderByClause=null,orderBy}return null}static buildSimpleValuesQuery(query){let columnCount=query.tuples.length>0?query.tuples[0].values.length:0;if(query.tuples.length===0)throw new Error("Empty VALUES clause cannot be converted to a SimpleSelectQuery");if(!query.columnAliases)throw new Error("Column aliases are required to convert a VALUES clause to SimpleSelectQuery. Please specify column aliases.");if(query.columnAliases.length!==columnCount)throw new Error(`The number of column aliases (${query.columnAliases.length}) does not match the number of columns in the first tuple (${columnCount}).`);let subQuerySource=new SubQuerySource(query),sourceExpr=new SourceExpression(subQuerySource,new SourceAliasExpression("vq",query.columnAliases)),fromClause=new FromClause(sourceExpr,null),selectItems=query.columnAliases.map(name=>new SelectItem(new ColumnReference("vq",name),name)),selectClause=new SelectClause(selectItems,null);return new SimpleSelectQuery({selectClause,fromClause})}static createSelectAllClause(){let columnRef=new ColumnReference(null,"*"),selectItem=new SelectItem(columnRef,"*");return new SelectClause([selectItem],null)}static buildCreateTableQuery(query,tableName,isTemporary=!1,ifNotExists=!1){return new CreateTableQuery({tableName,isTemporary,ifNotExists,asSelectQuery:query})}static buildInsertQuery(selectQuery,targetOrOptions,explicitColumns){let options=_QueryBuilder.normalizeInsertOptions(targetOrOptions,explicitColumns),columnNames=_QueryBuilder.prepareInsertColumns(selectQuery,options.columns??null),withClause=_QueryBuilder.extractWithClause(selectQuery),sourceExpr=SourceExpressionParser.parse(options.target);return new InsertQuery({withClause:withClause??void 0,insertClause:new InsertClause(sourceExpr,columnNames),selectQuery})}static convertInsertValuesToSelect(insertQuery){return InsertQuerySelectValuesConverter.toSelectUnion(insertQuery)}static convertInsertSelectToValues(insertQuery){return InsertQuerySelectValuesConverter.toValues(insertQuery)}static buildUpdateQuery(selectQuery,selectSourceOrOptions,updateTableExprRaw,primaryKeys){let options=_QueryBuilder.normalizeUpdateOptions(selectSourceOrOptions,updateTableExprRaw,primaryKeys),updateColumns=_QueryBuilder.prepareUpdateColumns(selectQuery,options.primaryKeys,options.columns??null),updateClause=new UpdateClause(SourceExpressionParser.parse(options.target)),targetAlias=updateClause.getSourceAliasName();if(!targetAlias)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let withClause=_QueryBuilder.extractWithClause(selectQuery),setItems=updateColumns.map(column=>new SetClauseItem(column,_QueryBuilder.toColumnReference(options.sourceAlias,column)));if(setItems.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 setClause=new SetClause(setItems),fromClause=new FromClause(selectQuery.toSource(options.sourceAlias),null),whereClause=new WhereClause(_QueryBuilder.buildEqualityPredicate(targetAlias,options.sourceAlias,options.primaryKeys));return new UpdateQuery({updateClause,setClause,fromClause,whereClause,withClause:withClause??void 0})}static buildDeleteQuery(selectQuery,options){let normalized=_QueryBuilder.normalizeDeleteOptions(options),predicateColumns=_QueryBuilder.prepareDeleteColumns(selectQuery,normalized.primaryKeys,normalized.columns??null),deleteClause=new DeleteClause(SourceExpressionParser.parse(normalized.target)),targetAlias=deleteClause.getSourceAliasName();if(!targetAlias)throw new Error("Source expression does not have an alias. Please provide an alias for the delete target.");let withClause=_QueryBuilder.extractWithClause(selectQuery),predicate=_QueryBuilder.buildEqualityPredicate(targetAlias,normalized.sourceAlias,predicateColumns),sourceExpression=selectQuery.toSource(normalized.sourceAlias),existsSelectClause=new SelectClause([new SelectItem(new LiteralValue(1))]),existsSubquery=new SimpleSelectQuery({selectClause:existsSelectClause,fromClause:new FromClause(sourceExpression,null),whereClause:new WhereClause(predicate)}),whereClause=new WhereClause(new UnaryExpression("exists",new InlineQuery(existsSubquery)));return new DeleteQuery({deleteClause,whereClause,withClause:withClause??void 0})}static buildMergeQuery(selectQuery,options){let normalized=_QueryBuilder.normalizeMergeOptions(options),mergeColumnPlan=_QueryBuilder.prepareMergeColumns(selectQuery,normalized.primaryKeys,normalized.updateColumns??null,normalized.insertColumns??null,normalized.matchedAction??"update",normalized.notMatchedAction??"insert"),targetExpression=SourceExpressionParser.parse(normalized.target),targetAlias=targetExpression.getAliasName();if(!targetAlias)throw new Error("Source expression does not have an alias. Please provide an alias for the merge target.");let withClause=_QueryBuilder.extractWithClause(selectQuery),onCondition=_QueryBuilder.buildEqualityPredicate(targetAlias,normalized.sourceAlias,normalized.primaryKeys),sourceExpression=selectQuery.toSource(normalized.sourceAlias),whenClauses=[],matchedAction=normalized.matchedAction??"update";if(matchedAction==="update"){if(mergeColumnPlan.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 setItems=mergeColumnPlan.updateColumns.map(column=>new SetClauseItem(column,_QueryBuilder.toColumnReference(normalized.sourceAlias,column)));whenClauses.push(new MergeWhenClause("matched",new MergeUpdateAction(new SetClause(setItems))))}else matchedAction==="delete"?whenClauses.push(new MergeWhenClause("matched",new MergeDeleteAction)):matchedAction==="doNothing"&&whenClauses.push(new MergeWhenClause("matched",new MergeDoNothingAction));let notMatchedAction=normalized.notMatchedAction??"insert";if(notMatchedAction==="insert"){if(mergeColumnPlan.insertColumns.length===0)throw new Error("Unable to infer MERGE insert columns. Provide insertColumns explicitly.");let insertValues=new ValueList(mergeColumnPlan.insertColumns.map(column=>_QueryBuilder.toColumnReference(normalized.sourceAlias,column)));whenClauses.push(new MergeWhenClause("not_matched",new MergeInsertAction({columns:mergeColumnPlan.insertColumns,values:insertValues})))}else notMatchedAction==="doNothing"&&whenClauses.push(new MergeWhenClause("not_matched",new MergeDoNothingAction));let notMatchedBySourceAction=normalized.notMatchedBySourceAction??"doNothing";if(notMatchedBySourceAction==="delete"?whenClauses.push(new MergeWhenClause("not_matched_by_source",new MergeDeleteAction)):notMatchedBySourceAction==="doNothing"&&whenClauses.push(new MergeWhenClause("not_matched_by_source",new MergeDoNothingAction)),whenClauses.length===0)throw new Error("At least one MERGE action must be generated. Adjust the merge conversion options.");return new MergeQuery({withClause:withClause??void 0,target:targetExpression,source:sourceExpression,onCondition,whenClauses})}static normalizeInsertOptions(targetOrOptions,explicitColumns){return typeof targetOrOptions=="string"?{target:targetOrOptions,columns:explicitColumns}:explicitColumns&&explicitColumns.length>0?{...targetOrOptions,columns:explicitColumns}:{...targetOrOptions}}static normalizeUpdateOptions(selectSourceOrOptions,updateTableExprRaw,primaryKeys){if(typeof selectSourceOrOptions=="string"){if(!updateTableExprRaw)throw new Error("updateTableExprRaw is required when using the legacy buildUpdateQuery signature.");if(primaryKeys===void 0)throw new Error("primaryKeys are required when using the legacy buildUpdateQuery signature.");return{target:updateTableExprRaw,primaryKeys:_QueryBuilder.normalizeColumnArray(primaryKeys),sourceAlias:selectSourceOrOptions}}return{target:selectSourceOrOptions.target,primaryKeys:_QueryBuilder.normalizeColumnArray(selectSourceOrOptions.primaryKeys),sourceAlias:selectSourceOrOptions.sourceAlias??"src",columns:selectSourceOrOptions.columns}}static normalizeDeleteOptions(options){return{...options,primaryKeys:_QueryBuilder.normalizeColumnArray(options.primaryKeys),sourceAlias:options.sourceAlias??"src"}}static normalizeMergeOptions(options){return{...options,primaryKeys:_QueryBuilder.normalizeColumnArray(options.primaryKeys),sourceAlias:options.sourceAlias??"src"}}static normalizeColumnArray(columns){let normalized=(Array.isArray(columns)?columns:[columns]).map(col=>col.trim()).filter(col=>col.length>0);if(!normalized.length)throw new Error("At least one column must be specified.");return normalized}static collectSelectItems(selectQuery){return new SelectValueCollector().collect(selectQuery)}static collectSelectColumnNames(selectQuery){let items=_QueryBuilder.collectSelectItems(selectQuery),names=[];for(let item of items){if(!item.name||item.name==="*")throw new Error("Columns cannot be inferred from the selectQuery. Make sure you are not using wildcards or unnamed columns.");names.includes(item.name)||names.push(item.name)}if(!names.length)throw new Error("Unable to determine any column names from selectQuery.");return names}static ensurePrimaryKeys(selectColumns,primaryKeys){let available=new Set(selectColumns);for(let pk of primaryKeys)if(!available.has(pk))throw new Error(`Primary key column '${pk}' is not present in selectQuery select list.`)}static prepareInsertColumns(selectQuery,optionColumns){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);if(optionColumns&&optionColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(optionColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>!selectColumns.includes(name));if(missing.length>0)throw new Error(`Columns specified in conversion options were not found in selectQuery select list: [${missing.join(", ")}].`);return _QueryBuilder.rebuildSelectClause(selectQuery,uniqueNormalized),_QueryBuilder.ensureSelectClauseSize(selectQuery,uniqueNormalized.length),uniqueNormalized}return _QueryBuilder.ensureSelectClauseSize(selectQuery,selectColumns.length),selectColumns}static prepareUpdateColumns(selectQuery,primaryKeys,explicitColumns){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);_QueryBuilder.ensurePrimaryKeys(selectColumns,primaryKeys);let primaryKeySet=new Set(primaryKeys),updateCandidates=selectColumns.filter(name=>!primaryKeySet.has(name)),updateColumnsOrdered;if(explicitColumns&&explicitColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>primaryKeySet.has(name)||!updateCandidates.includes(name));if(missing.length>0)throw new Error(`Provided update columns were not found in selectQuery output or are primary keys: [${missing.join(", ")}].`);updateColumnsOrdered=uniqueNormalized}else updateColumnsOrdered=Array.from(new Set(updateCandidates));let desiredOrder=Array.from(new Set([...primaryKeys,...updateColumnsOrdered]));return _QueryBuilder.rebuildSelectClause(selectQuery,desiredOrder),_QueryBuilder.ensureSelectClauseSize(selectQuery,desiredOrder.length),updateColumnsOrdered}static prepareDeleteColumns(selectQuery,primaryKeys,explicitColumns){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);_QueryBuilder.ensurePrimaryKeys(selectColumns,primaryKeys);let primaryKeySet=new Set(primaryKeys),matchColumns=[];if(explicitColumns&&explicitColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitColumns),preferred=new Set(normalized);matchColumns=selectColumns.filter(name=>preferred.has(name)&&!primaryKeySet.has(name))}let requiredColumns=new Set;primaryKeys.forEach(key=>requiredColumns.add(key)),matchColumns.forEach(col=>requiredColumns.add(col));let desiredOrder=selectColumns.filter(name=>requiredColumns.has(name));return _QueryBuilder.rebuildSelectClause(selectQuery,desiredOrder),_QueryBuilder.ensureSelectClauseSize(selectQuery,desiredOrder.length),desiredOrder}static prepareMergeColumns(selectQuery,primaryKeys,explicitUpdateColumns,explicitInsertColumns,matchedAction,notMatchedAction){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);_QueryBuilder.ensurePrimaryKeys(selectColumns,primaryKeys);let primaryKeySet=new Set(primaryKeys),updateColumnsOrdered=[];if(matchedAction==="update"){let candidates=selectColumns.filter(name=>!primaryKeySet.has(name));if(explicitUpdateColumns&&explicitUpdateColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitUpdateColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>primaryKeySet.has(name)||!candidates.includes(name));if(missing.length>0)throw new Error(`Provided update columns were not found in selectQuery output or are primary keys: [${missing.join(", ")}].`);updateColumnsOrdered=uniqueNormalized}else updateColumnsOrdered=Array.from(new Set(candidates))}let insertColumnsOrdered=[];if(notMatchedAction==="insert")if(explicitInsertColumns&&explicitInsertColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitInsertColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>!selectColumns.includes(name));if(missing.length>0)throw new Error(`Provided insert columns were not found in selectQuery output: [${missing.join(", ")}].`);insertColumnsOrdered=uniqueNormalized}else insertColumnsOrdered=Array.from(new Set(selectColumns));let desiredOrder=Array.from(new Set([...primaryKeys,...updateColumnsOrdered,...insertColumnsOrdered,...selectColumns])).filter(name=>selectColumns.includes(name));return _QueryBuilder.rebuildSelectClause(selectQuery,desiredOrder),_QueryBuilder.ensureSelectClauseSize(selectQuery,desiredOrder.length),{updateColumns:matchedAction==="update"?updateColumnsOrdered:[],insertColumns:notMatchedAction==="insert"?insertColumnsOrdered:[]}}static rebuildSelectClause(selectQuery,desiredColumns){let itemMap=new Map;for(let item of selectQuery.selectClause.items){let name=_QueryBuilder.getSelectItemName(item);name&&(itemMap.has(name)||itemMap.set(name,item))}let rebuiltItems=[],seen=new Set;for(let column of desiredColumns){if(seen.has(column))continue;let item=itemMap.get(column);if(!item)throw new Error(`Column '${column}' not found in select clause.`);rebuiltItems.push(item),seen.add(column)}if(!rebuiltItems.length)throw new Error("Unable to rebuild select clause with the requested columns.");selectQuery.selectClause.items=rebuiltItems}static getSelectItemName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}static ensureSelectClauseSize(selectQuery,expected){if(selectQuery.selectClause.items.length!==expected)throw new Error(`Select clause column count (${selectQuery.selectClause.items.length}) does not match expected count (${expected}).`)}static extractWithClause(selectQuery){let collected=new CTECollector().collect(selectQuery);return collected.length===0?null:(new CTEDisabler().execute(selectQuery),new WithClause(!1,collected))}static buildEqualityPredicate(leftAlias,rightAlias,columns){let uniqueColumns=_QueryBuilder.mergeUniqueColumns(columns);if(!uniqueColumns.length)throw new Error("At least one column is required to build a comparison predicate.");let predicate=null;for(let column of uniqueColumns){let comparison=new BinaryExpression(_QueryBuilder.toColumnReference(leftAlias,column),"=",_QueryBuilder.toColumnReference(rightAlias,column));predicate=predicate?new BinaryExpression(predicate,"and",comparison):comparison}return predicate}static toColumnReference(alias,column){return new ColumnReference(alias,column)}static mergeUniqueColumns(columns){let seen=new Set,result=[];for(let column of columns)seen.has(column)||(seen.add(column),result.push(column));return result}};var SimpleSelectQuery=class extends SqlComponent{constructor(params){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.cteNameCache=new Set;this.withClause=params.withClause??null,this.selectClause=params.selectClause,this.fromClause=params.fromClause??null,this.whereClause=params.whereClause??null,this.groupByClause=params.groupByClause??null,this.havingClause=params.havingClause??null,this.orderByClause=params.orderByClause??null,this.windowClause=params.windowClause??null,this.limitClause=params.limitClause??null,this.offsetClause=params.offsetClause??null,this.fetchClause=params.fetchClause??null,this.forClause=params.forClause??null,this.initializeCTECache()}static{this.kind=Symbol("SelectQuery")}initializeCTECache(){if(this.cteNameCache.clear(),this.withClause?.tables)for(let table of this.withClause.tables)this.cteNameCache.add(table.aliasExpression.table.name)}toUnion(rightQuery){return this.toBinaryQuery("union",rightQuery)}toUnionAll(rightQuery){return this.toBinaryQuery("union all",rightQuery)}toInsertQuery(options){return QueryBuilder.buildInsertQuery(this,options)}toUpdateQuery(options){return QueryBuilder.buildUpdateQuery(this,options)}toDeleteQuery(options){return QueryBuilder.buildDeleteQuery(this,options)}toMergeQuery(options){return QueryBuilder.buildMergeQuery(this,options)}toIntersect(rightQuery){return this.toBinaryQuery("intersect",rightQuery)}toIntersectAll(rightQuery){return this.toBinaryQuery("intersect all",rightQuery)}toExcept(rightQuery){return this.toBinaryQuery("except",rightQuery)}toExceptAll(rightQuery){return this.toBinaryQuery("except all",rightQuery)}toBinaryQuery(operator,rightQuery){return QueryBuilder.buildBinaryQuery([this,rightQuery],operator)}appendWhereRaw(rawCondition){let parsedCondition=ValueParser.parse(rawCondition);this.appendWhere(parsedCondition)}appendWhere(condition){this.whereClause?this.whereClause.condition=new BinaryExpression(this.whereClause.condition,"and",condition):this.whereClause=new WhereClause(condition)}appendHavingRaw(rawCondition){let parsedCondition=ValueParser.parse(rawCondition);this.appendHaving(parsedCondition)}appendHaving(condition){this.havingClause?this.havingClause.condition=new BinaryExpression(this.havingClause.condition,"and",condition):this.havingClause=new HavingClause(condition)}innerJoinRaw(joinSourceRawText,alias,columns,resolver=null){this.joinSourceRaw("inner join",joinSourceRawText,alias,columns,resolver)}leftJoinRaw(joinSourceRawText,alias,columns,resolver=null){this.joinSourceRaw("left join",joinSourceRawText,alias,columns,resolver)}rightJoinRaw(joinSourceRawText,alias,columns,resolver=null){this.joinSourceRaw("right join",joinSourceRawText,alias,columns,resolver)}innerJoin(sourceExpr,columns,resolver=null){this.joinSource("inner join",sourceExpr,columns,resolver)}leftJoin(sourceExpr,columns,resolver=null){this.joinSource("left join",sourceExpr,columns,resolver)}rightJoin(sourceExpr,columns,resolver=null){this.joinSource("right join",sourceExpr,columns,resolver)}joinSourceRaw(joinType,joinSourceRawText,alias,columns,resolver=null){let tableSource=SourceParser.parse(joinSourceRawText),sourceExpr=new SourceExpression(tableSource,new SourceAliasExpression(alias,null));this.joinSource(joinType,sourceExpr,columns,resolver)}joinSource(joinType,sourceExpr,columns,resolver=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let columnsArr=Array.isArray(columns)?columns:[columns],valueSets=new SelectableColumnCollector(resolver).collect(this),joinCondition=null,count=0,sourceAlias=sourceExpr.getAliasName();if(!sourceAlias)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let valueSet of valueSets)if(columnsArr.some(col=>col==valueSet.name)){let expr=new BinaryExpression(valueSet.value,"=",new ColumnReference([sourceAlias],valueSet.name));joinCondition?joinCondition=new BinaryExpression(joinCondition,"and",expr):joinCondition=expr,count++}if(!joinCondition||count!==columnsArr.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${columnsArr.join(", ")}`);let joinOnClause=new JoinOnClause(joinCondition),joinClause=new JoinClause(joinType,sourceExpr,joinOnClause,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(joinClause):this.fromClause.joins=[joinClause]),CTENormalizer.normalize(this)}toSource(alias){if(!alias||alias.trim()==="")throw new Error("Alias is required for toSource(). Please specify a non-empty alias name.");return new SourceExpression(new SubQuerySource(this),new SourceAliasExpression(alias,null))}appendWith(commonTable){let tables=Array.isArray(commonTable)?commonTable:[commonTable];this.withClause?this.withClause.tables.push(...tables):this.withClause=new WithClause(!1,tables),CTENormalizer.normalize(this)}appendWithRaw(rawText,alias){let query=SelectQueryParser.parse(rawText),commonTable=new CommonTable(query,alias,null);this.appendWith(commonTable)}overrideSelectItemExpr(columnName,fn){let items=this.selectClause.items.filter(item2=>item2.identifier?.name===columnName);if(items.length===0)throw new Error(`Column ${columnName} not found in the query`);if(items.length>1)throw new Error(`Duplicate column name ${columnName} found in the query`);let item=items[0],exprSql=new Formatter().visit(item.value),newValue=fn(exprSql);item.value=ValueParser.parse(newValue)}appendWhereExpr(columnName,exprBuilder,options){if(options&&options.upstream){let queries=new UpstreamSelectQueryFinder().find(this,[columnName]),collector=new SelectableColumnCollector,formatter=new Formatter;for(let q of queries){let exprs=collector.collect(q).filter(item=>item.name===columnName).map(item=>item.value);if(exprs.length!==1)throw new Error(`Expected exactly one expression for column '${columnName}'`);let exprStr=formatter.format(exprs[0]);q.appendWhereRaw(exprBuilder(exprStr))}}else{let collector=new SelectableColumnCollector,formatter=new Formatter,exprs=collector.collect(this).filter(item=>item.name===columnName).map(item=>item.value);if(exprs.length!==1)throw new Error(`Expected exactly one expression for column '${columnName}'`);let exprStr=formatter.format(exprs[0]);this.appendWhereRaw(exprBuilder(exprStr))}}setParameter(name,value){return ParameterHelper.set(this,name,value),this}toSimpleQuery(){return this}addCTE(name,query,options){if(!name||name.trim()==="")throw new InvalidCTENameError(name,"name cannot be empty or whitespace-only");if(this.hasCTE(name))throw new DuplicateCTEError(name);let materialized=options?.materialized??null,commonTable=new CommonTable(query,name,materialized);return this.appendWith(commonTable),this.cteNameCache.add(name),this}removeCTE(name){if(!this.hasCTE(name))throw new CTENotFoundError(name);return this.withClause&&(this.withClause.tables=this.withClause.tables.filter(table=>table.aliasExpression.table.name!==name),this.withClause.tables.length===0&&(this.withClause=null)),this.cteNameCache.delete(name),this}hasCTE(name){return this.cteNameCache.has(name)}getCTENames(){return this.withClause?.tables.map(table=>table.aliasExpression.table.name)??[]}replaceCTE(name,query,options){if(!name||name.trim()==="")throw new InvalidCTENameError(name,"name cannot be empty or whitespace-only");this.hasCTE(name)&&this.removeCTE(name);let materialized=options?.materialized??null,commonTable=new CommonTable(query,name,materialized);return this.appendWith(commonTable),this.cteNameCache.add(name),this}};var SelectClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The SELECT clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,distinct=null,selectTokenComments=idx<lexemes.length?lexemes[idx].comments:null;if(lexemes[idx].value!=="select")throw new Error(`Syntax error at position ${idx}: Expected 'SELECT' keyword but found "${lexemes[idx].value}". SELECT clauses must start with the SELECT keyword.`);idx++;let hints=[];for(;idx<lexemes.length&&HintClause.isHintClause(lexemes[idx].value);){let hintContent=HintClause.extractHintContent(lexemes[idx].value);hints.push(new HintClause(hintContent)),idx++}if(idx<lexemes.length&&lexemes[idx].value==="distinct")idx++,distinct=new Distinct;else if(idx<lexemes.length&&lexemes[idx].value==="distinct on"){idx++;let argument=ValueParser.parseArgument(4,8,lexemes,idx);distinct=new DistinctOn(argument.value),idx=argument.newIndex}let items=[],item=SelectItemParser.parseItem(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=SelectItemParser.parseItem(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No select items found. The SELECT clause requires at least one expression to select.`);return{value:new SelectClause(items,distinct,hints),newIndex:idx}}},SelectItemParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseItem(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The select item is complete but there are additional tokens.`);return result.value}static parseItem(lexemes,index){let idx=index,valueTokenComments=this.extractValueTokenComments(lexemes,idx),parsedValue=ValueParser.parseFromLexeme(lexemes,idx),value=parsedValue.value;idx=parsedValue.newIndex;let{asComments,newIndex:asIndex}=this.parseAsKeyword(lexemes,idx);if(idx=asIndex,idx<lexemes.length&&lexemes[idx].type&64){let alias=lexemes[idx].value,aliasComments=lexemes[idx].comments,aliasPositionedComments=lexemes[idx].positionedComments;idx++;let selectItem2=new SelectItem(value,alias);return this.applyValueTokenComments(selectItem2,valueTokenComments),this.applyAsKeywordComments(selectItem2,asComments),this.applyAliasComments(selectItem2,aliasComments,aliasPositionedComments),{value:selectItem2,newIndex:idx}}else if(value instanceof ColumnReference&&value.column.name!=="*"){let selectItem2=new SelectItem(value,value.column.name);return this.applyValueTokenComments(selectItem2,valueTokenComments),this.applyAsKeywordComments(selectItem2,asComments),{value:selectItem2,newIndex:idx}}let selectItem=new SelectItem(value);return this.applyValueTokenComments(selectItem,valueTokenComments),this.applyAsKeywordComments(selectItem,asComments),{value:selectItem,newIndex:idx}}static clearPositionedCommentsRecursively(component){!component||typeof component!="object"||("positionedComments"in component&&(component.positionedComments=null),component.left&&this.clearPositionedCommentsRecursively(component.left),component.right&&this.clearPositionedCommentsRecursively(component.right),component.qualifiedName&&this.clearPositionedCommentsRecursively(component.qualifiedName),component.table&&this.clearPositionedCommentsRecursively(component.table),component.name&&this.clearPositionedCommentsRecursively(component.name),component.args&&Array.isArray(component.args)&&component.args.forEach(arg=>{this.clearPositionedCommentsRecursively(arg)}),component.value&&this.clearPositionedCommentsRecursively(component.value))}static extractValueTokenComments(lexemes,index){if(index>=lexemes.length)return{positioned:null,legacy:null};let token=lexemes[index];return{positioned:token.positionedComments&&token.positionedComments.length>0?token.positionedComments:null,legacy:null}}static parseAsKeyword(lexemes,index){if(index>=lexemes.length||lexemes[index].value!=="as")return{asComments:{positioned:null,legacy:null},newIndex:index};let asToken=lexemes[index];return{asComments:{positioned:asToken.positionedComments&&asToken.positionedComments.length>0?asToken.positionedComments:null,legacy:asToken.comments&&asToken.comments.length>0?asToken.comments:null},newIndex:index+1}}static applyValueTokenComments(selectItem,valueTokenComments){if(valueTokenComments.positioned){for(let posComment of valueTokenComments.positioned)selectItem.addPositionedComments(posComment.position,posComment.comments);this.clearValueTokenComments(selectItem)}}static applyAsKeywordComments(selectItem,asComments){asComments.positioned?selectItem.asKeywordPositionedComments=asComments.positioned:asComments.legacy&&(selectItem.asKeywordComments=asComments.legacy)}static applyAliasComments(selectItem,aliasComments,aliasPositionedComments){aliasPositionedComments&&aliasPositionedComments.length>0?selectItem.aliasPositionedComments=aliasPositionedComments:aliasComments&&aliasComments.length>0&&(selectItem.aliasComments=aliasComments)}static clearValueTokenComments(selectItem){if("positionedComments"in selectItem.value&&(selectItem.value.positionedComments=null),selectItem.value instanceof ColumnReference){let columnRef=selectItem.value;columnRef.qualifiedName&&columnRef.qualifiedName.name&&(columnRef.qualifiedName.name.positionedComments=null)}selectItem.value instanceof BinaryExpression&&this.clearPositionedCommentsRecursively(selectItem.value)}};var JoinOnClauseParser=class{static tryParse(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].value==="on"){idx++;let condition=ValueParser.parseFromLexeme(lexemes,idx);return idx=condition.newIndex,{value:new JoinOnClause(condition.value),newIndex:idx}}return null}};var JoinUsingClauseParser=class{static tryParse(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].value==="using"){idx++;let result=ValueParser.parseArgument(4,8,lexemes,idx),usingColumns=result.value;return idx=result.newIndex,{value:new JoinUsingClause(usingColumns),newIndex:idx}}return null}};var JoinClauseParser=class{static tryParse(lexemes,index){let idx=index,joins=[];for(;this.isJoinCommand(lexemes,idx);){let joinClause=this.parseJoinClause(lexemes,idx);joins.push(joinClause.value),idx=joinClause.newIndex}return joins.length>0?{value:joins,newIndex:idx}:null}static isJoinKeyword(value){return!!joinkeywordParser.parse(value,0)}static parseLateral(lexemes,index){let idx=index;return idx<lexemes.length&&lexemes[idx].value==="lateral"?(idx++,{value:!0,newIndex:idx}):{value:!1,newIndex:idx}}static isJoinCommand(lexemes,index){return index>=lexemes.length?!1:!!(lexemes[index].type&16||this.isJoinKeyword(lexemes[index].value)===!0)}static parseJoinClause(lexemes,index){let idx=index,{joinType,joinComments,newIndex:joinIndex}=this.parseJoinKeyword(lexemes,idx);idx=joinIndex;let lateralResult=this.parseLateral(lexemes,idx),lateral=lateralResult.value;idx=lateralResult.newIndex;let sourceResult=SourceExpressionParser.parseFromLexeme(lexemes,idx);idx=sourceResult.newIndex;let joinClause=this.parseJoinCondition(lexemes,idx,joinType,sourceResult.value,lateral,joinComments);if(joinClause)return joinClause;let naturalJoinClause=new JoinClause(joinType,sourceResult.value,null,lateral);return this.applyJoinComments(naturalJoinClause,joinComments),{value:naturalJoinClause,newIndex:idx}}static parseJoinKeyword(lexemes,index){let joinType=lexemes[index].value===","?"cross join":lexemes[index].value,joinComments=this.extractJoinKeywordComments(lexemes[index]);return{joinType,joinComments,newIndex:index+1}}static extractJoinKeywordComments(token){return{positioned:token.positionedComments&&token.positionedComments.length>0?token.positionedComments:null,legacy:token.comments&&token.comments.length>0?token.comments:null}}static parseJoinCondition(lexemes,index,joinType,sourceValue,lateral,joinComments){if(index>=lexemes.length)return null;let onResult=JoinOnClauseParser.tryParse(lexemes,index);if(onResult){let joinClause=new JoinClause(joinType,sourceValue,onResult.value,lateral);return this.applyJoinComments(joinClause,joinComments),{value:joinClause,newIndex:onResult.newIndex}}let usingResult=JoinUsingClauseParser.tryParse(lexemes,index);if(usingResult){let joinClause=new JoinClause(joinType,sourceValue,usingResult.value,lateral);return this.applyJoinComments(joinClause,joinComments),{value:joinClause,newIndex:usingResult.newIndex}}return null}static applyJoinComments(joinClause,joinComments){joinComments.positioned?joinClause.joinKeywordPositionedComments=joinComments.positioned:joinComments.legacy&&(joinClause.joinKeywordComments=joinComments.legacy)}};var CommentUtils=class{static collectClauseComments(lexemes,currentIndex,keywordValue){if(currentIndex>=lexemes.length||lexemes[currentIndex].value.toLowerCase()!==keywordValue.toLowerCase())return null;let comments=[];lexemes[currentIndex].comments&&comments.push(...lexemes[currentIndex].comments);let checkIndex=currentIndex-1;for(;checkIndex>=0;){let prevToken=lexemes[checkIndex];if(prevToken.comments&&prevToken.comments.length>0){let clauseSpecificComments=prevToken.comments.filter(comment=>{let lowerComment=comment.toLowerCase();return lowerComment.includes(keywordValue.toLowerCase())||lowerComment.includes("\u306E")||lowerComment.includes("\u30B3\u30E1\u30F3\u30C8")});clauseSpecificComments.length>0&&(comments.unshift(...clauseSpecificComments),prevToken.comments=prevToken.comments.filter(c=>!clauseSpecificComments.includes(c)),prevToken.comments.length===0&&(prevToken.comments=null));break}if(this.isSignificantSqlKeyword(prevToken.value))break;checkIndex--}return comments.length>0?comments:null}static isSignificantSqlKeyword(value){return new Set(["select","from","where","group by","having","order by","limit","offset"]).has(value.toLowerCase())}};var FromClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The FROM clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,fromTokenComments=CommentUtils.collectClauseComments(lexemes,idx,"from");if(lexemes[idx].value!=="from")throw new Error(`Syntax error at position ${idx}: Expected 'FROM' keyword but found "${lexemes[idx].value}". FROM clauses must start with the FROM keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FROM' keyword. The FROM clause requires a table reference.");let sourceExpression=SourceExpressionParser.parseFromLexeme(lexemes,idx);idx=sourceExpression.newIndex;let join=JoinClauseParser.tryParse(lexemes,idx);if(idx=join?.newIndex||idx,join!==null){let clause=new FromClause(sourceExpression.value,join.value);return{value:clause,newIndex:idx}}else{let clause=new FromClause(sourceExpression.value,null);return{value:clause,newIndex:idx}}}};var WhereClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The WHERE clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,whereLexeme=lexemes[idx],whereTokenComments=CommentUtils.collectClauseComments(lexemes,idx,"where"),wherePositionedComments=whereLexeme.positionedComments;if(whereLexeme.value!=="where")throw new Error(`Syntax error at position ${idx}: Expected 'WHERE' keyword but found "${lexemes[idx].value}". WHERE clauses must start with the WHERE keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'WHERE' keyword. The WHERE clause requires a condition expression.");let item=ValueParser.parseFromLexeme(lexemes,idx),clause=new WhereClause(item.value);return clause.comments=whereTokenComments,wherePositionedComments&&wherePositionedComments.length>0&&(clause.positionedComments=wherePositionedComments.map(comment=>({position:comment.position,comments:[...comment.comments]}))),{value:clause,newIndex:item.newIndex}}};var GroupByClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The GROUP BY clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="group by")throw new Error(`Syntax error at position ${idx}: Expected 'GROUP BY' keyword but found "${lexemes[idx].value}". GROUP BY clauses must start with the GROUP BY keywords.`);if(idx++,idx>=lexemes.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 items=[],item=this.parseItem(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=this.parseItem(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No grouping expressions found. The GROUP BY clause requires at least one expression to group by.`);return{value:new GroupByClause(items),newIndex:idx}}static parseItem(lexemes,index){let idx=index,parsedValue=ValueParser.parseFromLexeme(lexemes,idx),value=parsedValue.value;return idx=parsedValue.newIndex,{value,newIndex:idx}}};var HavingClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The HAVING clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="having")throw new Error(`Syntax error at position ${idx}: Expected 'HAVING' keyword but found "${lexemes[idx].value}". HAVING clauses must start with the HAVING keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'HAVING' keyword. The HAVING clause requires a condition expression.");let item=ValueParser.parseFromLexeme(lexemes,idx);return{value:new HavingClause(item.value),newIndex:item.newIndex}}};var WindowClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The WINDOW clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="window")throw new Error(`Syntax error at position ${idx}: Expected 'WINDOW' keyword but found "${lexemes[idx].value}". WINDOW clauses must start with the WINDOW keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'WINDOW' keyword. The WINDOW clause requires at least one window definition.");let windows=[];for(;idx<lexemes.length;){if(idx>=lexemes.length||lexemes[idx].type!==64)throw new Error("Syntax error: Expected window name after 'WINDOW' keyword.");let name=lexemes[idx].value;if(idx++,idx>=lexemes.length||lexemes[idx].value!=="as")throw new Error(`Syntax error at position ${idx}: Expected 'AS' keyword after window name.`);idx++;let expr=WindowExpressionParser.parseFromLexeme(lexemes,idx);if(idx=expr.newIndex,windows.push(new WindowFrameClause(name,expr.value)),idx<lexemes.length&&lexemes[idx].type&16)idx++;else break}if(windows.length===0)throw new Error("At least one WINDOW clause is required after WINDOW keyword.");return{value:new WindowsClause(windows),newIndex:idx}}};var LimitClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The LIMIT clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="limit")throw new Error(`Syntax error at position ${idx}: Expected 'LIMIT' keyword but found "${lexemes[idx].value}". LIMIT clauses must start with the LIMIT keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'LIMIT' keyword. The LIMIT clause requires a numeric expression.");let limitItem=ValueParser.parseFromLexeme(lexemes,idx);return idx=limitItem.newIndex,{value:new LimitClause(limitItem.value),newIndex:idx}}};var ForClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The FOR clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value.toLowerCase()!=="for")throw new Error(`Syntax error at position ${idx}: Expected 'FOR' keyword but found "${lexemes[idx].value}". FOR clauses must start with the FOR keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FOR' keyword. The FOR clause requires a lock mode specification.");let lockModeValue=lexemes[idx].value,lockMode;switch(lockModeValue){case"update":lockMode="update",idx++;break;case"share":lockMode="share",idx++;break;case"key share":lockMode="key share",idx++;break;case"no key update":lockMode="no key update",idx++;break;default:throw new Error(`Syntax error at position ${idx}: Invalid lock mode "${lockModeValue}". Valid lock modes are: UPDATE, SHARE, KEY SHARE, NO KEY UPDATE.`)}return{value:new ForClause(lockMode),newIndex:idx}}};var CommonTableParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The CommonTable definition is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,aliasResult=SourceAliasExpressionParser.parseFromLexeme(lexemes,idx);idx=aliasResult.newIndex,this.collectPrecedingComments(lexemes,index,aliasResult),idx=this.parseAsKeyword(lexemes,idx);let{materialized,newIndex:materializedIndex}=this.parseMaterializedFlag(lexemes,idx);idx=materializedIndex;let{selectQuery,trailingComments,newIndex:selectIndex}=this.parseInnerSelectQuery(lexemes,idx);return idx=selectIndex,{value:new CommonTable(selectQuery,aliasResult.value,materialized),newIndex:idx,trailingComments}}static collectPrecedingComments(lexemes,index,aliasResult){if(!aliasResult.value?.table)return;let cteTable=aliasResult.value.table;for(let i=index-1;i>=0;i--){let token=lexemes[i];if(token.value.toLowerCase()==="with"){this.collectWithTokenComments(token,cteTable);break}if(token.type&16||token.value.toLowerCase()==="recursive")break;this.collectTokenComments(token,cteTable)}}static collectWithTokenComments(token,cteTable){let hasPositionedComments=!1;if(token.positionedComments&&token.positionedComments.length>0)for(let posComment of token.positionedComments)posComment.position==="after"&&posComment.comments&&(this.addPositionedComment(cteTable,"before",posComment.comments),hasPositionedComments=!0);!hasPositionedComments&&token.comments&&token.comments.length>0&&this.addPositionedComment(cteTable,"before",token.comments)}static collectTokenComments(token,cteTable){token.comments&&token.comments.length>0&&this.addPositionedComment(cteTable,"before",token.comments),token.positionedComments&&token.positionedComments.length>0&&(cteTable.positionedComments||(cteTable.positionedComments=[]),cteTable.positionedComments.unshift(...token.positionedComments))}static addPositionedComment(cteTable,position,comments){cteTable.positionedComments||(cteTable.positionedComments=[]),cteTable.positionedComments.unshift({position,comments:[...comments]})}static parseAsKeyword(lexemes,index){if(index<lexemes.length&&lexemes[index].value!=="as")throw new Error(`Syntax error at position ${index}: Expected 'AS' keyword after CTE name but found "${lexemes[index].value}".`);return index+1}static parseMaterializedFlag(lexemes,index){if(index>=lexemes.length)return{materialized:null,newIndex:index};let currentValue=lexemes[index].value;return currentValue==="materialized"?{materialized:!0,newIndex:index+1}:currentValue==="not materialized"?{materialized:!1,newIndex:index+1}:{materialized:null,newIndex:index}}static parseInnerSelectQuery(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type!==4)throw new Error(`Syntax error at position ${idx}: Expected '(' after CTE name but found "${lexemes[idx].value}".`);let cteQueryHeaderComments=this.extractComments(lexemes[idx]);idx++;let queryResult=SelectQueryParser.parseFromLexeme(lexemes,idx);if(idx=queryResult.newIndex,cteQueryHeaderComments.length>0&&(queryResult.value.headerComments?queryResult.value.headerComments=[...cteQueryHeaderComments,...queryResult.value.headerComments]:queryResult.value.headerComments=cteQueryHeaderComments),idx<lexemes.length&&lexemes[idx].type!==8)throw new Error(`Syntax error at position ${idx}: Expected ')' after CTE query but found "${lexemes[idx].value}".`);let closingParenComments=this.extractComments(lexemes[idx]);return idx++,{selectQuery:queryResult.value,trailingComments:closingParenComments.length>0?closingParenComments:null,newIndex:idx}}static extractComments(lexeme){let comments=[];if(lexeme.positionedComments)for(let posComment of lexeme.positionedComments)posComment.comments&&comments.push(...posComment.comments);return lexeme.comments&&lexeme.comments.length>0&&comments.push(...lexeme.comments),comments}};var WithClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The WITH clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,headerComments=this.extractWithTokenHeaderComments(lexemes,idx);idx=this.parseWithKeyword(lexemes,idx);let{recursive,newIndex:recursiveIndex}=this.parseRecursiveFlag(lexemes,idx);idx=recursiveIndex;let{tables,trailingComments,newIndex:ctesIndex}=this.parseAllCommonTables(lexemes,idx);idx=ctesIndex;let withClause=new WithClause(recursive,tables);return trailingComments.length>0&&(withClause.trailingComments=trailingComments),{value:withClause,newIndex:idx,headerComments}}static extractWithTokenHeaderComments(lexemes,index){if(index>=lexemes.length)return null;let withToken=lexemes[index],headerComments=null;if(withToken.positionedComments&&withToken.positionedComments.length>0)for(let posComment of withToken.positionedComments)posComment.position==="before"&&posComment.comments&&(headerComments||(headerComments=[]),headerComments.push(...posComment.comments));return!headerComments&&withToken.comments&&withToken.comments.length>0&&(headerComments=[...withToken.comments]),headerComments}static parseWithKeyword(lexemes,index){if(index<lexemes.length&&lexemes[index].value.toLowerCase()==="with")return index+1;throw new Error(`Syntax error at position ${index}: Expected WITH keyword.`)}static parseRecursiveFlag(lexemes,index){let recursive=index<lexemes.length&&lexemes[index].value.toLowerCase()==="recursive";return{recursive,newIndex:recursive?index+1:index}}static parseAllCommonTables(lexemes,index){let idx=index,tables=[],allTrailingComments=[],firstCte=CommonTableParser.parseFromLexeme(lexemes,idx);for(tables.push(firstCte.value),idx=firstCte.newIndex,firstCte.trailingComments&&allTrailingComments.push(...firstCte.trailingComments);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let cteResult=CommonTableParser.parseFromLexeme(lexemes,idx);tables.push(cteResult.value),idx=cteResult.newIndex,cteResult.trailingComments&&allTrailingComments.push(...cteResult.trailingComments)}return{tables,trailingComments:allTrailingComments,newIndex:idx}}};var ValuesQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The VALUES clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(idx>=lexemes.length)throw new Error(`Syntax error at position ${idx}: Expected 'VALUES' keyword but input ended early.`);let valuesLexeme=lexemes[idx];if(valuesLexeme.value.toLowerCase()!=="values")throw new Error(`Syntax error at position ${idx}: Expected 'VALUES' keyword but found "${valuesLexeme.value}". VALUES clauses must start with the VALUES keyword.`);let valuesComments=extractLexemeComments(valuesLexeme);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'VALUES' keyword. The VALUES clause requires at least one tuple expression.");let tuples=[],firstTuple=this.parseTuple(lexemes,idx);for(tuples.push(firstTuple.value),idx=firstTuple.newIndex,valuesComments.after.length>0&&firstTuple.value.addPositionedComments("before",valuesComments.after);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let tuple=this.parseTuple(lexemes,idx);tuples.push(tuple.value),idx=tuple.newIndex}let query=new ValuesQuery(tuples);return valuesComments.before.length>0&&(query.headerComments=valuesComments.before),{value:query,newIndex:idx}}static parseTuple(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].type!==4)throw new Error(`Syntax error at position ${idx}: Expected opening parenthesis but found "${idx<lexemes.length?lexemes[idx].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);let openingComments=extractLexemeComments(lexemes[idx]);idx++;let values=[];if(idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after opening parenthesis in tuple expression.");if(lexemes[idx].type&8){let tuple2=new TupleExpression([]),closingComments2=extractLexemeComments(lexemes[idx]);return idx++,openingComments.before.length>0&&tuple2.addPositionedComments("before",openingComments.before),closingComments2.after.length>0&&tuple2.addPositionedComments("after",closingComments2.after),{value:tuple2,newIndex:idx}}let firstValue=ValueParser.parseFromLexeme(lexemes,idx);for(values.push(firstValue.value),idx=firstValue.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after comma in tuple expression.");let value=ValueParser.parseFromLexeme(lexemes,idx);values.push(value.value),idx=value.newIndex}if(idx>=lexemes.length||lexemes[idx].type!==8)throw new Error(`Syntax error at position ${idx}: Expected closing parenthesis but found "${idx<lexemes.length?lexemes[idx].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);let closingComments=extractLexemeComments(lexemes[idx]);idx++;let tuple=new TupleExpression(values);return openingComments.before.length>0&&tuple.addPositionedComments("before",openingComments.before),openingComments.after.length>0&&values.length>0&&values[0].addPositionedComments("before",openingComments.after),closingComments.before.length>0&&values.length>0&&values[values.length-1].addPositionedComments("after",closingComments.before),closingComments.after.length>0&&tuple.addPositionedComments("after",closingComments.after),{value:tuple,newIndex:idx}}};var FetchClauseParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="fetch")throw new Error(`Syntax error at position ${idx}: Expected 'FETCH' keyword but found "${lexemes[idx].value}".`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH' keyword.");let fetchExprResult=FetchExpressionParser.parseFromLexeme(lexemes,idx),fetchExpr=fetchExprResult.value;return idx=fetchExprResult.newIndex,{value:new FetchClause(fetchExpr),newIndex:idx}}},FetchExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index,type,typeToken=lexemes[idx].value;if(typeToken==="first")type="first";else if(typeToken==="next")type="next";else throw new Error(`Syntax error at position ${idx}: Expected 'FIRST' or 'NEXT' after 'FETCH' but found "${lexemes[idx].value}".`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT'.");let count=null,unit=null;if(lexemes[idx].value==="row only"||lexemes[idx].value==="rows only")return count=new LiteralValue(1),unit="rows only",idx++,{value:new FetchExpression(type,count,unit),newIndex:idx};let countResult=ValueParser.parseFromLexeme(lexemes,idx);if(count=countResult.value,idx=countResult.newIndex,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT <count>'.");if(lexemes[idx].value==="rows only"?(unit="rows only",idx++):lexemes[idx].value==="percent"?(unit="percent",idx++):lexemes[idx].value==="percent with ties"&&(unit="percent with ties",idx++),!unit)throw new Error("Syntax error: Expected 'ROWS ONLY', 'PERCENT', or 'PERCENT WITH TIES' after 'FETCH FIRST|NEXT <count>'.");return{value:new FetchExpression(type,count,unit),newIndex:idx}}};var OffsetClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The OFFSET clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="offset")throw new Error(`Syntax error at position ${idx}: Expected 'OFFSET' keyword but found "${lexemes[idx].value}". OFFSET clauses must start with the OFFSET keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'OFFSET' keyword. The OFFSET clause requires a numeric expression.");let offsetItem=ValueParser.parseFromLexeme(lexemes,idx);return idx=offsetItem.newIndex,idx<lexemes.length&&(lexemes[idx].value==="row"||lexemes[idx].value==="rows")&&idx++,{value:new OffsetClause(offsetItem.value),newIndex:idx}}};var LexemeCursor=class{static{this.SQL_COMMANDS=new Set(["select","from","where","and","or","order","by","group","having","limit","offset","as","on","inner","left","right","join","union","insert","update","delete","into","values","set"])}static findLexemeAtLineColumn(sql,position){let charOffset=this.lineColumnToCharOffset(sql,position);return charOffset===-1?null:this.findLexemeAtPosition(sql,charOffset)}static findLexemeAtPosition(sql,cursorPosition){if(cursorPosition<0||cursorPosition>=sql.length)return null;let lexemes=this.getAllLexemesWithPosition(sql);for(let lexeme of lexemes)if(lexeme.position&&cursorPosition>=lexeme.position.startPosition&&cursorPosition<lexeme.position.endPosition)return lexeme;return null}static getAllLexemesWithPosition(sql){if(!sql?.trim())return[];try{let lexemes=[],position=0;for(;position<sql.length&&(position=this.skipWhitespaceAndComments(sql,position),!(position>=sql.length));){let lexeme=this.parseNextToken(sql,position);lexeme?(lexemes.push(lexeme),position=lexeme.position.endPosition):position++}return lexemes}catch{return[]}}static skipWhitespaceAndComments(sql,position){return StringUtils.readWhiteSpaceAndComment(sql,position).position}static parseNextToken(sql,startPos){let char=sql[startPos];return char==="'"||char==='"'?this.parseStringLiteral(sql,startPos):/[=<>!+\-*/%().*]/.test(char)?this.parseOperator(sql,startPos):char===","?this.createLexeme(16,",",startPos,startPos+1):/[a-zA-Z0-9_]/.test(char)?this.parseWordToken(sql,startPos):null}static parseStringLiteral(sql,startPos){let quote=sql[startPos],position=startPos+1,token=quote;for(;position<sql.length&&sql[position]!==quote;)token+=sql[position++];return position<sql.length&&(token+=sql[position++]),this.createLexeme(1,token,startPos,position)}static parseOperator(sql,startPos){let token=sql[startPos],position=startPos+1;position<sql.length&&/[=<>!]/.test(sql[position])&&/[=<>!]/.test(token)&&(token+=sql[position++]);let tokenType=this.getOperatorTokenType(token);return this.createLexeme(tokenType,token,startPos,position)}static parseWordToken(sql,startPos){let position=startPos,token="";for(;position<sql.length&&/[a-zA-Z0-9_]/.test(sql[position]);)token+=sql[position++];let tokenType=this.getWordTokenType(token,sql,position),value=this.shouldLowercase(tokenType)?token.toLowerCase():token;return this.createLexeme(tokenType,value,startPos,position)}static getOperatorTokenType(token){switch(token){case"(":return 4;case")":return 8;case"*":return 64;default:return 2}}static getWordTokenType(token,sql,position){let lowerToken=token.toLowerCase();if(this.SQL_COMMANDS.has(lowerToken))return 128;let nextNonWhitespacePos=this.skipWhitespaceAndComments(sql,position);return nextNonWhitespacePos<sql.length&&sql[nextNonWhitespacePos]==="("?2048:64}static shouldLowercase(tokenType){return!!(tokenType&128)||!!(tokenType&2)||!!(tokenType&2048)}static createLexeme(type,value,startPos,endPos){return{type,value,comments:null,position:{startPosition:startPos,endPosition:endPos}}}static lineColumnToCharOffset(sql,position){if(position.line<1||position.column<1)return-1;let lines=sql.split(`
29
29
  `);if(position.line>lines.length)return-1;let targetLine=lines[position.line-1];if(position.column>targetLine.length+1)return-1;let offset=0;for(let i=0;i<position.line-1;i++)offset+=lines[i].length+1;return offset+=position.column-1,offset}static charOffsetToLineColumn(sql,charOffset){if(charOffset<0||charOffset>sql.length)return null;let lines=sql.split(`
30
30
  `),currentOffset=0;for(let lineIndex=0;lineIndex<lines.length;lineIndex++){let lineLength=lines[lineIndex].length;if(charOffset<currentOffset+lineLength)return{line:lineIndex+1,column:charOffset-currentOffset+1};if(charOffset===currentOffset+lineLength&&lineIndex<lines.length-1)return{line:lineIndex+2,column:1};currentOffset+=lineLength+1}if(charOffset===sql.length){let lastLine=lines[lines.length-1];return{line:lines.length,column:lastLine.length+1}}return null}};var CTERegionDetector=class{static analyzeCursorPosition(sql,cursorPosition){let cteRegions=this.extractCTERegions(sql),currentCTE=this.calculateExtendedCTEBoundaries(sql,cteRegions).find(region=>cursorPosition>=region.startPosition&&cursorPosition<region.extendedEndPosition);return currentCTE?{isInCTE:!0,cteRegion:{name:currentCTE.name,startPosition:currentCTE.startPosition,endPosition:currentCTE.endPosition,sqlContent:currentCTE.sqlContent},executableSQL:currentCTE.sqlContent}:{isInCTE:!1,cteRegion:null,executableSQL:this.extractMainQuery(sql,cteRegions)}}static getCursorCte(sql,cursorPosition){try{let analysis=this.analyzeCursorPosition(sql,cursorPosition);return analysis.isInCTE&&analysis.cteRegion?.name||null}catch{return null}}static getCursorCteAt(sql,line,column){try{let position=this.lineColumnToPosition(sql,line,column);return position===-1?null:this.getCursorCte(sql,position)}catch{return null}}static lineColumnToPosition(text,line,column){if(line<1||column<1)return-1;let lines=text.split(`
31
31
  `);if(line>lines.length)return-1;let targetLine=lines[line-1];if(column>targetLine.length+1)return-1;let position=0;for(let i=0;i<line-1;i++)position+=lines[i].length+1;return position+=column-1,position}static positionToLineColumn(text,position){if(position<0||position>text.length)return null;let lines=text.substring(0,position).split(`
32
- `);return{line:lines.length,column:lines[lines.length-1].length+1}}static extractCTERegions(sql){let lexemes=LexemeCursor.getAllLexemesWithPosition(sql),cteRegions=[],i=0,inWithClause=!1;for(;i<lexemes.length;){let lexeme=lexemes[i];if(lexeme.value.toLowerCase()==="with"&&!inWithClause){inWithClause=!0,i++;continue}if(inWithClause&&lexeme.value.toLowerCase()==="recursive"){i++;continue}if(inWithClause&&lexeme.type===64&&i+1<lexemes.length&&lexemes[i+1].value.toLowerCase()==="as"){let cteName=lexeme.value,cteStartPos=lexeme.position.startPosition,parenIndex=i+2;for(;parenIndex<lexemes.length&&lexemes[parenIndex].value!=="(";)parenIndex++;if(parenIndex<lexemes.length){let cteEndInfo=this.findMatchingParen(lexemes,parenIndex);if(cteEndInfo){let cteEndPos=cteEndInfo.endPosition,sqlContent=this.extractCTESQL(sql,lexemes,parenIndex,cteEndInfo.index);cteRegions.push({name:cteName,startPosition:cteStartPos,endPosition:cteEndPos,sqlContent}),i=cteEndInfo.index+1;continue}}}if(inWithClause&&lexeme.value.toLowerCase()==="select"&&this.isMainQuerySelect(lexemes,i))break;i++}return cteRegions}static findMatchingParen(lexemes,openParenIndex){let depth=1,i=openParenIndex+1;for(;i<lexemes.length&&depth>0;){if(lexemes[i].value==="("?depth++:lexemes[i].value===")"&&depth--,depth===0)return{index:i,endPosition:lexemes[i].position.endPosition};i++}return null}static extractCTESQL(sql,lexemes,openParenIndex,closeParenIndex){let startPos=lexemes[openParenIndex+1].position.startPosition,endPos=lexemes[closeParenIndex-1].position.endPosition;return sql.substring(startPos,endPos).trim()}static isMainQuerySelect(lexemes,selectIndex){let depth=0;for(let i=selectIndex-1;i>=0;i--)lexemes[i].value===")"?depth++:lexemes[i].value==="("&&depth--;return depth===0}static calculateExtendedCTEBoundaries(sql,cteRegions){return cteRegions.length===0?[]:cteRegions.map((region,index)=>{let extendedEndPosition;return index<cteRegions.length-1?extendedEndPosition=cteRegions[index+1].startPosition:extendedEndPosition=this.findMainQueryStart(sql,region.endPosition),{...region,extendedEndPosition}})}static findMainQueryStart(sql,afterPosition){let pos=afterPosition;for(;pos<sql.length;){if(sql.substring(pos).toLowerCase().trim().startsWith("select")){let selectIndex=sql.toLowerCase().indexOf("select",pos);return selectIndex!==-1?selectIndex:pos}pos++}return sql.length}static extractMainQuery(sql,cteRegions){if(cteRegions.length===0)return sql.trim();let selectPos=cteRegions[cteRegions.length-1].endPosition;for(;selectPos<sql.length&&!sql.substring(selectPos).toLowerCase().trim().startsWith("select");)selectPos++;return sql.substring(selectPos).trim()}static getCTEPositions(sql){let cteRegions=this.extractCTERegions(sql),results=[];if(cteRegions.forEach(region=>{results.push({name:region.name,startPosition:region.startPosition,type:"CTE"})}),cteRegions.length>0){let mainQueryPos=cteRegions[cteRegions.length-1].endPosition;for(;mainQueryPos<sql.length;){if(sql.substring(mainQueryPos).toLowerCase().trim().startsWith("select")){results.push({name:"MAIN_QUERY",startPosition:mainQueryPos,type:"MAIN_QUERY"});break}mainQueryPos++}}else results.push({name:"MAIN_QUERY",startPosition:0,type:"MAIN_QUERY"});return results}};var SelectQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`[SelectQueryParser] Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The SELECT query is complete but there are additional tokens.`);return result.value}static calculateCharacterPosition(query,lexemes,tokenIndex){if(tokenIndex>=lexemes.length)return query.length;let lexeme=lexemes[tokenIndex];if(lexeme.position?.startPosition!==void 0)return lexeme.position.startPosition;let searchStart=0;for(let i=0;i<tokenIndex;i++){let tokenValue=lexemes[i].value,tokenPos2=query.indexOf(tokenValue,searchStart);tokenPos2!==-1&&(searchStart=tokenPos2+tokenValue.length)}let targetToken=lexemes[tokenIndex].value,tokenPos=query.indexOf(targetToken,searchStart);return tokenPos!==-1?tokenPos:searchStart}static analyze(query){let lexemes=[];try{lexemes=new SqlTokenizer(query).readLexmes();let result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length){let remainingTokens=lexemes.slice(result.newIndex).map(lex=>lex.value),errorLexeme=lexemes[result.newIndex],errorPosition=this.calculateCharacterPosition(query,lexemes,result.newIndex);return{success:!1,query:result.value,error:`Syntax error: Unexpected token "${errorLexeme.value}" at character position ${errorPosition}. The SELECT query is complete but there are additional tokens.`,errorPosition,remainingTokens}}return{success:!0,query:result.value}}catch(error){let errorPosition,errorMessage=error instanceof Error?error.message:String(error),positionMatch=errorMessage.match(/position (\d+)/);if(positionMatch){let tokenIndex=parseInt(positionMatch[1],10);errorPosition=this.calculateCharacterPosition(query,lexemes,tokenIndex)}return{success:!1,error:errorMessage,errorPosition}}}static async parseAsync(query){return Promise.resolve(this.parse(query))}static{this.unionCommandSet=new Set(["union","union all","intersect","intersect all","except","except all"])}static{this.selectCommandSet=new Set(["with","select"])}static transferHeaderComments(source,target){source.headerComments&&(target.headerComments=source.headerComments,source.headerComments=null)}static extractUnionTokenComments(unionLexeme){let comments=[];if(unionLexeme.positionedComments&&unionLexeme.positionedComments.length>0){for(let posComment of unionLexeme.positionedComments)posComment.comments&&posComment.comments.length>0&&comments.push(...posComment.comments);unionLexeme.positionedComments=void 0}return unionLexeme.comments&&unionLexeme.comments.length>0&&(comments.push(...unionLexeme.comments),unionLexeme.comments=null),comments.length>0?comments:null}static parseFromLexeme(lexemes,index){let idx=index;if(idx>=lexemes.length)throw new Error(`Syntax error: Unexpected end of input at position ${index}.`);let firstToken=lexemes[idx].value;if(!this.selectCommandSet.has(firstToken)&&firstToken!=="values")throw new Error(`Syntax error at position ${idx}: Expected 'SELECT' or 'VALUES' keyword but found "${lexemes[idx].value}".`);let firstResult=this.selectCommandSet.has(firstToken)?this.parseSimpleSelectQuery(lexemes,idx):this.parseValuesQuery(lexemes,idx),query=firstResult.value;for(idx=firstResult.newIndex;idx<lexemes.length&&this.unionCommandSet.has(lexemes[idx].value.toLowerCase());){let operatorLexeme=lexemes[idx],operator=operatorLexeme.value.toLowerCase(),unionComments=this.extractUnionTokenComments(operatorLexeme);if(idx++,idx>=lexemes.length)throw new Error(`Syntax error at position ${idx}: Expected a query after '${operator.toUpperCase()}' but found end of input.`);let nextToken=lexemes[idx].value.toLowerCase();if(this.selectCommandSet.has(nextToken)){let result=this.parseSimpleSelectQuery(lexemes,idx),binaryQuery=new BinarySelectQuery(query,operator,result.value);this.transferHeaderComments(query,binaryQuery),unionComments&&unionComments.length>0&&(result.value.headerComments?result.value.headerComments=[...unionComments,...result.value.headerComments]:result.value.headerComments=unionComments),query=binaryQuery,idx=result.newIndex}else if(nextToken==="values"){let result=this.parseValuesQuery(lexemes,idx),binaryQuery=new BinarySelectQuery(query,operator,result.value);this.transferHeaderComments(query,binaryQuery),unionComments&&unionComments.length>0&&(result.value.headerComments?result.value.headerComments=[...unionComments,...result.value.headerComments]:result.value.headerComments=unionComments),query=binaryQuery,idx=result.newIndex}else throw new Error(`Syntax error at position ${idx}: Expected 'SELECT' or 'VALUES' after '${operator.toUpperCase()}' but found "${lexemes[idx].value}".`)}return{value:query,newIndex:idx}}static parseSimpleSelectQuery(lexemes,index){let idx=index,{withClauseResult,newIndex:withEndIndex,selectQuery:queryTemplate}=this.parseWithClauseAndComments(lexemes,idx);idx=withEndIndex;let{clauses,newIndex:clausesEndIndex,selectTokenComments}=this.parseAllClauses(lexemes,idx,withClauseResult);if(idx=clausesEndIndex,selectTokenComments&&selectTokenComments.length>0)if(withClauseResult){let merged=[...queryTemplate.betweenClauseComments??[]];for(let comment of selectTokenComments)merged.includes(comment)||merged.push(comment);queryTemplate.betweenClauseComments=merged,queryTemplate.mainSelectPrefixComments=void 0}else{let existingHeader=queryTemplate.headerComments??[];queryTemplate.headerComments=[...existingHeader,...selectTokenComments]}let selectQuery=new SimpleSelectQuery({withClause:withClauseResult?withClauseResult.value:null,...clauses});return this.applyCommentsToQuery(selectQuery,queryTemplate,withClauseResult),{value:selectQuery,newIndex:idx}}static parseWithClauseAndComments(lexemes,index){let idx=index,withClauseResult=null,queryTemplate={};for(queryTemplate.headerComments=this.collectHeaderComments(lexemes,idx);idx<lexemes.length&&lexemes[idx].value.toLowerCase()!=="with"&&lexemes[idx].value.toLowerCase()!=="select";)idx++;return idx<lexemes.length&&lexemes[idx].value.toLowerCase()==="with"&&this.collectWithTokenHeaderComments(lexemes[idx],queryTemplate),idx<lexemes.length&&lexemes[idx].value==="with"&&(withClauseResult=WithClauseParser.parseFromLexeme(lexemes,idx),idx=withClauseResult.newIndex,queryTemplate.mainSelectPrefixComments=this.collectMainSelectPrefixComments(lexemes,withClauseResult,idx),queryTemplate.betweenClauseComments=this.collectBetweenClauseComments(lexemes,withClauseResult,idx)),{withClauseResult,newIndex:idx,selectQuery:queryTemplate}}static parseAllClauses(lexemes,index,withClauseResult){let idx=index;idx=this.findMainSelectToken(lexemes,idx,withClauseResult);let selectTokenComments=this.collectSelectTokenComments(lexemes,idx),selectClauseResult=SelectClauseParser.parseFromLexeme(lexemes,idx);idx=selectClauseResult.newIndex;let fromClauseResult=this.parseOptionalClause(lexemes,idx,"from",FromClauseParser);idx=fromClauseResult.newIndex;let whereClauseResult=this.parseOptionalClause(lexemes,fromClauseResult.newIndex,"where",WhereClauseParser);idx=whereClauseResult.newIndex;let groupByClauseResult=this.parseOptionalClause(lexemes,whereClauseResult.newIndex,"group by",GroupByClauseParser);idx=groupByClauseResult.newIndex;let havingClauseResult=this.parseOptionalClause(lexemes,groupByClauseResult.newIndex,"having",HavingClauseParser);idx=havingClauseResult.newIndex;let windowClauseResult=this.parseOptionalClause(lexemes,havingClauseResult.newIndex,"window",WindowClauseParser);idx=windowClauseResult.newIndex;let orderByClauseResult=this.parseOptionalClause(lexemes,windowClauseResult.newIndex,"order by",OrderByClauseParser);idx=orderByClauseResult.newIndex;let limitClauseResult=this.parseOptionalClause(lexemes,orderByClauseResult.newIndex,"limit",LimitClauseParser);idx=limitClauseResult.newIndex;let offsetClauseResult=this.parseOptionalClause(lexemes,limitClauseResult.newIndex,"offset",OffsetClauseParser);idx=offsetClauseResult.newIndex;let fetchClauseResult=this.parseOptionalClause(lexemes,offsetClauseResult.newIndex,"fetch",FetchClauseParser);idx=fetchClauseResult.newIndex;let forClauseResult=this.parseOptionalClause(lexemes,fetchClauseResult.newIndex,"for",ForClauseParser);return idx=forClauseResult.newIndex,{clauses:{selectClause:selectClauseResult.value,fromClause:fromClauseResult.value,whereClause:whereClauseResult.value,groupByClause:groupByClauseResult.value,havingClause:havingClauseResult.value,orderByClause:orderByClauseResult.value,windowClause:windowClauseResult.value,limitClause:limitClauseResult.value,offsetClause:offsetClauseResult.value,fetchClause:fetchClauseResult.value,forClause:forClauseResult.value},newIndex:idx,selectTokenComments}}static parseOptionalClause(lexemes,index,keyword,parser){return index<lexemes.length&&lexemes[index].value.toLowerCase()===keyword?parser.parseFromLexeme(lexemes,index):{value:null,newIndex:index}}static collectHeaderComments(lexemes,startIndex){let headerComments=[],idx=startIndex;for(;idx<lexemes.length&&lexemes[idx].value.toLowerCase()!=="with"&&lexemes[idx].value.toLowerCase()!=="select";){let token=lexemes[idx];if(token.positionedComments)for(let posComment of token.positionedComments)posComment.comments&&headerComments.push(...posComment.comments);token.comments&&token.comments.length>0&&headerComments.push(...token.comments),idx++}return headerComments}static collectWithTokenHeaderComments(withToken,queryTemplate){if(!withToken.positionedComments)return;queryTemplate.headerComments||(queryTemplate.headerComments=[]);let remainingPositioned=[];for(let posComment of withToken.positionedComments)posComment.position==="before"&&posComment.comments?queryTemplate.headerComments.push(...posComment.comments):remainingPositioned.push(posComment);withToken.positionedComments=remainingPositioned.length>0?remainingPositioned:void 0}static collectMainSelectPrefixComments(lexemes,withClauseResult,currentIndex){let mainSelectPrefixComments=[];withClauseResult?.value.trailingComments&&mainSelectPrefixComments.push(...withClauseResult.value.trailingComments);let mainSelectIdx=this.findMainSelectIndex(lexemes,withClauseResult,currentIndex);if(withClauseResult&&mainSelectIdx>withClauseResult.newIndex)for(let tempIdx=withClauseResult.newIndex;tempIdx<mainSelectIdx;tempIdx++){let token=lexemes[tempIdx];if(token.positionedComments)for(let posComment of token.positionedComments)posComment.comments&&mainSelectPrefixComments.push(...posComment.comments);token.comments&&token.comments.length>0&&mainSelectPrefixComments.push(...token.comments)}return mainSelectPrefixComments}static collectBetweenClauseComments(lexemes,withClauseResult,currentIndex){if(!withClauseResult)return[];let betweenClauseComments=[],withEndIndex=withClauseResult.newIndex,scanStartIndex=Math.max(0,withEndIndex-1);for(let i=scanStartIndex;i<currentIndex;i++){let token=lexemes[i];if(token.positionedComments&&token.positionedComments.length>0){for(let posComment of token.positionedComments)posComment.comments&&betweenClauseComments.push(...posComment.comments);token.positionedComments=void 0}token.comments&&token.comments.length>0&&(betweenClauseComments.push(...token.comments),token.comments=null)}return betweenClauseComments}static findMainSelectIndex(lexemes,withClauseResult,fallbackIndex){if(withClauseResult){for(let i=withClauseResult.newIndex;i<lexemes.length;i++)if(lexemes[i].value.toLowerCase()==="select")return i}return fallbackIndex}static findMainSelectToken(lexemes,index,withClauseResult){let mainSelectIdx=this.findMainSelectIndex(lexemes,withClauseResult,index);if(mainSelectIdx>=lexemes.length||lexemes[mainSelectIdx].value!=="select")throw new Error(`Syntax error at position ${mainSelectIdx}: Expected 'SELECT' keyword but found "${mainSelectIdx<lexemes.length?lexemes[mainSelectIdx].value:"end of input"}". SELECT queries must start with the SELECT keyword.`);return mainSelectIdx}static collectSelectTokenComments(lexemes,selectIndex){let selectToken=lexemes[selectIndex],selectComments=[];if(selectToken.comments&&selectToken.comments.length>0&&(selectComments.push(...selectToken.comments),selectToken.comments=null),selectToken.positionedComments&&selectToken.positionedComments.length>0){for(let posComment of selectToken.positionedComments)posComment.position==="before"&&posComment.comments&&selectComments.push(...posComment.comments);selectToken.positionedComments=void 0}return selectComments}static applyCommentsToQuery(selectQuery,queryTemplate,withClauseResult){queryTemplate.headerComments?.length>0&&(selectQuery.headerComments=queryTemplate.headerComments);let mergeBetweenComments=source=>{if(!source||source.length===0)return;let existing=selectQuery.comments??[],merged=[];for(let comment of source)merged.includes(comment)||merged.push(comment);for(let comment of existing)merged.includes(comment)||merged.push(comment);selectQuery.comments=merged};mergeBetweenComments(queryTemplate.mainSelectPrefixComments),mergeBetweenComments(queryTemplate.betweenClauseComments)}static parseValuesQuery(lexemes,index){let result=ValuesQueryParser.parseFromLexeme(lexemes,index);return{value:result.value,newIndex:result.newIndex}}static getCursorCte(sql,cursorPosition){return CTERegionDetector.getCursorCte(sql,cursorPosition)}static getCursorCteAt(sql,line,column){return CTERegionDetector.getCursorCteAt(sql,line,column)}static positionToLineColumn(text,position){return CTERegionDetector.positionToLineColumn(text,position)}};var ReturningClauseParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx]?.value!=="returning")throw new Error(`Syntax error at position ${idx}: Expected 'RETURNING' but found '${lexemes[idx]?.value}'.`);let returningLexeme=lexemes[idx],returningComments=extractLexemeComments(returningLexeme);idx++;let columns=[],pendingBeforeForNext=[...returningComments.after];for(;idx<lexemes.length;){let lexeme=lexemes[idx],column=null;if(lexeme.type&64?column=new IdentifierString(lexeme.value):lexeme.value==="*"&&(column=new IdentifierString("*")),!column)break;let columnComments=extractLexemeComments(lexeme),beforeComments=[];if(pendingBeforeForNext.length>0&&beforeComments.push(...pendingBeforeForNext),columnComments.before.length>0&&beforeComments.push(...columnComments.before),beforeComments.length>0&&column.addPositionedComments("before",beforeComments),columnComments.after.length>0&&column.addPositionedComments("after",columnComments.after),columns.push(column),pendingBeforeForNext=[],idx++,lexemes[idx]?.type===16){pendingBeforeForNext=[...extractLexemeComments(lexemes[idx]).after],idx++;continue}break}if(pendingBeforeForNext.length>0&&columns.length>0&&columns[columns.length-1].addPositionedComments("after",pendingBeforeForNext),columns.length===0){let position=lexemes[idx]?.position?.startPosition??idx;throw new Error(`[ReturningClauseParser] Expected a column or '*' after RETURNING at position ${position}.`)}let clause=new ReturningClause(columns);return returningComments.before.length>0&&clause.addPositionedComments("before",returningComments.before),{value:clause,newIndex:idx}}};var InsertQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The INSERT query is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value==="with"){let result=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=result.value,idx=result.newIndex}if(!lexemes[idx]||lexemes[idx].value!=="insert into"){let found=lexemes[idx]?.value??"end of input";throw new Error(`Syntax error at position ${idx}: Expected 'INSERT INTO' but found '${found}'.`)}let insertKeywordLexeme=lexemes[idx],insertKeywordComments=extractLexemeComments(insertKeywordLexeme);idx++;let sourceResult=SourceExpressionParser.parseTableSourceFromLexemes(lexemes,idx),targetSource=sourceResult.value,targetDatasource=targetSource.datasource;idx=sourceResult.newIndex,insertKeywordComments.after.length>0&&targetDatasource.addPositionedComments("before",insertKeywordComments.after);let columnIdentifiers=null,trailingInsertComments=[];if(lexemes[idx]?.type===4){let openParenLexeme=lexemes[idx],parenComments=extractLexemeComments(openParenLexeme);idx++,parenComments.before.length>0&&targetDatasource.addPositionedComments("after",parenComments.before),columnIdentifiers=[];let pendingBeforeForNext=[...parenComments.after];for(;idx<lexemes.length&&lexemes[idx].type&64;){let columnLexeme=lexemes[idx],columnComments=extractLexemeComments(columnLexeme),column=new IdentifierString(columnLexeme.value),beforeComments=[];if(pendingBeforeForNext.length>0&&beforeComments.push(...pendingBeforeForNext),columnComments.before.length>0&&beforeComments.push(...columnComments.before),beforeComments.length>0&&column.addPositionedComments("before",beforeComments),columnComments.after.length>0&&column.addPositionedComments("after",columnComments.after),columnIdentifiers.push(column),pendingBeforeForNext=[],idx++,lexemes[idx]?.type===16){pendingBeforeForNext=[...extractLexemeComments(lexemes[idx]).after],idx++;continue}break}if(pendingBeforeForNext.length>0&&columnIdentifiers.length>0&&(columnIdentifiers[columnIdentifiers.length-1].addPositionedComments("after",pendingBeforeForNext),pendingBeforeForNext=[]),lexemes[idx]?.type!==8)throw new Error(`Syntax error at position ${idx}: Expected ')' after column list.`);let closeParenComments=extractLexemeComments(lexemes[idx]);idx++,closeParenComments.before.length>0&&columnIdentifiers.length>0&&columnIdentifiers[columnIdentifiers.length-1].addPositionedComments("after",closeParenComments.before),closeParenComments.after.length>0&&(trailingInsertComments=closeParenComments.after),columnIdentifiers.length===0&&(columnIdentifiers=[])}if(idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input while parsing INSERT statement. VALUES or SELECT clause expected.");let nextToken=lexemes[idx].value.toLowerCase(),dataQuery;if(nextToken==="values"){let valuesResult=ValuesQueryParser.parseFromLexeme(lexemes,idx);dataQuery=valuesResult.value,idx=valuesResult.newIndex}else{let selectResult=SelectQueryParser.parseFromLexeme(lexemes,idx);dataQuery=selectResult.value,idx=selectResult.newIndex}let returningClause=null;if(lexemes[idx]?.value==="returning"){let returningResult=ReturningClauseParser.parseFromLexeme(lexemes,idx);returningClause=returningResult.value,idx=returningResult.newIndex}let insertClause=new InsertClause(targetSource,columnIdentifiers??null);return insertKeywordComments.before.length>0&&insertClause.addPositionedComments("before",insertKeywordComments.before),trailingInsertComments.length>0&&insertClause.addPositionedComments("after",trailingInsertComments),{value:new InsertQuery({withClause,insertClause,selectQuery:dataQuery,returning:returningClause}),newIndex:idx}}};var UpdateClauseParser=class{static parseFromLexeme(lexemes,index){let result=SourceExpressionParser.parseFromLexeme(lexemes,index);return{value:new UpdateClause(result.value),newIndex:result.newIndex}}};var SetClauseParser=class{static parseFromLexeme(lexemes,idx){if(lexemes[idx].value!=="set")throw new Error(`Syntax error at position ${idx}: Expected 'SET' but found '${lexemes[idx].value}'.`);let setLexeme=lexemes[idx],setKeywordComments=extractLexemeComments(setLexeme);idx++;let items=[],pendingBeforeForNext=[...setKeywordComments.after],mergeUnique=(target,source)=>{for(let comment of source)target.includes(comment)||target.push(comment)},addUniquePositionedComments=(component,position,comments)=>{if(comments.length===0)return;let existing=component.getPositionedComments(position),newOnes=comments.filter(comment=>!existing.includes(comment));newOnes.length>0&&component.addPositionedComments(position,newOnes)};for(;idx<lexemes.length;){let currentLexeme=lexemes[idx];if(!currentLexeme||currentLexeme.value==="where"||currentLexeme.value==="from"||currentLexeme.value==="returning"||!(currentLexeme.type&10816))break;let columnStartComments=extractLexemeComments(currentLexeme),columnParseResult=FullNameParser.parseFromLexeme(lexemes,idx);idx=columnParseResult.newIndex;let equalsLexeme=lexemes[idx];if(!equalsLexeme||!(equalsLexeme.type&2)||equalsLexeme.value!=="=")throw new Error(`Syntax error at position ${idx}: Expected '=' after column name in SET clause.`);let equalsComments=extractLexemeComments(equalsLexeme);idx++;let valueParseResult=ValueParser.parseFromLexeme(lexemes,idx);idx=valueParseResult.newIndex;let setItem=new SetClauseItem({namespaces:columnParseResult.namespaces,column:columnParseResult.name},valueParseResult.value),beforeComments=[];if(mergeUnique(beforeComments,pendingBeforeForNext),mergeUnique(beforeComments,columnStartComments.before),beforeComments.length>0&&addUniquePositionedComments(columnParseResult.name,"before",beforeComments),pendingBeforeForNext=[],columnStartComments.after.length>0){let afterComments=[];mergeUnique(afterComments,columnStartComments.after),addUniquePositionedComments(columnParseResult.name,"after",afterComments)}if(equalsComments.before.length>0){let equalsBefore=[];mergeUnique(equalsBefore,equalsComments.before),addUniquePositionedComments(columnParseResult.name,"after",equalsBefore)}if(equalsComments.after.length>0){let equalsAfter=[];mergeUnique(equalsAfter,equalsComments.after),addUniquePositionedComments(valueParseResult.value,"before",equalsAfter)}if(items.push(setItem),lexemes[idx]?.type===16){let commaLexeme=lexemes[idx],commaComments=extractLexemeComments(commaLexeme);if(idx++,commaComments.before.length>0){let commaBefore=[];mergeUnique(commaBefore,commaComments.before),addUniquePositionedComments(setItem,"after",commaBefore)}let nextBefore=[];mergeUnique(nextBefore,commaComments.after),pendingBeforeForNext=nextBefore;continue}break}if(pendingBeforeForNext.length>0&&items.length>0){let trailingComments=[];mergeUnique(trailingComments,pendingBeforeForNext),trailingComments.length>0&&addUniquePositionedComments(items[items.length-1],"after",trailingComments)}let setClause=new SetClause(items);return setKeywordComments.before.length>0&&setClause.addPositionedComments("before",setKeywordComments.before),{setClause,newIndex:idx}}};var UpdateQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The UPDATE query is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value?.toLowerCase()==="with"){let withResult=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=withResult.value,idx=withResult.newIndex}if(lexemes[idx].value!=="update")throw new Error(`Syntax error at position ${idx}: Expected 'UPDATE' but found '${lexemes[idx].value}'.`);let updateLexeme=lexemes[idx],updateKeywordComments=extractLexemeComments(updateLexeme);idx++;let updateClauseResult=UpdateClauseParser.parseFromLexeme(lexemes,idx),updateClause=updateClauseResult.value;idx=updateClauseResult.newIndex,updateKeywordComments.before.length>0&&updateClause.addPositionedComments("before",updateKeywordComments.before),updateKeywordComments.after.length>0&&updateClause.addPositionedComments("after",updateKeywordComments.after);let setClauseResult=SetClauseParser.parseFromLexeme(lexemes,idx),setClause=setClauseResult.setClause;idx=setClauseResult.newIndex;let from=null;if(lexemes[idx]?.value==="from"){let result=FromClauseParser.parseFromLexeme(lexemes,idx);from=result.value,idx=result.newIndex}let where=null;if(lexemes[idx]?.value==="where"){let result=WhereClauseParser.parseFromLexeme(lexemes,idx);where=result.value,idx=result.newIndex}let returning=null;if(lexemes[idx]?.value==="returning"){let result=ReturningClauseParser.parseFromLexeme(lexemes,idx);returning=result.value,idx=result.newIndex}return{value:new UpdateQuery({withClause,updateClause,setClause,whereClause:where,fromClause:from,returning}),newIndex:idx}}};var DeleteClauseParser=class{static parseFromLexeme(lexemes,index){if(index>=lexemes.length)throw new Error(`[DeleteClauseParser] Unexpected end of input at position ${index}: expected 'DELETE FROM'.`);let deleteToken=lexemes[index];if(deleteToken?.value?.toLowerCase()!=="delete from"){let position=lexemes[index]?.position?.startPosition??index;throw new Error(`[DeleteClauseParser] Syntax error at position ${position}: expected 'DELETE FROM' but found '${lexemes[index]?.value}'.`)}let deleteTokenComments=extractLexemeComments(deleteToken),targetResult=SourceExpressionParser.parseFromLexeme(lexemes,index+1),deleteClause=new DeleteClause(targetResult.value);return deleteTokenComments.before.length>0&&deleteClause.addPositionedComments("before",deleteTokenComments.before),deleteTokenComments.after.length>0&&deleteClause.addPositionedComments("after",deleteTokenComments.after),{value:deleteClause,newIndex:targetResult.newIndex}}};var UsingClauseParser=class{static parseFromLexeme(lexemes,index){if(lexemes[index].value!=="using")throw new Error(`Syntax error at position ${index}: Expected 'USING' but found '${lexemes[index].value}'.`);let idx=index+1,sources=[],firstSource=SourceExpressionParser.parseFromLexeme(lexemes,idx);for(sources.push(firstSource.value),idx=firstSource.newIndex;lexemes[idx]?.type===16;){idx++;let nextSource=SourceExpressionParser.parseFromLexeme(lexemes,idx);sources.push(nextSource.value),idx=nextSource.newIndex}return{value:new UsingClause(sources),newIndex:idx}}};var DeleteQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The DELETE query is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value==="with"){let withResult=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=withResult.value,idx=withResult.newIndex}let deleteClauseResult=DeleteClauseParser.parseFromLexeme(lexemes,idx),deleteClause=deleteClauseResult.value;idx=deleteClauseResult.newIndex;let usingClause=null;if(lexemes[idx]?.value==="using"){let usingResult=UsingClauseParser.parseFromLexeme(lexemes,idx);usingClause=usingResult.value,idx=usingResult.newIndex}let whereClause=null;if(lexemes[idx]?.value==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}let returningClause=null;if(lexemes[idx]?.value==="returning"){let returningResult=ReturningClauseParser.parseFromLexeme(lexemes,idx);returningClause=returningResult.value,idx=returningResult.newIndex}return{value:new DeleteQuery({withClause,deleteClause,usingClause,whereClause,returning:returningClause}),newIndex:idx}}};var NO_SPACE_BEFORE=new Set([",",")","]","}",";"]),NO_SPACE_AFTER=new Set(["(","[","{"]);function joinLexemeValues(lexemes,start,end){let result="";for(let i=start;i<end;i++){let current=lexemes[i];if(!current)continue;if(result.length===0){result=current.value;continue}let previous=lexemes[i-1]?.value??"",omitSpace=NO_SPACE_BEFORE.has(current.value)||NO_SPACE_AFTER.has(previous)||current.value==="."||previous===".";result+=omitSpace?current.value:` ${current.value}`}return result}var CreateTableParser=class{static{this.TABLE_CONSTRAINT_STARTERS=new Set(["constraint","primary key","unique","unique key","foreign key","check"])}static{this.COLUMN_CONSTRAINT_STARTERS=new Set(["constraint","not null","null","default","primary key","unique","unique key","references","check","generated always","generated always as identity","generated by default","generated by default as identity"])}static{this.MATCH_KEYWORDS=new Map([["match full","full"],["match partial","partial"],["match simple","simple"]])}static{this.REFERENTIAL_ACTIONS=new Map([["cascade","cascade"],["restrict","restrict"],["no action","no action"],["set null","set null"],["set default","set default"]])}static{this.DEFERRABILITY_KEYWORDS=new Map([["deferrable","deferrable"],["not deferrable","not deferrable"]])}static{this.INITIALLY_KEYWORDS=new Map([["initially immediate","immediate"],["initially deferred","deferred"]])}static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The CREATE TABLE statement is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(idx>=lexemes.length)throw new Error(`[CreateTableParser] Unexpected end of input at position ${idx}.`);let commandLexeme=lexemes[idx],leadingCreateComments=this.popLexemeComments(commandLexeme,"before"),commandToken=commandLexeme.value.toLowerCase(),isTemporary=commandToken==="create temporary table";if(commandToken!=="create table"&&!isTemporary)throw new Error(`[CreateTableParser] Syntax error at position ${idx}: expected 'CREATE TABLE' but found '${lexemes[idx].value}'.`);idx++;let tokenAt=offset=>lexemes[idx+offset]?.value.toLowerCase(),ifNotExists=!1;tokenAt(0)==="if not exists"&&(idx++,ifNotExists=!0);let tableNameResult=this.parseQualifiedName(lexemes,idx);idx=tableNameResult.newIndex;let tableName=tableNameResult.name,tableNamespaces=tableNameResult.namespaces,positionedComments=tableName.positionedComments?[...tableName.positionedComments]:null,legacyComments=tableName.comments?[...tableName.comments]:null,columns=[],tableConstraints=[],tableOptions=null,asSelectQuery,withDataOption=null;if(lexemes[idx]?.type===4&&({columns,tableConstraints,newIndex:idx}=this.parseDefinitionList(lexemes,idx)),idx<lexemes.length){let nextValue=tokenAt(0);if(!this.isSelectKeyword(nextValue,lexemes[idx+1])){let optionsEnd=this.findClauseBoundary(lexemes,idx);optionsEnd>idx&&(tableOptions=new RawString(joinLexemeValues(lexemes,idx,optionsEnd)),idx=optionsEnd)}}let nextToken=tokenAt(0);if(nextToken==="as"){idx++;let selectResult=SelectQueryParser.parseFromLexeme(lexemes,idx);asSelectQuery=selectResult.value,idx=selectResult.newIndex}else if(nextToken==="select"||nextToken==="with"||nextToken==="values"){let selectResult=SelectQueryParser.parseFromLexeme(lexemes,idx);asSelectQuery=selectResult.value,idx=selectResult.newIndex}if(asSelectQuery){let withResult=this.parseWithDataOption(lexemes,idx);withResult&&(withDataOption=withResult.value,idx=withResult.newIndex)}let query=new CreateTableQuery({tableName:tableName.name,namespaces:tableNamespaces,isTemporary,ifNotExists,columns,tableConstraints,tableOptions,asSelectQuery,withDataOption});return positionedComments&&(query.tableName.positionedComments=positionedComments.map(pc=>({position:pc.position,comments:[...pc.comments]}))),legacyComments&&(query.tableName.comments=[...legacyComments]),leadingCreateComments.length>0&&query.addPositionedComments("before",leadingCreateComments),{value:query,newIndex:idx}}static parseQualifiedName(lexemes,index){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,index);return{namespaces:namespaces?[...namespaces]:null,name,newIndex}}static parseDefinitionList(lexemes,index){let idx=index,columns=[],constraints=[],openParenLexeme=lexemes[idx],pendingLeading=this.toOptionalComments(this.popLexemeComments(openParenLexeme,"after"));for(idx++;idx<lexemes.length;){let lexeme=lexemes[idx];if(lexeme.type===8){let closingLeading=this.popLexemeComments(lexeme,"before");if(closingLeading.length>0){let target=(constraints.length>0?constraints[constraints.length-1]:columns[columns.length-1])??null;target&&target.addPositionedComments("after",closingLeading)}idx++;break}let tokenValue=lexeme.value.toLowerCase(),isConstraint=this.TABLE_CONSTRAINT_STARTERS.has(tokenValue),entryResult=isConstraint?this.parseTableConstraint(lexemes,idx):this.parseColumnDefinition(lexemes,idx),entry=entryResult.value;pendingLeading&&pendingLeading.length>0&&(entry.addPositionedComments("before",pendingLeading),pendingLeading=null);let trailingComments=this.popLexemeComments(lexemes[Math.max(entryResult.newIndex-1,idx)],"after");if(trailingComments.length>0&&entry.addPositionedComments("after",trailingComments),isConstraint?constraints.push(entry):columns.push(entry),idx=entryResult.newIndex,idx<lexemes.length&&lexemes[idx].type&16){let commaLexeme=lexemes[idx],commaTrailing=this.popLexemeComments(commaLexeme,"after");pendingLeading=this.toOptionalComments(commaTrailing),idx++;continue}if(idx<lexemes.length&&lexemes[idx].type===8){let closingLexeme=lexemes[idx],closingLeading=this.popLexemeComments(closingLexeme,"before");if(closingLeading.length>0){let target=(constraints.length>0?constraints[constraints.length-1]:columns[columns.length-1])??null;target&&target.addPositionedComments("after",closingLeading)}idx++;break}pendingLeading=null}return{columns,tableConstraints:constraints,newIndex:idx}}static parseColumnDefinition(lexemes,index){let idx=index,columnNameResult=this.parseQualifiedName(lexemes,idx);if(idx=columnNameResult.newIndex,columnNameResult.namespaces&&columnNameResult.namespaces.length>0){let qualified=[...columnNameResult.namespaces,columnNameResult.name.name].join(".");throw new Error(`[CreateTableParser] Column name '${qualified}' must not include a schema or namespace qualifier.`)}let columnName=columnNameResult.name,dataType;if(idx<lexemes.length&&!this.isColumnConstraintStart(lexemes[idx])&&!this.isColumnTerminator(lexemes[idx])){let typeResult=this.parseColumnType(lexemes,idx);dataType=typeResult.value,idx=typeResult.newIndex}let constraints=[];for(;idx<lexemes.length&&!this.isColumnTerminator(lexemes[idx]);){let constraintResult=this.parseColumnConstraint(lexemes,idx);constraints.push(constraintResult.value),idx=constraintResult.newIndex}return{value:new TableColumnDefinition({name:columnName,dataType,constraints}),newIndex:idx}}static parseColumnType(lexemes,index){try{let result=FunctionExpressionParser.parseTypeValue(lexemes,index);return{value:result.value,newIndex:result.newIndex}}catch{let typeEnd=this.findFirstConstraintIndex(lexemes,index),rawText=joinLexemeValues(lexemes,index,typeEnd);return{value:new RawString(rawText),newIndex:typeEnd}}}static parseColumnConstraint(lexemes,index){let idx=index,constraintName;if(lexemes[idx]?.value.toLowerCase()==="constraint"){idx++;let nameResult=this.parseQualifiedName(lexemes,idx);constraintName=nameResult.name,idx=nameResult.newIndex}let token=lexemes[idx];if(!token)throw new Error(`[CreateTableParser] Expected constraint definition at index ${idx}.`);let value=token.value.toLowerCase();if(value==="not null"||value==="null")return idx++,{value:new ColumnConstraintDefinition({kind:value==="not null"?"not-null":"null",constraintName}),newIndex:idx};if(value==="default"){idx++;let exprResult=ValueParser.parseFromLexeme(lexemes,idx);return idx=exprResult.newIndex,{value:new ColumnConstraintDefinition({kind:"default",constraintName,defaultValue:exprResult.value}),newIndex:idx}}if(value==="primary key")return idx++,{value:new ColumnConstraintDefinition({kind:"primary-key",constraintName}),newIndex:idx};if(value==="unique"||value==="unique key")return idx++,{value:new ColumnConstraintDefinition({kind:"unique",constraintName}),newIndex:idx};if(value==="references"){let referenceResult=this.parseReferenceDefinition(lexemes,idx);return idx=referenceResult.newIndex,{value:new ColumnConstraintDefinition({kind:"references",constraintName,reference:referenceResult.value}),newIndex:idx}}if(value==="check"){idx++;let checkExpression=this.parseParenExpression(lexemes,idx);return idx=checkExpression.newIndex,{value:new ColumnConstraintDefinition({kind:"check",constraintName,checkExpression:checkExpression.value}),newIndex:idx}}if(value.startsWith("generated")){let clauseEnd=this.findFirstConstraintIndex(lexemes,idx+1),text=joinLexemeValues(lexemes,idx,clauseEnd);idx=clauseEnd;let kind=value.startsWith("generated always")?"generated-always-identity":"generated-by-default-identity";return{value:new ColumnConstraintDefinition({kind,constraintName,rawClause:new RawString(text)}),newIndex:idx}}let rawEnd=this.findFirstConstraintIndex(lexemes,idx+1),rawText=joinLexemeValues(lexemes,idx,rawEnd);return{value:new ColumnConstraintDefinition({kind:"raw",constraintName,rawClause:new RawString(rawText)}),newIndex:rawEnd}}static parseTableConstraint(lexemes,index){let idx=index,constraintName;if(lexemes[idx]?.value.toLowerCase()==="constraint"){idx++;let nameResult=this.parseQualifiedName(lexemes,idx);constraintName=nameResult.name,idx=nameResult.newIndex}let token=lexemes[idx];if(!token)throw new Error(`[CreateTableParser] Expected table constraint at index ${idx}.`);let value=token.value.toLowerCase();if(value==="primary key"){idx++;let{identifiers,newIndex}=this.parseIdentifierList(lexemes,idx);return idx=newIndex,{value:new TableConstraintDefinition({kind:"primary-key",constraintName,columns:identifiers}),newIndex:idx}}if(value==="unique"||value==="unique key"){idx++;let inlineKeyName;if(idx<lexemes.length&&lexemes[idx].value!=="("&&!(lexemes[idx].type&128)){let inlineNameResult=this.parseQualifiedName(lexemes,idx);inlineKeyName=inlineNameResult.name,idx=inlineNameResult.newIndex}let{identifiers,newIndex}=this.parseIdentifierList(lexemes,idx);return idx=newIndex,{value:new TableConstraintDefinition({kind:"unique",constraintName:constraintName??inlineKeyName,columns:identifiers}),newIndex:idx}}if(value==="foreign key"){idx++;let inlineKeyName;if(idx<lexemes.length&&lexemes[idx].value!=="("&&!(lexemes[idx].type&128)){let inlineNameResult=this.parseQualifiedName(lexemes,idx);inlineKeyName=inlineNameResult.name,idx=inlineNameResult.newIndex}let{identifiers,newIndex}=this.parseIdentifierList(lexemes,idx);idx=newIndex;let referenceResult=this.parseReferenceDefinition(lexemes,idx);return idx=referenceResult.newIndex,{value:new TableConstraintDefinition({kind:"foreign-key",constraintName:constraintName??inlineKeyName,columns:identifiers,reference:referenceResult.value,deferrable:referenceResult.value.deferrable,initially:referenceResult.value.initially}),newIndex:idx}}if(value==="check"){idx++;let checkExpression=this.parseParenExpression(lexemes,idx);return idx=checkExpression.newIndex,{value:new TableConstraintDefinition({kind:"check",constraintName,checkExpression:checkExpression.value}),newIndex:idx}}let rawEnd=this.findFirstConstraintIndex(lexemes,idx+1),rawText=joinLexemeValues(lexemes,idx,rawEnd);return{value:new TableConstraintDefinition({kind:"raw",constraintName,rawClause:new RawString(rawText)}),newIndex:rawEnd}}static parseIdentifierList(lexemes,index){let idx=index,identifiers=[];if(lexemes[idx]?.type!==4)throw new Error(`[CreateTableParser] Expected '(' to start identifier list at index ${idx}.`);for(idx++;idx<lexemes.length;){let nameResult=this.parseQualifiedName(lexemes,idx);if(identifiers.push(nameResult.name),idx=nameResult.newIndex,lexemes[idx]?.type===16){idx++;continue}if(lexemes[idx]?.type===8){idx++;break}}return{identifiers,newIndex:idx}}static parseReferenceDefinition(lexemes,index){let idx=index;if(lexemes[idx]?.value.toLowerCase()!=="references")throw new Error(`[CreateTableParser] Expected REFERENCES clause at index ${idx}.`);idx++;let tableNameResult=this.parseQualifiedName(lexemes,idx);idx=tableNameResult.newIndex;let targetTable=new QualifiedName(tableNameResult.namespaces,tableNameResult.name),columns=null;if(lexemes[idx]?.type===4){let listResult=this.parseIdentifierList(lexemes,idx);columns=listResult.identifiers,idx=listResult.newIndex}let matchType=null,onDelete=null,onUpdate=null,deferrable=null,initially=null;for(;idx<lexemes.length;){let current=lexemes[idx].value.toLowerCase();if(this.MATCH_KEYWORDS.has(current)){matchType=this.MATCH_KEYWORDS.get(current),idx++;continue}if(current==="match"){idx++,matchType=lexemes[idx]?.value.toLowerCase()??"",idx++;continue}if(current==="on delete"){idx++;let action=lexemes[idx]?.value.toLowerCase()??"";onDelete=this.REFERENTIAL_ACTIONS.get(action)??null,idx++;continue}if(current==="on update"){idx++;let action=lexemes[idx]?.value.toLowerCase()??"";onUpdate=this.REFERENTIAL_ACTIONS.get(action)??null,idx++;continue}if(this.DEFERRABILITY_KEYWORDS.has(current)){deferrable=this.DEFERRABILITY_KEYWORDS.get(current),idx++;continue}if(this.INITIALLY_KEYWORDS.has(current)){initially=this.INITIALLY_KEYWORDS.get(current),idx++;continue}break}return{value:new ReferenceDefinition({targetTable,columns,matchType,onDelete,onUpdate,deferrable,initially}),newIndex:idx}}static parseParenExpression(lexemes,index){let idx=index;if(lexemes[idx]?.type!==4)throw new Error(`[CreateTableParser] Expected '(' introducing expression at index ${idx}.`);idx++;let expressionResult=ValueParser.parseFromLexeme(lexemes,idx);if(idx=expressionResult.newIndex,lexemes[idx]?.type!==8)throw new Error(`[CreateTableParser] Expected ')' terminating expression at index ${idx}.`);return idx++,{value:expressionResult.value,newIndex:idx}}static isColumnConstraintStart(lexeme){if(!lexeme)return!1;let lower=lexeme.value.toLowerCase();return this.COLUMN_CONSTRAINT_STARTERS.has(lower)}static isColumnTerminator(lexeme){return!!(!lexeme||lexeme.type&24)}static isSelectKeyword(value,nextLexeme){return!value||value==="with"&&nextLexeme?.type===4?!1:value==="as"||value==="select"||value==="with"||value==="values"}static findClauseBoundary(lexemes,index){let idx=index;for(;idx<lexemes.length;){let lower=lexemes[idx].value.toLowerCase();if(this.isSelectKeyword(lower,lexemes[idx+1]))break;idx++}return idx}static findFirstConstraintIndex(lexemes,index){let idx=index;for(;idx<lexemes.length&&!this.isColumnConstraintStart(lexemes[idx])&&!this.isColumnTerminator(lexemes[idx]);)idx++;return idx}static parseWithDataOption(lexemes,index){let current=lexemes[index];if(!current)return null;let value=current.value.toLowerCase();if(value==="with data")return{value:"with-data",newIndex:index+1};if(value==="with no data")return{value:"with-no-data",newIndex:index+1};if(value!=="with")return null;let nextValue=lexemes[index+1]?.value.toLowerCase();if(nextValue==="data")return{value:"with-data",newIndex:index+2};if(nextValue==="data")return{value:"with-data",newIndex:index+2};if(nextValue==="no data")return{value:"with-no-data",newIndex:index+2};if(nextValue==="no"){let following=lexemes[index+2];if(following&&following.value.toLowerCase()==="data")return{value:"with-no-data",newIndex:index+3}}return null}static popLexemeComments(lexeme,position){if(!lexeme)return[];let collected=[];if(lexeme.positionedComments&&lexeme.positionedComments.length>0){let matchIndex=lexeme.positionedComments.findIndex(pc=>pc.position===position);if(matchIndex>=0){collected=[...lexeme.positionedComments[matchIndex].comments];let remaining=lexeme.positionedComments.filter((_,idx)=>idx!==matchIndex);lexeme.positionedComments=remaining.length>0?remaining:void 0}}if(collected.length>0)return collected;if(lexeme.comments&&lexeme.comments.length>0){let legacy=[...lexeme.comments];return lexeme.comments=null,legacy}return[]}static toOptionalComments(comments){return comments.length>0?comments:null}};var MergeQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The MERGE statement is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value==="with"){let withResult=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=withResult.value,idx=withResult.newIndex}let mergeKeywordLexeme=lexemes[idx],mergeKeywordComments=extractLexemeComments(mergeKeywordLexeme);if(mergeKeywordLexeme?.value!=="merge into"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'MERGE INTO' but found '${actual}'.`)}idx++;let targetResult=SourceExpressionParser.parseFromLexeme(lexemes,idx),target=targetResult.value;if(idx=targetResult.newIndex,this.addUniquePositionedComments(target.datasource,"before",mergeKeywordComments.after),lexemes[idx]?.value!=="using"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'USING' but found '${actual}'.`)}idx++;let sourceResult=SourceExpressionParser.parseFromLexeme(lexemes,idx),source=sourceResult.value;if(idx=sourceResult.newIndex,lexemes[idx]?.value!=="on"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'ON' but found '${actual}'.`)}idx++;let onConditionResult=ValueParser.parseFromLexeme(lexemes,idx),onCondition=onConditionResult.value;idx=onConditionResult.newIndex;let whenResult=this.parseWhenClauses(lexemes,idx);if(whenResult.clauses.length===0)throw new Error("[MergeQueryParser] MERGE statement must contain at least one WHEN clause.");let mergeQuery=new MergeQuery({withClause,target,source,onCondition,whenClauses:whenResult.clauses});return this.addUniquePositionedComments(mergeQuery,"before",mergeKeywordComments.before),{value:mergeQuery,newIndex:whenResult.newIndex}}static parseWhenClauses(lexemes,index){let clauses=[],idx=index;for(;this.getLowerValue(lexemes[idx])==="when";){idx++;let{matchType,newIndex:matchIndex}=this.parseMatchType(lexemes,idx);idx=matchIndex;let additionalCondition=null;if(this.getLowerValue(lexemes[idx])==="and"){idx++;let conditionResult=ValueParser.parseFromLexeme(lexemes,idx);additionalCondition=conditionResult.value,idx=conditionResult.newIndex}let thenLexeme=lexemes[idx];if(this.getLowerValue(thenLexeme)!=="then"){let actual=thenLexeme?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'THEN' but found '${actual}'.`)}let thenComments=extractLexemeComments(thenLexeme),commentsBeforeThen=[],precedingLexeme=lexemes[idx-1];if(precedingLexeme){let precedingComments=extractLexemeComments(precedingLexeme);this.mergeUnique(commentsBeforeThen,precedingComments.after)}this.mergeUnique(commentsBeforeThen,thenComments.before),idx++;let actionResult=this.parseAction(lexemes,idx,thenComments.after??[]);idx=actionResult.newIndex;let whenClause=new MergeWhenClause(matchType,actionResult.action,additionalCondition);whenClause.addThenLeadingComments(commentsBeforeThen),clauses.push(whenClause)}return{clauses,newIndex:idx}}static parseMatchType(lexemes,index){let idx=index,value=this.getLowerValue(lexemes[idx]);if(value==="matched")return idx++,{matchType:"matched",newIndex:idx};if(value==="not matched")return idx++,{matchType:"not_matched",newIndex:idx};if(value==="not matched by source")return idx++,{matchType:"not_matched_by_source",newIndex:idx};if(value==="not matched by target")return idx++,{matchType:"not_matched_by_target",newIndex:idx};let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'MATCHED' or 'NOT MATCHED' but found '${actual}'.`)}static parseAction(lexemes,index,leadingComments=[]){let idx=index,token=lexemes[idx];if(!token)throw new Error("[MergeQueryParser] Unexpected end of input while parsing WHEN clause action.");let tokenValue=token.value.toLowerCase(),tokenComments=extractLexemeComments(token),actionLeadingComments=[];if(this.mergeUnique(actionLeadingComments,leadingComments),this.mergeUnique(actionLeadingComments,tokenComments.before),tokenValue==="update"||tokenValue==="update set"){let expectSetKeyword=tokenValue==="update";idx++;let pendingSetClauseComments=tokenComments.after,setResult=this.parseSetClause(lexemes,idx,expectSetKeyword,pendingSetClauseComments);idx=setResult.newIndex;let whereClause=null;if(lexemes[idx]?.value==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}let action=new MergeUpdateAction(setResult.setClause,whereClause);return this.addUniquePositionedComments(action,"before",actionLeadingComments),{action,newIndex:idx}}if(tokenValue==="delete"){idx++;let whereClause=null;if(this.getLowerValue(lexemes[idx])==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}let action=new MergeDeleteAction(whereClause);return this.addUniquePositionedComments(action,"before",actionLeadingComments),this.addUniquePositionedComments(action,"after",tokenComments.after),{action,newIndex:idx}}if(tokenValue==="do nothing"){idx++;let action=new MergeDoNothingAction;return this.addUniquePositionedComments(action,"before",actionLeadingComments),this.addUniquePositionedComments(action,"after",tokenComments.after),{action,newIndex:idx}}if(tokenValue==="insert default values"){idx++;let columnResult=this.parseInsertColumnProjection(lexemes,idx,tokenComments.after);idx=columnResult.newIndex;let action=new MergeInsertAction({columns:columnResult.columns,defaultValues:!0});return this.addUniquePositionedComments(action,"before",actionLeadingComments),this.addUniquePositionedComments(action,"after",columnResult.trailingComments),{action,newIndex:idx}}if(tokenValue==="insert"){idx++;let insertResult=this.parseInsertAction(lexemes,idx,{pendingCommentsAfterInsert:tokenComments.after});return this.addUniquePositionedComments(insertResult.action,"before",actionLeadingComments),insertResult}let actual=token.value;throw new Error(`[MergeQueryParser] Unsupported action '${actual}'. Only UPDATE, DELETE, INSERT, and DO NOTHING are supported within MERGE WHEN clauses.`)}static parseSetClause(lexemes,index,expectSetKeyword,pendingCommentsAfterUpdate=[]){let idx=index,setKeywordComments=extractLexemeComments(lexemes[idx]);if(expectSetKeyword){if(this.getLowerValue(lexemes[idx])!=="set"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'SET' but found '${actual}'.`)}idx++}else this.getLowerValue(lexemes[idx])==="set"?(setKeywordComments=extractLexemeComments(lexemes[idx]),idx++):setKeywordComments={before:[],after:[]};let items=[],pendingBeforeForNext=[];for(this.mergeUnique(pendingBeforeForNext,pendingCommentsAfterUpdate),this.mergeUnique(pendingBeforeForNext,setKeywordComments.after);idx<lexemes.length;){let currentLexeme=lexemes[idx];if(!currentLexeme||this.isSetClauseTerminator(currentLexeme)||!(currentLexeme.type&10816))break;let columnComments=extractLexemeComments(currentLexeme),{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,lexemes[idx]?.type!==2||lexemes[idx].value!=="="){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected '=' in SET clause but found '${actual}'.`)}let equalsLexeme=lexemes[idx],equalsComments=extractLexemeComments(equalsLexeme);idx++;let valueResult=ValueParser.parseFromLexeme(lexemes,idx);idx=valueResult.newIndex;let setItem=new SetClauseItem({namespaces,column:name},valueResult.value),beforeComments=[];if(this.mergeUnique(beforeComments,pendingBeforeForNext),this.mergeUnique(beforeComments,columnComments.before),this.addUniquePositionedComments(name,"before",beforeComments),pendingBeforeForNext=[],this.addUniquePositionedComments(name,"after",columnComments.after),this.addUniquePositionedComments(setItem,"after",equalsComments.before),this.addUniquePositionedComments(valueResult.value,"before",equalsComments.after),items.push(setItem),lexemes[idx]?.type===16){let commaLexeme=lexemes[idx],commaComments=extractLexemeComments(commaLexeme);idx++,this.addUniquePositionedComments(setItem,"after",commaComments.before),pendingBeforeForNext=[],this.mergeUnique(pendingBeforeForNext,commaComments.after);continue}break}if(pendingBeforeForNext.length>0&&items.length>0&&this.addUniquePositionedComments(items[items.length-1],"after",pendingBeforeForNext),items.length===0)throw new Error("[MergeQueryParser] SET clause must contain at least one column assignment.");let setClause=new SetClause(items);return this.addUniquePositionedComments(setClause,"before",setKeywordComments.before),{setClause,newIndex:idx}}static parseInsertAction(lexemes,index,options){let idx=index,pendingAfterInsert=options?.pendingCommentsAfterInsert??[],columnResult=this.parseInsertColumnProjection(lexemes,idx,pendingAfterInsert),columns=columnResult.columns;idx=columnResult.newIndex;let pendingBeforeValues=columnResult.trailingComments;if(this.getLowerValue(lexemes[idx])==="values"){let valuesLexeme=lexemes[idx],valuesComments=extractLexemeComments(valuesLexeme);idx++;let beforeValuesComments=[];this.mergeUnique(beforeValuesComments,pendingBeforeValues),this.mergeUnique(beforeValuesComments,valuesComments.before);let valuesResult=ValueParser.parseArgument(4,8,lexemes,idx);if(idx=valuesResult.newIndex,!(valuesResult.value instanceof ValueList))throw new Error("[MergeQueryParser] Unexpected VALUES payload. Expected a parenthesized value list.");let valueList=valuesResult.value,closingParenComments=extractLexemeComments(lexemes[idx-1]);this.addUniquePositionedComments(valueList,"after",closingParenComments.after),this.addUniquePositionedComments(valueList,"after",valuesComments.after);let action=new MergeInsertAction({columns,values:valueList});return action.addValuesLeadingComments(beforeValuesComments),{action,newIndex:idx}}let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Unsupported INSERT payload '${actual}'. Use VALUES (...) or DEFAULT VALUES.`)}static parseInsertColumnProjection(lexemes,index,pendingBeforeFirstColumn){let idx=index;if(lexemes[idx]?.type!==4)return{columns:null,newIndex:idx,trailingComments:[...pendingBeforeFirstColumn]};let openParenLexeme=lexemes[idx],parenComments=extractLexemeComments(openParenLexeme);idx++;let columns=[],pendingBeforeForNext=[];for(this.mergeUnique(pendingBeforeForNext,pendingBeforeFirstColumn),this.mergeUnique(pendingBeforeForNext,parenComments.before),this.mergeUnique(pendingBeforeForNext,parenComments.after);idx<lexemes.length&&lexemes[idx].type&64;){let columnLexeme=lexemes[idx],columnComments=extractLexemeComments(columnLexeme),column=new IdentifierString(columnLexeme.value),beforeComments=[];if(this.mergeUnique(beforeComments,pendingBeforeForNext),this.mergeUnique(beforeComments,columnComments.before),this.addUniquePositionedComments(column,"before",beforeComments),pendingBeforeForNext=[],this.addUniquePositionedComments(column,"after",columnComments.after),columns.push(column),idx++,lexemes[idx]?.type===16){let commaLexeme=lexemes[idx],commaComments=extractLexemeComments(commaLexeme);idx++,this.addUniquePositionedComments(column,"after",commaComments.before),pendingBeforeForNext=[],this.mergeUnique(pendingBeforeForNext,commaComments.after);continue}break}if(pendingBeforeForNext.length>0&&columns.length>0&&(this.addUniquePositionedComments(columns[columns.length-1],"after",pendingBeforeForNext),pendingBeforeForNext=[]),lexemes[idx]?.type!==8){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected ')' after column list but found '${actual}'.`)}let closeParenLexeme=lexemes[idx],closeParenComments=extractLexemeComments(closeParenLexeme);idx++,closeParenComments.before.length>0&&columns.length>0&&this.addUniquePositionedComments(columns[columns.length-1],"after",closeParenComments.before);let trailingComments=[];return this.mergeUnique(trailingComments,closeParenComments.after),this.mergeUnique(trailingComments,pendingBeforeForNext),{columns:columns.length>0?columns:[],newIndex:idx,trailingComments}}static isSetClauseTerminator(lexeme){if(!lexeme)return!1;let value=this.getLowerValue(lexeme);return value?value==="where"||value==="from"||value==="returning"||value==="when":!1}static mergeUnique(target,source){if(!(!source||source.length===0))for(let comment of source)target.includes(comment)||target.push(comment)}static addUniquePositionedComments(component,position,comments){if(!component||!comments||comments.length===0)return;let existing=component.getPositionedComments(position),newOnes=comments.filter(comment=>!existing.includes(comment));newOnes.length>0&&component.addPositionedComments(position,newOnes)}static getLowerValue(lexeme){return lexeme&&typeof lexeme.value=="string"?lexeme.value.toLowerCase():null}};var DropTableParser=class{static parse(sql){let lexemes=new SqlTokenizer(sql).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`[DropTableParser] Unexpected token "${lexemes[result.newIndex].value}" after DROP TABLE statement.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx]?.value.toLowerCase()!=="drop table")throw new Error(`[DropTableParser] Expected DROP TABLE at index ${idx}.`);idx++;let ifExists=!1;lexemes[idx]?.value.toLowerCase()==="if exists"&&(ifExists=!0,idx++);let tables=[];for(;idx<lexemes.length;){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(tables.push(new QualifiedName(namespaces,name)),idx=newIndex,lexemes[idx]?.type===16){idx++;continue}break}if(tables.length===0)throw new Error("[DropTableParser] DROP TABLE must specify at least one table.");let behavior=null,nextValue=lexemes[idx]?.value.toLowerCase();return(nextValue==="cascade"||nextValue==="restrict")&&(behavior=nextValue,idx++),{value:new DropTableStatement({tables,ifExists,behavior}),newIndex:idx}}};var DropIndexParser=class{static parse(sql){let lexemes=new SqlTokenizer(sql).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`[DropIndexParser] Unexpected token "${lexemes[result.newIndex].value}" after DROP INDEX statement.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx]?.value.toLowerCase()!=="drop index")throw new Error(`[DropIndexParser] Expected DROP INDEX at index ${idx}.`);idx++;let concurrently=!1;lexemes[idx]?.value.toLowerCase()==="concurrently"&&(concurrently=!0,idx++);let ifExists=!1;if(lexemes[idx]?.value.toLowerCase()==="if exists"){ifExists=!0,idx++;let next=lexemes[idx];if(!next||next.type!==64)throw new Error("[DropIndexParser] Expected index name immediately after IF EXISTS.")}let indexNames=[];for(;idx<lexemes.length;){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(indexNames.push(new QualifiedName(namespaces,name)),idx=newIndex,lexemes[idx]?.type===16){idx++;continue}break}if(indexNames.length===0)throw new Error("[DropIndexParser] DROP INDEX must specify at least one index name.");let behavior=null,nextValue=lexemes[idx]?.value.toLowerCase();return(nextValue==="cascade"||nextValue==="restrict")&&(behavior=nextValue,idx++),{value:new DropIndexStatement({indexNames,concurrently,ifExists,behavior}),newIndex:idx}}};var CreateIndexParser=class{static parse(sql){let lexemes=new SqlTokenizer(sql).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`[CreateIndexParser] Unexpected token "${lexemes[result.newIndex].value}" after CREATE INDEX.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,firstToken=lexemes[idx]?.value.toLowerCase();if(firstToken!=="create index"&&firstToken!=="create unique index")throw new Error(`[CreateIndexParser] Expected CREATE INDEX at index ${idx}.`);let unique=firstToken==="create unique index";idx++;let concurrently=!1;lexemes[idx]?.value.toLowerCase()==="concurrently"&&(concurrently=!0,idx++);let ifNotExists=!1;lexemes[idx]?.value.toLowerCase()==="if not exists"&&(ifNotExists=!0,idx++);let indexNameResult=FullNameParser.parseFromLexeme(lexemes,idx),indexName=new QualifiedName(indexNameResult.namespaces,indexNameResult.name);if(idx=indexNameResult.newIndex,lexemes[idx]?.value.toLowerCase()!=="on")throw new Error(`[CreateIndexParser] Expected ON keyword before table name at index ${idx}.`);idx++;let tableResult=FullNameParser.parseFromLexeme(lexemes,idx),tableName=new QualifiedName(tableResult.namespaces,tableResult.name);idx=tableResult.newIndex;let usingMethod=null;if(lexemes[idx]?.value.toLowerCase()==="using"){idx++;let methodResult=FullNameParser.parseFromLexeme(lexemes,idx);usingMethod=methodResult.name,idx=methodResult.newIndex}let columnsResult=this.parseIndexColumnList(lexemes,idx),columns=columnsResult.columns;idx=columnsResult.newIndex;let include=null;if(lexemes[idx]?.value.toLowerCase()==="include"){idx++;let includeResult=this.parseIdentifierList(lexemes,idx);include=includeResult.identifiers,idx=includeResult.newIndex}let withOptions=null;if(lexemes[idx]?.value.toLowerCase()==="with"){let withResult=this.parseWithOptions(lexemes,idx);withOptions=withResult.options,idx=withResult.newIndex}let tablespace=null;if(lexemes[idx]?.value.toLowerCase()==="tablespace"){idx++;let tablespaceResult=FullNameParser.parseFromLexeme(lexemes,idx);tablespace=tablespaceResult.name,idx=tablespaceResult.newIndex}let whereClause;if(lexemes[idx]?.value.toLowerCase()==="where"){idx++;let whereResult=ValueParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}return{value:new CreateIndexStatement({unique,concurrently,ifNotExists,indexName,tableName,usingMethod,columns,include,withOptions,tablespace,where:whereClause}),newIndex:idx}}static parseIndexColumnList(lexemes,index){let idx=index;if(lexemes[idx]?.type!==4)throw new Error(`[CreateIndexParser] Expected '(' starting column list at index ${idx}.`);idx++;let columns=[];for(;idx<lexemes.length;){let expressionResult=ValueParser.parseFromLexeme(lexemes,idx);idx=expressionResult.newIndex;let sortOrder=null,nullsOrder=null,collation=null,operatorClass=null;for(;idx<lexemes.length;){let tokenValue=lexemes[idx].value.toLowerCase();if(tokenValue==="asc"||tokenValue==="desc"){sortOrder=tokenValue,idx++;continue}if(tokenValue==="nulls first"||tokenValue==="nulls last"){nullsOrder=tokenValue.endsWith("first")?"first":"last",idx++;continue}if(tokenValue==="collate"){idx++;let collateResult=FullNameParser.parseFromLexeme(lexemes,idx);collation=new QualifiedName(collateResult.namespaces,collateResult.name),idx=collateResult.newIndex;continue}if(this.isClauseTerminator(tokenValue)||lexemes[idx].type&24)break;if(lexemes[idx].type&10304){let opClassResult=FullNameParser.parseFromLexeme(lexemes,idx);operatorClass=new QualifiedName(opClassResult.namespaces,opClassResult.name),idx=opClassResult.newIndex;continue}break}if(columns.push(new IndexColumnDefinition({expression:expressionResult.value,sortOrder,nullsOrder,collation,operatorClass})),lexemes[idx]?.type===16){idx++;continue}if(lexemes[idx]?.type===8){idx++;break}}if(lexemes[idx-1]?.type!==8)throw new Error(`[CreateIndexParser] Expected ')' to close column list starting at index ${index}.`);return{columns,newIndex:idx}}static parseIdentifierList(lexemes,index){let idx=index;if(lexemes[idx]?.type!==4)throw new Error(`[CreateIndexParser] Expected '(' starting identifier list at index ${idx}.`);idx++;let identifiers=[];for(;idx<lexemes.length;){let result=FullNameParser.parseFromLexeme(lexemes,idx);if(identifiers.push(result.name),idx=result.newIndex,lexemes[idx]?.type===16){idx++;continue}if(lexemes[idx]?.type===8){idx++;break}}if(lexemes[idx-1]?.type!==8)throw new Error(`[CreateIndexParser] Expected ')' to close identifier list starting at index ${index}.`);return{identifiers,newIndex:idx}}static parseWithOptions(lexemes,index){let idx=index,start=idx;if(lexemes[idx]?.value.toLowerCase()!=="with")throw new Error(`[CreateIndexParser] Expected WITH keyword at index ${idx}.`);if(idx++,lexemes[idx]?.type!==4)throw new Error(`[CreateIndexParser] Expected '(' after WITH at index ${idx}.`);let depth=0;for(;idx<lexemes.length;){if(lexemes[idx].type===4)depth++;else if(lexemes[idx].type===8&&(depth--,depth===0)){idx++;break}idx++}if(depth!==0)throw new Error(`[CreateIndexParser] Unterminated WITH options starting at index ${start}; unbalanced parentheses.`);let text=joinLexemeValues(lexemes,start,idx);return{options:new RawString(text),newIndex:idx}}static isClauseTerminator(value){return value==="include"||value==="with"||value==="where"||value==="tablespace"}};var AlterTableParser=class{static{this.CONSTRAINT_TYPE_TOKENS=new Set(["primary key","unique","unique key","foreign key","check"])}static{this.MATCH_KEYWORDS=new Map([["match full","full"],["match partial","partial"],["match simple","simple"]])}static{this.REFERENTIAL_ACTIONS=new Map([["cascade","cascade"],["restrict","restrict"],["no action","no action"],["set null","set null"],["set default","set default"]])}static{this.DEFERRABILITY_KEYWORDS=new Map([["deferrable","deferrable"],["not deferrable","not deferrable"]])}static{this.INITIALLY_KEYWORDS=new Map([["initially immediate","immediate"],["initially deferred","deferred"]])}static parse(sql){let lexemes=new SqlTokenizer(sql).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`[AlterTableParser] Unexpected token "${lexemes[result.newIndex].value}" after ALTER TABLE statement.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx]?.value.toLowerCase()!=="alter table")throw new Error(`[AlterTableParser] Expected ALTER TABLE at index ${idx}.`);idx++;let ifExists=!1;lexemes[idx]?.value.toLowerCase()==="if exists"&&(ifExists=!0,idx++);let only=!1;lexemes[idx]?.value.toLowerCase()==="only"&&(only=!0,idx++);let tableResult=FullNameParser.parseFromLexeme(lexemes,idx),tableName=new QualifiedName(tableResult.namespaces,tableResult.name);idx=tableResult.newIndex;let actions=[];for(;idx<lexemes.length;){let value=lexemes[idx].value.toLowerCase();if(value==="add constraint"){let result=this.parseAddConstraintAction(lexemes,idx);actions.push(result.value),idx=result.newIndex}else if(value==="drop constraint"){let result=this.parseDropConstraintAction(lexemes,idx);actions.push(result.value),idx=result.newIndex}else if(value==="drop column"||value==="drop"){let result=this.parseDropColumnAction(lexemes,idx);actions.push(result.value),idx=result.newIndex}else throw new Error(`[AlterTableParser] Unsupported ALTER TABLE action '${lexemes[idx].value}' at index ${idx}.`);if(lexemes[idx]?.type===16){idx++;continue}break}if(actions.length===0)throw new Error("[AlterTableParser] ALTER TABLE requires at least one action.");return{value:new AlterTableStatement({table:tableName,only,ifExists,actions}),newIndex:idx}}static parseAddConstraintAction(lexemes,index){let idx=index,initialToken=lexemes[idx]?.value.toLowerCase();if(initialToken!=="add"&&initialToken!=="add constraint")throw new Error(`[AlterTableParser] Expected ADD or ADD CONSTRAINT at index ${idx}.`);idx++,initialToken==="add"&&lexemes[idx]?.value.toLowerCase()==="constraint"&&idx++;let ifNotExists=!1;lexemes[idx]?.value.toLowerCase()==="if not exists"&&(ifNotExists=!0,idx++);let constraintName,nextValue=lexemes[idx]?.value.toLowerCase();if(nextValue&&!this.CONSTRAINT_TYPE_TOKENS.has(nextValue)){let nameResult=FullNameParser.parseFromLexeme(lexemes,idx);constraintName=nameResult.name,idx=nameResult.newIndex}let constraintResult=this.parseTableConstraintDefinition(lexemes,idx,constraintName);idx=constraintResult.newIndex;let notValid=!1;return lexemes[idx]?.value.toLowerCase()==="not valid"&&(notValid=!0,idx++),{value:new AlterTableAddConstraint({constraint:constraintResult.constraint,ifNotExists,notValid}),newIndex:idx}}static parseDropConstraintAction(lexemes,index){let idx=index,initialValue=lexemes[idx]?.value.toLowerCase();if(initialValue==="drop constraint")idx++;else if(initialValue==="drop"){if(idx++,lexemes[idx]?.value.toLowerCase()!=="constraint")throw new Error(`[AlterTableParser] Expected CONSTRAINT keyword after DROP at index ${idx}.`);idx++}else throw new Error(`[AlterTableParser] Expected DROP CONSTRAINT at index ${idx}.`);let ifExists=!1;lexemes[idx]?.value.toLowerCase()==="if exists"&&(ifExists=!0,idx++);let nameResult=FullNameParser.parseFromLexeme(lexemes,idx);idx=nameResult.newIndex;let behavior=null,nextValue=lexemes[idx]?.value.toLowerCase();return(nextValue==="cascade"||nextValue==="restrict")&&(behavior=nextValue,idx++),{value:new AlterTableDropConstraint({constraintName:nameResult.name,ifExists,behavior}),newIndex:idx}}static parseDropColumnAction(lexemes,index){let idx=index,initialValue=lexemes[idx]?.value.toLowerCase();if(initialValue==="drop column")idx++;else if(initialValue==="drop"){if(idx++,lexemes[idx]?.value.toLowerCase()!=="column")throw new Error(`[AlterTableParser] Expected COLUMN keyword after DROP at index ${idx}.`);idx++}else throw new Error(`[AlterTableParser] Expected DROP COLUMN at index ${idx}.`);let ifExists=!1;lexemes[idx]?.value.toLowerCase()==="if exists"&&(ifExists=!0,idx++);let nameResult=FullNameParser.parseFromLexeme(lexemes,idx),columnName=nameResult.name;idx=nameResult.newIndex;let behavior=null,nextValue=lexemes[idx]?.value.toLowerCase();return(nextValue==="cascade"||nextValue==="restrict")&&(behavior=nextValue,idx++),{value:new AlterTableDropColumn({columnName,ifExists,behavior}),newIndex:idx}}static parseTableConstraintDefinition(lexemes,index,constraintName){let idx=index,token=lexemes[idx];if(!token)throw new Error(`[AlterTableParser] Missing constraint definition at index ${idx}.`);let value=token.value.toLowerCase();if(value==="primary key"){idx++;let listResult=this.parseIdentifierList(lexemes,idx);return idx=listResult.newIndex,{constraint:new TableConstraintDefinition({kind:"primary-key",constraintName,columns:listResult.identifiers}),newIndex:idx}}if(value==="unique"||value==="unique key"){idx++;let listResult=this.parseIdentifierList(lexemes,idx);return idx=listResult.newIndex,{constraint:new TableConstraintDefinition({kind:"unique",constraintName,columns:listResult.identifiers}),newIndex:idx}}if(value==="foreign key"){idx++;let listResult=this.parseIdentifierList(lexemes,idx);idx=listResult.newIndex;let referenceResult=this.parseReferenceDefinition(lexemes,idx);return idx=referenceResult.newIndex,{constraint:new TableConstraintDefinition({kind:"foreign-key",constraintName,columns:listResult.identifiers,reference:referenceResult.reference,deferrable:referenceResult.reference.deferrable,initially:referenceResult.reference.initially}),newIndex:idx}}if(value==="check"){idx++;let checkExpression=this.parseParenExpression(lexemes,idx);return idx=checkExpression.newIndex,{constraint:new TableConstraintDefinition({kind:"check",constraintName,checkExpression:checkExpression.value}),newIndex:idx}}let rawEnd=this.findConstraintClauseEnd(lexemes,idx+1),rawText=joinLexemeValues(lexemes,idx,rawEnd);return{constraint:new TableConstraintDefinition({kind:"raw",constraintName,rawClause:new RawString(rawText)}),newIndex:rawEnd}}static parseIdentifierList(lexemes,index){let idx=index,identifiers=[];if(lexemes[idx]?.type!==4)throw new Error(`[AlterTableParser] Expected '(' to start identifier list at index ${idx}.`);for(idx++;idx<lexemes.length;){let nameResult=FullNameParser.parseFromLexeme(lexemes,idx);if(identifiers.push(nameResult.name),idx=nameResult.newIndex,lexemes[idx]?.type===16){idx++;continue}if(lexemes[idx]?.type===8){idx++;break}}return{identifiers,newIndex:idx}}static parseReferenceDefinition(lexemes,index){let idx=index;if(lexemes[idx]?.value.toLowerCase()!=="references")throw new Error(`[AlterTableParser] Expected REFERENCES clause at index ${idx}.`);idx++;let tableResult=FullNameParser.parseFromLexeme(lexemes,idx),targetTable=new QualifiedName(tableResult.namespaces,tableResult.name);idx=tableResult.newIndex;let columns=null;if(lexemes[idx]?.type===4){let listResult=this.parseIdentifierList(lexemes,idx);columns=listResult.identifiers,idx=listResult.newIndex}let matchType=null,onDelete=null,onUpdate=null,deferrable=null,initially=null;for(;idx<lexemes.length;){let current=lexemes[idx].value.toLowerCase();if(this.MATCH_KEYWORDS.has(current)){matchType=this.MATCH_KEYWORDS.get(current),idx++;continue}if(current==="match"){idx++,matchType=lexemes[idx]?.value.toLowerCase()??"",idx++;continue}if(current==="on delete"){idx++;let action=lexemes[idx]?.value.toLowerCase()??"";onDelete=this.REFERENTIAL_ACTIONS.get(action)??null,idx++;continue}if(current==="on update"){idx++;let action=lexemes[idx]?.value.toLowerCase()??"";onUpdate=this.REFERENTIAL_ACTIONS.get(action)??null,idx++;continue}if(this.DEFERRABILITY_KEYWORDS.has(current)){deferrable=this.DEFERRABILITY_KEYWORDS.get(current),idx++;continue}if(this.INITIALLY_KEYWORDS.has(current)){initially=this.INITIALLY_KEYWORDS.get(current),idx++;continue}break}return{reference:new ReferenceDefinition({targetTable,columns,matchType,onDelete,onUpdate,deferrable,initially}),newIndex:idx}}static parseParenExpression(lexemes,index){let idx=index;if(lexemes[idx]?.type!==4)throw new Error(`[AlterTableParser] Expected '(' starting CHECK expression at index ${idx}.`);idx++;let result=ValueParser.parseFromLexeme(lexemes,idx);if(idx=result.newIndex,lexemes[idx]?.type!==8)throw new Error(`[AlterTableParser] Expected ')' closing CHECK expression at index ${idx}.`);return idx++,{value:result.value,newIndex:idx}}static findConstraintClauseEnd(lexemes,index){let idx=index;for(;idx<lexemes.length;){let token=lexemes[idx];if(token.type&24||token.value.toLowerCase()==="not valid")break;idx++}return idx}};var DropConstraintParser=class{static parse(sql){let lexemes=new SqlTokenizer(sql).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`[DropConstraintParser] Unexpected token "${lexemes[result.newIndex].value}" after DROP CONSTRAINT statement.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx]?.value.toLowerCase()!=="drop constraint")throw new Error(`[DropConstraintParser] Expected DROP CONSTRAINT at index ${idx}.`);idx++;let ifExists=!1;lexemes[idx]?.value.toLowerCase()==="if exists"&&(ifExists=!0,idx++);let{name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);idx=newIndex;let behavior=null,nextValue=lexemes[idx]?.value.toLowerCase();return(nextValue==="cascade"||nextValue==="restrict")&&(behavior=nextValue,idx++),{value:new DropConstraintStatement({constraintName:name,ifExists,behavior}),newIndex:idx}}};var SqlParser=class{static parse(sql,options={}){let skipEmpty=options.skipEmptyStatements??!0,mode=options.mode??"single",tokenizer=new SqlTokenizer(sql),first=this.consumeNextStatement(tokenizer,0,skipEmpty);if(!first)throw new Error("[SqlParser] No SQL statements found in input.");let parsed=this.dispatchParse(first.segment,1);if(mode==="single"&&this.consumeNextStatement(tokenizer,first.nextCursor,skipEmpty))throw new Error('[SqlParser] Unexpected additional statement detected at index 2. Use parseMany or set mode to "multiple" to allow multiple statements.');return parsed}static parseMany(sql,options={}){let skipEmpty=options.skipEmptyStatements??!0,tokenizer=new SqlTokenizer(sql),statements=[],cursor=0,carry=null,index=0;for(;;){let segment=tokenizer.readNextStatement(cursor,carry);if(carry=null,!segment)break;cursor=segment.nextPosition,!(segment.lexemes.length===0&&(segment.leadingComments&&segment.leadingComments.length>0&&(carry=segment.leadingComments),skipEmpty||segment.rawText.trim().length===0))&&(index++,statements.push(this.dispatchParse(segment,index)))}return statements}static dispatchParse(segment,statementIndex){if(segment.lexemes.length===0)throw new Error(`[SqlParser] Statement ${statementIndex} does not contain any tokens.`);let firstToken=segment.lexemes[0].value.toLowerCase();if(firstToken==="with"){let commandAfterWith=this.getCommandAfterWith(segment.lexemes);return commandAfterWith==="insert into"?this.parseInsertStatement(segment,statementIndex):commandAfterWith==="update"?this.parseUpdateStatement(segment,statementIndex):commandAfterWith==="delete from"?this.parseDeleteStatement(segment,statementIndex):commandAfterWith==="merge into"?this.parseMergeStatement(segment,statementIndex):this.parseSelectStatement(segment,statementIndex)}if(firstToken==="select"||firstToken==="values")return this.parseSelectStatement(segment,statementIndex);if(firstToken==="insert into")return this.parseInsertStatement(segment,statementIndex);if(firstToken==="update")return this.parseUpdateStatement(segment,statementIndex);if(firstToken==="delete from")return this.parseDeleteStatement(segment,statementIndex);if(firstToken==="create table"||firstToken==="create temporary table")return this.parseCreateTableStatement(segment,statementIndex);if(firstToken==="merge into")return this.parseMergeStatement(segment,statementIndex);if(firstToken==="create index"||firstToken==="create unique index")return this.parseCreateIndexStatement(segment,statementIndex);if(firstToken==="drop table")return this.parseDropTableStatement(segment,statementIndex);if(firstToken==="drop index")return this.parseDropIndexStatement(segment,statementIndex);if(firstToken==="alter table")return this.parseAlterTableStatement(segment,statementIndex);if(firstToken==="drop constraint")return this.parseDropConstraintStatement(segment,statementIndex);throw new Error(`[SqlParser] Statement ${statementIndex} starts with unsupported token "${segment.lexemes[0].value}". Support for additional statement types will be introduced soon.`)}static parseSelectStatement(segment,statementIndex){try{let result=SelectQueryParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse SELECT statement ${statementIndex}: ${message}`)}}static parseInsertStatement(segment,statementIndex){try{let result=InsertQueryParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse INSERT statement ${statementIndex}: ${message}`)}}static parseUpdateStatement(segment,statementIndex){try{let result=UpdateQueryParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse UPDATE statement ${statementIndex}: ${message}`)}}static parseDeleteStatement(segment,statementIndex){try{let result=DeleteQueryParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse DELETE statement ${statementIndex}: ${message}`)}}static parseCreateTableStatement(segment,statementIndex){try{let result=CreateTableParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse CREATE TABLE statement ${statementIndex}: ${message}`)}}static parseDropTableStatement(segment,statementIndex){try{let result=DropTableParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse DROP TABLE statement ${statementIndex}: ${message}`)}}static parseDropIndexStatement(segment,statementIndex){try{let result=DropIndexParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse DROP INDEX statement ${statementIndex}: ${message}`)}}static parseCreateIndexStatement(segment,statementIndex){try{let result=CreateIndexParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse CREATE INDEX statement ${statementIndex}: ${message}`)}}static parseAlterTableStatement(segment,statementIndex){try{let result=AlterTableParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse ALTER TABLE statement ${statementIndex}: ${message}`)}}static parseDropConstraintStatement(segment,statementIndex){try{let result=DropConstraintParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse DROP CONSTRAINT statement ${statementIndex}: ${message}`)}}static parseMergeStatement(segment,statementIndex){try{let result=MergeQueryParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse MERGE statement ${statementIndex}: ${message}`)}}static getCommandAfterWith(lexemes){try{let clone=this.cloneLexemeArray(lexemes),withResult=WithClauseParser.parseFromLexeme(clone,0);return lexemes[withResult.newIndex]?.value.toLowerCase()??null}catch{return null}}static cloneLexemeArray(lexemes){return lexemes.map(lexeme=>({...lexeme,comments:lexeme.comments?[...lexeme.comments]:null,positionedComments:lexeme.positionedComments?lexeme.positionedComments.map(pc=>({position:pc.position,comments:[...pc.comments]})):void 0,position:lexeme.position?{...lexeme.position}:void 0}))}static consumeNextStatement(tokenizer,cursor,skipEmpty){let localCursor=cursor,carry=null;for(;;){let segment=tokenizer.readNextStatement(localCursor,carry);if(carry=null,!segment)return null;if(localCursor=segment.nextPosition,!(segment.lexemes.length===0&&(segment.leadingComments&&segment.leadingComments.length>0&&(carry=segment.leadingComments),skipEmpty||segment.rawText.trim().length===0)))return{segment,nextCursor:localCursor}}}};var CTETableReferenceCollector=class{constructor(){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.visitOffsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr))}collect(query){return this.visit(query),this.getTableSources()}getTableSources(){return this.tableSources}reset(){this.tableSources=[],this.tableNameMap.clear(),this.visitedNodes.clear()}getTableIdentifier(source){return source.qualifiedName.namespaces&&source.qualifiedName.namespaces.length>0?source.qualifiedName.namespaces.map(ns=>ns.name).join(".")+"."+(source.qualifiedName.name instanceof RawString?source.qualifiedName.name.value:source.qualifiedName.name.name):source.qualifiedName.name instanceof RawString?source.qualifiedName.name.value:source.qualifiedName.name.name}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}}visitSimpleSelectQuery(query){if(query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.orderByClause&&query.orderByClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.limitClause&&query.limitClause.accept(this),query.offsetClause&&query.offsetClause.accept(this),query.fetchClause&&query.fetchClause.accept(this),query.forClause&&query.forClause.accept(this),query.selectClause.accept(this)}visitBinarySelectQuery(query){query.left.accept(this),query.right.accept(this)}visitValuesQuery(query){for(let tuple of query.tuples)tuple.accept(this)}visitFromClause(fromClause){if(fromClause.source.accept(this),fromClause.joins)for(let join of fromClause.joins)join.accept(this)}visitSourceExpression(source){source.datasource.accept(this)}visitTableSource(source){let identifier=this.getTableIdentifier(source);this.tableNameMap.has(identifier)||(this.tableNameMap.set(identifier,!0),this.tableSources.push(source))}visitFunctionSource(source){source.argument&&this.visitValueComponent(source.argument)}visitValueComponent(value){value.accept(this)}visitParenSource(source){source.source.accept(this)}visitSubQuerySource(subQuery){subQuery.query.accept(this)}visitInlineQuery(inlineQuery){inlineQuery.selectQuery.accept(this)}visitJoinClause(joinClause){joinClause.source.accept(this),joinClause.condition&&joinClause.condition.accept(this)}visitJoinOnClause(joinOn){joinOn.condition.accept(this)}visitJoinUsingClause(joinUsing){joinUsing.condition.accept(this)}visitWhereClause(whereClause){whereClause.condition.accept(this)}visitGroupByClause(clause){for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition.accept(this)}visitOrderByClause(clause){for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitLimitClause(clause){clause.value.accept(this)}visitOffsetClause(clause){clause.value.accept(this)}visitFetchClause(clause){clause.expression.accept(this)}visitForClause(_clause){}visitOrderByItem(item){item.value.accept(this)}visitSelectClause(clause){for(let item of clause.items)item.accept(this)}visitSelectItem(item){item.value.accept(this)}visitParenExpression(expr){expr.expression.accept(this)}visitBinaryExpression(expr){expr.left.accept(this),expr.right.accept(this)}visitUnaryExpression(expr){expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase.accept(this)}visitSwitchCaseArgument(switchCase){for(let caseItem of switchCase.cases)caseItem.accept(this);switchCase.elseValue&&switchCase.elseValue.accept(this)}visitCaseKeyValuePair(pair){pair.key.accept(this),pair.value.accept(this)}visitBetweenExpression(expr){expr.expression.accept(this),expr.lower.accept(this),expr.upper.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this)}visitArrayExpression(expr){expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitTupleExpression(expr){for(let value of expr.values)value.accept(this)}visitCastExpression(expr){expr.input.accept(this),expr.castType.accept(this)}visitValueList(valueList){for(let value of valueList.values)value.accept(this)}visitStringSpecifierExpression(_expr){}};var CTEDependencyAnalyzer=class _CTEDependencyAnalyzer{constructor(){this.dependencyGraph=null;this.cteMap=new Map;this.sourceCollector=new TableSourceCollector(!1),this.cteReferenceCollector=new CTETableReferenceCollector,this.cteCollector=new CTECollector}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(query){let ctes=this.cteCollector.collect(query);return this.buildCTEMap(ctes),this.dependencyGraph=this.buildDependencyGraph(ctes,query),this.dependencyGraph}getDependencies(cteName){this.ensureAnalyzed();let node=this.findNodeByName(cteName);return node?[...node.dependencies]:[]}getDependents(cteName){this.ensureAnalyzed();let node=this.findNodeByName(cteName);return node?[...node.dependents]:[]}getMainQueryDependencies(){this.ensureAnalyzed();let mainQueryNode=this.findNodeByName(_CTEDependencyAnalyzer.MAIN_QUERY_NAME);return mainQueryNode?[...mainQueryNode.dependencies]:[]}getNodesByType(nodeType){return this.ensureAnalyzed(),this.dependencyGraph.nodes.filter(n=>n.type===nodeType)}getMainQueryNode(){return this.ensureAnalyzed(),this.findNodeByName(_CTEDependencyAnalyzer.MAIN_QUERY_NAME)}hasCircularDependency(){this.ensureAnalyzed();try{return this.getExecutionOrder(),!1}catch(error){if(error instanceof Error&&error.message.includes(_CTEDependencyAnalyzer.ERROR_MESSAGES.CIRCULAR_REFERENCE))return!0;throw error}}getExecutionOrder(){this.ensureAnalyzed();let visited=new Set,visiting=new Set,result=[],dependencyMap=new Map;for(let node of this.dependencyGraph.nodes)dependencyMap.set(node.name,new Set(node.dependencies));let visit=nodeName=>{if(visited.has(nodeName))return;if(visiting.has(nodeName))throw new Error(`${_CTEDependencyAnalyzer.ERROR_MESSAGES.CIRCULAR_REFERENCE}: ${nodeName}`);visiting.add(nodeName);let deps=dependencyMap.get(nodeName)||new Set;for(let dep of deps)visit(dep);visiting.delete(nodeName),visited.add(nodeName),result.push(nodeName)};for(let node of this.dependencyGraph.nodes)visited.has(node.name)||visit(node.name);return result}buildDependencyGraph(ctes,mainQuery){let nodes=[],edges=[],dependencyMap=new Map,dependentMap=new Map;for(let cte of ctes){let name=_CTEDependencyAnalyzer.getCTEName(cte);dependencyMap.set(name,new Set),dependentMap.set(name,new Set)}dependencyMap.set(_CTEDependencyAnalyzer.MAIN_QUERY_NAME,new Set),dependentMap.set(_CTEDependencyAnalyzer.MAIN_QUERY_NAME,new Set);for(let cte of ctes){let cteName=_CTEDependencyAnalyzer.getCTEName(cte),referencedTables=this.sourceCollector.collect(cte.query);for(let referencedTable of referencedTables){let referencedName=referencedTable.table.name;this.cteMap.has(referencedName)&&referencedName!==cteName&&(dependencyMap.get(cteName).add(referencedName),dependentMap.get(referencedName).add(cteName),edges.push({from:cteName,to:referencedName}))}}let mainQueryWithoutCTE=this.getMainQueryWithoutCTE(mainQuery);if(mainQueryWithoutCTE){let mainQueryReferences=this.cteReferenceCollector.collect(mainQueryWithoutCTE);for(let referencedTable of mainQueryReferences){let referencedName=referencedTable.table.name;this.cteMap.has(referencedName)&&(dependencyMap.get(_CTEDependencyAnalyzer.MAIN_QUERY_NAME).add(referencedName),dependentMap.get(referencedName).add(_CTEDependencyAnalyzer.MAIN_QUERY_NAME),edges.push({from:_CTEDependencyAnalyzer.MAIN_QUERY_NAME,to:referencedName}))}}for(let cte of ctes){let name=_CTEDependencyAnalyzer.getCTEName(cte);nodes.push({name,type:"CTE",cte,dependencies:Array.from(dependencyMap.get(name)||new Set),dependents:Array.from(dependentMap.get(name)||new Set)})}return nodes.push({name:_CTEDependencyAnalyzer.MAIN_QUERY_NAME,type:"ROOT",cte:null,dependencies:Array.from(dependencyMap.get(_CTEDependencyAnalyzer.MAIN_QUERY_NAME)||new Set),dependents:Array.from(dependentMap.get(_CTEDependencyAnalyzer.MAIN_QUERY_NAME)||new Set)}),{nodes,edges}}ensureAnalyzed(){if(!this.dependencyGraph)throw new Error(_CTEDependencyAnalyzer.ERROR_MESSAGES.NOT_ANALYZED)}buildCTEMap(ctes){this.cteMap.clear();for(let cte of ctes){let name=_CTEDependencyAnalyzer.getCTEName(cte);this.cteMap.set(name,cte)}}findNodeByName(cteName){return this.dependencyGraph?.nodes.find(n=>n.name===cteName)}getMainQueryWithoutCTE(query){return query.withClause?new SimpleSelectQuery({selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:query.orderByClause,limitClause:query.limitClause,offsetClause:query.offsetClause,fetchClause:query.fetchClause,forClause:query.forClause,windowClause:query.windowClause}):query}static getCTEName(cte){return cte.aliasExpression.table.name}};var CommentEditor=class{static addComment(component,comment,position="before"){if(this.isSelectQuery(component)){let selectQuery=component;selectQuery.headerComments||(selectQuery.headerComments=[]),selectQuery.headerComments.push(comment)}else component.addPositionedComments(position,[comment])}static isSelectQuery(component){return"__selectQueryType"in component&&component.__selectQueryType==="SelectQuery"}static editComment(component,index,newComment,position="before"){if(this.isSelectQuery(component)){let selectQuery=component;if(!selectQuery.headerComments||index<0||index>=selectQuery.headerComments.length)throw new Error(`Invalid comment index: ${index}. Component has ${selectQuery.headerComments?.length||0} comments.`);selectQuery.headerComments[index]=newComment}else{let positionedComments=component.getPositionedComments(position);if(!positionedComments||index<0||index>=positionedComments.length)throw new Error(`Invalid comment index: ${index}. Component has ${positionedComments?.length||0} ${position} positioned comments.`);let positioned=component.positionedComments?.find(pc=>pc.position===position);positioned&&(positioned.comments[index]=newComment)}}static deleteComment(component,index,position="before"){if(this.isSelectQuery(component)){let selectQuery=component;if(!selectQuery.headerComments||index<0||index>=selectQuery.headerComments.length)throw new Error(`Invalid comment index: ${index}. Component has ${selectQuery.headerComments?.length||0} comments.`);selectQuery.headerComments.splice(index,1),selectQuery.headerComments.length===0&&(selectQuery.headerComments=null)}else{let positionedComments=component.getPositionedComments(position);if(!positionedComments||index<0||index>=positionedComments.length)throw new Error(`Invalid comment index: ${index}. Component has ${positionedComments?.length||0} ${position} positioned comments.`);let positioned=component.positionedComments?.find(pc=>pc.position===position);positioned&&(positioned.comments.splice(index,1),positioned.comments.length===0&&(component.positionedComments=component.positionedComments?.filter(pc=>pc.position!==position)||null,component.positionedComments?.length===0&&(component.positionedComments=null)))}}static deleteAllComments(component){if(this.isSelectQuery(component)){let selectQuery=component;selectQuery.headerComments=null}else component.positionedComments=null}static getComments(component){return this.isSelectQuery(component)?component.headerComments||[]:component.getAllPositionedComments()}static findComponentsWithComment(root,searchText,caseSensitive=!1){let results=[],searchTerm=caseSensitive?searchText:searchText.toLowerCase(),traverse=component=>{if(component&&component instanceof SqlComponent){let hasMatchingComment=!1,allPositionedComments=component.getAllPositionedComments();if(allPositionedComments&&allPositionedComments.some(c=>(caseSensitive?c:c.toLowerCase()).includes(searchTerm))&&(hasMatchingComment=!0),this.isSelectQuery(component)){let selectQuery=component;selectQuery.headerComments&&selectQuery.headerComments.some(c=>(caseSensitive?c:c.toLowerCase()).includes(searchTerm))&&(hasMatchingComment=!0)}hasMatchingComment&&results.push(component)}for(let key in component)component[key]&&typeof component[key]=="object"&&(Array.isArray(component[key])?component[key].forEach(traverse):traverse(component[key]))};return traverse(root),results}static replaceInComments(root,searchText,replaceText,caseSensitive=!1){let replacementCount=0,traverse=component=>{if(component&&component instanceof SqlComponent){if(component.comments)for(let i=0;i<component.comments.length;i++){let originalComment=component.comments[i],flags=caseSensitive?"g":"gi",regex=new RegExp(searchText.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),flags),newComment=originalComment.replace(regex,replaceText);newComment!==originalComment&&(component.comments[i]=newComment,replacementCount++)}if(component.positionedComments){for(let posComment of component.positionedComments)if(posComment.comments)for(let i=0;i<posComment.comments.length;i++){let originalComment=posComment.comments[i],flags=caseSensitive?"g":"gi",regex=new RegExp(searchText.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),flags),newComment=originalComment.replace(regex,replaceText);newComment!==originalComment&&(posComment.comments[i]=newComment,replacementCount++)}}if(this.isSelectQuery(component)){let selectQuery=component;if(selectQuery.headerComments)for(let i=0;i<selectQuery.headerComments.length;i++){let originalComment=selectQuery.headerComments[i],flags=caseSensitive?"g":"gi",regex=new RegExp(searchText.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),flags),newComment=originalComment.replace(regex,replaceText);newComment!==originalComment&&(selectQuery.headerComments[i]=newComment,replacementCount++)}}}for(let key in component)component[key]&&typeof component[key]=="object"&&(Array.isArray(component[key])?component[key].forEach(traverse):traverse(component[key]))};return traverse(root),replacementCount}static countComments(root){let count=0,traverse=component=>{if(component&&component instanceof SqlComponent){let positionedComments=component.getAllPositionedComments();if(positionedComments&&(count+=positionedComments.length),this.isSelectQuery(component)){let selectQuery=component;selectQuery.headerComments&&(count+=selectQuery.headerComments.length)}}for(let key in component)component[key]&&typeof component[key]=="object"&&(Array.isArray(component[key])?component[key].forEach(traverse):traverse(component[key]))};return traverse(root),count}static getAllComments(root){let results=[],traverse=component=>{if(component&&component instanceof SqlComponent){let positionedComments=component.getAllPositionedComments();if(positionedComments&&positionedComments.forEach((comment,index)=>{results.push({comment,component,index})}),this.isSelectQuery(component)){let selectQuery=component;selectQuery.headerComments&&selectQuery.headerComments.forEach((comment,index)=>{results.push({comment,component,index})})}}for(let key in component)component[key]&&typeof component[key]=="object"&&(Array.isArray(component[key])?component[key].forEach(traverse):traverse(component[key]))};return traverse(root),results}};var TableSchema=class{constructor(name,columns){this.name=name,this.columns=columns}},SchemaCollector=class{constructor(tableColumnResolver=null,allowWildcardWithoutResolver=!1){this.tableColumnResolver=tableColumnResolver;this.allowWildcardWithoutResolver=allowWildcardWithoutResolver;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(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr))}collect(arg){return this.visit(arg),this.tableSchemas}analyze(arg){this.isAnalyzeMode=!0;try{return this.visit(arg),{success:this.unresolvedColumns.length===0&&!this.analysisError,schemas:this.tableSchemas,unresolvedColumns:this.unresolvedColumns,error:this.analysisError}}finally{this.isAnalyzeMode=!1}}visit(arg){if(this.running){this.visitNode(arg);return}this.reset(),this.running=!0;try{if(!(arg instanceof SimpleSelectQuery||arg instanceof BinarySelectQuery))throw new Error(`Unsupported SQL component type for schema collection. Received: ${arg.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let cteCollector=new CTECollector;this.commonTables=cteCollector.collect(arg),this.visitNode(arg),this.consolidateTableSchemas()}finally{this.running=!1}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}}reset(){this.tableSchemas=[],this.visitedNodes=new Set,this.commonTables=[],this.unresolvedColumns=[],this.analysisError=void 0}consolidateTableSchemas(){let consolidatedSchemas=new Map;for(let schema of this.tableSchemas)if(!consolidatedSchemas.has(schema.name))consolidatedSchemas.set(schema.name,new Set(schema.columns));else{let existingColumns=consolidatedSchemas.get(schema.name);schema.columns.forEach(column=>existingColumns?.add(column))}this.tableSchemas=Array.from(consolidatedSchemas.entries()).sort(([nameA],[nameB])=>nameA.localeCompare(nameB)).map(([name,columns])=>new TableSchema(name,Array.from(columns).sort()))}handleSourceExpression(source,queryColumns,includeUnnamed){if(source.datasource instanceof TableSource){let tableName=source.datasource.getSourceName(),cte=this.commonTables.filter(table=>table.getSourceAliasName()===tableName);if(cte.length>0){cte[0].query.accept(this);let cteAlias=source.getAliasName()??tableName;this.processCTETableSchema(cte[0],cteAlias,queryColumns,includeUnnamed)}else{let tableAlias=source.getAliasName()??tableName;this.processCollectTableSchema(tableName,tableAlias,queryColumns,includeUnnamed)}}else source.datasource instanceof SubQuerySource&&this.visitNode(source.datasource.query)}visitSimpleSelectQuery(query){if(query.fromClause===null)return;let columns=new SelectableColumnCollector(this.tableColumnResolver,!0,"fullName").collect(query),queryColumns;if(this.allowWildcardWithoutResolver){let selectColumns=this.getSelectClauseColumns(query);queryColumns=columns.filter(column=>column.value instanceof ColumnReference).map(column=>column.value).filter(columnRef=>{let tableName=columnRef.getNamespace(),columnName=columnRef.column.name;return selectColumns.some(selectCol=>{if(selectCol.value instanceof ColumnReference){let selectTableName=selectCol.value.getNamespace(),selectColumnName=selectCol.value.column.name;if(selectTableName===tableName&&selectColumnName===columnName)return!0;if(selectColumnName==="*"){if(this.allowWildcardWithoutResolver&&this.tableColumnResolver===null)return!1;if(selectTableName===""||selectTableName===tableName)return!0}}return!1})}).map(columnRef=>({table:columnRef.getNamespace(),column:columnRef.column.name}))}else queryColumns=columns.filter(column=>column.value instanceof ColumnReference).map(column=>column.value).map(columnRef=>({table:columnRef.getNamespace(),column:columnRef.column.name}));if(query.fromClause.joins!==null&&query.fromClause.joins.length>0){let columnsWithoutTable=queryColumns.filter(columnRef=>columnRef.table==="").map(columnRef=>columnRef.column);if(columnsWithoutTable.length>0)if(this.isAnalyzeMode)this.unresolvedColumns.push(...columnsWithoutTable),this.analysisError=`Column reference(s) without table name found in query: ${columnsWithoutTable.join(", ")}`;else throw new Error(`Column reference(s) without table name found in query: ${columnsWithoutTable.join(", ")}`)}if(query.fromClause.source.datasource instanceof TableSource?this.handleSourceExpression(query.fromClause.source,queryColumns,!0):query.fromClause.source.datasource instanceof SubQuerySource&&query.fromClause.source.datasource.query.accept(this),query.fromClause?.joins)for(let join of query.fromClause.joins)join.source.datasource instanceof TableSource?this.handleSourceExpression(join.source,queryColumns,!1):join.source.datasource instanceof SubQuerySource&&join.source.datasource.query.accept(this)}visitBinarySelectQuery(query){this.visitNode(query.left),this.visitNode(query.right)}getSelectClauseColumns(query){if(!query.selectClause)return[];let selectColumns=[];for(let item of query.selectClause.items)if(item.value instanceof ColumnReference){let columnName=item.value.column.name;selectColumns.push({name:columnName,value:item.value})}return selectColumns}processCollectTableSchema(tableName,tableAlias,queryColumns,includeUnnamed=!1){if(this.tableColumnResolver===null&&queryColumns.filter(columnRef=>columnRef.table===tableAlias||includeUnnamed&&columnRef.table==="").filter(columnRef=>columnRef.column==="*").length>0&&!this.allowWildcardWithoutResolver){let errorMessage=tableName?`Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards. Target table: ${tableName}`:"Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards.";if(this.isAnalyzeMode){this.analysisError=errorMessage;let wildcardColumns=queryColumns.filter(columnRef=>columnRef.table===tableAlias||includeUnnamed&&columnRef.table==="").filter(columnRef=>columnRef.column==="*").map(columnRef=>columnRef.table?`${columnRef.table}.*`:"*");this.unresolvedColumns.push(...wildcardColumns)}else throw new Error(errorMessage)}let tableColumns=queryColumns.filter(columnRef=>columnRef.column!=="*").filter(columnRef=>columnRef.table===tableAlias||includeUnnamed&&columnRef.table==="").map(columnRef=>columnRef.column),tableSchema=new TableSchema(tableName,tableColumns);this.tableSchemas.push(tableSchema)}processCTETableSchema(cte,cteAlias,queryColumns,includeUnnamed=!1){let cteName=cte.getSourceAliasName(),cteColumns=this.getCTEColumns(cte),cteReferencedColumns=queryColumns.filter(columnRef=>columnRef.table===cteAlias||includeUnnamed&&columnRef.table==="").map(columnRef=>columnRef.column);if(cteReferencedColumns.includes("*")){if(this.tableColumnResolver!==null){let resolvedColumns=this.tableColumnResolver(cteName);if(resolvedColumns.length>0){let tableSchema2=new TableSchema(cteName,resolvedColumns);this.tableSchemas.push(tableSchema2);return}}if(cteColumns.length>0){let tableSchema2=new TableSchema(cteName,cteColumns);this.tableSchemas.push(tableSchema2);return}else if(this.allowWildcardWithoutResolver){let tableSchema2=new TableSchema(cteName,[]);this.tableSchemas.push(tableSchema2);return}else{let errorMessage=`Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards. Target table: ${cteName}`;if(this.isAnalyzeMode)this.analysisError=errorMessage,this.unresolvedColumns.push(cteAlias?`${cteAlias}.*`:"*");else throw new Error(errorMessage);return}}let tableColumns=cteReferencedColumns.filter(column=>column!=="*");if(this.isAnalyzeMode){let availableColumns=cteColumns;if(this.tableColumnResolver){let resolvedColumns=this.tableColumnResolver(cteName);resolvedColumns.length>0&&(availableColumns=resolvedColumns)}if(availableColumns.length>0){let invalidColumns=tableColumns.filter(column=>!availableColumns.includes(column));invalidColumns.length>0&&(this.unresolvedColumns.push(...invalidColumns),this.analysisError||(this.analysisError=`Undefined column(s) found in CTE "${cteName}": ${invalidColumns.join(", ")}`))}else if(!this.allowWildcardWithoutResolver){let invalidColumns=tableColumns;invalidColumns.length>0&&(this.unresolvedColumns.push(...invalidColumns),this.analysisError||(this.analysisError=`Undefined column(s) found in CTE "${cteName}": ${invalidColumns.join(", ")}`))}}let tableSchema=new TableSchema(cteName,tableColumns);this.tableSchemas.push(tableSchema)}getCTEColumns(cte){try{return cte.query instanceof SimpleSelectQuery&&cte.query.selectClause?this.extractColumnsFromSelectItems(cte.query.selectClause.items,cte):this.extractColumnsUsingCollector(cte.query)}catch{return[]}}extractColumnsFromSelectItems(selectItems,cte){let columns=[];for(let item of selectItems)if(item.value instanceof ColumnReference){let columnName=item.identifier?.name||item.value.column.name;if(item.value.column.name==="*"){let wildcardColumns=this.resolveWildcardInCTE(item.value,cte);if(wildcardColumns===null)return[];columns.push(...wildcardColumns)}else columns.push(columnName)}else item.identifier&&columns.push(item.identifier.name);return this.removeDuplicates(columns)}resolveWildcardInCTE(columnRef,cte){let tableNamespace=columnRef.getNamespace();return tableNamespace?this.resolveQualifiedWildcard(tableNamespace):this.resolveUnqualifiedWildcard(cte)}resolveQualifiedWildcard(tableNamespace){let referencedCTE=this.commonTables.find(cte=>cte.getSourceAliasName()===tableNamespace);if(referencedCTE){let referencedColumns=this.getCTEColumns(referencedCTE);if(referencedColumns.length>0)return referencedColumns}return null}resolveUnqualifiedWildcard(cte){if(!(cte.query instanceof SimpleSelectQuery)||!cte.query.fromClause)return null;let fromSource=cte.query.fromClause.source;return fromSource.datasource instanceof TableSource?this.resolveTableWildcard(fromSource.datasource.table.name):(fromSource.datasource instanceof SubQuerySource,null)}resolveTableWildcard(tableName){if(this.tableColumnResolver){let resolvedColumns=this.tableColumnResolver(tableName);if(resolvedColumns.length>0)return resolvedColumns}return this.allowWildcardWithoutResolver,null}extractColumnsUsingCollector(query){return new SelectableColumnCollector(null,!0,"fullName").collect(query).filter(column=>column.value instanceof ColumnReference).map(column=>column.value).map(columnRef=>columnRef.column.name).filter((name,index,array)=>array.indexOf(name)===index)}removeDuplicates(columns){return columns.filter((name,index,array)=>array.indexOf(name)===index)}};var SqlSchemaValidator=class{static validate(sql,tableResolver){let sqlComponent=typeof sql=="string"?SelectQueryParser.parse(sql):sql,resolver=Array.isArray(tableResolver)?tableName=>{let schema=tableResolver.find(t=>t.name===tableName);return schema?schema.columns:[]}:tableResolver,tableSchemas=new SchemaCollector(resolver).collect(sqlComponent),errors=[];for(let tableSchema of tableSchemas){let resolvedColumns=resolver(tableSchema.name);if(resolvedColumns.length===0){errors.push(`Table '${tableSchema.name}' is not defined.`);continue}let undefinedColumns=tableSchema.columns.filter(column=>!resolvedColumns.includes(column));undefinedColumns.length>0&&errors.push(`Table '${tableSchema.name}' contains undefined columns: ${undefinedColumns.join(", ")}.`)}if(errors.length>0)throw new Error(errors.join(`
32
+ `);return{line:lines.length,column:lines[lines.length-1].length+1}}static extractCTERegions(sql){let lexemes=LexemeCursor.getAllLexemesWithPosition(sql),cteRegions=[],i=0,inWithClause=!1;for(;i<lexemes.length;){let lexeme=lexemes[i];if(lexeme.value.toLowerCase()==="with"&&!inWithClause){inWithClause=!0,i++;continue}if(inWithClause&&lexeme.value.toLowerCase()==="recursive"){i++;continue}if(inWithClause&&lexeme.type===64&&i+1<lexemes.length&&lexemes[i+1].value.toLowerCase()==="as"){let cteName=lexeme.value,cteStartPos=lexeme.position.startPosition,parenIndex=i+2;for(;parenIndex<lexemes.length&&lexemes[parenIndex].value!=="(";)parenIndex++;if(parenIndex<lexemes.length){let cteEndInfo=this.findMatchingParen(lexemes,parenIndex);if(cteEndInfo){let cteEndPos=cteEndInfo.endPosition,sqlContent=this.extractCTESQL(sql,lexemes,parenIndex,cteEndInfo.index);cteRegions.push({name:cteName,startPosition:cteStartPos,endPosition:cteEndPos,sqlContent}),i=cteEndInfo.index+1;continue}}}if(inWithClause&&lexeme.value.toLowerCase()==="select"&&this.isMainQuerySelect(lexemes,i))break;i++}return cteRegions}static findMatchingParen(lexemes,openParenIndex){let depth=1,i=openParenIndex+1;for(;i<lexemes.length&&depth>0;){if(lexemes[i].value==="("?depth++:lexemes[i].value===")"&&depth--,depth===0)return{index:i,endPosition:lexemes[i].position.endPosition};i++}return null}static extractCTESQL(sql,lexemes,openParenIndex,closeParenIndex){let startPos=lexemes[openParenIndex+1].position.startPosition,endPos=lexemes[closeParenIndex-1].position.endPosition;return sql.substring(startPos,endPos).trim()}static isMainQuerySelect(lexemes,selectIndex){let depth=0;for(let i=selectIndex-1;i>=0;i--)lexemes[i].value===")"?depth++:lexemes[i].value==="("&&depth--;return depth===0}static calculateExtendedCTEBoundaries(sql,cteRegions){return cteRegions.length===0?[]:cteRegions.map((region,index)=>{let extendedEndPosition;return index<cteRegions.length-1?extendedEndPosition=cteRegions[index+1].startPosition:extendedEndPosition=this.findMainQueryStart(sql,region.endPosition),{...region,extendedEndPosition}})}static findMainQueryStart(sql,afterPosition){let pos=afterPosition;for(;pos<sql.length;){if(sql.substring(pos).toLowerCase().trim().startsWith("select")){let selectIndex=sql.toLowerCase().indexOf("select",pos);return selectIndex!==-1?selectIndex:pos}pos++}return sql.length}static extractMainQuery(sql,cteRegions){if(cteRegions.length===0)return sql.trim();let selectPos=cteRegions[cteRegions.length-1].endPosition;for(;selectPos<sql.length&&!sql.substring(selectPos).toLowerCase().trim().startsWith("select");)selectPos++;return sql.substring(selectPos).trim()}static getCTEPositions(sql){let cteRegions=this.extractCTERegions(sql),results=[];if(cteRegions.forEach(region=>{results.push({name:region.name,startPosition:region.startPosition,type:"CTE"})}),cteRegions.length>0){let mainQueryPos=cteRegions[cteRegions.length-1].endPosition;for(;mainQueryPos<sql.length;){if(sql.substring(mainQueryPos).toLowerCase().trim().startsWith("select")){results.push({name:"MAIN_QUERY",startPosition:mainQueryPos,type:"MAIN_QUERY"});break}mainQueryPos++}}else results.push({name:"MAIN_QUERY",startPosition:0,type:"MAIN_QUERY"});return results}};var SelectQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`[SelectQueryParser] Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The SELECT query is complete but there are additional tokens.`);return result.value}static calculateCharacterPosition(query,lexemes,tokenIndex){if(tokenIndex>=lexemes.length)return query.length;let lexeme=lexemes[tokenIndex];if(lexeme.position?.startPosition!==void 0)return lexeme.position.startPosition;let searchStart=0;for(let i=0;i<tokenIndex;i++){let tokenValue=lexemes[i].value,tokenPos2=query.indexOf(tokenValue,searchStart);tokenPos2!==-1&&(searchStart=tokenPos2+tokenValue.length)}let targetToken=lexemes[tokenIndex].value,tokenPos=query.indexOf(targetToken,searchStart);return tokenPos!==-1?tokenPos:searchStart}static analyze(query){let lexemes=[];try{lexemes=new SqlTokenizer(query).readLexmes();let result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length){let remainingTokens=lexemes.slice(result.newIndex).map(lex=>lex.value),errorLexeme=lexemes[result.newIndex],errorPosition=this.calculateCharacterPosition(query,lexemes,result.newIndex);return{success:!1,query:result.value,error:`Syntax error: Unexpected token "${errorLexeme.value}" at character position ${errorPosition}. The SELECT query is complete but there are additional tokens.`,errorPosition,remainingTokens}}return{success:!0,query:result.value}}catch(error){let errorPosition,errorMessage=error instanceof Error?error.message:String(error),positionMatch=errorMessage.match(/position (\d+)/);if(positionMatch){let tokenIndex=parseInt(positionMatch[1],10);errorPosition=this.calculateCharacterPosition(query,lexemes,tokenIndex)}return{success:!1,error:errorMessage,errorPosition}}}static async parseAsync(query){return Promise.resolve(this.parse(query))}static{this.unionCommandSet=new Set(["union","union all","intersect","intersect all","except","except all"])}static{this.selectCommandSet=new Set(["with","select"])}static transferHeaderComments(source,target){source.headerComments&&(target.headerComments=source.headerComments,source.headerComments=null)}static extractUnionTokenComments(unionLexeme){let comments=[];if(unionLexeme.positionedComments&&unionLexeme.positionedComments.length>0){for(let posComment of unionLexeme.positionedComments)posComment.comments&&posComment.comments.length>0&&comments.push(...posComment.comments);unionLexeme.positionedComments=void 0}return unionLexeme.comments&&unionLexeme.comments.length>0&&(comments.push(...unionLexeme.comments),unionLexeme.comments=null),comments.length>0?comments:null}static parseFromLexeme(lexemes,index){let idx=index;if(idx>=lexemes.length)throw new Error(`Syntax error: Unexpected end of input at position ${index}.`);let firstToken=lexemes[idx].value;if(!this.selectCommandSet.has(firstToken)&&firstToken!=="values")throw new Error(`Syntax error at position ${idx}: Expected 'SELECT' or 'VALUES' keyword but found "${lexemes[idx].value}".`);let firstResult=this.selectCommandSet.has(firstToken)?this.parseSimpleSelectQuery(lexemes,idx):this.parseValuesQuery(lexemes,idx),query=firstResult.value;for(idx=firstResult.newIndex;idx<lexemes.length&&this.unionCommandSet.has(lexemes[idx].value.toLowerCase());){let operatorLexeme=lexemes[idx],operator=operatorLexeme.value.toLowerCase(),unionComments=this.extractUnionTokenComments(operatorLexeme);if(idx++,idx>=lexemes.length)throw new Error(`Syntax error at position ${idx}: Expected a query after '${operator.toUpperCase()}' but found end of input.`);let nextToken=lexemes[idx].value.toLowerCase();if(this.selectCommandSet.has(nextToken)){let result=this.parseSimpleSelectQuery(lexemes,idx),binaryQuery=new BinarySelectQuery(query,operator,result.value);this.transferHeaderComments(query,binaryQuery),unionComments&&unionComments.length>0&&(result.value.headerComments?result.value.headerComments=[...unionComments,...result.value.headerComments]:result.value.headerComments=unionComments),query=binaryQuery,idx=result.newIndex}else if(nextToken==="values"){let result=this.parseValuesQuery(lexemes,idx),binaryQuery=new BinarySelectQuery(query,operator,result.value);this.transferHeaderComments(query,binaryQuery),unionComments&&unionComments.length>0&&(result.value.headerComments?result.value.headerComments=[...unionComments,...result.value.headerComments]:result.value.headerComments=unionComments),query=binaryQuery,idx=result.newIndex}else throw new Error(`Syntax error at position ${idx}: Expected 'SELECT' or 'VALUES' after '${operator.toUpperCase()}' but found "${lexemes[idx].value}".`)}return{value:query,newIndex:idx}}static parseSimpleSelectQuery(lexemes,index){let idx=index,{withClauseResult,newIndex:withEndIndex,selectQuery:queryTemplate}=this.parseWithClauseAndComments(lexemes,idx);idx=withEndIndex;let{clauses,newIndex:clausesEndIndex,selectTokenComments}=this.parseAllClauses(lexemes,idx,withClauseResult);if(idx=clausesEndIndex,selectTokenComments&&selectTokenComments.length>0)if(withClauseResult){let merged=[...queryTemplate.betweenClauseComments??[]];for(let comment of selectTokenComments)merged.includes(comment)||merged.push(comment);queryTemplate.betweenClauseComments=merged,queryTemplate.mainSelectPrefixComments=void 0}else{let existingHeader=queryTemplate.headerComments??[];queryTemplate.headerComments=[...existingHeader,...selectTokenComments]}let selectQuery=new SimpleSelectQuery({withClause:withClauseResult?withClauseResult.value:null,...clauses});return this.applyCommentsToQuery(selectQuery,queryTemplate,withClauseResult),{value:selectQuery,newIndex:idx}}static parseWithClauseAndComments(lexemes,index){let idx=index,withClauseResult=null,queryTemplate={};for(queryTemplate.headerComments=this.collectHeaderComments(lexemes,idx);idx<lexemes.length&&lexemes[idx].value.toLowerCase()!=="with"&&lexemes[idx].value.toLowerCase()!=="select";)idx++;return idx<lexemes.length&&lexemes[idx].value.toLowerCase()==="with"&&this.collectWithTokenHeaderComments(lexemes[idx],queryTemplate),idx<lexemes.length&&lexemes[idx].value==="with"&&(withClauseResult=WithClauseParser.parseFromLexeme(lexemes,idx),idx=withClauseResult.newIndex,queryTemplate.mainSelectPrefixComments=this.collectMainSelectPrefixComments(lexemes,withClauseResult,idx),queryTemplate.betweenClauseComments=this.collectBetweenClauseComments(lexemes,withClauseResult,idx)),{withClauseResult,newIndex:idx,selectQuery:queryTemplate}}static parseAllClauses(lexemes,index,withClauseResult){let idx=index;idx=this.findMainSelectToken(lexemes,idx,withClauseResult);let selectTokenComments=this.collectSelectTokenComments(lexemes,idx),selectClauseResult=SelectClauseParser.parseFromLexeme(lexemes,idx);idx=selectClauseResult.newIndex;let fromClauseResult=this.parseOptionalClause(lexemes,idx,"from",FromClauseParser);idx=fromClauseResult.newIndex;let whereClauseResult=this.parseOptionalClause(lexemes,fromClauseResult.newIndex,"where",WhereClauseParser);idx=whereClauseResult.newIndex;let groupByClauseResult=this.parseOptionalClause(lexemes,whereClauseResult.newIndex,"group by",GroupByClauseParser);idx=groupByClauseResult.newIndex;let havingClauseResult=this.parseOptionalClause(lexemes,groupByClauseResult.newIndex,"having",HavingClauseParser);idx=havingClauseResult.newIndex;let windowClauseResult=this.parseOptionalClause(lexemes,havingClauseResult.newIndex,"window",WindowClauseParser);idx=windowClauseResult.newIndex;let orderByClauseResult=this.parseOptionalClause(lexemes,windowClauseResult.newIndex,"order by",OrderByClauseParser);idx=orderByClauseResult.newIndex;let limitClauseResult=this.parseOptionalClause(lexemes,orderByClauseResult.newIndex,"limit",LimitClauseParser);idx=limitClauseResult.newIndex;let offsetClauseResult=this.parseOptionalClause(lexemes,limitClauseResult.newIndex,"offset",OffsetClauseParser);idx=offsetClauseResult.newIndex;let fetchClauseResult=this.parseOptionalClause(lexemes,offsetClauseResult.newIndex,"fetch",FetchClauseParser);idx=fetchClauseResult.newIndex;let forClauseResult=this.parseOptionalClause(lexemes,fetchClauseResult.newIndex,"for",ForClauseParser);return idx=forClauseResult.newIndex,{clauses:{selectClause:selectClauseResult.value,fromClause:fromClauseResult.value,whereClause:whereClauseResult.value,groupByClause:groupByClauseResult.value,havingClause:havingClauseResult.value,orderByClause:orderByClauseResult.value,windowClause:windowClauseResult.value,limitClause:limitClauseResult.value,offsetClause:offsetClauseResult.value,fetchClause:fetchClauseResult.value,forClause:forClauseResult.value},newIndex:idx,selectTokenComments}}static parseOptionalClause(lexemes,index,keyword,parser){return index<lexemes.length&&lexemes[index].value.toLowerCase()===keyword?parser.parseFromLexeme(lexemes,index):{value:null,newIndex:index}}static collectHeaderComments(lexemes,startIndex){let headerComments=[],idx=startIndex;for(;idx<lexemes.length&&lexemes[idx].value.toLowerCase()!=="with"&&lexemes[idx].value.toLowerCase()!=="select";){let token=lexemes[idx];if(token.positionedComments)for(let posComment of token.positionedComments)posComment.comments&&headerComments.push(...posComment.comments);token.comments&&token.comments.length>0&&headerComments.push(...token.comments),idx++}return headerComments}static collectWithTokenHeaderComments(withToken,queryTemplate){if(!withToken.positionedComments)return;queryTemplate.headerComments||(queryTemplate.headerComments=[]);let remainingPositioned=[];for(let posComment of withToken.positionedComments)posComment.position==="before"&&posComment.comments?queryTemplate.headerComments.push(...posComment.comments):remainingPositioned.push(posComment);withToken.positionedComments=remainingPositioned.length>0?remainingPositioned:void 0}static collectMainSelectPrefixComments(lexemes,withClauseResult,currentIndex){let mainSelectPrefixComments=[];withClauseResult?.value.trailingComments&&mainSelectPrefixComments.push(...withClauseResult.value.trailingComments);let mainSelectIdx=this.findMainSelectIndex(lexemes,withClauseResult,currentIndex);if(withClauseResult&&mainSelectIdx>withClauseResult.newIndex)for(let tempIdx=withClauseResult.newIndex;tempIdx<mainSelectIdx;tempIdx++){let token=lexemes[tempIdx];if(token.positionedComments)for(let posComment of token.positionedComments)posComment.comments&&mainSelectPrefixComments.push(...posComment.comments);token.comments&&token.comments.length>0&&mainSelectPrefixComments.push(...token.comments)}return mainSelectPrefixComments}static collectBetweenClauseComments(lexemes,withClauseResult,currentIndex){if(!withClauseResult)return[];let betweenClauseComments=[],withEndIndex=withClauseResult.newIndex,scanStartIndex=Math.max(0,withEndIndex-1);for(let i=scanStartIndex;i<currentIndex;i++){let token=lexemes[i];if(token.positionedComments&&token.positionedComments.length>0){for(let posComment of token.positionedComments)posComment.comments&&betweenClauseComments.push(...posComment.comments);token.positionedComments=void 0}token.comments&&token.comments.length>0&&(betweenClauseComments.push(...token.comments),token.comments=null)}return betweenClauseComments}static findMainSelectIndex(lexemes,withClauseResult,fallbackIndex){if(withClauseResult){for(let i=withClauseResult.newIndex;i<lexemes.length;i++)if(lexemes[i].value.toLowerCase()==="select")return i}return fallbackIndex}static findMainSelectToken(lexemes,index,withClauseResult){let mainSelectIdx=this.findMainSelectIndex(lexemes,withClauseResult,index);if(mainSelectIdx>=lexemes.length||lexemes[mainSelectIdx].value!=="select")throw new Error(`Syntax error at position ${mainSelectIdx}: Expected 'SELECT' keyword but found "${mainSelectIdx<lexemes.length?lexemes[mainSelectIdx].value:"end of input"}". SELECT queries must start with the SELECT keyword.`);return mainSelectIdx}static collectSelectTokenComments(lexemes,selectIndex){let selectToken=lexemes[selectIndex],selectComments=[];if(selectToken.comments&&selectToken.comments.length>0&&(selectComments.push(...selectToken.comments),selectToken.comments=null),selectToken.positionedComments&&selectToken.positionedComments.length>0){for(let posComment of selectToken.positionedComments)posComment.position==="before"&&posComment.comments&&selectComments.push(...posComment.comments);selectToken.positionedComments=void 0}return selectComments}static applyCommentsToQuery(selectQuery,queryTemplate,withClauseResult){queryTemplate.headerComments?.length>0&&(selectQuery.headerComments=queryTemplate.headerComments);let mergeBetweenComments=source=>{if(!source||source.length===0)return;let existing=selectQuery.comments??[],merged=[];for(let comment of source)merged.includes(comment)||merged.push(comment);for(let comment of existing)merged.includes(comment)||merged.push(comment);selectQuery.comments=merged};mergeBetweenComments(queryTemplate.mainSelectPrefixComments),mergeBetweenComments(queryTemplate.betweenClauseComments)}static parseValuesQuery(lexemes,index){let result=ValuesQueryParser.parseFromLexeme(lexemes,index);return{value:result.value,newIndex:result.newIndex}}static getCursorCte(sql,cursorPosition){return CTERegionDetector.getCursorCte(sql,cursorPosition)}static getCursorCteAt(sql,line,column){return CTERegionDetector.getCursorCteAt(sql,line,column)}static positionToLineColumn(text,position){return CTERegionDetector.positionToLineColumn(text,position)}};var ReturningClauseParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx]?.value!=="returning")throw new Error(`Syntax error at position ${idx}: Expected 'RETURNING' but found '${lexemes[idx]?.value}'.`);let returningLexeme=lexemes[idx],returningComments=extractLexemeComments(returningLexeme);idx++;let columns=[],pendingBeforeForNext=[...returningComments.after];for(;idx<lexemes.length;){let lexeme=lexemes[idx],column=null;if(lexeme.type&64?column=new IdentifierString(lexeme.value):lexeme.value==="*"&&(column=new IdentifierString("*")),!column)break;let columnComments=extractLexemeComments(lexeme),beforeComments=[];if(pendingBeforeForNext.length>0&&beforeComments.push(...pendingBeforeForNext),columnComments.before.length>0&&beforeComments.push(...columnComments.before),beforeComments.length>0&&column.addPositionedComments("before",beforeComments),columnComments.after.length>0&&column.addPositionedComments("after",columnComments.after),columns.push(column),pendingBeforeForNext=[],idx++,lexemes[idx]?.type===16){pendingBeforeForNext=[...extractLexemeComments(lexemes[idx]).after],idx++;continue}break}if(pendingBeforeForNext.length>0&&columns.length>0&&columns[columns.length-1].addPositionedComments("after",pendingBeforeForNext),columns.length===0){let position=lexemes[idx]?.position?.startPosition??idx;throw new Error(`[ReturningClauseParser] Expected a column or '*' after RETURNING at position ${position}.`)}let clause=new ReturningClause(columns);return returningComments.before.length>0&&clause.addPositionedComments("before",returningComments.before),{value:clause,newIndex:idx}}};var InsertQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The INSERT query is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value==="with"){let result=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=result.value,idx=result.newIndex}if(!lexemes[idx]||lexemes[idx].value!=="insert into"){let found=lexemes[idx]?.value??"end of input";throw new Error(`Syntax error at position ${idx}: Expected 'INSERT INTO' but found '${found}'.`)}let insertKeywordLexeme=lexemes[idx],insertKeywordComments=extractLexemeComments(insertKeywordLexeme);idx++;let sourceResult=SourceExpressionParser.parseTableSourceFromLexemes(lexemes,idx),targetSource=sourceResult.value,targetDatasource=targetSource.datasource;idx=sourceResult.newIndex,insertKeywordComments.after.length>0&&targetDatasource.addPositionedComments("before",insertKeywordComments.after);let columnIdentifiers=null,trailingInsertComments=[];if(lexemes[idx]?.type===4){let openParenLexeme=lexemes[idx],parenComments=extractLexemeComments(openParenLexeme);idx++,parenComments.before.length>0&&targetDatasource.addPositionedComments("after",parenComments.before),columnIdentifiers=[];let pendingBeforeForNext=[...parenComments.after];for(;idx<lexemes.length&&lexemes[idx].type&64;){let columnLexeme=lexemes[idx],columnComments=extractLexemeComments(columnLexeme),column=new IdentifierString(columnLexeme.value),beforeComments=[];if(pendingBeforeForNext.length>0&&beforeComments.push(...pendingBeforeForNext),columnComments.before.length>0&&beforeComments.push(...columnComments.before),beforeComments.length>0&&column.addPositionedComments("before",beforeComments),columnComments.after.length>0&&column.addPositionedComments("after",columnComments.after),columnIdentifiers.push(column),pendingBeforeForNext=[],idx++,lexemes[idx]?.type===16){pendingBeforeForNext=[...extractLexemeComments(lexemes[idx]).after],idx++;continue}break}if(pendingBeforeForNext.length>0&&columnIdentifiers.length>0&&(columnIdentifiers[columnIdentifiers.length-1].addPositionedComments("after",pendingBeforeForNext),pendingBeforeForNext=[]),lexemes[idx]?.type!==8)throw new Error(`Syntax error at position ${idx}: Expected ')' after column list.`);let closeParenComments=extractLexemeComments(lexemes[idx]);idx++,closeParenComments.before.length>0&&columnIdentifiers.length>0&&columnIdentifiers[columnIdentifiers.length-1].addPositionedComments("after",closeParenComments.before),closeParenComments.after.length>0&&(trailingInsertComments=closeParenComments.after),columnIdentifiers.length===0&&(columnIdentifiers=[])}if(idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input while parsing INSERT statement. VALUES or SELECT clause expected.");let nextToken=lexemes[idx].value.toLowerCase(),dataQuery;if(nextToken==="values"){let valuesResult=ValuesQueryParser.parseFromLexeme(lexemes,idx);dataQuery=valuesResult.value,idx=valuesResult.newIndex}else{let selectResult=SelectQueryParser.parseFromLexeme(lexemes,idx);dataQuery=selectResult.value,idx=selectResult.newIndex}let returningClause=null;if(lexemes[idx]?.value==="returning"){let returningResult=ReturningClauseParser.parseFromLexeme(lexemes,idx);returningClause=returningResult.value,idx=returningResult.newIndex}let insertClause=new InsertClause(targetSource,columnIdentifiers??null);return insertKeywordComments.before.length>0&&insertClause.addPositionedComments("before",insertKeywordComments.before),trailingInsertComments.length>0&&insertClause.addPositionedComments("after",trailingInsertComments),{value:new InsertQuery({withClause,insertClause,selectQuery:dataQuery,returning:returningClause}),newIndex:idx}}};var UpdateClauseParser=class{static parseFromLexeme(lexemes,index){let result=SourceExpressionParser.parseFromLexeme(lexemes,index);return{value:new UpdateClause(result.value),newIndex:result.newIndex}}};var SetClauseParser=class{static parseFromLexeme(lexemes,idx){if(lexemes[idx].value!=="set")throw new Error(`Syntax error at position ${idx}: Expected 'SET' but found '${lexemes[idx].value}'.`);let setLexeme=lexemes[idx],setKeywordComments=extractLexemeComments(setLexeme);idx++;let items=[],pendingBeforeForNext=[...setKeywordComments.after],mergeUnique=(target,source)=>{for(let comment of source)target.includes(comment)||target.push(comment)},addUniquePositionedComments=(component,position,comments)=>{if(comments.length===0)return;let existing=component.getPositionedComments(position),newOnes=comments.filter(comment=>!existing.includes(comment));newOnes.length>0&&component.addPositionedComments(position,newOnes)};for(;idx<lexemes.length;){let currentLexeme=lexemes[idx];if(!currentLexeme||currentLexeme.value==="where"||currentLexeme.value==="from"||currentLexeme.value==="returning"||!(currentLexeme.type&10816))break;let columnStartComments=extractLexemeComments(currentLexeme),columnParseResult=FullNameParser.parseFromLexeme(lexemes,idx);idx=columnParseResult.newIndex;let equalsLexeme=lexemes[idx];if(!equalsLexeme||!(equalsLexeme.type&2)||equalsLexeme.value!=="=")throw new Error(`Syntax error at position ${idx}: Expected '=' after column name in SET clause.`);let equalsComments=extractLexemeComments(equalsLexeme);idx++;let valueParseResult=ValueParser.parseFromLexeme(lexemes,idx);idx=valueParseResult.newIndex;let setItem=new SetClauseItem({namespaces:columnParseResult.namespaces,column:columnParseResult.name},valueParseResult.value),beforeComments=[];if(mergeUnique(beforeComments,pendingBeforeForNext),mergeUnique(beforeComments,columnStartComments.before),beforeComments.length>0&&addUniquePositionedComments(columnParseResult.name,"before",beforeComments),pendingBeforeForNext=[],columnStartComments.after.length>0){let afterComments=[];mergeUnique(afterComments,columnStartComments.after),addUniquePositionedComments(columnParseResult.name,"after",afterComments)}if(equalsComments.before.length>0){let equalsBefore=[];mergeUnique(equalsBefore,equalsComments.before),addUniquePositionedComments(columnParseResult.name,"after",equalsBefore)}if(equalsComments.after.length>0){let equalsAfter=[];mergeUnique(equalsAfter,equalsComments.after),addUniquePositionedComments(valueParseResult.value,"before",equalsAfter)}if(items.push(setItem),lexemes[idx]?.type===16){let commaLexeme=lexemes[idx],commaComments=extractLexemeComments(commaLexeme);if(idx++,commaComments.before.length>0){let commaBefore=[];mergeUnique(commaBefore,commaComments.before),addUniquePositionedComments(setItem,"after",commaBefore)}let nextBefore=[];mergeUnique(nextBefore,commaComments.after),pendingBeforeForNext=nextBefore;continue}break}if(pendingBeforeForNext.length>0&&items.length>0){let trailingComments=[];mergeUnique(trailingComments,pendingBeforeForNext),trailingComments.length>0&&addUniquePositionedComments(items[items.length-1],"after",trailingComments)}let setClause=new SetClause(items);return setKeywordComments.before.length>0&&setClause.addPositionedComments("before",setKeywordComments.before),{setClause,newIndex:idx}}};var UpdateQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The UPDATE query is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value?.toLowerCase()==="with"){let withResult=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=withResult.value,idx=withResult.newIndex}if(lexemes[idx].value!=="update")throw new Error(`Syntax error at position ${idx}: Expected 'UPDATE' but found '${lexemes[idx].value}'.`);let updateLexeme=lexemes[idx],updateKeywordComments=extractLexemeComments(updateLexeme);idx++;let updateClauseResult=UpdateClauseParser.parseFromLexeme(lexemes,idx),updateClause=updateClauseResult.value;idx=updateClauseResult.newIndex,updateKeywordComments.before.length>0&&updateClause.addPositionedComments("before",updateKeywordComments.before),updateKeywordComments.after.length>0&&updateClause.addPositionedComments("after",updateKeywordComments.after);let setClauseResult=SetClauseParser.parseFromLexeme(lexemes,idx),setClause=setClauseResult.setClause;idx=setClauseResult.newIndex;let from=null;if(lexemes[idx]?.value==="from"){let result=FromClauseParser.parseFromLexeme(lexemes,idx);from=result.value,idx=result.newIndex}let where=null;if(lexemes[idx]?.value==="where"){let result=WhereClauseParser.parseFromLexeme(lexemes,idx);where=result.value,idx=result.newIndex}let returning=null;if(lexemes[idx]?.value==="returning"){let result=ReturningClauseParser.parseFromLexeme(lexemes,idx);returning=result.value,idx=result.newIndex}return{value:new UpdateQuery({withClause,updateClause,setClause,whereClause:where,fromClause:from,returning}),newIndex:idx}}};var DeleteClauseParser=class{static parseFromLexeme(lexemes,index){if(index>=lexemes.length)throw new Error(`[DeleteClauseParser] Unexpected end of input at position ${index}: expected 'DELETE FROM'.`);let deleteToken=lexemes[index];if(deleteToken?.value?.toLowerCase()!=="delete from"){let position=lexemes[index]?.position?.startPosition??index;throw new Error(`[DeleteClauseParser] Syntax error at position ${position}: expected 'DELETE FROM' but found '${lexemes[index]?.value}'.`)}let deleteTokenComments=extractLexemeComments(deleteToken),targetResult=SourceExpressionParser.parseFromLexeme(lexemes,index+1),deleteClause=new DeleteClause(targetResult.value);return deleteTokenComments.before.length>0&&deleteClause.addPositionedComments("before",deleteTokenComments.before),deleteTokenComments.after.length>0&&deleteClause.addPositionedComments("after",deleteTokenComments.after),{value:deleteClause,newIndex:targetResult.newIndex}}};var UsingClauseParser=class{static parseFromLexeme(lexemes,index){if(lexemes[index].value!=="using")throw new Error(`Syntax error at position ${index}: Expected 'USING' but found '${lexemes[index].value}'.`);let idx=index+1,sources=[],firstSource=SourceExpressionParser.parseFromLexeme(lexemes,idx);for(sources.push(firstSource.value),idx=firstSource.newIndex;lexemes[idx]?.type===16;){idx++;let nextSource=SourceExpressionParser.parseFromLexeme(lexemes,idx);sources.push(nextSource.value),idx=nextSource.newIndex}return{value:new UsingClause(sources),newIndex:idx}}};var DeleteQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The DELETE query is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value==="with"){let withResult=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=withResult.value,idx=withResult.newIndex}let deleteClauseResult=DeleteClauseParser.parseFromLexeme(lexemes,idx),deleteClause=deleteClauseResult.value;idx=deleteClauseResult.newIndex;let usingClause=null;if(lexemes[idx]?.value==="using"){let usingResult=UsingClauseParser.parseFromLexeme(lexemes,idx);usingClause=usingResult.value,idx=usingResult.newIndex}let whereClause=null;if(lexemes[idx]?.value==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}let returningClause=null;if(lexemes[idx]?.value==="returning"){let returningResult=ReturningClauseParser.parseFromLexeme(lexemes,idx);returningClause=returningResult.value,idx=returningResult.newIndex}return{value:new DeleteQuery({withClause,deleteClause,usingClause,whereClause,returning:returningClause}),newIndex:idx}}};var NO_SPACE_BEFORE=new Set([",",")","]","}",";"]),NO_SPACE_AFTER=new Set(["(","[","{"]);function joinLexemeValues(lexemes,start,end){let result="";for(let i=start;i<end;i++){let current=lexemes[i];if(!current)continue;if(result.length===0){result=current.value;continue}let previous=lexemes[i-1]?.value??"",omitSpace=NO_SPACE_BEFORE.has(current.value)||NO_SPACE_AFTER.has(previous)||current.value==="."||previous===".";result+=omitSpace?current.value:` ${current.value}`}return result}var CreateTableParser=class{static{this.TABLE_CONSTRAINT_STARTERS=new Set(["constraint","primary key","unique","unique key","foreign key","check"])}static{this.COLUMN_CONSTRAINT_STARTERS=new Set(["constraint","not null","null","default","primary key","unique","unique key","references","check","generated always","generated always as identity","generated by default","generated by default as identity"])}static{this.MATCH_KEYWORDS=new Map([["match full","full"],["match partial","partial"],["match simple","simple"]])}static{this.REFERENTIAL_ACTIONS=new Map([["cascade","cascade"],["restrict","restrict"],["no action","no action"],["set null","set null"],["set default","set default"]])}static{this.DEFERRABILITY_KEYWORDS=new Map([["deferrable","deferrable"],["not deferrable","not deferrable"]])}static{this.INITIALLY_KEYWORDS=new Map([["initially immediate","immediate"],["initially deferred","deferred"]])}static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The CREATE TABLE statement is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(idx>=lexemes.length)throw new Error(`[CreateTableParser] Unexpected end of input at position ${idx}.`);let commandLexeme=lexemes[idx],leadingCreateComments=this.popLexemeComments(commandLexeme,"before"),commandToken=commandLexeme.value.toLowerCase(),isTemporary=commandToken==="create temporary table";if(commandToken!=="create table"&&!isTemporary)throw new Error(`[CreateTableParser] Syntax error at position ${idx}: expected 'CREATE TABLE' but found '${lexemes[idx].value}'.`);idx++;let tokenAt=offset=>lexemes[idx+offset]?.value.toLowerCase(),ifNotExists=!1;tokenAt(0)==="if not exists"&&(idx++,ifNotExists=!0);let tableNameResult=this.parseQualifiedName(lexemes,idx);idx=tableNameResult.newIndex;let tableName=tableNameResult.name,tableNamespaces=tableNameResult.namespaces,positionedComments=tableName.positionedComments?[...tableName.positionedComments]:null,legacyComments=tableName.comments?[...tableName.comments]:null,columns=[],tableConstraints=[],tableOptions=null,asSelectQuery,withDataOption=null;if(lexemes[idx]?.type===4&&({columns,tableConstraints,newIndex:idx}=this.parseDefinitionList(lexemes,idx)),idx<lexemes.length){let nextValue=tokenAt(0);if(!this.isSelectKeyword(nextValue,lexemes[idx+1])){let optionsEnd=this.findClauseBoundary(lexemes,idx);optionsEnd>idx&&(tableOptions=new RawString(joinLexemeValues(lexemes,idx,optionsEnd)),idx=optionsEnd)}}let nextToken=tokenAt(0);if(nextToken==="as"){idx++;let selectResult=SelectQueryParser.parseFromLexeme(lexemes,idx);asSelectQuery=selectResult.value,idx=selectResult.newIndex}else if(nextToken==="select"||nextToken==="with"||nextToken==="values"){let selectResult=SelectQueryParser.parseFromLexeme(lexemes,idx);asSelectQuery=selectResult.value,idx=selectResult.newIndex}if(asSelectQuery){let withResult=this.parseWithDataOption(lexemes,idx);withResult&&(withDataOption=withResult.value,idx=withResult.newIndex)}let query=new CreateTableQuery({tableName:tableName.name,namespaces:tableNamespaces,isTemporary,ifNotExists,columns,tableConstraints,tableOptions,asSelectQuery,withDataOption});return positionedComments&&(query.tableName.positionedComments=positionedComments.map(pc=>({position:pc.position,comments:[...pc.comments]}))),legacyComments&&(query.tableName.comments=[...legacyComments]),leadingCreateComments.length>0&&query.addPositionedComments("before",leadingCreateComments),{value:query,newIndex:idx}}static parseQualifiedName(lexemes,index){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,index);return{namespaces:namespaces?[...namespaces]:null,name,newIndex}}static parseDefinitionList(lexemes,index){let idx=index,columns=[],constraints=[],openParenLexeme=lexemes[idx],pendingLeading=this.toOptionalComments(this.popLexemeComments(openParenLexeme,"after"));for(idx++;idx<lexemes.length;){let lexeme=lexemes[idx];if(lexeme.type===8){let closingLeading=this.popLexemeComments(lexeme,"before");if(closingLeading.length>0){let target=(constraints.length>0?constraints[constraints.length-1]:columns[columns.length-1])??null;target&&target.addPositionedComments("after",closingLeading)}idx++;break}let tokenValue=lexeme.value.toLowerCase(),isConstraint=this.TABLE_CONSTRAINT_STARTERS.has(tokenValue),entryResult=isConstraint?this.parseTableConstraint(lexemes,idx):this.parseColumnDefinition(lexemes,idx),entry=entryResult.value;pendingLeading&&pendingLeading.length>0&&(entry.addPositionedComments("before",pendingLeading),pendingLeading=null);let trailingComments=this.popLexemeComments(lexemes[Math.max(entryResult.newIndex-1,idx)],"after");if(trailingComments.length>0&&entry.addPositionedComments("after",trailingComments),isConstraint?constraints.push(entry):columns.push(entry),idx=entryResult.newIndex,idx<lexemes.length&&lexemes[idx].type&16){let commaLexeme=lexemes[idx],commaTrailing=this.popLexemeComments(commaLexeme,"after");pendingLeading=this.toOptionalComments(commaTrailing),idx++;continue}if(idx<lexemes.length&&lexemes[idx].type===8){let closingLexeme=lexemes[idx],closingLeading=this.popLexemeComments(closingLexeme,"before");if(closingLeading.length>0){let target=(constraints.length>0?constraints[constraints.length-1]:columns[columns.length-1])??null;target&&target.addPositionedComments("after",closingLeading)}idx++;break}pendingLeading=null}return{columns,tableConstraints:constraints,newIndex:idx}}static parseColumnDefinition(lexemes,index){let idx=index,columnNameResult=this.parseQualifiedName(lexemes,idx);if(idx=columnNameResult.newIndex,columnNameResult.namespaces&&columnNameResult.namespaces.length>0){let qualified=[...columnNameResult.namespaces,columnNameResult.name.name].join(".");throw new Error(`[CreateTableParser] Column name '${qualified}' must not include a schema or namespace qualifier.`)}let columnName=columnNameResult.name,dataType;if(idx<lexemes.length&&!this.isColumnConstraintStart(lexemes[idx])&&!this.isColumnTerminator(lexemes[idx])){let typeResult=this.parseColumnType(lexemes,idx);dataType=typeResult.value,idx=typeResult.newIndex}let constraints=[];for(;idx<lexemes.length&&!this.isColumnTerminator(lexemes[idx]);){let constraintResult=this.parseColumnConstraint(lexemes,idx);constraints.push(constraintResult.value),idx=constraintResult.newIndex}return{value:new TableColumnDefinition({name:columnName,dataType,constraints}),newIndex:idx}}static parseColumnType(lexemes,index){try{let result=FunctionExpressionParser.parseTypeValue(lexemes,index);return{value:result.value,newIndex:result.newIndex}}catch{let typeEnd=this.findFirstConstraintIndex(lexemes,index),rawText=joinLexemeValues(lexemes,index,typeEnd);return{value:new RawString(rawText),newIndex:typeEnd}}}static parseColumnConstraint(lexemes,index){let idx=index,constraintName;if(lexemes[idx]?.value.toLowerCase()==="constraint"){idx++;let nameResult=this.parseQualifiedName(lexemes,idx);constraintName=nameResult.name,idx=nameResult.newIndex}let token=lexemes[idx];if(!token)throw new Error(`[CreateTableParser] Expected constraint definition at index ${idx}.`);let value=token.value.toLowerCase();if(value==="not null"||value==="null")return idx++,{value:new ColumnConstraintDefinition({kind:value==="not null"?"not-null":"null",constraintName}),newIndex:idx};if(value==="default"){idx++;let exprResult=ValueParser.parseFromLexeme(lexemes,idx);return idx=exprResult.newIndex,{value:new ColumnConstraintDefinition({kind:"default",constraintName,defaultValue:exprResult.value}),newIndex:idx}}if(value==="primary key")return idx++,{value:new ColumnConstraintDefinition({kind:"primary-key",constraintName}),newIndex:idx};if(value==="unique"||value==="unique key")return idx++,{value:new ColumnConstraintDefinition({kind:"unique",constraintName}),newIndex:idx};if(value==="references"){let referenceResult=this.parseReferenceDefinition(lexemes,idx);return idx=referenceResult.newIndex,{value:new ColumnConstraintDefinition({kind:"references",constraintName,reference:referenceResult.value}),newIndex:idx}}if(value==="check"){idx++;let checkExpression=this.parseParenExpression(lexemes,idx);return idx=checkExpression.newIndex,{value:new ColumnConstraintDefinition({kind:"check",constraintName,checkExpression:checkExpression.value}),newIndex:idx}}if(value.startsWith("generated")){let clauseEnd=this.findFirstConstraintIndex(lexemes,idx+1),text=joinLexemeValues(lexemes,idx,clauseEnd);idx=clauseEnd;let kind=value.startsWith("generated always")?"generated-always-identity":"generated-by-default-identity";return{value:new ColumnConstraintDefinition({kind,constraintName,rawClause:new RawString(text)}),newIndex:idx}}let rawEnd=this.findFirstConstraintIndex(lexemes,idx+1),rawText=joinLexemeValues(lexemes,idx,rawEnd);return{value:new ColumnConstraintDefinition({kind:"raw",constraintName,rawClause:new RawString(rawText)}),newIndex:rawEnd}}static parseTableConstraint(lexemes,index){let idx=index,constraintName;if(lexemes[idx]?.value.toLowerCase()==="constraint"){idx++;let nameResult=this.parseQualifiedName(lexemes,idx);constraintName=nameResult.name,idx=nameResult.newIndex}let token=lexemes[idx];if(!token)throw new Error(`[CreateTableParser] Expected table constraint at index ${idx}.`);let value=token.value.toLowerCase();if(value==="primary key"){idx++;let{identifiers,newIndex}=this.parseIdentifierList(lexemes,idx);return idx=newIndex,{value:new TableConstraintDefinition({kind:"primary-key",constraintName,columns:identifiers}),newIndex:idx}}if(value==="unique"||value==="unique key"){idx++;let inlineKeyName;if(idx<lexemes.length&&lexemes[idx].value!=="("&&!(lexemes[idx].type&128)){let inlineNameResult=this.parseQualifiedName(lexemes,idx);inlineKeyName=inlineNameResult.name,idx=inlineNameResult.newIndex}let{identifiers,newIndex}=this.parseIdentifierList(lexemes,idx);return idx=newIndex,{value:new TableConstraintDefinition({kind:"unique",constraintName:constraintName??inlineKeyName,columns:identifiers}),newIndex:idx}}if(value==="foreign key"){idx++;let inlineKeyName;if(idx<lexemes.length&&lexemes[idx].value!=="("&&!(lexemes[idx].type&128)){let inlineNameResult=this.parseQualifiedName(lexemes,idx);inlineKeyName=inlineNameResult.name,idx=inlineNameResult.newIndex}let{identifiers,newIndex}=this.parseIdentifierList(lexemes,idx);idx=newIndex;let referenceResult=this.parseReferenceDefinition(lexemes,idx);return idx=referenceResult.newIndex,{value:new TableConstraintDefinition({kind:"foreign-key",constraintName:constraintName??inlineKeyName,columns:identifiers,reference:referenceResult.value,deferrable:referenceResult.value.deferrable,initially:referenceResult.value.initially}),newIndex:idx}}if(value==="check"){idx++;let checkExpression=this.parseParenExpression(lexemes,idx);return idx=checkExpression.newIndex,{value:new TableConstraintDefinition({kind:"check",constraintName,checkExpression:checkExpression.value}),newIndex:idx}}let rawEnd=this.findFirstConstraintIndex(lexemes,idx+1),rawText=joinLexemeValues(lexemes,idx,rawEnd);return{value:new TableConstraintDefinition({kind:"raw",constraintName,rawClause:new RawString(rawText)}),newIndex:rawEnd}}static parseIdentifierList(lexemes,index){let idx=index,identifiers=[];if(lexemes[idx]?.type!==4)throw new Error(`[CreateTableParser] Expected '(' to start identifier list at index ${idx}.`);for(idx++;idx<lexemes.length;){let nameResult=this.parseQualifiedName(lexemes,idx);if(identifiers.push(nameResult.name),idx=nameResult.newIndex,lexemes[idx]?.type===16){idx++;continue}if(lexemes[idx]?.type===8){idx++;break}}return{identifiers,newIndex:idx}}static parseReferenceDefinition(lexemes,index){let idx=index;if(lexemes[idx]?.value.toLowerCase()!=="references")throw new Error(`[CreateTableParser] Expected REFERENCES clause at index ${idx}.`);idx++;let tableNameResult=this.parseQualifiedName(lexemes,idx);idx=tableNameResult.newIndex;let targetTable=new QualifiedName(tableNameResult.namespaces,tableNameResult.name),columns=null;if(lexemes[idx]?.type===4){let listResult=this.parseIdentifierList(lexemes,idx);columns=listResult.identifiers,idx=listResult.newIndex}let matchType=null,onDelete=null,onUpdate=null,deferrable=null,initially=null;for(;idx<lexemes.length;){let current=lexemes[idx].value.toLowerCase();if(this.MATCH_KEYWORDS.has(current)){matchType=this.MATCH_KEYWORDS.get(current),idx++;continue}if(current==="match"){idx++,matchType=lexemes[idx]?.value.toLowerCase()??"",idx++;continue}if(current==="on delete"){idx++;let action=lexemes[idx]?.value.toLowerCase()??"";onDelete=this.REFERENTIAL_ACTIONS.get(action)??null,idx++;continue}if(current==="on update"){idx++;let action=lexemes[idx]?.value.toLowerCase()??"";onUpdate=this.REFERENTIAL_ACTIONS.get(action)??null,idx++;continue}if(this.DEFERRABILITY_KEYWORDS.has(current)){deferrable=this.DEFERRABILITY_KEYWORDS.get(current),idx++;continue}if(this.INITIALLY_KEYWORDS.has(current)){initially=this.INITIALLY_KEYWORDS.get(current),idx++;continue}break}return{value:new ReferenceDefinition({targetTable,columns,matchType,onDelete,onUpdate,deferrable,initially}),newIndex:idx}}static parseParenExpression(lexemes,index){let idx=index;if(lexemes[idx]?.type!==4)throw new Error(`[CreateTableParser] Expected '(' introducing expression at index ${idx}.`);idx++;let expressionResult=ValueParser.parseFromLexeme(lexemes,idx);if(idx=expressionResult.newIndex,lexemes[idx]?.type!==8)throw new Error(`[CreateTableParser] Expected ')' terminating expression at index ${idx}.`);return idx++,{value:expressionResult.value,newIndex:idx}}static isColumnConstraintStart(lexeme){if(!lexeme)return!1;let lower=lexeme.value.toLowerCase();return this.COLUMN_CONSTRAINT_STARTERS.has(lower)}static isColumnTerminator(lexeme){return!!(!lexeme||lexeme.type&24)}static isSelectKeyword(value,nextLexeme){return!value||value==="with"&&nextLexeme?.type===4?!1:value==="as"||value==="select"||value==="with"||value==="values"}static findClauseBoundary(lexemes,index){let idx=index;for(;idx<lexemes.length;){let lower=lexemes[idx].value.toLowerCase();if(this.isSelectKeyword(lower,lexemes[idx+1]))break;idx++}return idx}static findFirstConstraintIndex(lexemes,index){let idx=index;for(;idx<lexemes.length&&!this.isColumnConstraintStart(lexemes[idx])&&!this.isColumnTerminator(lexemes[idx]);)idx++;return idx}static parseWithDataOption(lexemes,index){let current=lexemes[index];if(!current)return null;let value=current.value.toLowerCase();if(value==="with data")return{value:"with-data",newIndex:index+1};if(value==="with no data")return{value:"with-no-data",newIndex:index+1};if(value!=="with")return null;let nextValue=lexemes[index+1]?.value.toLowerCase();if(nextValue==="data")return{value:"with-data",newIndex:index+2};if(nextValue==="data")return{value:"with-data",newIndex:index+2};if(nextValue==="no data")return{value:"with-no-data",newIndex:index+2};if(nextValue==="no"){let following=lexemes[index+2];if(following&&following.value.toLowerCase()==="data")return{value:"with-no-data",newIndex:index+3}}return null}static popLexemeComments(lexeme,position){if(!lexeme)return[];let collected=[];if(lexeme.positionedComments&&lexeme.positionedComments.length>0){let matchIndex=lexeme.positionedComments.findIndex(pc=>pc.position===position);if(matchIndex>=0){collected=[...lexeme.positionedComments[matchIndex].comments];let remaining=lexeme.positionedComments.filter((_,idx)=>idx!==matchIndex);lexeme.positionedComments=remaining.length>0?remaining:void 0}}if(collected.length>0)return collected;if(lexeme.comments&&lexeme.comments.length>0){let legacy=[...lexeme.comments];return lexeme.comments=null,legacy}return[]}static toOptionalComments(comments){return comments.length>0?comments:null}};var MergeQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The MERGE statement is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value==="with"){let withResult=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=withResult.value,idx=withResult.newIndex}let mergeKeywordLexeme=lexemes[idx],mergeKeywordComments=extractLexemeComments(mergeKeywordLexeme);if(mergeKeywordLexeme?.value!=="merge into"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'MERGE INTO' but found '${actual}'.`)}idx++;let targetResult=SourceExpressionParser.parseFromLexeme(lexemes,idx),target=targetResult.value;if(idx=targetResult.newIndex,this.addUniquePositionedComments(target.datasource,"before",mergeKeywordComments.after),lexemes[idx]?.value!=="using"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'USING' but found '${actual}'.`)}idx++;let sourceResult=SourceExpressionParser.parseFromLexeme(lexemes,idx),source=sourceResult.value;if(idx=sourceResult.newIndex,lexemes[idx]?.value!=="on"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'ON' but found '${actual}'.`)}idx++;let onConditionResult=ValueParser.parseFromLexeme(lexemes,idx),onCondition=onConditionResult.value;idx=onConditionResult.newIndex;let whenResult=this.parseWhenClauses(lexemes,idx);if(whenResult.clauses.length===0)throw new Error("[MergeQueryParser] MERGE statement must contain at least one WHEN clause.");let mergeQuery=new MergeQuery({withClause,target,source,onCondition,whenClauses:whenResult.clauses});return this.addUniquePositionedComments(mergeQuery,"before",mergeKeywordComments.before),{value:mergeQuery,newIndex:whenResult.newIndex}}static parseWhenClauses(lexemes,index){let clauses=[],idx=index;for(;this.getLowerValue(lexemes[idx])==="when";){idx++;let{matchType,newIndex:matchIndex}=this.parseMatchType(lexemes,idx);idx=matchIndex;let additionalCondition=null;if(this.getLowerValue(lexemes[idx])==="and"){idx++;let conditionResult=ValueParser.parseFromLexeme(lexemes,idx);additionalCondition=conditionResult.value,idx=conditionResult.newIndex}let thenLexeme=lexemes[idx];if(this.getLowerValue(thenLexeme)!=="then"){let actual=thenLexeme?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'THEN' but found '${actual}'.`)}let thenComments=extractLexemeComments(thenLexeme),commentsBeforeThen=[],precedingLexeme=lexemes[idx-1];if(precedingLexeme){let precedingComments=extractLexemeComments(precedingLexeme);this.mergeUnique(commentsBeforeThen,precedingComments.after)}this.mergeUnique(commentsBeforeThen,thenComments.before),idx++;let actionResult=this.parseAction(lexemes,idx,thenComments.after??[]);idx=actionResult.newIndex;let whenClause=new MergeWhenClause(matchType,actionResult.action,additionalCondition);whenClause.addThenLeadingComments(commentsBeforeThen),clauses.push(whenClause)}return{clauses,newIndex:idx}}static parseMatchType(lexemes,index){let idx=index,value=this.getLowerValue(lexemes[idx]);if(value==="matched")return idx++,{matchType:"matched",newIndex:idx};if(value==="not matched")return idx++,{matchType:"not_matched",newIndex:idx};if(value==="not matched by source")return idx++,{matchType:"not_matched_by_source",newIndex:idx};if(value==="not matched by target")return idx++,{matchType:"not_matched_by_target",newIndex:idx};let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'MATCHED' or 'NOT MATCHED' but found '${actual}'.`)}static parseAction(lexemes,index,leadingComments=[]){let idx=index,token=lexemes[idx];if(!token)throw new Error("[MergeQueryParser] Unexpected end of input while parsing WHEN clause action.");let tokenValue=token.value.toLowerCase(),tokenComments=extractLexemeComments(token),actionLeadingComments=[];if(this.mergeUnique(actionLeadingComments,leadingComments),this.mergeUnique(actionLeadingComments,tokenComments.before),tokenValue==="update"||tokenValue==="update set"){let expectSetKeyword=tokenValue==="update";idx++;let pendingSetClauseComments=tokenComments.after,setResult=this.parseSetClause(lexemes,idx,expectSetKeyword,pendingSetClauseComments);idx=setResult.newIndex;let whereClause=null;if(lexemes[idx]?.value==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}let action=new MergeUpdateAction(setResult.setClause,whereClause);return this.addUniquePositionedComments(action,"before",actionLeadingComments),{action,newIndex:idx}}if(tokenValue==="delete"){idx++;let whereClause=null;if(this.getLowerValue(lexemes[idx])==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}let action=new MergeDeleteAction(whereClause);return this.addUniquePositionedComments(action,"before",actionLeadingComments),this.addUniquePositionedComments(action,"after",tokenComments.after),{action,newIndex:idx}}if(tokenValue==="do nothing"){idx++;let action=new MergeDoNothingAction;return this.addUniquePositionedComments(action,"before",actionLeadingComments),this.addUniquePositionedComments(action,"after",tokenComments.after),{action,newIndex:idx}}if(tokenValue==="insert default values"){idx++;let columnResult=this.parseInsertColumnProjection(lexemes,idx,tokenComments.after);idx=columnResult.newIndex;let action=new MergeInsertAction({columns:columnResult.columns,defaultValues:!0});return this.addUniquePositionedComments(action,"before",actionLeadingComments),this.addUniquePositionedComments(action,"after",columnResult.trailingComments),{action,newIndex:idx}}if(tokenValue==="insert"){idx++;let insertResult=this.parseInsertAction(lexemes,idx,{pendingCommentsAfterInsert:tokenComments.after});return this.addUniquePositionedComments(insertResult.action,"before",actionLeadingComments),insertResult}let actual=token.value;throw new Error(`[MergeQueryParser] Unsupported action '${actual}'. Only UPDATE, DELETE, INSERT, and DO NOTHING are supported within MERGE WHEN clauses.`)}static parseSetClause(lexemes,index,expectSetKeyword,pendingCommentsAfterUpdate=[]){let idx=index,setKeywordComments=extractLexemeComments(lexemes[idx]);if(expectSetKeyword){if(this.getLowerValue(lexemes[idx])!=="set"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'SET' but found '${actual}'.`)}idx++}else this.getLowerValue(lexemes[idx])==="set"?(setKeywordComments=extractLexemeComments(lexemes[idx]),idx++):setKeywordComments={before:[],after:[]};let items=[],pendingBeforeForNext=[];for(this.mergeUnique(pendingBeforeForNext,pendingCommentsAfterUpdate),this.mergeUnique(pendingBeforeForNext,setKeywordComments.after);idx<lexemes.length;){let currentLexeme=lexemes[idx];if(!currentLexeme||this.isSetClauseTerminator(currentLexeme)||!(currentLexeme.type&10816))break;let columnComments=extractLexemeComments(currentLexeme),{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,lexemes[idx]?.type!==2||lexemes[idx].value!=="="){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected '=' in SET clause but found '${actual}'.`)}let equalsLexeme=lexemes[idx],equalsComments=extractLexemeComments(equalsLexeme);idx++;let valueResult=ValueParser.parseFromLexeme(lexemes,idx);idx=valueResult.newIndex;let setItem=new SetClauseItem({namespaces,column:name},valueResult.value),beforeComments=[];if(this.mergeUnique(beforeComments,pendingBeforeForNext),this.mergeUnique(beforeComments,columnComments.before),this.addUniquePositionedComments(name,"before",beforeComments),pendingBeforeForNext=[],this.addUniquePositionedComments(name,"after",columnComments.after),this.addUniquePositionedComments(setItem,"after",equalsComments.before),this.addUniquePositionedComments(valueResult.value,"before",equalsComments.after),items.push(setItem),lexemes[idx]?.type===16){let commaLexeme=lexemes[idx],commaComments=extractLexemeComments(commaLexeme);idx++,this.addUniquePositionedComments(setItem,"after",commaComments.before),pendingBeforeForNext=[],this.mergeUnique(pendingBeforeForNext,commaComments.after);continue}break}if(pendingBeforeForNext.length>0&&items.length>0&&this.addUniquePositionedComments(items[items.length-1],"after",pendingBeforeForNext),items.length===0)throw new Error("[MergeQueryParser] SET clause must contain at least one column assignment.");let setClause=new SetClause(items);return this.addUniquePositionedComments(setClause,"before",setKeywordComments.before),{setClause,newIndex:idx}}static parseInsertAction(lexemes,index,options){let idx=index,pendingAfterInsert=options?.pendingCommentsAfterInsert??[],columnResult=this.parseInsertColumnProjection(lexemes,idx,pendingAfterInsert),columns=columnResult.columns;idx=columnResult.newIndex;let pendingBeforeValues=columnResult.trailingComments;if(this.getLowerValue(lexemes[idx])==="values"){let valuesLexeme=lexemes[idx],valuesComments=extractLexemeComments(valuesLexeme);idx++;let beforeValuesComments=[];this.mergeUnique(beforeValuesComments,pendingBeforeValues),this.mergeUnique(beforeValuesComments,valuesComments.before);let valuesResult=ValueParser.parseArgument(4,8,lexemes,idx);if(idx=valuesResult.newIndex,!(valuesResult.value instanceof ValueList))throw new Error("[MergeQueryParser] Unexpected VALUES payload. Expected a parenthesized value list.");let valueList=valuesResult.value,closingParenComments=extractLexemeComments(lexemes[idx-1]);this.addUniquePositionedComments(valueList,"after",closingParenComments.after),this.addUniquePositionedComments(valueList,"after",valuesComments.after);let action=new MergeInsertAction({columns,values:valueList});return action.addValuesLeadingComments(beforeValuesComments),{action,newIndex:idx}}let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Unsupported INSERT payload '${actual}'. Use VALUES (...) or DEFAULT VALUES.`)}static parseInsertColumnProjection(lexemes,index,pendingBeforeFirstColumn){let idx=index;if(lexemes[idx]?.type!==4)return{columns:null,newIndex:idx,trailingComments:[...pendingBeforeFirstColumn]};let openParenLexeme=lexemes[idx],parenComments=extractLexemeComments(openParenLexeme);idx++;let columns=[],pendingBeforeForNext=[];for(this.mergeUnique(pendingBeforeForNext,pendingBeforeFirstColumn),this.mergeUnique(pendingBeforeForNext,parenComments.before),this.mergeUnique(pendingBeforeForNext,parenComments.after);idx<lexemes.length&&lexemes[idx].type&64;){let columnLexeme=lexemes[idx],columnComments=extractLexemeComments(columnLexeme),column=new IdentifierString(columnLexeme.value),beforeComments=[];if(this.mergeUnique(beforeComments,pendingBeforeForNext),this.mergeUnique(beforeComments,columnComments.before),this.addUniquePositionedComments(column,"before",beforeComments),pendingBeforeForNext=[],this.addUniquePositionedComments(column,"after",columnComments.after),columns.push(column),idx++,lexemes[idx]?.type===16){let commaLexeme=lexemes[idx],commaComments=extractLexemeComments(commaLexeme);idx++,this.addUniquePositionedComments(column,"after",commaComments.before),pendingBeforeForNext=[],this.mergeUnique(pendingBeforeForNext,commaComments.after);continue}break}if(pendingBeforeForNext.length>0&&columns.length>0&&(this.addUniquePositionedComments(columns[columns.length-1],"after",pendingBeforeForNext),pendingBeforeForNext=[]),lexemes[idx]?.type!==8){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected ')' after column list but found '${actual}'.`)}let closeParenLexeme=lexemes[idx],closeParenComments=extractLexemeComments(closeParenLexeme);idx++,closeParenComments.before.length>0&&columns.length>0&&this.addUniquePositionedComments(columns[columns.length-1],"after",closeParenComments.before);let trailingComments=[];return this.mergeUnique(trailingComments,closeParenComments.after),this.mergeUnique(trailingComments,pendingBeforeForNext),{columns:columns.length>0?columns:[],newIndex:idx,trailingComments}}static isSetClauseTerminator(lexeme){if(!lexeme)return!1;let value=this.getLowerValue(lexeme);return value?value==="where"||value==="from"||value==="returning"||value==="when":!1}static mergeUnique(target,source){if(!(!source||source.length===0))for(let comment of source)target.includes(comment)||target.push(comment)}static addUniquePositionedComments(component,position,comments){if(!component||!comments||comments.length===0)return;let existing=component.getPositionedComments(position),newOnes=comments.filter(comment=>!existing.includes(comment));newOnes.length>0&&component.addPositionedComments(position,newOnes)}static getLowerValue(lexeme){return lexeme&&typeof lexeme.value=="string"?lexeme.value.toLowerCase():null}};var DropTableParser=class{static parse(sql){let lexemes=new SqlTokenizer(sql).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`[DropTableParser] Unexpected token "${lexemes[result.newIndex].value}" after DROP TABLE statement.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx]?.value.toLowerCase()!=="drop table")throw new Error(`[DropTableParser] Expected DROP TABLE at index ${idx}.`);idx++;let ifExists=!1;lexemes[idx]?.value.toLowerCase()==="if exists"&&(ifExists=!0,idx++);let tables=[];for(;idx<lexemes.length;){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(tables.push(new QualifiedName(namespaces,name)),idx=newIndex,lexemes[idx]?.type===16){idx++;continue}break}if(tables.length===0)throw new Error("[DropTableParser] DROP TABLE must specify at least one table.");let behavior=null,nextValue=lexemes[idx]?.value.toLowerCase();return(nextValue==="cascade"||nextValue==="restrict")&&(behavior=nextValue,idx++),{value:new DropTableStatement({tables,ifExists,behavior}),newIndex:idx}}};var DropIndexParser=class{static parse(sql){let lexemes=new SqlTokenizer(sql).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`[DropIndexParser] Unexpected token "${lexemes[result.newIndex].value}" after DROP INDEX statement.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx]?.value.toLowerCase()!=="drop index")throw new Error(`[DropIndexParser] Expected DROP INDEX at index ${idx}.`);idx++;let concurrently=!1;lexemes[idx]?.value.toLowerCase()==="concurrently"&&(concurrently=!0,idx++);let ifExists=!1;if(lexemes[idx]?.value.toLowerCase()==="if exists"){ifExists=!0,idx++;let next=lexemes[idx];if(!next||next.type!==64)throw new Error("[DropIndexParser] Expected index name immediately after IF EXISTS.")}let indexNames=[];for(;idx<lexemes.length;){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(indexNames.push(new QualifiedName(namespaces,name)),idx=newIndex,lexemes[idx]?.type===16){idx++;continue}break}if(indexNames.length===0)throw new Error("[DropIndexParser] DROP INDEX must specify at least one index name.");let behavior=null,nextValue=lexemes[idx]?.value.toLowerCase();return(nextValue==="cascade"||nextValue==="restrict")&&(behavior=nextValue,idx++),{value:new DropIndexStatement({indexNames,concurrently,ifExists,behavior}),newIndex:idx}}};var CreateIndexParser=class{static parse(sql){let lexemes=new SqlTokenizer(sql).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`[CreateIndexParser] Unexpected token "${lexemes[result.newIndex].value}" after CREATE INDEX.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,firstToken=lexemes[idx]?.value.toLowerCase();if(firstToken!=="create index"&&firstToken!=="create unique index")throw new Error(`[CreateIndexParser] Expected CREATE INDEX at index ${idx}.`);let unique=firstToken==="create unique index";idx++;let concurrently=!1;lexemes[idx]?.value.toLowerCase()==="concurrently"&&(concurrently=!0,idx++);let ifNotExists=!1;lexemes[idx]?.value.toLowerCase()==="if not exists"&&(ifNotExists=!0,idx++);let indexNameResult=FullNameParser.parseFromLexeme(lexemes,idx),indexName=new QualifiedName(indexNameResult.namespaces,indexNameResult.name);if(idx=indexNameResult.newIndex,lexemes[idx]?.value.toLowerCase()!=="on")throw new Error(`[CreateIndexParser] Expected ON keyword before table name at index ${idx}.`);idx++;let tableResult=FullNameParser.parseFromLexeme(lexemes,idx),tableName=new QualifiedName(tableResult.namespaces,tableResult.name);idx=tableResult.newIndex;let usingMethod=null;if(lexemes[idx]?.value.toLowerCase()==="using"){idx++;let methodResult=FullNameParser.parseFromLexeme(lexemes,idx);usingMethod=methodResult.name,idx=methodResult.newIndex}let columnsResult=this.parseIndexColumnList(lexemes,idx),columns=columnsResult.columns;idx=columnsResult.newIndex;let include=null;if(lexemes[idx]?.value.toLowerCase()==="include"){idx++;let includeResult=this.parseIdentifierList(lexemes,idx);include=includeResult.identifiers,idx=includeResult.newIndex}let withOptions=null;if(lexemes[idx]?.value.toLowerCase()==="with"){let withResult=this.parseWithOptions(lexemes,idx);withOptions=withResult.options,idx=withResult.newIndex}let tablespace=null;if(lexemes[idx]?.value.toLowerCase()==="tablespace"){idx++;let tablespaceResult=FullNameParser.parseFromLexeme(lexemes,idx);tablespace=tablespaceResult.name,idx=tablespaceResult.newIndex}let whereClause;if(lexemes[idx]?.value.toLowerCase()==="where"){idx++;let whereResult=ValueParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}return{value:new CreateIndexStatement({unique,concurrently,ifNotExists,indexName,tableName,usingMethod,columns,include,withOptions,tablespace,where:whereClause}),newIndex:idx}}static parseIndexColumnList(lexemes,index){let idx=index;if(lexemes[idx]?.type!==4)throw new Error(`[CreateIndexParser] Expected '(' starting column list at index ${idx}.`);idx++;let columns=[];for(;idx<lexemes.length;){let expressionResult=ValueParser.parseFromLexeme(lexemes,idx);idx=expressionResult.newIndex;let sortOrder=null,nullsOrder=null,collation=null,operatorClass=null;for(;idx<lexemes.length;){let tokenValue=lexemes[idx].value.toLowerCase();if(tokenValue==="asc"||tokenValue==="desc"){sortOrder=tokenValue,idx++;continue}if(tokenValue==="nulls first"||tokenValue==="nulls last"){nullsOrder=tokenValue.endsWith("first")?"first":"last",idx++;continue}if(tokenValue==="collate"){idx++;let collateResult=FullNameParser.parseFromLexeme(lexemes,idx);collation=new QualifiedName(collateResult.namespaces,collateResult.name),idx=collateResult.newIndex;continue}if(this.isClauseTerminator(tokenValue)||lexemes[idx].type&24)break;if(lexemes[idx].type&10304){let opClassResult=FullNameParser.parseFromLexeme(lexemes,idx);operatorClass=new QualifiedName(opClassResult.namespaces,opClassResult.name),idx=opClassResult.newIndex;continue}break}if(columns.push(new IndexColumnDefinition({expression:expressionResult.value,sortOrder,nullsOrder,collation,operatorClass})),lexemes[idx]?.type===16){idx++;continue}if(lexemes[idx]?.type===8){idx++;break}}if(lexemes[idx-1]?.type!==8)throw new Error(`[CreateIndexParser] Expected ')' to close column list starting at index ${index}.`);return{columns,newIndex:idx}}static parseIdentifierList(lexemes,index){let idx=index;if(lexemes[idx]?.type!==4)throw new Error(`[CreateIndexParser] Expected '(' starting identifier list at index ${idx}.`);idx++;let identifiers=[];for(;idx<lexemes.length;){let result=FullNameParser.parseFromLexeme(lexemes,idx);if(identifiers.push(result.name),idx=result.newIndex,lexemes[idx]?.type===16){idx++;continue}if(lexemes[idx]?.type===8){idx++;break}}if(lexemes[idx-1]?.type!==8)throw new Error(`[CreateIndexParser] Expected ')' to close identifier list starting at index ${index}.`);return{identifiers,newIndex:idx}}static parseWithOptions(lexemes,index){let idx=index,start=idx;if(lexemes[idx]?.value.toLowerCase()!=="with")throw new Error(`[CreateIndexParser] Expected WITH keyword at index ${idx}.`);if(idx++,lexemes[idx]?.type!==4)throw new Error(`[CreateIndexParser] Expected '(' after WITH at index ${idx}.`);let depth=0;for(;idx<lexemes.length;){if(lexemes[idx].type===4)depth++;else if(lexemes[idx].type===8&&(depth--,depth===0)){idx++;break}idx++}if(depth!==0)throw new Error(`[CreateIndexParser] Unterminated WITH options starting at index ${start}; unbalanced parentheses.`);let text=joinLexemeValues(lexemes,start,idx);return{options:new RawString(text),newIndex:idx}}static isClauseTerminator(value){return value==="include"||value==="with"||value==="where"||value==="tablespace"}};var AlterTableParser=class{static{this.CONSTRAINT_TYPE_TOKENS=new Set(["primary key","unique","unique key","foreign key","check"])}static{this.MATCH_KEYWORDS=new Map([["match full","full"],["match partial","partial"],["match simple","simple"]])}static{this.REFERENTIAL_ACTIONS=new Map([["cascade","cascade"],["restrict","restrict"],["no action","no action"],["set null","set null"],["set default","set default"]])}static{this.DEFERRABILITY_KEYWORDS=new Map([["deferrable","deferrable"],["not deferrable","not deferrable"]])}static{this.INITIALLY_KEYWORDS=new Map([["initially immediate","immediate"],["initially deferred","deferred"]])}static parse(sql){let lexemes=new SqlTokenizer(sql).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`[AlterTableParser] Unexpected token "${lexemes[result.newIndex].value}" after ALTER TABLE statement.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx]?.value.toLowerCase()!=="alter table")throw new Error(`[AlterTableParser] Expected ALTER TABLE at index ${idx}.`);idx++;let ifExists=!1;lexemes[idx]?.value.toLowerCase()==="if exists"&&(ifExists=!0,idx++);let only=!1;lexemes[idx]?.value.toLowerCase()==="only"&&(only=!0,idx++);let tableResult=FullNameParser.parseFromLexeme(lexemes,idx),tableName=new QualifiedName(tableResult.namespaces,tableResult.name);idx=tableResult.newIndex;let actions=[];for(;idx<lexemes.length;){let value=lexemes[idx].value.toLowerCase();if(value==="add constraint"){let result=this.parseAddConstraintAction(lexemes,idx);actions.push(result.value),idx=result.newIndex}else if(value==="drop constraint"){let result=this.parseDropConstraintAction(lexemes,idx);actions.push(result.value),idx=result.newIndex}else if(value==="drop column"||value==="drop"){let result=this.parseDropColumnAction(lexemes,idx);actions.push(result.value),idx=result.newIndex}else throw new Error(`[AlterTableParser] Unsupported ALTER TABLE action '${lexemes[idx].value}' at index ${idx}.`);if(lexemes[idx]?.type===16){idx++;continue}break}if(actions.length===0)throw new Error("[AlterTableParser] ALTER TABLE requires at least one action.");return{value:new AlterTableStatement({table:tableName,only,ifExists,actions}),newIndex:idx}}static parseAddConstraintAction(lexemes,index){let idx=index,initialToken=lexemes[idx]?.value.toLowerCase();if(initialToken!=="add"&&initialToken!=="add constraint")throw new Error(`[AlterTableParser] Expected ADD or ADD CONSTRAINT at index ${idx}.`);idx++,initialToken==="add"&&lexemes[idx]?.value.toLowerCase()==="constraint"&&idx++;let ifNotExists=!1;lexemes[idx]?.value.toLowerCase()==="if not exists"&&(ifNotExists=!0,idx++);let constraintName,nextValue=lexemes[idx]?.value.toLowerCase();if(nextValue&&!this.CONSTRAINT_TYPE_TOKENS.has(nextValue)){let nameResult=FullNameParser.parseFromLexeme(lexemes,idx);constraintName=nameResult.name,idx=nameResult.newIndex}let constraintResult=this.parseTableConstraintDefinition(lexemes,idx,constraintName);idx=constraintResult.newIndex;let notValid=!1;return lexemes[idx]?.value.toLowerCase()==="not valid"&&(notValid=!0,idx++),{value:new AlterTableAddConstraint({constraint:constraintResult.constraint,ifNotExists,notValid}),newIndex:idx}}static parseDropConstraintAction(lexemes,index){let idx=index,initialValue=lexemes[idx]?.value.toLowerCase();if(initialValue==="drop constraint")idx++;else if(initialValue==="drop"){if(idx++,lexemes[idx]?.value.toLowerCase()!=="constraint")throw new Error(`[AlterTableParser] Expected CONSTRAINT keyword after DROP at index ${idx}.`);idx++}else throw new Error(`[AlterTableParser] Expected DROP CONSTRAINT at index ${idx}.`);let ifExists=!1;lexemes[idx]?.value.toLowerCase()==="if exists"&&(ifExists=!0,idx++);let nameResult=FullNameParser.parseFromLexeme(lexemes,idx);idx=nameResult.newIndex;let behavior=null,nextValue=lexemes[idx]?.value.toLowerCase();return(nextValue==="cascade"||nextValue==="restrict")&&(behavior=nextValue,idx++),{value:new AlterTableDropConstraint({constraintName:nameResult.name,ifExists,behavior}),newIndex:idx}}static parseDropColumnAction(lexemes,index){let idx=index,initialValue=lexemes[idx]?.value.toLowerCase();if(initialValue==="drop column")idx++;else if(initialValue==="drop"){if(idx++,lexemes[idx]?.value.toLowerCase()!=="column")throw new Error(`[AlterTableParser] Expected COLUMN keyword after DROP at index ${idx}.`);idx++}else throw new Error(`[AlterTableParser] Expected DROP COLUMN at index ${idx}.`);let ifExists=!1;lexemes[idx]?.value.toLowerCase()==="if exists"&&(ifExists=!0,idx++);let nameResult=FullNameParser.parseFromLexeme(lexemes,idx),columnName=nameResult.name;idx=nameResult.newIndex;let behavior=null,nextValue=lexemes[idx]?.value.toLowerCase();return(nextValue==="cascade"||nextValue==="restrict")&&(behavior=nextValue,idx++),{value:new AlterTableDropColumn({columnName,ifExists,behavior}),newIndex:idx}}static parseTableConstraintDefinition(lexemes,index,constraintName){let idx=index,token=lexemes[idx];if(!token)throw new Error(`[AlterTableParser] Missing constraint definition at index ${idx}.`);let value=token.value.toLowerCase();if(value==="primary key"){idx++;let listResult=this.parseIdentifierList(lexemes,idx);return idx=listResult.newIndex,{constraint:new TableConstraintDefinition({kind:"primary-key",constraintName,columns:listResult.identifiers}),newIndex:idx}}if(value==="unique"||value==="unique key"){idx++;let listResult=this.parseIdentifierList(lexemes,idx);return idx=listResult.newIndex,{constraint:new TableConstraintDefinition({kind:"unique",constraintName,columns:listResult.identifiers}),newIndex:idx}}if(value==="foreign key"){idx++;let listResult=this.parseIdentifierList(lexemes,idx);idx=listResult.newIndex;let referenceResult=this.parseReferenceDefinition(lexemes,idx);return idx=referenceResult.newIndex,{constraint:new TableConstraintDefinition({kind:"foreign-key",constraintName,columns:listResult.identifiers,reference:referenceResult.reference,deferrable:referenceResult.reference.deferrable,initially:referenceResult.reference.initially}),newIndex:idx}}if(value==="check"){idx++;let checkExpression=this.parseParenExpression(lexemes,idx);return idx=checkExpression.newIndex,{constraint:new TableConstraintDefinition({kind:"check",constraintName,checkExpression:checkExpression.value}),newIndex:idx}}let rawEnd=this.findConstraintClauseEnd(lexemes,idx+1),rawText=joinLexemeValues(lexemes,idx,rawEnd);return{constraint:new TableConstraintDefinition({kind:"raw",constraintName,rawClause:new RawString(rawText)}),newIndex:rawEnd}}static parseIdentifierList(lexemes,index){let idx=index,identifiers=[];if(lexemes[idx]?.type!==4)throw new Error(`[AlterTableParser] Expected '(' to start identifier list at index ${idx}.`);for(idx++;idx<lexemes.length;){let nameResult=FullNameParser.parseFromLexeme(lexemes,idx);if(identifiers.push(nameResult.name),idx=nameResult.newIndex,lexemes[idx]?.type===16){idx++;continue}if(lexemes[idx]?.type===8){idx++;break}}return{identifiers,newIndex:idx}}static parseReferenceDefinition(lexemes,index){let idx=index;if(lexemes[idx]?.value.toLowerCase()!=="references")throw new Error(`[AlterTableParser] Expected REFERENCES clause at index ${idx}.`);idx++;let tableResult=FullNameParser.parseFromLexeme(lexemes,idx),targetTable=new QualifiedName(tableResult.namespaces,tableResult.name);idx=tableResult.newIndex;let columns=null;if(lexemes[idx]?.type===4){let listResult=this.parseIdentifierList(lexemes,idx);columns=listResult.identifiers,idx=listResult.newIndex}let matchType=null,onDelete=null,onUpdate=null,deferrable=null,initially=null;for(;idx<lexemes.length;){let current=lexemes[idx].value.toLowerCase();if(this.MATCH_KEYWORDS.has(current)){matchType=this.MATCH_KEYWORDS.get(current),idx++;continue}if(current==="match"){idx++,matchType=lexemes[idx]?.value.toLowerCase()??"",idx++;continue}if(current==="on delete"){idx++;let action=lexemes[idx]?.value.toLowerCase()??"";onDelete=this.REFERENTIAL_ACTIONS.get(action)??null,idx++;continue}if(current==="on update"){idx++;let action=lexemes[idx]?.value.toLowerCase()??"";onUpdate=this.REFERENTIAL_ACTIONS.get(action)??null,idx++;continue}if(this.DEFERRABILITY_KEYWORDS.has(current)){deferrable=this.DEFERRABILITY_KEYWORDS.get(current),idx++;continue}if(this.INITIALLY_KEYWORDS.has(current)){initially=this.INITIALLY_KEYWORDS.get(current),idx++;continue}break}return{reference:new ReferenceDefinition({targetTable,columns,matchType,onDelete,onUpdate,deferrable,initially}),newIndex:idx}}static parseParenExpression(lexemes,index){let idx=index;if(lexemes[idx]?.type!==4)throw new Error(`[AlterTableParser] Expected '(' starting CHECK expression at index ${idx}.`);idx++;let result=ValueParser.parseFromLexeme(lexemes,idx);if(idx=result.newIndex,lexemes[idx]?.type!==8)throw new Error(`[AlterTableParser] Expected ')' closing CHECK expression at index ${idx}.`);return idx++,{value:result.value,newIndex:idx}}static findConstraintClauseEnd(lexemes,index){let idx=index;for(;idx<lexemes.length;){let token=lexemes[idx];if(token.type&24||token.value.toLowerCase()==="not valid")break;idx++}return idx}};var DropConstraintParser=class{static parse(sql){let lexemes=new SqlTokenizer(sql).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`[DropConstraintParser] Unexpected token "${lexemes[result.newIndex].value}" after DROP CONSTRAINT statement.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx]?.value.toLowerCase()!=="drop constraint")throw new Error(`[DropConstraintParser] Expected DROP CONSTRAINT at index ${idx}.`);idx++;let ifExists=!1;lexemes[idx]?.value.toLowerCase()==="if exists"&&(ifExists=!0,idx++);let{name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);idx=newIndex;let behavior=null,nextValue=lexemes[idx]?.value.toLowerCase();return(nextValue==="cascade"||nextValue==="restrict")&&(behavior=nextValue,idx++),{value:new DropConstraintStatement({constraintName:name,ifExists,behavior}),newIndex:idx}}};var AnalyzeStatementParser=class{static parse(sql){let lexemes=new SqlTokenizer(sql).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`[AnalyzeStatementParser] Unexpected token "${lexemes[result.newIndex].value}" after ANALYZE statement.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx]?.value.toLowerCase()!=="analyze")throw new Error(`[AnalyzeStatementParser] Expected ANALYZE at index ${idx}.`);idx++;let verbose=!1;lexemes[idx]?.value.toLowerCase()==="verbose"&&(verbose=!0,idx++);let target=null;if(this.canStartQualifiedName(lexemes[idx])){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);target=new QualifiedName(namespaces,name),idx=newIndex}let columns=null;if(lexemes[idx]?.type&4){if(!target)throw new Error("[AnalyzeStatementParser] Column list requires a target relation before '('.");for(idx++,columns=[];idx<lexemes.length;){if(lexemes[idx].type&8){if(columns.length===0)throw new Error("[AnalyzeStatementParser] Column list must include at least one column identifier.");idx++;break}let{name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(columns.push(name),idx=newIndex,lexemes[idx]?.type&16){idx++;continue}if(lexemes[idx]?.type&8){idx++;break}throw new Error(`[AnalyzeStatementParser] Expected ',' or ')' after column identifier at index ${idx}.`)}if(columns===null||columns.length===0)throw new Error("[AnalyzeStatementParser] Column list cannot be empty.")}if(!target&&lexemes[idx]&&!(lexemes[idx].type&8))throw new Error(`[AnalyzeStatementParser] Unexpected token "${lexemes[idx].value}" after ANALYZE clause.`);return{value:new AnalyzeStatement({verbose,target,columns}),newIndex:idx}}static canStartQualifiedName(lexeme){return lexeme?lexeme.type&10432?!0:(lexeme.type&512)!==0:!1}};var ExplainStatementParser=class{static parse(sql,parseNested){let lexemes=new SqlTokenizer(sql).readLexemes(),result=this.parseFromLexeme(lexemes,0,parseNested);if(result.newIndex<lexemes.length)throw new Error(`[ExplainStatementParser] Unexpected token "${lexemes[result.newIndex].value}" after EXPLAIN statement.`);return result.value}static parseFromLexeme(lexemes,index,parseNested){let idx=index,first=lexemes[idx];if(!first||first.value.toLowerCase()!=="explain")throw new Error(`[ExplainStatementParser] Expected EXPLAIN at index ${idx}.`);idx++;let options=[];for(;this.isLegacyFlag(lexemes[idx]);){let flagLexeme=lexemes[idx],optionName=new IdentifierString(flagLexeme.value.toLowerCase());flagLexeme.comments&&flagLexeme.comments.length>0&&(optionName.comments=[...flagLexeme.comments]);let option=new ExplainOption({name:optionName,value:new RawString("true")});options.push(option),idx++}if(lexemes[idx]&&(lexemes[idx].type&4)!==0){let optionResult=this.parseOptionList(lexemes,idx);options.push(...optionResult.options),idx=optionResult.newIndex,optionResult.trailingComments&&optionResult.trailingComments.length>0&&this.attachTrailingCommentsToNextLexeme(lexemes,idx,optionResult.trailingComments)}if(idx>=lexemes.length)throw new Error("[ExplainStatementParser] EXPLAIN must be followed by a statement to analyze.");let nested=parseNested(lexemes,idx),statement=nested.value;return idx=nested.newIndex,{value:new ExplainStatement({options:options.length>0?options:null,statement}),newIndex:idx}}static parseOptionList(lexemes,index){let idx=index;if(!(lexemes[idx].type&4))throw new Error(`[ExplainStatementParser] Expected '(' to start option list at index ${idx}.`);idx++;let options=[],trailingComments=null;for(;idx<lexemes.length;){let token=lexemes[idx];if(!token)throw new Error("[ExplainStatementParser] Unterminated option list.");if(token.type&8){idx++;break}if(!this.canStartOptionName(token))throw new Error(`[ExplainStatementParser] Expected option name inside EXPLAIN option list at index ${idx}, found "${token.value}".`);let nameComponent=new IdentifierString(token.value.toLowerCase());token.comments&&token.comments.length>0&&(nameComponent.comments=[...token.comments]),idx++;let value=null;if(lexemes[idx]&&lexemes[idx].type&2&&lexemes[idx].value==="="&&idx++,lexemes[idx]&&!(lexemes[idx].type&16)&&!(lexemes[idx].type&8)){let parsedValue=ValueParser.parseFromLexeme(lexemes,idx);value=parsedValue.value,idx=parsedValue.newIndex}if(value||(value=new RawString("true")),options.push(new ExplainOption({name:nameComponent,value})),!lexemes[idx])throw new Error("[ExplainStatementParser] Unterminated option list.");if(lexemes[idx].type&16){idx++;continue}if(lexemes[idx].type&8){trailingComments=this.extractAfterComments(lexemes[idx]),idx++;break}throw new Error(`[ExplainStatementParser] Expected ',' or ')' after EXPLAIN option at index ${idx}, found "${lexemes[idx].value}".`)}return{options,newIndex:idx,trailingComments}}static isLegacyFlag(lexeme){if(!lexeme||!(lexeme.type&10432))return!1;let keyword=lexeme.value.toLowerCase();return keyword==="analyze"||keyword==="verbose"}static canStartOptionName(lexeme){return(lexeme.type&10432)!==0}static extractAfterComments(token){let collected=null;if(token.positionedComments&&token.positionedComments.length>0){let retained=[];for(let posComment of token.positionedComments){if(posComment.position==="after"&&posComment.comments&&posComment.comments.length>0){collected||(collected=[]),collected.push(...posComment.comments);continue}retained.push(posComment)}token.positionedComments=retained.length>0?retained:void 0}return token.comments&&token.comments.length>0&&(collected||(collected=[]),collected.push(...token.comments),token.comments=null),collected}static attachTrailingCommentsToNextLexeme(lexemes,index,comments){if(!comments||comments.length===0)return;let target=lexemes[index];if(!target)return;target.positionedComments||(target.positionedComments=[]);let beforeEntry=target.positionedComments.find(pos=>pos.position==="before");beforeEntry?beforeEntry.comments.push(...comments):target.positionedComments.push({position:"before",comments:[...comments]})}};var SqlParser=class{static parse(sql,options={}){let skipEmpty=options.skipEmptyStatements??!0,mode=options.mode??"single",tokenizer=new SqlTokenizer(sql),first=this.consumeNextStatement(tokenizer,0,skipEmpty);if(!first)throw new Error("[SqlParser] No SQL statements found in input.");let parsed=this.dispatchParse(first.segment,1);if(mode==="single"&&this.consumeNextStatement(tokenizer,first.nextCursor,skipEmpty))throw new Error('[SqlParser] Unexpected additional statement detected at index 2. Use parseMany or set mode to "multiple" to allow multiple statements.');return parsed}static parseMany(sql,options={}){let skipEmpty=options.skipEmptyStatements??!0,tokenizer=new SqlTokenizer(sql),statements=[],cursor=0,carry=null,index=0;for(;;){let segment=tokenizer.readNextStatement(cursor,carry);if(carry=null,!segment)break;cursor=segment.nextPosition,!(segment.lexemes.length===0&&(segment.leadingComments&&segment.leadingComments.length>0&&(carry=segment.leadingComments),skipEmpty||segment.rawText.trim().length===0))&&(index++,statements.push(this.dispatchParse(segment,index)))}return statements}static dispatchParse(segment,statementIndex){if(segment.lexemes.length===0)throw new Error(`[SqlParser] Statement ${statementIndex} does not contain any tokens.`);let firstToken=segment.lexemes[0].value.toLowerCase();if(firstToken==="with"){let commandAfterWith=this.getCommandAfterWith(segment.lexemes);return commandAfterWith==="insert into"?this.parseInsertStatement(segment,statementIndex):commandAfterWith==="update"?this.parseUpdateStatement(segment,statementIndex):commandAfterWith==="delete from"?this.parseDeleteStatement(segment,statementIndex):commandAfterWith==="merge into"?this.parseMergeStatement(segment,statementIndex):this.parseSelectStatement(segment,statementIndex)}if(firstToken==="select"||firstToken==="values")return this.parseSelectStatement(segment,statementIndex);if(firstToken==="insert into")return this.parseInsertStatement(segment,statementIndex);if(firstToken==="update")return this.parseUpdateStatement(segment,statementIndex);if(firstToken==="delete from")return this.parseDeleteStatement(segment,statementIndex);if(firstToken==="create table"||firstToken==="create temporary table")return this.parseCreateTableStatement(segment,statementIndex);if(firstToken==="merge into")return this.parseMergeStatement(segment,statementIndex);if(firstToken==="create index"||firstToken==="create unique index")return this.parseCreateIndexStatement(segment,statementIndex);if(firstToken==="drop table")return this.parseDropTableStatement(segment,statementIndex);if(firstToken==="drop index")return this.parseDropIndexStatement(segment,statementIndex);if(firstToken==="alter table")return this.parseAlterTableStatement(segment,statementIndex);if(firstToken==="drop constraint")return this.parseDropConstraintStatement(segment,statementIndex);if(firstToken==="analyze")return this.parseAnalyzeStatement(segment,statementIndex);if(firstToken==="explain")return this.parseExplainStatement(segment,statementIndex);throw new Error(`[SqlParser] Statement ${statementIndex} starts with unsupported token "${segment.lexemes[0].value}". Support for additional statement types will be introduced soon.`)}static parseSelectStatement(segment,statementIndex){try{let result=SelectQueryParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse SELECT statement ${statementIndex}: ${message}`)}}static parseExplainStatement(segment,statementIndex){try{let result=ExplainStatementParser.parseFromLexeme(segment.lexemes,0,(lexemes,nestedStart)=>{if(nestedStart>=lexemes.length)throw new Error("[ExplainStatementParser] Missing statement after EXPLAIN options.");let nestedSegment={lexemes:lexemes.slice(nestedStart),statementStart:segment.statementStart,statementEnd:segment.statementEnd,nextPosition:segment.nextPosition,rawText:segment.rawText,leadingComments:segment.leadingComments};return{value:this.dispatchParse(nestedSegment,statementIndex),newIndex:lexemes.length}});if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in EXPLAIN statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse EXPLAIN statement ${statementIndex}: ${message}`)}}static parseInsertStatement(segment,statementIndex){try{let result=InsertQueryParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse INSERT statement ${statementIndex}: ${message}`)}}static parseUpdateStatement(segment,statementIndex){try{let result=UpdateQueryParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse UPDATE statement ${statementIndex}: ${message}`)}}static parseDeleteStatement(segment,statementIndex){try{let result=DeleteQueryParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse DELETE statement ${statementIndex}: ${message}`)}}static parseCreateTableStatement(segment,statementIndex){try{let result=CreateTableParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse CREATE TABLE statement ${statementIndex}: ${message}`)}}static parseDropTableStatement(segment,statementIndex){try{let result=DropTableParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse DROP TABLE statement ${statementIndex}: ${message}`)}}static parseDropIndexStatement(segment,statementIndex){try{let result=DropIndexParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse DROP INDEX statement ${statementIndex}: ${message}`)}}static parseCreateIndexStatement(segment,statementIndex){try{let result=CreateIndexParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse CREATE INDEX statement ${statementIndex}: ${message}`)}}static parseAlterTableStatement(segment,statementIndex){try{let result=AlterTableParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse ALTER TABLE statement ${statementIndex}: ${message}`)}}static parseDropConstraintStatement(segment,statementIndex){try{let result=DropConstraintParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse DROP CONSTRAINT statement ${statementIndex}: ${message}`)}}static parseAnalyzeStatement(segment,statementIndex){try{let result=AnalyzeStatementParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse ANALYZE statement ${statementIndex}: ${message}`)}}static parseMergeStatement(segment,statementIndex){try{let result=MergeQueryParser.parseFromLexeme(segment.lexemes,0);if(result.newIndex<segment.lexemes.length){let unexpected=segment.lexemes[result.newIndex],position=unexpected.position?.startPosition??segment.statementStart;throw new Error(`[SqlParser] Unexpected token "${unexpected.value}" in statement ${statementIndex} at character ${position}.`)}return result.value}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`[SqlParser] Failed to parse MERGE statement ${statementIndex}: ${message}`)}}static getCommandAfterWith(lexemes){try{let clone=this.cloneLexemeArray(lexemes),withResult=WithClauseParser.parseFromLexeme(clone,0);return lexemes[withResult.newIndex]?.value.toLowerCase()??null}catch{return null}}static cloneLexemeArray(lexemes){return lexemes.map(lexeme=>({...lexeme,comments:lexeme.comments?[...lexeme.comments]:null,positionedComments:lexeme.positionedComments?lexeme.positionedComments.map(pc=>({position:pc.position,comments:[...pc.comments]})):void 0,position:lexeme.position?{...lexeme.position}:void 0}))}static consumeNextStatement(tokenizer,cursor,skipEmpty){let localCursor=cursor,carry=null;for(;;){let segment=tokenizer.readNextStatement(localCursor,carry);if(carry=null,!segment)return null;if(localCursor=segment.nextPosition,!(segment.lexemes.length===0&&(segment.leadingComments&&segment.leadingComments.length>0&&(carry=segment.leadingComments),skipEmpty||segment.rawText.trim().length===0)))return{segment,nextCursor:localCursor}}}};var CTETableReferenceCollector=class{constructor(){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.visitOffsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr))}collect(query){return this.visit(query),this.getTableSources()}getTableSources(){return this.tableSources}reset(){this.tableSources=[],this.tableNameMap.clear(),this.visitedNodes.clear()}getTableIdentifier(source){return source.qualifiedName.namespaces&&source.qualifiedName.namespaces.length>0?source.qualifiedName.namespaces.map(ns=>ns.name).join(".")+"."+(source.qualifiedName.name instanceof RawString?source.qualifiedName.name.value:source.qualifiedName.name.name):source.qualifiedName.name instanceof RawString?source.qualifiedName.name.value:source.qualifiedName.name.name}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}}visitSimpleSelectQuery(query){if(query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.orderByClause&&query.orderByClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.limitClause&&query.limitClause.accept(this),query.offsetClause&&query.offsetClause.accept(this),query.fetchClause&&query.fetchClause.accept(this),query.forClause&&query.forClause.accept(this),query.selectClause.accept(this)}visitBinarySelectQuery(query){query.left.accept(this),query.right.accept(this)}visitValuesQuery(query){for(let tuple of query.tuples)tuple.accept(this)}visitFromClause(fromClause){if(fromClause.source.accept(this),fromClause.joins)for(let join of fromClause.joins)join.accept(this)}visitSourceExpression(source){source.datasource.accept(this)}visitTableSource(source){let identifier=this.getTableIdentifier(source);this.tableNameMap.has(identifier)||(this.tableNameMap.set(identifier,!0),this.tableSources.push(source))}visitFunctionSource(source){source.argument&&this.visitValueComponent(source.argument)}visitValueComponent(value){value.accept(this)}visitParenSource(source){source.source.accept(this)}visitSubQuerySource(subQuery){subQuery.query.accept(this)}visitInlineQuery(inlineQuery){inlineQuery.selectQuery.accept(this)}visitJoinClause(joinClause){joinClause.source.accept(this),joinClause.condition&&joinClause.condition.accept(this)}visitJoinOnClause(joinOn){joinOn.condition.accept(this)}visitJoinUsingClause(joinUsing){joinUsing.condition.accept(this)}visitWhereClause(whereClause){whereClause.condition.accept(this)}visitGroupByClause(clause){for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition.accept(this)}visitOrderByClause(clause){for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitLimitClause(clause){clause.value.accept(this)}visitOffsetClause(clause){clause.value.accept(this)}visitFetchClause(clause){clause.expression.accept(this)}visitForClause(_clause){}visitOrderByItem(item){item.value.accept(this)}visitSelectClause(clause){for(let item of clause.items)item.accept(this)}visitSelectItem(item){item.value.accept(this)}visitParenExpression(expr){expr.expression.accept(this)}visitBinaryExpression(expr){expr.left.accept(this),expr.right.accept(this)}visitUnaryExpression(expr){expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase.accept(this)}visitSwitchCaseArgument(switchCase){for(let caseItem of switchCase.cases)caseItem.accept(this);switchCase.elseValue&&switchCase.elseValue.accept(this)}visitCaseKeyValuePair(pair){pair.key.accept(this),pair.value.accept(this)}visitBetweenExpression(expr){expr.expression.accept(this),expr.lower.accept(this),expr.upper.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this)}visitArrayExpression(expr){expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitTupleExpression(expr){for(let value of expr.values)value.accept(this)}visitCastExpression(expr){expr.input.accept(this),expr.castType.accept(this)}visitValueList(valueList){for(let value of valueList.values)value.accept(this)}visitStringSpecifierExpression(_expr){}};var CTEDependencyAnalyzer=class _CTEDependencyAnalyzer{constructor(){this.dependencyGraph=null;this.cteMap=new Map;this.sourceCollector=new TableSourceCollector(!1),this.cteReferenceCollector=new CTETableReferenceCollector,this.cteCollector=new CTECollector}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(query){let ctes=this.cteCollector.collect(query);return this.buildCTEMap(ctes),this.dependencyGraph=this.buildDependencyGraph(ctes,query),this.dependencyGraph}getDependencies(cteName){this.ensureAnalyzed();let node=this.findNodeByName(cteName);return node?[...node.dependencies]:[]}getDependents(cteName){this.ensureAnalyzed();let node=this.findNodeByName(cteName);return node?[...node.dependents]:[]}getMainQueryDependencies(){this.ensureAnalyzed();let mainQueryNode=this.findNodeByName(_CTEDependencyAnalyzer.MAIN_QUERY_NAME);return mainQueryNode?[...mainQueryNode.dependencies]:[]}getNodesByType(nodeType){return this.ensureAnalyzed(),this.dependencyGraph.nodes.filter(n=>n.type===nodeType)}getMainQueryNode(){return this.ensureAnalyzed(),this.findNodeByName(_CTEDependencyAnalyzer.MAIN_QUERY_NAME)}hasCircularDependency(){this.ensureAnalyzed();try{return this.getExecutionOrder(),!1}catch(error){if(error instanceof Error&&error.message.includes(_CTEDependencyAnalyzer.ERROR_MESSAGES.CIRCULAR_REFERENCE))return!0;throw error}}getExecutionOrder(){this.ensureAnalyzed();let visited=new Set,visiting=new Set,result=[],dependencyMap=new Map;for(let node of this.dependencyGraph.nodes)dependencyMap.set(node.name,new Set(node.dependencies));let visit=nodeName=>{if(visited.has(nodeName))return;if(visiting.has(nodeName))throw new Error(`${_CTEDependencyAnalyzer.ERROR_MESSAGES.CIRCULAR_REFERENCE}: ${nodeName}`);visiting.add(nodeName);let deps=dependencyMap.get(nodeName)||new Set;for(let dep of deps)visit(dep);visiting.delete(nodeName),visited.add(nodeName),result.push(nodeName)};for(let node of this.dependencyGraph.nodes)visited.has(node.name)||visit(node.name);return result}buildDependencyGraph(ctes,mainQuery){let nodes=[],edges=[],dependencyMap=new Map,dependentMap=new Map;for(let cte of ctes){let name=_CTEDependencyAnalyzer.getCTEName(cte);dependencyMap.set(name,new Set),dependentMap.set(name,new Set)}dependencyMap.set(_CTEDependencyAnalyzer.MAIN_QUERY_NAME,new Set),dependentMap.set(_CTEDependencyAnalyzer.MAIN_QUERY_NAME,new Set);for(let cte of ctes){let cteName=_CTEDependencyAnalyzer.getCTEName(cte),referencedTables=this.sourceCollector.collect(cte.query);for(let referencedTable of referencedTables){let referencedName=referencedTable.table.name;this.cteMap.has(referencedName)&&referencedName!==cteName&&(dependencyMap.get(cteName).add(referencedName),dependentMap.get(referencedName).add(cteName),edges.push({from:cteName,to:referencedName}))}}let mainQueryWithoutCTE=this.getMainQueryWithoutCTE(mainQuery);if(mainQueryWithoutCTE){let mainQueryReferences=this.cteReferenceCollector.collect(mainQueryWithoutCTE);for(let referencedTable of mainQueryReferences){let referencedName=referencedTable.table.name;this.cteMap.has(referencedName)&&(dependencyMap.get(_CTEDependencyAnalyzer.MAIN_QUERY_NAME).add(referencedName),dependentMap.get(referencedName).add(_CTEDependencyAnalyzer.MAIN_QUERY_NAME),edges.push({from:_CTEDependencyAnalyzer.MAIN_QUERY_NAME,to:referencedName}))}}for(let cte of ctes){let name=_CTEDependencyAnalyzer.getCTEName(cte);nodes.push({name,type:"CTE",cte,dependencies:Array.from(dependencyMap.get(name)||new Set),dependents:Array.from(dependentMap.get(name)||new Set)})}return nodes.push({name:_CTEDependencyAnalyzer.MAIN_QUERY_NAME,type:"ROOT",cte:null,dependencies:Array.from(dependencyMap.get(_CTEDependencyAnalyzer.MAIN_QUERY_NAME)||new Set),dependents:Array.from(dependentMap.get(_CTEDependencyAnalyzer.MAIN_QUERY_NAME)||new Set)}),{nodes,edges}}ensureAnalyzed(){if(!this.dependencyGraph)throw new Error(_CTEDependencyAnalyzer.ERROR_MESSAGES.NOT_ANALYZED)}buildCTEMap(ctes){this.cteMap.clear();for(let cte of ctes){let name=_CTEDependencyAnalyzer.getCTEName(cte);this.cteMap.set(name,cte)}}findNodeByName(cteName){return this.dependencyGraph?.nodes.find(n=>n.name===cteName)}getMainQueryWithoutCTE(query){return query.withClause?new SimpleSelectQuery({selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:query.orderByClause,limitClause:query.limitClause,offsetClause:query.offsetClause,fetchClause:query.fetchClause,forClause:query.forClause,windowClause:query.windowClause}):query}static getCTEName(cte){return cte.aliasExpression.table.name}};var CommentEditor=class{static addComment(component,comment,position="before"){if(this.isSelectQuery(component)){let selectQuery=component;selectQuery.headerComments||(selectQuery.headerComments=[]),selectQuery.headerComments.push(comment)}else component.addPositionedComments(position,[comment])}static isSelectQuery(component){return"__selectQueryType"in component&&component.__selectQueryType==="SelectQuery"}static editComment(component,index,newComment,position="before"){if(this.isSelectQuery(component)){let selectQuery=component;if(!selectQuery.headerComments||index<0||index>=selectQuery.headerComments.length)throw new Error(`Invalid comment index: ${index}. Component has ${selectQuery.headerComments?.length||0} comments.`);selectQuery.headerComments[index]=newComment}else{let positionedComments=component.getPositionedComments(position);if(!positionedComments||index<0||index>=positionedComments.length)throw new Error(`Invalid comment index: ${index}. Component has ${positionedComments?.length||0} ${position} positioned comments.`);let positioned=component.positionedComments?.find(pc=>pc.position===position);positioned&&(positioned.comments[index]=newComment)}}static deleteComment(component,index,position="before"){if(this.isSelectQuery(component)){let selectQuery=component;if(!selectQuery.headerComments||index<0||index>=selectQuery.headerComments.length)throw new Error(`Invalid comment index: ${index}. Component has ${selectQuery.headerComments?.length||0} comments.`);selectQuery.headerComments.splice(index,1),selectQuery.headerComments.length===0&&(selectQuery.headerComments=null)}else{let positionedComments=component.getPositionedComments(position);if(!positionedComments||index<0||index>=positionedComments.length)throw new Error(`Invalid comment index: ${index}. Component has ${positionedComments?.length||0} ${position} positioned comments.`);let positioned=component.positionedComments?.find(pc=>pc.position===position);positioned&&(positioned.comments.splice(index,1),positioned.comments.length===0&&(component.positionedComments=component.positionedComments?.filter(pc=>pc.position!==position)||null,component.positionedComments?.length===0&&(component.positionedComments=null)))}}static deleteAllComments(component){if(this.isSelectQuery(component)){let selectQuery=component;selectQuery.headerComments=null}else component.positionedComments=null}static getComments(component){return this.isSelectQuery(component)?component.headerComments||[]:component.getAllPositionedComments()}static findComponentsWithComment(root,searchText,caseSensitive=!1){let results=[],searchTerm=caseSensitive?searchText:searchText.toLowerCase(),traverse=component=>{if(component&&component instanceof SqlComponent){let hasMatchingComment=!1,allPositionedComments=component.getAllPositionedComments();if(allPositionedComments&&allPositionedComments.some(c=>(caseSensitive?c:c.toLowerCase()).includes(searchTerm))&&(hasMatchingComment=!0),this.isSelectQuery(component)){let selectQuery=component;selectQuery.headerComments&&selectQuery.headerComments.some(c=>(caseSensitive?c:c.toLowerCase()).includes(searchTerm))&&(hasMatchingComment=!0)}hasMatchingComment&&results.push(component)}for(let key in component)component[key]&&typeof component[key]=="object"&&(Array.isArray(component[key])?component[key].forEach(traverse):traverse(component[key]))};return traverse(root),results}static replaceInComments(root,searchText,replaceText,caseSensitive=!1){let replacementCount=0,traverse=component=>{if(component&&component instanceof SqlComponent){if(component.comments)for(let i=0;i<component.comments.length;i++){let originalComment=component.comments[i],flags=caseSensitive?"g":"gi",regex=new RegExp(searchText.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),flags),newComment=originalComment.replace(regex,replaceText);newComment!==originalComment&&(component.comments[i]=newComment,replacementCount++)}if(component.positionedComments){for(let posComment of component.positionedComments)if(posComment.comments)for(let i=0;i<posComment.comments.length;i++){let originalComment=posComment.comments[i],flags=caseSensitive?"g":"gi",regex=new RegExp(searchText.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),flags),newComment=originalComment.replace(regex,replaceText);newComment!==originalComment&&(posComment.comments[i]=newComment,replacementCount++)}}if(this.isSelectQuery(component)){let selectQuery=component;if(selectQuery.headerComments)for(let i=0;i<selectQuery.headerComments.length;i++){let originalComment=selectQuery.headerComments[i],flags=caseSensitive?"g":"gi",regex=new RegExp(searchText.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),flags),newComment=originalComment.replace(regex,replaceText);newComment!==originalComment&&(selectQuery.headerComments[i]=newComment,replacementCount++)}}}for(let key in component)component[key]&&typeof component[key]=="object"&&(Array.isArray(component[key])?component[key].forEach(traverse):traverse(component[key]))};return traverse(root),replacementCount}static countComments(root){let count=0,traverse=component=>{if(component&&component instanceof SqlComponent){let positionedComments=component.getAllPositionedComments();if(positionedComments&&(count+=positionedComments.length),this.isSelectQuery(component)){let selectQuery=component;selectQuery.headerComments&&(count+=selectQuery.headerComments.length)}}for(let key in component)component[key]&&typeof component[key]=="object"&&(Array.isArray(component[key])?component[key].forEach(traverse):traverse(component[key]))};return traverse(root),count}static getAllComments(root){let results=[],traverse=component=>{if(component&&component instanceof SqlComponent){let positionedComments=component.getAllPositionedComments();if(positionedComments&&positionedComments.forEach((comment,index)=>{results.push({comment,component,index})}),this.isSelectQuery(component)){let selectQuery=component;selectQuery.headerComments&&selectQuery.headerComments.forEach((comment,index)=>{results.push({comment,component,index})})}}for(let key in component)component[key]&&typeof component[key]=="object"&&(Array.isArray(component[key])?component[key].forEach(traverse):traverse(component[key]))};return traverse(root),results}};var TableSchema=class{constructor(name,columns){this.name=name,this.columns=columns}},SchemaCollector=class{constructor(tableColumnResolver=null,allowWildcardWithoutResolver=!1){this.tableColumnResolver=tableColumnResolver;this.allowWildcardWithoutResolver=allowWildcardWithoutResolver;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(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr))}collect(arg){return this.visit(arg),this.tableSchemas}analyze(arg){this.isAnalyzeMode=!0;try{return this.visit(arg),{success:this.unresolvedColumns.length===0&&!this.analysisError,schemas:this.tableSchemas,unresolvedColumns:this.unresolvedColumns,error:this.analysisError}}finally{this.isAnalyzeMode=!1}}visit(arg){if(this.running){this.visitNode(arg);return}this.reset(),this.running=!0;try{if(!(arg instanceof SimpleSelectQuery||arg instanceof BinarySelectQuery))throw new Error(`Unsupported SQL component type for schema collection. Received: ${arg.constructor.name}. Expected: SimpleSelectQuery or BinarySelectQuery.`);let cteCollector=new CTECollector;this.commonTables=cteCollector.collect(arg),this.visitNode(arg),this.consolidateTableSchemas()}finally{this.running=!1}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}}reset(){this.tableSchemas=[],this.visitedNodes=new Set,this.commonTables=[],this.unresolvedColumns=[],this.analysisError=void 0}consolidateTableSchemas(){let consolidatedSchemas=new Map;for(let schema of this.tableSchemas)if(!consolidatedSchemas.has(schema.name))consolidatedSchemas.set(schema.name,new Set(schema.columns));else{let existingColumns=consolidatedSchemas.get(schema.name);schema.columns.forEach(column=>existingColumns?.add(column))}this.tableSchemas=Array.from(consolidatedSchemas.entries()).sort(([nameA],[nameB])=>nameA.localeCompare(nameB)).map(([name,columns])=>new TableSchema(name,Array.from(columns).sort()))}handleSourceExpression(source,queryColumns,includeUnnamed){if(source.datasource instanceof TableSource){let tableName=source.datasource.getSourceName(),cte=this.commonTables.filter(table=>table.getSourceAliasName()===tableName);if(cte.length>0){cte[0].query.accept(this);let cteAlias=source.getAliasName()??tableName;this.processCTETableSchema(cte[0],cteAlias,queryColumns,includeUnnamed)}else{let tableAlias=source.getAliasName()??tableName;this.processCollectTableSchema(tableName,tableAlias,queryColumns,includeUnnamed)}}else source.datasource instanceof SubQuerySource&&this.visitNode(source.datasource.query)}visitSimpleSelectQuery(query){if(query.fromClause===null)return;let columns=new SelectableColumnCollector(this.tableColumnResolver,!0,"fullName").collect(query),queryColumns;if(this.allowWildcardWithoutResolver){let selectColumns=this.getSelectClauseColumns(query);queryColumns=columns.filter(column=>column.value instanceof ColumnReference).map(column=>column.value).filter(columnRef=>{let tableName=columnRef.getNamespace(),columnName=columnRef.column.name;return selectColumns.some(selectCol=>{if(selectCol.value instanceof ColumnReference){let selectTableName=selectCol.value.getNamespace(),selectColumnName=selectCol.value.column.name;if(selectTableName===tableName&&selectColumnName===columnName)return!0;if(selectColumnName==="*"){if(this.allowWildcardWithoutResolver&&this.tableColumnResolver===null)return!1;if(selectTableName===""||selectTableName===tableName)return!0}}return!1})}).map(columnRef=>({table:columnRef.getNamespace(),column:columnRef.column.name}))}else queryColumns=columns.filter(column=>column.value instanceof ColumnReference).map(column=>column.value).map(columnRef=>({table:columnRef.getNamespace(),column:columnRef.column.name}));if(query.fromClause.joins!==null&&query.fromClause.joins.length>0){let columnsWithoutTable=queryColumns.filter(columnRef=>columnRef.table==="").map(columnRef=>columnRef.column);if(columnsWithoutTable.length>0)if(this.isAnalyzeMode)this.unresolvedColumns.push(...columnsWithoutTable),this.analysisError=`Column reference(s) without table name found in query: ${columnsWithoutTable.join(", ")}`;else throw new Error(`Column reference(s) without table name found in query: ${columnsWithoutTable.join(", ")}`)}if(query.fromClause.source.datasource instanceof TableSource?this.handleSourceExpression(query.fromClause.source,queryColumns,!0):query.fromClause.source.datasource instanceof SubQuerySource&&query.fromClause.source.datasource.query.accept(this),query.fromClause?.joins)for(let join of query.fromClause.joins)join.source.datasource instanceof TableSource?this.handleSourceExpression(join.source,queryColumns,!1):join.source.datasource instanceof SubQuerySource&&join.source.datasource.query.accept(this)}visitBinarySelectQuery(query){this.visitNode(query.left),this.visitNode(query.right)}getSelectClauseColumns(query){if(!query.selectClause)return[];let selectColumns=[];for(let item of query.selectClause.items)if(item.value instanceof ColumnReference){let columnName=item.value.column.name;selectColumns.push({name:columnName,value:item.value})}return selectColumns}processCollectTableSchema(tableName,tableAlias,queryColumns,includeUnnamed=!1){if(this.tableColumnResolver===null&&queryColumns.filter(columnRef=>columnRef.table===tableAlias||includeUnnamed&&columnRef.table==="").filter(columnRef=>columnRef.column==="*").length>0&&!this.allowWildcardWithoutResolver){let errorMessage=tableName?`Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards. Target table: ${tableName}`:"Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards.";if(this.isAnalyzeMode){this.analysisError=errorMessage;let wildcardColumns=queryColumns.filter(columnRef=>columnRef.table===tableAlias||includeUnnamed&&columnRef.table==="").filter(columnRef=>columnRef.column==="*").map(columnRef=>columnRef.table?`${columnRef.table}.*`:"*");this.unresolvedColumns.push(...wildcardColumns)}else throw new Error(errorMessage)}let tableColumns=queryColumns.filter(columnRef=>columnRef.column!=="*").filter(columnRef=>columnRef.table===tableAlias||includeUnnamed&&columnRef.table==="").map(columnRef=>columnRef.column),tableSchema=new TableSchema(tableName,tableColumns);this.tableSchemas.push(tableSchema)}processCTETableSchema(cte,cteAlias,queryColumns,includeUnnamed=!1){let cteName=cte.getSourceAliasName(),cteColumns=this.getCTEColumns(cte),cteReferencedColumns=queryColumns.filter(columnRef=>columnRef.table===cteAlias||includeUnnamed&&columnRef.table==="").map(columnRef=>columnRef.column);if(cteReferencedColumns.includes("*")){if(this.tableColumnResolver!==null){let resolvedColumns=this.tableColumnResolver(cteName);if(resolvedColumns.length>0){let tableSchema2=new TableSchema(cteName,resolvedColumns);this.tableSchemas.push(tableSchema2);return}}if(cteColumns.length>0){let tableSchema2=new TableSchema(cteName,cteColumns);this.tableSchemas.push(tableSchema2);return}else if(this.allowWildcardWithoutResolver){let tableSchema2=new TableSchema(cteName,[]);this.tableSchemas.push(tableSchema2);return}else{let errorMessage=`Wildcard (*) is used. A TableColumnResolver is required to resolve wildcards. Target table: ${cteName}`;if(this.isAnalyzeMode)this.analysisError=errorMessage,this.unresolvedColumns.push(cteAlias?`${cteAlias}.*`:"*");else throw new Error(errorMessage);return}}let tableColumns=cteReferencedColumns.filter(column=>column!=="*");if(this.isAnalyzeMode){let availableColumns=cteColumns;if(this.tableColumnResolver){let resolvedColumns=this.tableColumnResolver(cteName);resolvedColumns.length>0&&(availableColumns=resolvedColumns)}if(availableColumns.length>0){let invalidColumns=tableColumns.filter(column=>!availableColumns.includes(column));invalidColumns.length>0&&(this.unresolvedColumns.push(...invalidColumns),this.analysisError||(this.analysisError=`Undefined column(s) found in CTE "${cteName}": ${invalidColumns.join(", ")}`))}else if(!this.allowWildcardWithoutResolver){let invalidColumns=tableColumns;invalidColumns.length>0&&(this.unresolvedColumns.push(...invalidColumns),this.analysisError||(this.analysisError=`Undefined column(s) found in CTE "${cteName}": ${invalidColumns.join(", ")}`))}}let tableSchema=new TableSchema(cteName,tableColumns);this.tableSchemas.push(tableSchema)}getCTEColumns(cte){try{return cte.query instanceof SimpleSelectQuery&&cte.query.selectClause?this.extractColumnsFromSelectItems(cte.query.selectClause.items,cte):this.extractColumnsUsingCollector(cte.query)}catch{return[]}}extractColumnsFromSelectItems(selectItems,cte){let columns=[];for(let item of selectItems)if(item.value instanceof ColumnReference){let columnName=item.identifier?.name||item.value.column.name;if(item.value.column.name==="*"){let wildcardColumns=this.resolveWildcardInCTE(item.value,cte);if(wildcardColumns===null)return[];columns.push(...wildcardColumns)}else columns.push(columnName)}else item.identifier&&columns.push(item.identifier.name);return this.removeDuplicates(columns)}resolveWildcardInCTE(columnRef,cte){let tableNamespace=columnRef.getNamespace();return tableNamespace?this.resolveQualifiedWildcard(tableNamespace):this.resolveUnqualifiedWildcard(cte)}resolveQualifiedWildcard(tableNamespace){let referencedCTE=this.commonTables.find(cte=>cte.getSourceAliasName()===tableNamespace);if(referencedCTE){let referencedColumns=this.getCTEColumns(referencedCTE);if(referencedColumns.length>0)return referencedColumns}return null}resolveUnqualifiedWildcard(cte){if(!(cte.query instanceof SimpleSelectQuery)||!cte.query.fromClause)return null;let fromSource=cte.query.fromClause.source;return fromSource.datasource instanceof TableSource?this.resolveTableWildcard(fromSource.datasource.table.name):(fromSource.datasource instanceof SubQuerySource,null)}resolveTableWildcard(tableName){if(this.tableColumnResolver){let resolvedColumns=this.tableColumnResolver(tableName);if(resolvedColumns.length>0)return resolvedColumns}return this.allowWildcardWithoutResolver,null}extractColumnsUsingCollector(query){return new SelectableColumnCollector(null,!0,"fullName").collect(query).filter(column=>column.value instanceof ColumnReference).map(column=>column.value).map(columnRef=>columnRef.column.name).filter((name,index,array)=>array.indexOf(name)===index)}removeDuplicates(columns){return columns.filter((name,index,array)=>array.indexOf(name)===index)}};var SqlSchemaValidator=class{static validate(sql,tableResolver){let sqlComponent=typeof sql=="string"?SelectQueryParser.parse(sql):sql,resolver=Array.isArray(tableResolver)?tableName=>{let schema=tableResolver.find(t=>t.name===tableName);return schema?schema.columns:[]}:tableResolver,tableSchemas=new SchemaCollector(resolver).collect(sqlComponent),errors=[];for(let tableSchema of tableSchemas){let resolvedColumns=resolver(tableSchema.name);if(resolvedColumns.length===0){errors.push(`Table '${tableSchema.name}' is not defined.`);continue}let undefinedColumns=tableSchema.columns.filter(column=>!resolvedColumns.includes(column));undefinedColumns.length>0&&errors.push(`Table '${tableSchema.name}' contains undefined columns: ${undefinedColumns.join(", ")}.`)}if(errors.length>0)throw new Error(errors.join(`
33
33
  `))}};var CTEComposer=class{constructor(options={}){this.knownCTENames=[];this.options=options,this.formatter=new SqlFormatter(options),this.dependencyAnalyzer=new CTEDependencyAnalyzer}compose(editedCTEs,rootQuery){if(editedCTEs.length===0)return rootQuery;this.knownCTENames=editedCTEs.map(cte=>cte.name);let pureQueries=editedCTEs.map(cte=>({name:cte.name,query:this.extractPureQuery(cte.query,cte.name)})),tempQuery=this.buildTempQueryForAnalysis(pureQueries,rootQuery),dependencyGraph=this.dependencyAnalyzer.analyzeDependencies(tempQuery),sortedCTEs=this.sortCTEsByDependencies(pureQueries,dependencyGraph),isRecursive=this.detectRecursiveFromOriginalQueries(editedCTEs),cteDefinitions=sortedCTEs.map(cte=>`${cte.name} as (${cte.query})`),composedQuery=`${isRecursive?"with recursive":"with"} ${cteDefinitions.join(", ")} ${rootQuery}`;return this.options.validateSchema&&this.options.schema&&this.validateComposedQuery(composedQuery),this.formatFinalQuery(composedQuery)}extractPureQuery(query,cteName){if(!/^\s*with\s+/i.test(query)||/^\s*with\s+recursive\s+/i.test(query))return query;try{let parsed=SelectQueryParser.parse(query);if(parsed.withClause&&parsed.withClause.tables){let knownCTENames=this.getKnownCTENames();if(parsed.withClause.tables.map(cte=>this.getCTEName(cte)).every(name=>knownCTENames.includes(name))){let queryWithoutWith=new SimpleSelectQuery({selectClause:parsed.selectClause,fromClause:parsed.fromClause,whereClause:parsed.whereClause,groupByClause:parsed.groupByClause,havingClause:parsed.havingClause,orderByClause:parsed.orderByClause,windowClause:parsed.windowClause,limitClause:parsed.limitClause,offsetClause:parsed.offsetClause,fetchClause:parsed.fetchClause,forClause:parsed.forClause,withClause:void 0});return new SqlFormatter({identifierEscape:{start:"",end:""}}).format(queryWithoutWith).formattedSql}}}catch{}return query}getKnownCTENames(){return this.knownCTENames||[]}getCTEName(cte){return cte.aliasExpression.table.name}extractCTEWithRegex(query,cteName){let ctePattern=new RegExp(`${cteName}\\s+as\\s*\\(`,"i"),match=query.match(ctePattern);if(!match)return query;let startIndex=match.index+match[0].length,parenCount=1,endIndex=startIndex;for(;endIndex<query.length&&parenCount>0;){let char=query[endIndex];char==="("?parenCount++:char===")"&&parenCount--,endIndex++}return parenCount===0?query.substring(startIndex,endIndex-1).trim():query}buildTempQueryForAnalysis(pureQueries,rootQuery){let tempSql=`with ${pureQueries.map(cte=>`${cte.name} as (${cte.query})`).join(", ")} ${rootQuery}`;try{return SelectQueryParser.parse(tempSql)}catch(error){throw new Error(`Failed to parse temporary query for dependency analysis: ${error}`)}}sortCTEsByDependencies(pureQueries,dependencyGraph){let queryMap=new Map;return pureQueries.forEach(cte=>queryMap.set(cte.name,cte.query)),dependencyGraph.nodes.map(node=>({name:node.name,query:queryMap.get(node.name)||""})).filter(cte=>cte.query!=="")}detectRecursiveFromOriginalQueries(editedCTEs){return editedCTEs.some(cte=>cte.query.toLowerCase().includes("with recursive"))}detectRecursiveCTEs(query){return query.withClause?this.formatter.format(query).formattedSql.toLowerCase().includes("with recursive"):!1}validateComposedQuery(composedQuery){try{let parsed=SelectQueryParser.parse(composedQuery),tableSchemas=Object.entries(this.options.schema).map(([name,columns])=>({name,columns}));SqlSchemaValidator.validate(parsed,tableSchemas)}catch(error){throw error instanceof Error?new Error(`Schema validation failed: ${error.message}`):error}}formatFinalQuery(composedQuery){if(this.options.preset||this.options.keywordCase)try{let parsed=SelectQueryParser.parse(composedQuery);return this.formatter.format(parsed).formattedSql}catch{return composedQuery}return composedQuery}};var CTEQueryDecomposer=class _CTEQueryDecomposer{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(options={}){this.options=options,this.dependencyAnalyzer=new CTEDependencyAnalyzer,this.cteCollector=new CTECollector,this.formatter=new SqlFormatter(options)}decompose(query){let ctes=this.cteCollector.collect(query);if(ctes.length===0)return[];let recursiveCTEs=this.findRecursiveCTEs(query,ctes),dependencyGraph=this.dependencyAnalyzer.analyzeDependencies(query);return this.validateCircularDependencies(recursiveCTEs.length>0),this.processCTENodes(query,dependencyGraph.nodes,recursiveCTEs)}synchronize(editedCTEs,rootQuery){if(editedCTEs.length===0)return[];let flattenedCTEs=this.flattenNestedWithClauses(editedCTEs),composerOptions={...this.options,addComments:void 0},unifiedQuery=new CTEComposer(composerOptions).compose(flattenedCTEs,rootQuery),parsedQuery=SelectQueryParser.parse(unifiedQuery);return this.decompose(parsedQuery)}extractCTE(query,cteName){let warnings=[],allCTEs=this.cteCollector.collect(query);if(allCTEs.length===0)throw new Error("Query does not contain any CTEs");if(!allCTEs.find(cte=>this.getCTEName(cte)===cteName))throw new Error(`CTE not found in query: ${cteName}`);if(this.findRecursiveCTEs(query,allCTEs).includes(cteName))return warnings.push("Recursive CTE restoration requires the full query context"),{name:cteName,executableSql:this.formatter.format(query).formattedSql,dependencies:this.getAllCTENames(allCTEs).filter(name=>name!==cteName),warnings};let dependencyGraph=this.dependencyAnalyzer.analyzeDependencies(query);if(this.dependencyAnalyzer.hasCircularDependency())throw new Error("Circular dependency detected in CTEs");let targetNode=dependencyGraph.nodes.find(node=>node.name===cteName);if(!targetNode||!targetNode.cte)throw new Error(`CTE not found in dependency graph: ${cteName}`);let executableSql=this.buildExecutableQuery(targetNode,dependencyGraph.nodes),allDependencies=this.collectRequiredCTEs(targetNode,dependencyGraph.nodes).map(node=>node.name),finalSql=this.options.addComments?this.addRestorationComments(executableSql,targetNode,warnings):executableSql;return{name:cteName,executableSql:finalSql,dependencies:allDependencies,warnings}}flattenNestedWithClauses(editedCTEs){let flattened=[],extractedCTEs=new Map;for(let editedCTE of editedCTEs)try{if(/^\s*with\s+/i.test(editedCTE.query)){let parsed=SelectQueryParser.parse(editedCTE.query);if(parsed.withClause&&parsed.withClause.tables){for(let nestedCTE of parsed.withClause.tables){let cteName=this.getCTEName(nestedCTE);if(!extractedCTEs.has(cteName)){let nestedQuery=new SqlFormatter({identifierEscape:{start:"",end:""}}).format(nestedCTE.query).formattedSql;extractedCTEs.set(cteName,nestedQuery)}}let mainQueryWithoutWith=new SimpleSelectQuery({selectClause:parsed.selectClause,fromClause:parsed.fromClause,whereClause:parsed.whereClause,groupByClause:parsed.groupByClause,havingClause:parsed.havingClause,orderByClause:parsed.orderByClause,windowClause:parsed.windowClause,limitClause:parsed.limitClause,offsetClause:parsed.offsetClause,fetchClause:parsed.fetchClause,forClause:parsed.forClause,withClause:void 0}),mainQuery=new SqlFormatter({identifierEscape:{start:"",end:""}}).format(mainQueryWithoutWith).formattedSql;flattened.push({name:editedCTE.name,query:mainQuery})}else flattened.push(editedCTE)}else flattened.push(editedCTE)}catch{flattened.push(editedCTE)}let result=[];for(let[name,query]of extractedCTEs)result.push({name,query});return result.push(...flattened),result}validateCircularDependencies(hasRecursiveCTEs){if(this.dependencyAnalyzer.hasCircularDependency()&&!hasRecursiveCTEs)throw new Error(_CTEQueryDecomposer.ERROR_MESSAGES.CIRCULAR_REFERENCE)}processCTENodes(query,nodes,recursiveCTEs){let result=[];for(let node of nodes){if(node.type==="ROOT")continue;recursiveCTEs.includes(node.name)?result.push(this.createRecursiveCTE(node,query)):result.push(this.createStandardCTE(node,nodes))}return result}createRecursiveCTE(node,query){let formattedQuery=this.formatter.format(query).formattedSql,cteDependents=node.dependents.filter(dep=>dep!=="MAIN_QUERY"),finalQuery=this.addCommentsToQuery(formattedQuery,node.name,node.dependencies,node.dependents,!0);return{name:node.name,query:finalQuery,dependencies:[...node.dependencies],dependents:cteDependents,isRecursive:!0}}createStandardCTE(node,allNodes){let query=this.buildExecutableQuery(node,allNodes),finalQuery=this.addCommentsToQuery(query,node.name,node.dependencies,node.dependents,!1),cteDependents=node.dependents.filter(dep=>dep!=="MAIN_QUERY");return{name:node.name,query:finalQuery,dependencies:[...node.dependencies],dependents:cteDependents,isRecursive:!1}}buildExecutableQuery(targetNode,allNodes){if(targetNode.type==="ROOT"||!targetNode.cte)throw new Error(`Cannot build executable query for ROOT node: ${targetNode.name}`);let requiredCTEs=this.collectRequiredCTEs(targetNode,allNodes);if(requiredCTEs.length===0)return this.formatter.format(targetNode.cte.query).formattedSql;let withClause=this.buildWithClause(requiredCTEs),mainQuery=this.formatter.format(targetNode.cte.query).formattedSql;return`${withClause} ${mainQuery}`}collectRequiredCTEs(targetNode,allNodes){let visited=new Set,result=[],nodeMap=new Map;for(let node of allNodes)nodeMap.set(node.name,node);let collectDependencies=nodeName=>{if(visited.has(nodeName))return;visited.add(nodeName);let node=nodeMap.get(nodeName);if(node){for(let depName of node.dependencies)collectDependencies(depName);nodeName!==targetNode.name&&node.type!=="ROOT"&&result.push(node)}};for(let depName of targetNode.dependencies)collectDependencies(depName);return result}buildWithClause(requiredCTEs){return requiredCTEs.length===0?"":`with ${requiredCTEs.map(node=>{if(node.type==="ROOT"||!node.cte)throw new Error(`Cannot include ROOT node in WITH clause: ${node.name}`);let cteName=node.name,cteQuery=this.formatter.format(node.cte.query).formattedSql;return`${cteName} as (${cteQuery})`}).join(", ")}`}findRecursiveCTEs(query,ctes){return!query.withClause||!this.isRecursiveWithClause(query)?[]:ctes.map(cte=>this.getCTEName(cte))}isRecursiveWithClause(query){return this.formatter.format(query).formattedSql.toLowerCase().includes("with recursive")}addCommentsToQuery(query,cteName,dependencies,dependents,isRecursive){if(this.options.addComments!==!0)return query;try{let parsedQuery=SelectQueryParser.parse(query);return this.generateComments(cteName,dependencies,dependents,isRecursive).forEach(comment=>{CommentEditor.addComment(parsedQuery,comment)}),new SqlFormatter({...this.options,exportComment:!0}).format(parsedQuery).formattedSql}catch(error){return console.warn(`${_CTEQueryDecomposer.ERROR_MESSAGES.PARSING_FAILED}: ${error}`),this.addTextCommentsToQuery(query,cteName,dependencies,dependents,isRecursive)}}generateComments(cteName,dependencies,dependents,isRecursive){let{AUTO_GENERATED,ORIGINAL_CTE,DEPENDENCIES,DEPENDENTS,RECURSIVE_TYPE,NONE}=_CTEQueryDecomposer.COMMENT_TEXTS,comments=[];comments.push(AUTO_GENERATED),comments.push(`${ORIGINAL_CTE} ${cteName}`),isRecursive&&comments.push(RECURSIVE_TYPE);let depsText=dependencies.length>0?dependencies.join(", "):NONE;comments.push(`${DEPENDENCIES} ${depsText}`);let cteDependents=dependents.filter(dep=>dep!=="MAIN_QUERY"),dependentsText=cteDependents.length>0?cteDependents.join(", "):NONE;return comments.push(`${DEPENDENTS} ${dependentsText}`),comments}addTextCommentsToQuery(query,cteName,dependencies,dependents,isRecursive){return`${this.generateComments(cteName,dependencies,dependents,isRecursive).map(comment=>`-- ${comment}`).join(`
34
34
  `)}
35
35
  ${query}`}addRestorationComments(sql,targetNode,warnings){let comments=[];return comments.push("-- CTE Restoration: "+targetNode.name),targetNode.dependencies.length>0?comments.push("-- Dependencies: "+targetNode.dependencies.join(", ")):comments.push("-- Dependencies: none"),warnings.length>0&&comments.push("-- Warnings: "+warnings.join(", ")),comments.push("-- Generated by CTEQueryDecomposer.extractCTE()"),comments.push(""),comments.join(`
@@ -88,5 +88,5 @@ ${query}`}addRestorationComments(sql,targetNode,warnings){let comments=[];return
88
88
  `){inComment=!1;continue}!inString&&!inComment&&char===";"&&(boundaries.push({start:currentStart,end:i}),currentStart=i+1)}return currentStart<sql.length&&boundaries.push({start:currentStart,end:sql.length}),boundaries}static findQueryAtPosition(boundaries,position){return boundaries.find(boundary=>position>=boundary.start&&position<=boundary.end)}};var MultiQuerySplitter=class{static split(text){let queries=[];if(!text||text.trim()==="")return{queries:[],originalText:text,getActive:()=>{},getQuery:()=>{},getNonEmpty:()=>[]};let rawBoundaries=this.splitRespectingQuotesAndComments(text),boundaries=this.mergeTrailingCommentSegments(rawBoundaries,text),queryIndex=0;for(let boundary of boundaries){let rawSql=boundary.text.trim(),isEmpty=this.isEmptyQuery(rawSql),sql=rawSql,startLineCol=TextPositionUtils.charOffsetToLineColumn(text,boundary.start),endLineCol=TextPositionUtils.charOffsetToLineColumn(text,boundary.end);queries.push({sql,start:boundary.start,end:boundary.end,startLine:startLineCol?.line||1,endLine:endLineCol?.line||1,index:queryIndex++,isEmpty})}return{queries,originalText:text,getActive:cursorPosition=>{let charPos=typeof cursorPosition=="number"?cursorPosition:TextPositionUtils.lineColumnToCharOffset(text,cursorPosition);if(charPos!==-1)return queries.find(query=>charPos>=query.start&&charPos<=query.end)},getQuery:index=>queries[index],getNonEmpty:()=>queries.filter(q=>!q.isEmpty)}}static splitRespectingQuotesAndComments(text){let segments=[],currentStart=0,i=0;for(;i<=text.length;){if(i===text.length||i<text.length&&this.isValidSemicolon(text,i)){let segmentText=text.substring(currentStart,i);(segmentText.length>0||i<text.length)&&segments.push({text:segmentText,start:currentStart,end:i}),currentStart=i+1}i++}return segments}static isValidSemicolon(text,pos){if(text[pos]!==";")return!1;let inSingleQuote=!1,inDoubleQuote=!1,inLineComment=!1,inBlockComment=!1;for(let i=0;i<pos;i++){let char=text[i],nextChar=i+1<text.length?text[i+1]:"";if(!inSingleQuote&&!inDoubleQuote&&!inBlockComment&&char==="-"&&nextChar==="-"){inLineComment=!0,i++;continue}if(inLineComment&&char===`
89
89
  `){inLineComment=!1;continue}if(!inSingleQuote&&!inDoubleQuote&&!inLineComment&&char==="/"&&nextChar==="*"){inBlockComment=!0,i++;continue}if(inBlockComment&&char==="*"&&nextChar==="/"){inBlockComment=!1,i++;continue}if(!(inLineComment||inBlockComment)){if(char==="'"&&!inDoubleQuote){inSingleQuote&&nextChar==="'"?i++:inSingleQuote=!inSingleQuote;continue}if(char==='"'&&!inSingleQuote){inDoubleQuote&&nextChar==='"'?i++:inDoubleQuote=!inDoubleQuote;continue}}}return!inSingleQuote&&!inDoubleQuote&&!inLineComment&&!inBlockComment}static mergeTrailingCommentSegments(segments,fullText){let merged=[];for(let i=0;i<segments.length;i++){let segment=segments[i],segmentText=segment.text.trim();if(this.isEmptyQuery(segmentText)&&merged.length>0){let lastSegmentText=merged[merged.length-1].text.trim(),isTrailingLineComment=segmentText.startsWith("--"),previousHasSQL=!this.isEmptyQuery(lastSegmentText);if(isTrailingLineComment&&previousHasSQL){let lastSegment=merged[merged.length-1];merged[merged.length-1]={text:fullText.substring(lastSegment.start,segment.end),start:lastSegment.start,end:segment.end}}else merged.push(segment)}else merged.push(segment)}return merged}static cleanSqlComments(sql){if(!sql)return null;let cleaned=sql;cleaned=cleaned.split(`
90
90
  `).map(line=>{let commentStart=line.indexOf("--");return commentStart>=0?line.substring(0,commentStart):line}).join(`
91
- `),cleaned=cleaned.replace(/\/\*[\s\S]*?\*\//g,"");let result=cleaned.trim();return result.length>0?result:null}static isEmptyQuery(sql){return sql?this.cleanSqlComments(sql)===null:!0}},MultiQueryUtils=class{static getContextAt(text,cursorPosition){let activeQuery=MultiQuerySplitter.split(text).getActive(cursorPosition);if(!activeQuery)return;let charPos=typeof cursorPosition=="number"?cursorPosition:TextPositionUtils.lineColumnToCharOffset(text,cursorPosition);if(charPos===-1)return;let relativePosition=charPos-activeQuery.start;return{query:activeQuery,relativePosition}}static extractQueries(text){return MultiQuerySplitter.split(text).getNonEmpty().map(q=>q.sql)}};function parseToPosition(sql,cursorPosition,options={}){return PositionAwareParser.parseToPosition(sql,cursorPosition,options)}function getCursorContext(sql,cursorPosition){return typeof cursorPosition=="number"?CursorContextAnalyzer.analyzeIntelliSense(sql,cursorPosition):CursorContextAnalyzer.analyzeIntelliSenseAt(sql,cursorPosition)}function resolveScope(sql,cursorPosition){return typeof cursorPosition=="number"?ScopeResolver.resolve(sql,cursorPosition):ScopeResolver.resolveAt(sql,cursorPosition)}function splitQueries(sql){return MultiQuerySplitter.split(sql)}function getIntelliSenseInfo(sql,cursorPosition,options={}){let charPos=typeof cursorPosition=="number"?cursorPosition:TextPositionUtils.lineColumnToCharOffset(sql,cursorPosition);if(charPos===-1)return;let activeQuery=splitQueries(sql).getActive(charPos);if(!activeQuery)return;let relativePosition=charPos-activeQuery.start,querySQL=activeQuery.sql,context=getCursorContext(querySQL,relativePosition),scope=resolveScope(querySQL,relativePosition),parseResult=parseToPosition(querySQL,relativePosition,options);return{context,scope,parseResult,currentQuery:querySQL,relativePosition}}function getCompletionSuggestions(sql,cursorPosition){let charPos=typeof cursorPosition=="number"?cursorPosition:TextPositionUtils.lineColumnToCharOffset(sql,cursorPosition);if(charPos===-1)return[];let intelliSenseContext=CursorContextAnalyzer.analyzeIntelliSense(sql,charPos),scope=resolveScope(sql,cursorPosition),suggestions=[];return intelliSenseContext.suggestKeywords&&(intelliSenseContext.requiredKeywords?intelliSenseContext.requiredKeywords.forEach(keyword=>{suggestions.push({type:"keyword",value:keyword,detail:`Required keyword: ${keyword}`})}):getGeneralKeywords(intelliSenseContext).forEach(keyword=>{suggestions.push({type:"keyword",value:keyword.value,detail:keyword.detail})})),intelliSenseContext.suggestTables&&(scope.availableTables.forEach(table=>{suggestions.push({type:"table",value:table.alias||table.name,detail:`Table: ${table.fullName}`,documentation:`Available table${table.alias?` (alias: ${table.alias})`:""}`})}),scope.availableCTEs.forEach(cte=>{suggestions.push({type:"cte",value:cte.name,detail:`CTE: ${cte.name}`,documentation:`Common Table Expression${cte.columns?` with columns: ${cte.columns.join(", ")}`:""}`})})),intelliSenseContext.suggestColumns&&(intelliSenseContext.tableScope?scope.visibleColumns.filter(col=>col.tableName===intelliSenseContext.tableScope||col.tableAlias===intelliSenseContext.tableScope).forEach(col=>{suggestions.push({type:"column",value:col.name,detail:`Column: ${col.fullReference}`,documentation:`Column from ${col.tableName}${col.type?` (${col.type})`:""}`})}):scope.visibleColumns.forEach(col=>{suggestions.push({type:"column",value:col.name==="*"?"*":`${col.tableAlias||col.tableName}.${col.name}`,detail:`Column: ${col.fullReference}`,documentation:`Column from ${col.tableName}`})})),suggestions}function getGeneralKeywords(context){let prevToken=context.previousToken?.value?.toLowerCase(),currentToken=context.currentToken?.value?.toLowerCase();return prevToken==="select"||currentToken==="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"}]:prevToken==="from"||currentToken==="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(prevToken||"")||["where","having","on"].includes(currentToken||"")?[{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{AliasRenamer,AlterTableAddConstraint,AlterTableDropColumn,AlterTableDropConstraint,AlterTableParser,AlterTableStatement,ArrayExpression,ArrayIndexExpression,ArrayQueryExpression,ArraySliceExpression,BetweenExpression,BinaryExpression,BinarySelectQuery,CTECollector,CTEComposer,CTEDependencyAnalyzer,CTEDisabler,CTENormalizer,CTENotFoundError,CTEQueryDecomposer,CTERegionDetector,CTERenamer,CTETableReferenceCollector,CaseExpression,CaseKeyValuePair,CastExpression,ColumnConstraintDefinition,ColumnReference,ColumnReferenceCollector,CommentEditor,CreateIndexParser,CreateIndexStatement,CreateTableParser,CreateTableQuery,CursorContextAnalyzer,DeleteQuery,DeleteQueryParser,DropConstraintParser,DropConstraintStatement,DropIndexParser,DropIndexStatement,DropTableParser,DropTableStatement,DuplicateCTEError,DuplicateDetectionMode,DynamicQueryBuilder,FilterableItem,FilterableItemCollector,Formatter,FunctionCall,IdentifierString,IndexColumnDefinition,InlineQuery,InsertQuery,InsertQueryParser,InsertQuerySelectValuesConverter,InvalidCTENameError,JsonMappingConverter,JsonSchemaValidator,LexemeCursor,LiteralValue,MergeAction,MergeDeleteAction,MergeDoNothingAction,MergeInsertAction,MergeQuery,MergeQueryParser,MergeUpdateAction,MergeWhenClause,MultiQuerySplitter,MultiQueryUtils,OriginalFormatRestorer,ParameterExpression,ParenExpression,PositionAwareParser,PostgresJsonQueryBuilder,QualifiedName,QueryBuilder,QueryFlowDiagramGenerator,RawString,ReferenceDefinition,SchemaCollector,SchemaManager,ScopeResolver,SelectQueryParser,SelectValueCollector,SelectableColumnCollector,SimpleSelectQuery,SmartRenamer,SqlComponent,SqlDialectConfiguration,SqlFormatter,SqlIdentifierRenamer,SqlPaginationInjector,SqlParamInjector,SqlParser,SqlSchemaValidator,SqlSortInjector,StringSpecifierExpression,SwitchCaseArgument,TableColumnDefinition,TableConstraintDefinition,TableSchema,TableSourceCollector,TokenType,TupleExpression,TypeTransformationPostProcessor,TypeTransformers,TypeValue,UnaryExpression,UpdateQuery,UpdateQueryParser,UpstreamSelectQueryFinder,VALID_PRESETS,ValueList,ValuesQuery,WindowFrameBound,WindowFrameBoundStatic,WindowFrameBoundaryValue,WindowFrameExpression,WindowFrameSpec,WindowFrameType,WithClauseParser,convertColumnsToLegacy,convertModelDrivenMapping,convertToLegacyJsonMapping,createJsonMappingFromSchema,createSchemaManager,createTableColumnResolver,extractTypeProtection,getCompletionSuggestions,getCursorContext,getIntelliSenseInfo,isLegacyFormat,isModelDrivenFormat,isUnifiedFormat,parseToPosition,processJsonMapping,resolveScope,splitQueries,toLegacyMapping,transformDatabaseResult,unifyJsonMapping,validateModelDrivenMapping};
91
+ `),cleaned=cleaned.replace(/\/\*[\s\S]*?\*\//g,"");let result=cleaned.trim();return result.length>0?result:null}static isEmptyQuery(sql){return sql?this.cleanSqlComments(sql)===null:!0}},MultiQueryUtils=class{static getContextAt(text,cursorPosition){let activeQuery=MultiQuerySplitter.split(text).getActive(cursorPosition);if(!activeQuery)return;let charPos=typeof cursorPosition=="number"?cursorPosition:TextPositionUtils.lineColumnToCharOffset(text,cursorPosition);if(charPos===-1)return;let relativePosition=charPos-activeQuery.start;return{query:activeQuery,relativePosition}}static extractQueries(text){return MultiQuerySplitter.split(text).getNonEmpty().map(q=>q.sql)}};function parseToPosition(sql,cursorPosition,options={}){return PositionAwareParser.parseToPosition(sql,cursorPosition,options)}function getCursorContext(sql,cursorPosition){return typeof cursorPosition=="number"?CursorContextAnalyzer.analyzeIntelliSense(sql,cursorPosition):CursorContextAnalyzer.analyzeIntelliSenseAt(sql,cursorPosition)}function resolveScope(sql,cursorPosition){return typeof cursorPosition=="number"?ScopeResolver.resolve(sql,cursorPosition):ScopeResolver.resolveAt(sql,cursorPosition)}function splitQueries(sql){return MultiQuerySplitter.split(sql)}function getIntelliSenseInfo(sql,cursorPosition,options={}){let charPos=typeof cursorPosition=="number"?cursorPosition:TextPositionUtils.lineColumnToCharOffset(sql,cursorPosition);if(charPos===-1)return;let activeQuery=splitQueries(sql).getActive(charPos);if(!activeQuery)return;let relativePosition=charPos-activeQuery.start,querySQL=activeQuery.sql,context=getCursorContext(querySQL,relativePosition),scope=resolveScope(querySQL,relativePosition),parseResult=parseToPosition(querySQL,relativePosition,options);return{context,scope,parseResult,currentQuery:querySQL,relativePosition}}function getCompletionSuggestions(sql,cursorPosition){let charPos=typeof cursorPosition=="number"?cursorPosition:TextPositionUtils.lineColumnToCharOffset(sql,cursorPosition);if(charPos===-1)return[];let intelliSenseContext=CursorContextAnalyzer.analyzeIntelliSense(sql,charPos),scope=resolveScope(sql,cursorPosition),suggestions=[];return intelliSenseContext.suggestKeywords&&(intelliSenseContext.requiredKeywords?intelliSenseContext.requiredKeywords.forEach(keyword=>{suggestions.push({type:"keyword",value:keyword,detail:`Required keyword: ${keyword}`})}):getGeneralKeywords(intelliSenseContext).forEach(keyword=>{suggestions.push({type:"keyword",value:keyword.value,detail:keyword.detail})})),intelliSenseContext.suggestTables&&(scope.availableTables.forEach(table=>{suggestions.push({type:"table",value:table.alias||table.name,detail:`Table: ${table.fullName}`,documentation:`Available table${table.alias?` (alias: ${table.alias})`:""}`})}),scope.availableCTEs.forEach(cte=>{suggestions.push({type:"cte",value:cte.name,detail:`CTE: ${cte.name}`,documentation:`Common Table Expression${cte.columns?` with columns: ${cte.columns.join(", ")}`:""}`})})),intelliSenseContext.suggestColumns&&(intelliSenseContext.tableScope?scope.visibleColumns.filter(col=>col.tableName===intelliSenseContext.tableScope||col.tableAlias===intelliSenseContext.tableScope).forEach(col=>{suggestions.push({type:"column",value:col.name,detail:`Column: ${col.fullReference}`,documentation:`Column from ${col.tableName}${col.type?` (${col.type})`:""}`})}):scope.visibleColumns.forEach(col=>{suggestions.push({type:"column",value:col.name==="*"?"*":`${col.tableAlias||col.tableName}.${col.name}`,detail:`Column: ${col.fullReference}`,documentation:`Column from ${col.tableName}`})})),suggestions}function getGeneralKeywords(context){let prevToken=context.previousToken?.value?.toLowerCase(),currentToken=context.currentToken?.value?.toLowerCase();return prevToken==="select"||currentToken==="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"}]:prevToken==="from"||currentToken==="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(prevToken||"")||["where","having","on"].includes(currentToken||"")?[{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{AliasRenamer,AlterTableAddConstraint,AlterTableDropColumn,AlterTableDropConstraint,AlterTableParser,AlterTableStatement,AnalyzeStatement,ArrayExpression,ArrayIndexExpression,ArrayQueryExpression,ArraySliceExpression,BetweenExpression,BinaryExpression,BinarySelectQuery,CTECollector,CTEComposer,CTEDependencyAnalyzer,CTEDisabler,CTENormalizer,CTENotFoundError,CTEQueryDecomposer,CTERegionDetector,CTERenamer,CTETableReferenceCollector,CaseExpression,CaseKeyValuePair,CastExpression,ColumnConstraintDefinition,ColumnReference,ColumnReferenceCollector,CommentEditor,CreateIndexParser,CreateIndexStatement,CreateTableParser,CreateTableQuery,CursorContextAnalyzer,DeleteQuery,DeleteQueryParser,DropConstraintParser,DropConstraintStatement,DropIndexParser,DropIndexStatement,DropTableParser,DropTableStatement,DuplicateCTEError,DuplicateDetectionMode,DynamicQueryBuilder,ExplainOption,ExplainStatement,FilterableItem,FilterableItemCollector,Formatter,FunctionCall,IdentifierString,IndexColumnDefinition,InlineQuery,InsertQuery,InsertQueryParser,InsertQuerySelectValuesConverter,InvalidCTENameError,JsonMappingConverter,JsonSchemaValidator,LexemeCursor,LiteralValue,MergeAction,MergeDeleteAction,MergeDoNothingAction,MergeInsertAction,MergeQuery,MergeQueryParser,MergeUpdateAction,MergeWhenClause,MultiQuerySplitter,MultiQueryUtils,OriginalFormatRestorer,ParameterExpression,ParenExpression,PositionAwareParser,PostgresJsonQueryBuilder,QualifiedName,QueryBuilder,QueryFlowDiagramGenerator,RawString,ReferenceDefinition,SchemaCollector,SchemaManager,ScopeResolver,SelectQueryParser,SelectValueCollector,SelectableColumnCollector,SimpleSelectQuery,SmartRenamer,SqlComponent,SqlDialectConfiguration,SqlFormatter,SqlIdentifierRenamer,SqlPaginationInjector,SqlParamInjector,SqlParser,SqlSchemaValidator,SqlSortInjector,StringSpecifierExpression,SwitchCaseArgument,TableColumnDefinition,TableConstraintDefinition,TableSchema,TableSourceCollector,TokenType,TupleExpression,TypeTransformationPostProcessor,TypeTransformers,TypeValue,UnaryExpression,UpdateQuery,UpdateQueryParser,UpstreamSelectQueryFinder,VALID_PRESETS,ValueList,ValuesQuery,WindowFrameBound,WindowFrameBoundStatic,WindowFrameBoundaryValue,WindowFrameExpression,WindowFrameSpec,WindowFrameType,WithClauseParser,convertColumnsToLegacy,convertModelDrivenMapping,convertToLegacyJsonMapping,createJsonMappingFromSchema,createSchemaManager,createTableColumnResolver,extractTypeProtection,getCompletionSuggestions,getCursorContext,getIntelliSenseInfo,isLegacyFormat,isModelDrivenFormat,isUnifiedFormat,parseToPosition,processJsonMapping,resolveScope,splitQueries,toLegacyMapping,transformDatabaseResult,unifyJsonMapping,validateModelDrivenMapping};
92
92
  //# sourceMappingURL=index.min.js.map