rawsql-ts 0.24.3 → 0.25.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 (105) hide show
  1. package/README.md +10 -1
  2. package/dist/esm/index.d.ts +6 -0
  3. package/dist/esm/index.js +6 -0
  4. package/dist/esm/index.js.map +1 -1
  5. package/dist/esm/index.min.js +9 -9
  6. package/dist/esm/index.min.js.map +4 -4
  7. package/dist/esm/models/ValueComponent.d.ts +2 -1
  8. package/dist/esm/models/ValueComponent.js +2 -1
  9. package/dist/esm/models/ValueComponent.js.map +1 -1
  10. package/dist/esm/parsers/FunctionExpressionParser.d.ts +3 -0
  11. package/dist/esm/parsers/FunctionExpressionParser.js +50 -2
  12. package/dist/esm/parsers/FunctionExpressionParser.js.map +1 -1
  13. package/dist/esm/parsers/ParameterDecorator.d.ts +2 -2
  14. package/dist/esm/parsers/ParameterDecorator.js +1 -1
  15. package/dist/esm/parsers/ParameterDecorator.js.map +1 -1
  16. package/dist/esm/parsers/ParameterExpressionParser.js +2 -1
  17. package/dist/esm/parsers/ParameterExpressionParser.js.map +1 -1
  18. package/dist/esm/parsers/SqlPrintTokenParser.d.ts +16 -4
  19. package/dist/esm/parsers/SqlPrintTokenParser.js +76 -13
  20. package/dist/esm/parsers/SqlPrintTokenParser.js.map +1 -1
  21. package/dist/esm/transformers/AstCommentAttachmentExtractor.d.ts +61 -0
  22. package/dist/esm/transformers/AstCommentAttachmentExtractor.js +221 -0
  23. package/dist/esm/transformers/AstCommentAttachmentExtractor.js.map +1 -0
  24. package/dist/esm/transformers/ClauseScopedColumnReferenceCollector.d.ts +47 -0
  25. package/dist/esm/transformers/ClauseScopedColumnReferenceCollector.js +235 -0
  26. package/dist/esm/transformers/ClauseScopedColumnReferenceCollector.js.map +1 -0
  27. package/dist/esm/transformers/FormatOptionResolver.js +1 -0
  28. package/dist/esm/transformers/FormatOptionResolver.js.map +1 -1
  29. package/dist/esm/transformers/LinePrinter.d.ts +1 -1
  30. package/dist/esm/transformers/NamedQueryDefinitionExtractor.d.ts +53 -0
  31. package/dist/esm/transformers/NamedQueryDefinitionExtractor.js +370 -0
  32. package/dist/esm/transformers/NamedQueryDefinitionExtractor.js.map +1 -0
  33. package/dist/esm/transformers/OnelineFormattingHelper.d.ts +1 -0
  34. package/dist/esm/transformers/OnelineFormattingHelper.js.map +1 -1
  35. package/dist/esm/transformers/SelectBodyExtractor.d.ts +21 -0
  36. package/dist/esm/transformers/SelectBodyExtractor.js +137 -0
  37. package/dist/esm/transformers/SelectBodyExtractor.js.map +1 -0
  38. package/dist/esm/transformers/SelectOutputCollector.d.ts +47 -0
  39. package/dist/esm/transformers/SelectOutputCollector.js +281 -0
  40. package/dist/esm/transformers/SelectOutputCollector.js.map +1 -0
  41. package/dist/esm/transformers/SelectValueCollector.d.ts +9 -1
  42. package/dist/esm/transformers/SelectValueCollector.js +83 -58
  43. package/dist/esm/transformers/SelectValueCollector.js.map +1 -1
  44. package/dist/esm/transformers/SqlFormatter.d.ts +9 -5
  45. package/dist/esm/transformers/SqlFormatter.js +4 -4
  46. package/dist/esm/transformers/SqlFormatter.js.map +1 -1
  47. package/dist/esm/transformers/SqlPrinter.d.ts +17 -2
  48. package/dist/esm/transformers/SqlPrinter.js +182 -21
  49. package/dist/esm/transformers/SqlPrinter.js.map +1 -1
  50. package/dist/esm/transformers/WildcardColumnInferenceCollector.d.ts +129 -0
  51. package/dist/esm/transformers/WildcardColumnInferenceCollector.js +373 -0
  52. package/dist/esm/transformers/WildcardColumnInferenceCollector.js.map +1 -0
  53. package/dist/index.js +6 -0
  54. package/dist/index.js.map +1 -1
  55. package/dist/index.min.js +9 -9
  56. package/dist/index.min.js.map +4 -4
  57. package/dist/models/ValueComponent.js +2 -1
  58. package/dist/models/ValueComponent.js.map +1 -1
  59. package/dist/parsers/FunctionExpressionParser.js +49 -1
  60. package/dist/parsers/FunctionExpressionParser.js.map +1 -1
  61. package/dist/parsers/ParameterDecorator.js +1 -1
  62. package/dist/parsers/ParameterDecorator.js.map +1 -1
  63. package/dist/parsers/ParameterExpressionParser.js +2 -1
  64. package/dist/parsers/ParameterExpressionParser.js.map +1 -1
  65. package/dist/parsers/SqlPrintTokenParser.js +76 -13
  66. package/dist/parsers/SqlPrintTokenParser.js.map +1 -1
  67. package/dist/src/index.d.ts +6 -0
  68. package/dist/src/models/ValueComponent.d.ts +2 -1
  69. package/dist/src/parsers/FunctionExpressionParser.d.ts +3 -0
  70. package/dist/src/parsers/ParameterDecorator.d.ts +2 -2
  71. package/dist/src/parsers/SqlPrintTokenParser.d.ts +16 -4
  72. package/dist/src/transformers/AstCommentAttachmentExtractor.d.ts +61 -0
  73. package/dist/src/transformers/ClauseScopedColumnReferenceCollector.d.ts +47 -0
  74. package/dist/src/transformers/LinePrinter.d.ts +1 -1
  75. package/dist/src/transformers/NamedQueryDefinitionExtractor.d.ts +53 -0
  76. package/dist/src/transformers/OnelineFormattingHelper.d.ts +1 -0
  77. package/dist/src/transformers/SelectBodyExtractor.d.ts +21 -0
  78. package/dist/src/transformers/SelectOutputCollector.d.ts +47 -0
  79. package/dist/src/transformers/SelectValueCollector.d.ts +9 -1
  80. package/dist/src/transformers/SqlFormatter.d.ts +9 -5
  81. package/dist/src/transformers/SqlPrinter.d.ts +17 -2
  82. package/dist/src/transformers/WildcardColumnInferenceCollector.d.ts +129 -0
  83. package/dist/transformers/AstCommentAttachmentExtractor.js +231 -0
  84. package/dist/transformers/AstCommentAttachmentExtractor.js.map +1 -0
  85. package/dist/transformers/ClauseScopedColumnReferenceCollector.js +239 -0
  86. package/dist/transformers/ClauseScopedColumnReferenceCollector.js.map +1 -0
  87. package/dist/transformers/FormatOptionResolver.js +1 -0
  88. package/dist/transformers/FormatOptionResolver.js.map +1 -1
  89. package/dist/transformers/NamedQueryDefinitionExtractor.js +374 -0
  90. package/dist/transformers/NamedQueryDefinitionExtractor.js.map +1 -0
  91. package/dist/transformers/OnelineFormattingHelper.js.map +1 -1
  92. package/dist/transformers/SelectBodyExtractor.js +141 -0
  93. package/dist/transformers/SelectBodyExtractor.js.map +1 -0
  94. package/dist/transformers/SelectOutputCollector.js +291 -0
  95. package/dist/transformers/SelectOutputCollector.js.map +1 -0
  96. package/dist/transformers/SelectValueCollector.js +83 -58
  97. package/dist/transformers/SelectValueCollector.js.map +1 -1
  98. package/dist/transformers/SqlFormatter.js +5 -3
  99. package/dist/transformers/SqlFormatter.js.map +1 -1
  100. package/dist/transformers/SqlPrinter.js +182 -21
  101. package/dist/transformers/SqlPrinter.js.map +1 -1
  102. package/dist/transformers/WildcardColumnInferenceCollector.js +377 -0
  103. package/dist/transformers/WildcardColumnInferenceCollector.js.map +1 -0
  104. package/dist/tsconfig.browser.tsbuildinfo +1 -1
  105. package/package.json +2 -2
@@ -7,27 +7,27 @@ ${this.getDebugPositionInfo(start)}`);return this.position++,this.input.slice(st
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==="'"){if(this.canRead()&&this.input[this.position]==="'"){this.position++;continue}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 trie2=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"]]),keywordParser2=new KeywordParser(trie2),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=keywordParser2.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()||char==="$"&&looksLikeSqlServerMoneyLiteral(this.input,this.position))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 trie3=new KeywordTrie([["grouping","sets"],["array"]]),keywordParser3=new KeywordParser(trie3),FunctionTokenReader=class extends BaseTokenReader{tryReadDialectSpecificToken(_previous){return null}tryRead(previous){if(this.isEndOfInput())return null;let dialectToken=this.tryReadDialectSpecificToken(previous);if(dialectToken)return dialectToken;let keyword=keywordParser3.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 PostgresFunctionTokenReader=class extends FunctionTokenReader{tryReadDialectSpecificToken(_previous){return this.input.slice(this.position,this.position+6).toLowerCase()!=="array["?null:(this.position+=5,this.createLexeme(2048,"array"))}};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 QUOTE_CHAR_CODE=39,AMPERSAND_CHAR_CODE=38,StringSpecifierTokenReader=class extends BaseTokenReader{tryRead(previous){let start=this.position;if(!this.canRead(1))return null;let firstCode=this.input.charCodeAt(start),secondCode=this.input.charCodeAt(start+1);return secondCode===QUOTE_CHAR_CODE&&this.isSingleLetterStringPrefix(firstCode)?(this.position=start+1,this.createLexeme(4096,this.input[start])):this.canRead(2)&&this.isUnicodePrefix(firstCode)&&secondCode===AMPERSAND_CHAR_CODE&&this.input.charCodeAt(start+2)===QUOTE_CHAR_CODE?(this.position=start+2,this.createLexeme(4096,this.input.slice(start,start+2))):null}isSingleLetterStringPrefix(charCode){return charCode===69||charCode===101||charCode===88||charCode===120||charCode===66||charCode===98}isUnicodePrefix(charCode){return charCode===85||charCode===117}};var TokenReaderManager=class{constructor(input,position=0){this.input=input,this.position=position,this.readers=[]}register(reader){return this.readers.push(reader),this}registerAll(readers){for(let i=0;i<readers.length;i++)this.readers.push(readers[i]);return this}tryRead(position,previous){this.position=position;let readers=this.readers;for(let i=0;i<readers.length;i++){let reader=readers[i];reader.setPosition(position);let lexeme=reader.tryRead(previous);if(lexeme)return this.position=reader.getPosition(),lexeme}return null}getMaxPosition(){return this.position}getInput(){return this.input}getCacheStats(){return{hits:0,misses:0,ratio:0}}};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 SELECT_LIST_MODIFIER_VALUES=new Set(["all","distinct","distinct on","top"]),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 PostgresFunctionTokenReader(input)).register(new IdentifierTokenReader(input))}isEndOfInput(shift=0){return this.position+shift>=this.input.length}canRead(shift=0){return!this.isEndOfInput(shift)}isSelectListModifier(lexeme){return SELECT_LIST_MODIFIER_VALUES.has(lexeme.value.toLowerCase())}isMeaningfulSelectItemToken(lexeme){let isSelectableOperator=(lexeme.type&2)!==0&&(lexeme.value==="*"||lexeme.value==="exists");return(lexeme.type&64)!==0||(lexeme.type&1)!==0||isSelectableOperator?!0:(lexeme.type&128)!==0?!this.isSelectListModifier(lexeme):(lexeme.type&16)===0&&(lexeme.type&2)===0}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.hasCommentMetadata(tokenData)?this.buildLexemesFromTokenData(tokenData):this.extractLexemes(tokenData),nextPosition=this.skipPastTerminator(statementEnd);return{lexemes,statementStart,statementEnd,nextPosition,rawText:this.input.slice(statementStart,statementEnd),leadingComments:pendingLeading}}hasCommentMetadata(tokenData){for(let i=0;i<tokenData.length;i++){let token=tokenData[i];if(token.prefixComments&&token.prefixComments.length>0||token.suffixComments&&token.suffixComments.length>0||token.lexeme.comments&&token.lexeme.comments.length>0||token.lexeme.positionedComments&&token.lexeme.positionedComments.length>0)return!0}return!1}extractLexemes(tokenData){let lexemes=new Array(tokenData.length),resolveLineColumn=this.createOrderedLineColumnResolver();for(let i=0;i<tokenData.length;i++){let token=tokenData[i],lexeme=token.lexeme,startInfo=resolveLineColumn(token.startPos),endInfo=resolveLineColumn(token.endPos);lexeme.position={startPosition:token.startPos,endPosition:token.endPos,startLine:startInfo.line,startColumn:startInfo.column,endLine:endInfo.line,endColumn:endInfo.column},lexemes[i]=lexeme}return lexemes}buildLexemesFromTokenData(tokenData){let lexemes=new Array(tokenData.length),resolveLineColumn=this.createOrderedLineColumnResolver(),hasPositionedComments=!1;for(let i=0;i<tokenData.length;i++){let current=tokenData[i],lexeme=current.lexeme,lexemeValue=lexeme.value;if(current.suffixComments&&current.suffixComments.length>0){if(lexemeValue==="select"){let suffixComments=current.suffixComments,targetIndex=i+1;for(;targetIndex<tokenData.length;){let target=tokenData[targetIndex];if(this.isMeaningfulSelectItemToken(target.lexeme)){target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null;break}targetIndex++}}if(lexemeValue==="from"){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){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(current.suffixComments){let normalized=lexemeValue.toLowerCase();if(normalized==="union"||normalized==="intersect"||normalized==="except"){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);let startInfo=resolveLineColumn(current.startPos),endInfo=resolveLineColumn(current.endPos);lexeme.position={startPosition:current.startPos,endPosition:current.endPos,startLine:startInfo.line,startColumn:startInfo.column,endLine:endInfo.line,endColumn:endInfo.column},lexeme.positionedComments&&lexeme.positionedComments.length>0&&(hasPositionedComments=!0),lexemes[i]=lexeme}return hasPositionedComments&&this.relocateOrderByComments(lexemes),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}relocateOrderByComments(lexemes){for(let i=0;i<lexemes.length-1;i++){let current=lexemes[i];if(current.value.toLowerCase()!=="order by"||!current.positionedComments)continue;let afterComments=current.positionedComments.filter(comment=>comment.position==="after"&&comment.comments&&comment.comments.length>0);if(afterComments.length===0)continue;current.positionedComments=current.positionedComments.filter(comment=>comment.position!=="after"),current.positionedComments.length===0&&(current.positionedComments=void 0);let target=lexemes[i+1],beforeComments=afterComments.map(comment=>({position:"before",comments:[...comment.comments]}));target.positionedComments&&target.positionedComments.length>0?target.positionedComments=[...beforeComments,...target.positionedComments]:target.positionedComments=beforeComments}}attachCommentsToLexeme(lexeme,tokenData){let newPositionedComments=[],existingLegacyComments=[],allLegacyComments=[];lexeme.positionedComments&&lexeme.positionedComments.length>0&&newPositionedComments.push(...lexeme.positionedComments),lexeme.comments&&lexeme.comments.length>0&&(existingLegacyComments.push(...lexeme.comments),allLegacyComments.push(...lexeme.comments)),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=existingLegacyComments.length>0?existingLegacyComments:null):allLegacyComments.length>0?(lexeme.comments=allLegacyComments,lexeme.positionedComments=void 0):(lexeme.comments=null,lexeme.positionedComments=void 0)}readComment(){let pos=this.position,inputLength=this.input.length;if(pos>=inputLength)return{position:pos,lines:null};let code=this.input.charCodeAt(pos);if(code!==32&&code!==9&&code!==10&&code!==13)if(code===45){if(pos+1>=inputLength||this.input.charCodeAt(pos+1)!==45)return{position:pos,lines:null}}else if(code===47){if(pos+1>=inputLength||this.input.charCodeAt(pos+1)!==42)return{position:pos,lines:null}}else return{position:pos,lines:null};return StringUtils.readWhiteSpaceAndComment(this.input,pos)}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}}createOrderedLineColumnResolver(){let starts=this.ensureLineStartPositions(),lineIndex=0;return position=>{for(;lineIndex+1<starts.length&&starts[lineIndex+1]<=position;)lineIndex++;let 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(formatter2){return this.accept(formatter2)}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.insertClause=params.insertClause,this.selectQuery=params.selectQuery??null,this.onConflictClause=params.onConflict??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,filterCondition=null,nullsTreatment=null){super(),this.qualifiedName=new QualifiedName(namespaces,name),this.argument=argument,this.over=over,this.nullsTreatment=nullsTreatment,this.withinGroup=withinGroup,this.withOrdinality=withOrdinality,this.internalOrderBy=internalOrderBy,this.filterCondition=filterCondition}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}},JsonPredicateExpression=class extends SqlComponent{static{this.kind=Symbol("JsonPredicateExpression")}constructor(expression,negated,jsonType=null,uniqueKeys=null){super(),this.expression=expression,this.negated=negated,this.jsonType=jsonType,this.uniqueKeys=uniqueKeys}},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}},SortDirection=(SortDirection2=>(SortDirection2.Ascending="asc",SortDirection2.Descending="desc",SortDirection2))(SortDirection||{}),NullsSortDirection=(NullsSortDirection2=>(NullsSortDirection2.First="first",NullsSortDirection2.Last="last",NullsSortDirection2))(NullsSortDirection||{}),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,mode=null){super(),this.mode=mode,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,withOrdinality=!1){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,this.withOrdinality=withOrdinality}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}},FetchType=(FetchType2=>(FetchType2.Next="next",FetchType2.First="first",FetchType2))(FetchType||{}),FetchUnit=(FetchUnit2=>(FetchUnit2.RowsOnly="rows only",FetchUnit2.Percent="percent",FetchUnit2.PercentWithTies="percent with ties",FetchUnit2))(FetchUnit||{}),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}},LockMode=(LockMode2=>(LockMode2.Update="update",LockMode2.Share="share",LockMode2.KeyShare="key share",LockMode2.NokeyUpdate="no key update",LockMode2))(LockMode||{}),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}},ReturningAlias=class extends SqlComponent{static{this.kind=Symbol("ReturningAlias")}constructor(kind,alias){super(),this.kind=kind,this.alias=typeof alias=="string"?new IdentifierString(alias):alias}},ReturningClause=class extends SqlComponent{static{this.kind=Symbol("ReturningClause")}constructor(items,aliases=[]){super(),this.items=items,this.aliases=aliases}get columns(){return this.items.map(item=>item.value instanceof ColumnReference?item.value.column:new IdentifierString(item.identifier?.name??""))}},OnConflictClause=class extends SqlComponent{static{this.kind=Symbol("OnConflictClause")}constructor(params){super(),this.target=typeof params.target=="string"?new RawString(params.target):params.target??null,this.targetKind=params.targetKind??null,this.action=params.action,this.setClause=params.setClause??null,this.forClause=params.forClause??null,this.whereClause=params.whereClause??null}},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 POSTGRESQL_COMMAND_KEYWORDS_ALLOWED_AS_IDENTIFIER=new Set(["groups","rows","range","window","over","following","preceding","within","ordinality","lateral","recursive","materialized","partition"]),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]),(!identifierString.positionedComments||identifierString.positionedComments.length===0)&&lastLexeme.comments&&lastLexeme.comments.length>0&&(identifierString.comments=[...lastLexeme.comments])}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].type&1&&SQL_SPECIAL_VALUE_KEYWORD_SET.has(lexemes[idx].value.toLowerCase()))identifiers.push(lexemes[idx].value),idx++;else if(lexemes[idx].type&128&&POSTGRESQL_COMMAND_KEYWORDS_ALLOWED_AS_IDENTIFIER.has(lexemes[idx].value.toLowerCase()))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,commentPayload=this.splitCaseWhenKeywordComments(caseWhenKeywordComments,caseWhenKeywordPositionedComments),casewhenResult=this.parseCaseConditionValuePair(lexemes,idx);idx=casewhenResult.newIndex,this.addPositionedComments(casewhenResult.value,commentPayload.firstWhenPositioned);let caseWhenList=[casewhenResult.value],switchCaseResult=this.parseSwitchCaseArgument(lexemes,idx,caseWhenList);idx=switchCaseResult.newIndex;let result=new CaseExpression(null,switchCaseResult.value);return commentPayload.caseExpressionPositioned&&commentPayload.caseExpressionPositioned.length>0?result.positionedComments=commentPayload.caseExpressionPositioned:commentPayload.firstWhenPositioned&&commentPayload.firstWhenPositioned.length>0?result.positionedComments=[]:commentPayload.legacyCaseExpression&&commentPayload.legacyCaseExpression.length>0&&(result.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(commentPayload.legacyCaseExpression,"before")]),{value:result,newIndex:idx}}static splitCaseWhenKeywordComments(caseWhenKeywordComments,caseWhenKeywordPositionedComments){if(!caseWhenKeywordPositionedComments||caseWhenKeywordPositionedComments.length===0)return{caseExpressionPositioned:null,firstWhenPositioned:null,legacyCaseExpression:caseWhenKeywordComments??null};let caseExpressionPositioned=[],firstWhenPositioned=[];for(let comment of caseWhenKeywordPositionedComments)comment.position==="after"?firstWhenPositioned.push({position:"before",comments:[...comment.comments]}):caseExpressionPositioned.push({position:comment.position,comments:[...comment.comments]});return{caseExpressionPositioned:caseExpressionPositioned.length>0?caseExpressionPositioned:null,firstWhenPositioned:firstWhenPositioned.length>0?firstWhenPositioned:null,legacyCaseExpression:null}}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 addPositionedComments(target,comments){!comments||comments.length===0||(target.positionedComments=[...target.positionedComments??[],...comments])}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 appendUniqueComments(target,comments){if(!comments||comments.length===0)return target;let merged=target?[...target]:[];for(let comment of comments)merged.includes(comment)||merged.push(comment);return merged}static collectLexemeComments(token){let comments=null;if(token.positionedComments&&token.positionedComments.length>0)for(let posComment of token.positionedComments)comments=this.appendUniqueComments(comments,posComment.comments);return comments=this.appendUniqueComments(comments,token.comments),comments}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 orderByItemComments=null,sortDirection=null;if(idx<lexemes.length){let token=lexemes[idx];token.value==="asc"?(sortDirection="asc",idx++):token.value==="desc"&&(sortDirection="desc",idx++),sortDirection!==null&&(orderByItemComments=this.appendUniqueComments(orderByItemComments,this.collectLexemeComments(token)))}let nullsSortDirection=null;if(idx<lexemes.length){let token=lexemes[idx];token.value==="nulls first"?(nullsSortDirection="first",idx++):token.value==="nulls last"&&(nullsSortDirection="last",idx++),nullsSortDirection!==null&&(orderByItemComments=this.appendUniqueComments(orderByItemComments,this.collectLexemeComments(token)))}if(sortDirection===null&&nullsSortDirection===null)return{value,newIndex:idx};let item=new OrderByItem(value,sortDirection,nullsSortDirection);return orderByItemComments&&orderByItemComments.length>0&&(item.comments=orderByItemComments),{value:item,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.hasCommentMetadata(tokenData)?this.buildLexemesFromTokenData(tokenData):this.extractLexemes(tokenData),nextPosition=this.skipPastTerminator(statementEnd);return{lexemes,statementStart,statementEnd,nextPosition,rawText:this.input.slice(statementStart,statementEnd),leadingComments:pendingLeading}}hasCommentMetadata(tokenData){for(let i=0;i<tokenData.length;i++){let token=tokenData[i];if(token.prefixComments&&token.prefixComments.length>0||token.suffixComments&&token.suffixComments.length>0||token.lexeme.comments&&token.lexeme.comments.length>0||token.lexeme.positionedComments&&token.lexeme.positionedComments.length>0)return!0}return!1}extractLexemes(tokenData){let lexemes=new Array(tokenData.length),resolveLineColumn=this.createOrderedLineColumnResolver();for(let i=0;i<tokenData.length;i++){let token=tokenData[i],lexeme=token.lexeme,startInfo=resolveLineColumn(token.startPos),endInfo=resolveLineColumn(token.endPos);lexeme.position={startPosition:token.startPos,endPosition:token.endPos,startLine:startInfo.line,startColumn:startInfo.column,endLine:endInfo.line,endColumn:endInfo.column},lexemes[i]=lexeme}return lexemes}buildLexemesFromTokenData(tokenData){let lexemes=new Array(tokenData.length),resolveLineColumn=this.createOrderedLineColumnResolver(),hasPositionedComments=!1;for(let i=0;i<tokenData.length;i++){let current=tokenData[i],lexeme=current.lexeme,lexemeValue=lexeme.value;if(current.suffixComments&&current.suffixComments.length>0){if(lexemeValue==="select"){let suffixComments=current.suffixComments,targetIndex=i+1;for(;targetIndex<tokenData.length;){let target=tokenData[targetIndex];if(this.isMeaningfulSelectItemToken(target.lexeme)){target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null;break}targetIndex++}}if(lexemeValue==="from"){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){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(current.suffixComments){let normalized=lexemeValue.toLowerCase();if(normalized==="union"||normalized==="intersect"||normalized==="except"){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);let startInfo=resolveLineColumn(current.startPos),endInfo=resolveLineColumn(current.endPos);lexeme.position={startPosition:current.startPos,endPosition:current.endPos,startLine:startInfo.line,startColumn:startInfo.column,endLine:endInfo.line,endColumn:endInfo.column},lexeme.positionedComments&&lexeme.positionedComments.length>0&&(hasPositionedComments=!0),lexemes[i]=lexeme}return hasPositionedComments&&this.relocateOrderByComments(lexemes),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}relocateOrderByComments(lexemes){for(let i=0;i<lexemes.length-1;i++){let current=lexemes[i];if(current.value.toLowerCase()!=="order by"||!current.positionedComments)continue;let afterComments=current.positionedComments.filter(comment=>comment.position==="after"&&comment.comments&&comment.comments.length>0);if(afterComments.length===0)continue;current.positionedComments=current.positionedComments.filter(comment=>comment.position!=="after"),current.positionedComments.length===0&&(current.positionedComments=void 0);let target=lexemes[i+1],beforeComments=afterComments.map(comment=>({position:"before",comments:[...comment.comments]}));target.positionedComments&&target.positionedComments.length>0?target.positionedComments=[...beforeComments,...target.positionedComments]:target.positionedComments=beforeComments}}attachCommentsToLexeme(lexeme,tokenData){let newPositionedComments=[],existingLegacyComments=[],allLegacyComments=[];lexeme.positionedComments&&lexeme.positionedComments.length>0&&newPositionedComments.push(...lexeme.positionedComments),lexeme.comments&&lexeme.comments.length>0&&(existingLegacyComments.push(...lexeme.comments),allLegacyComments.push(...lexeme.comments)),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=existingLegacyComments.length>0?existingLegacyComments:null):allLegacyComments.length>0?(lexeme.comments=allLegacyComments,lexeme.positionedComments=void 0):(lexeme.comments=null,lexeme.positionedComments=void 0)}readComment(){let pos=this.position,inputLength=this.input.length;if(pos>=inputLength)return{position:pos,lines:null};let code=this.input.charCodeAt(pos);if(code!==32&&code!==9&&code!==10&&code!==13)if(code===45){if(pos+1>=inputLength||this.input.charCodeAt(pos+1)!==45)return{position:pos,lines:null}}else if(code===47){if(pos+1>=inputLength||this.input.charCodeAt(pos+1)!==42)return{position:pos,lines:null}}else return{position:pos,lines:null};return StringUtils.readWhiteSpaceAndComment(this.input,pos)}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}}createOrderedLineColumnResolver(){let starts=this.ensureLineStartPositions(),lineIndex=0;return position=>{for(;lineIndex+1<starts.length&&starts[lineIndex+1]<=position;)lineIndex++;let 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(formatter2){return this.accept(formatter2)}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.insertClause=params.insertClause,this.selectQuery=params.selectQuery??null,this.onConflictClause=params.onConflict??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,filterCondition=null,nullsTreatment=null){super(),this.qualifiedName=new QualifiedName(namespaces,name),this.argument=argument,this.over=over,this.nullsTreatment=nullsTreatment,this.withinGroup=withinGroup,this.withOrdinality=withOrdinality,this.internalOrderBy=internalOrderBy,this.filterCondition=filterCondition}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,sourceText=null){super(),this.name=new RawString(name),this.value=value,this.sourceText=sourceText,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}},JsonPredicateExpression=class extends SqlComponent{static{this.kind=Symbol("JsonPredicateExpression")}constructor(expression,negated,jsonType=null,uniqueKeys=null){super(),this.expression=expression,this.negated=negated,this.jsonType=jsonType,this.uniqueKeys=uniqueKeys}},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}},SortDirection=(SortDirection2=>(SortDirection2.Ascending="asc",SortDirection2.Descending="desc",SortDirection2))(SortDirection||{}),NullsSortDirection=(NullsSortDirection2=>(NullsSortDirection2.First="first",NullsSortDirection2.Last="last",NullsSortDirection2))(NullsSortDirection||{}),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,mode=null){super(),this.mode=mode,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,withOrdinality=!1){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,this.withOrdinality=withOrdinality}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}},FetchType=(FetchType2=>(FetchType2.Next="next",FetchType2.First="first",FetchType2))(FetchType||{}),FetchUnit=(FetchUnit2=>(FetchUnit2.RowsOnly="rows only",FetchUnit2.Percent="percent",FetchUnit2.PercentWithTies="percent with ties",FetchUnit2))(FetchUnit||{}),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}},LockMode=(LockMode2=>(LockMode2.Update="update",LockMode2.Share="share",LockMode2.KeyShare="key share",LockMode2.NokeyUpdate="no key update",LockMode2))(LockMode||{}),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}},ReturningAlias=class extends SqlComponent{static{this.kind=Symbol("ReturningAlias")}constructor(kind,alias){super(),this.kind=kind,this.alias=typeof alias=="string"?new IdentifierString(alias):alias}},ReturningClause=class extends SqlComponent{static{this.kind=Symbol("ReturningClause")}constructor(items,aliases=[]){super(),this.items=items,this.aliases=aliases}get columns(){return this.items.map(item=>item.value instanceof ColumnReference?item.value.column:new IdentifierString(item.identifier?.name??""))}},OnConflictClause=class extends SqlComponent{static{this.kind=Symbol("OnConflictClause")}constructor(params){super(),this.target=typeof params.target=="string"?new RawString(params.target):params.target??null,this.targetKind=params.targetKind??null,this.action=params.action,this.setClause=params.setClause??null,this.forClause=params.forClause??null,this.whereClause=params.whereClause??null}},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 POSTGRESQL_COMMAND_KEYWORDS_ALLOWED_AS_IDENTIFIER=new Set(["groups","rows","range","window","over","following","preceding","within","ordinality","lateral","recursive","materialized","partition"]),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]),(!identifierString.positionedComments||identifierString.positionedComments.length===0)&&lastLexeme.comments&&lastLexeme.comments.length>0&&(identifierString.comments=[...lastLexeme.comments])}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].type&1&&SQL_SPECIAL_VALUE_KEYWORD_SET.has(lexemes[idx].value.toLowerCase()))identifiers.push(lexemes[idx].value),idx++;else if(lexemes[idx].type&128&&POSTGRESQL_COMMAND_KEYWORDS_ALLOWED_AS_IDENTIFIER.has(lexemes[idx].value.toLowerCase()))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,sourceText=paramName;paramName.startsWith("${")&&paramName.endsWith("}")?paramName=paramName.slice(2,-1):paramName=paramName.slice(1);let value=new ParameterExpression(paramName,null,sourceText);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,commentPayload=this.splitCaseWhenKeywordComments(caseWhenKeywordComments,caseWhenKeywordPositionedComments),casewhenResult=this.parseCaseConditionValuePair(lexemes,idx);idx=casewhenResult.newIndex,this.addPositionedComments(casewhenResult.value,commentPayload.firstWhenPositioned);let caseWhenList=[casewhenResult.value],switchCaseResult=this.parseSwitchCaseArgument(lexemes,idx,caseWhenList);idx=switchCaseResult.newIndex;let result=new CaseExpression(null,switchCaseResult.value);return commentPayload.caseExpressionPositioned&&commentPayload.caseExpressionPositioned.length>0?result.positionedComments=commentPayload.caseExpressionPositioned:commentPayload.firstWhenPositioned&&commentPayload.firstWhenPositioned.length>0?result.positionedComments=[]:commentPayload.legacyCaseExpression&&commentPayload.legacyCaseExpression.length>0&&(result.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(commentPayload.legacyCaseExpression,"before")]),{value:result,newIndex:idx}}static splitCaseWhenKeywordComments(caseWhenKeywordComments,caseWhenKeywordPositionedComments){if(!caseWhenKeywordPositionedComments||caseWhenKeywordPositionedComments.length===0)return{caseExpressionPositioned:null,firstWhenPositioned:null,legacyCaseExpression:caseWhenKeywordComments??null};let caseExpressionPositioned=[],firstWhenPositioned=[];for(let comment of caseWhenKeywordPositionedComments)comment.position==="after"?firstWhenPositioned.push({position:"before",comments:[...comment.comments]}):caseExpressionPositioned.push({position:comment.position,comments:[...comment.comments]});return{caseExpressionPositioned:caseExpressionPositioned.length>0?caseExpressionPositioned:null,firstWhenPositioned:firstWhenPositioned.length>0?firstWhenPositioned:null,legacyCaseExpression:null}}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 addPositionedComments(target,comments){!comments||comments.length===0||(target.positionedComments=[...target.positionedComments??[],...comments])}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 appendUniqueComments(target,comments){if(!comments||comments.length===0)return target;let merged=target?[...target]:[];for(let comment of comments)merged.includes(comment)||merged.push(comment);return merged}static collectLexemeComments(token){let comments=null;if(token.positionedComments&&token.positionedComments.length>0)for(let posComment of token.positionedComments)comments=this.appendUniqueComments(comments,posComment.comments);return comments=this.appendUniqueComments(comments,token.comments),comments}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 orderByItemComments=null,sortDirection=null;if(idx<lexemes.length){let token=lexemes[idx];token.value==="asc"?(sortDirection="asc",idx++):token.value==="desc"&&(sortDirection="desc",idx++),sortDirection!==null&&(orderByItemComments=this.appendUniqueComments(orderByItemComments,this.collectLexemeComments(token)))}let nullsSortDirection=null;if(idx<lexemes.length){let token=lexemes[idx];token.value==="nulls first"?(nullsSortDirection="first",idx++):token.value==="nulls last"&&(nullsSortDirection="last",idx++),nullsSortDirection!==null&&(orderByItemComments=this.appendUniqueComments(orderByItemComments,this.collectLexemeComments(token)))}if(sortDirection===null&&nullsSortDirection===null)return{value,newIndex:idx};let item=new OrderByItem(value,sortDirection,nullsSortDirection);return orderByItemComments&&orderByItemComments.length>0&&(item.comments=orderByItemComments),{value:item,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 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 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{this.SQL_JSON_CONSTRUCTORS=new Set(["json_array","json_object","json_scalar","json_serialize"])}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.SQL_JSON_CONSTRUCTORS.has(functionName)){let result=this.parseRawFunctionArguments(lexemes,idx);arg={value:result.argument,newIndex:result.newIndex},closingComments=result.closingComments}else 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 filterCondition=null;if(idx<lexemes.length&&lexemes[idx].value==="filter"){let filterResult=this.parseFilterClause(lexemes,idx);filterCondition=filterResult.condition,idx=filterResult.newIndex}let withOrdinality=!1;idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++);let nullsTreatment=this.parseNullsTreatment(lexemes,idx);if(idx=nullsTreatment.newIndex,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,filterCondition,nullsTreatment.value);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,filterCondition,nullsTreatment.value);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 parseRawFunctionArguments(lexemes,index){let idx=index;if(idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected opening parenthesis.");let contentStart=idx+1,depth=1;for(idx++;idx<lexemes.length&&depth>0;){if(lexemes[idx].type&4?depth++:lexemes[idx].type&8&&depth--,depth===0){let closingComments=this.getClosingComments(lexemes[idx]),rawText=joinLexemeValues(lexemes,contentStart,idx);return idx++,{argument:rawText.length>0?new RawString(rawText):new ValueList([]),closingComments,newIndex:idx}}idx++}throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis.")}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;idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++);let nullsTreatment=this.parseNullsTreatment(lexemes,idx);if(idx=nullsTreatment.newIndex,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,null,nullsTreatment.value),newIndex:idx}}else return{value:new FunctionCall(namespaces,name.name,arg,null,withinGroup,withOrdinality,null,null,nullsTreatment.value),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 parseNullsTreatment(lexemes,index){let value=lexemes[index]?.value;return value==="ignore nulls"||value==="respect nulls"?{value,newIndex:index+1}:{value:null,newIndex:index}}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 parseFilterClause(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].value!=="filter")throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected 'FILTER' keyword.");if(idx++,idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected '(' after FILTER.");if(idx++,idx>=lexemes.length||lexemes[idx].value!=="where")throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected 'WHERE' inside FILTER clause.");idx++;let conditionResult=ValueParser.parseFromLexeme(lexemes,idx);if(idx=conditionResult.newIndex,idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected ')' after FILTER predicate.");return idx++,{condition:conditionResult.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,"||":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 jsonPredicate=this.tryParseJsonPredicate(lexemes,idx,result);if(jsonPredicate){result=jsonPredicate.value,idx=jsonPredicate.newIndex;continue}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 tryParseJsonPredicate(lexemes,index,expression){let operator=lexemes[index]?.value?.toLowerCase();if(operator!=="is"&&operator!=="is not")return null;let idx=index+1;if(idx>=lexemes.length||lexemes[idx].value.toLowerCase()!=="json")return null;idx++;let jsonType=null,typeCandidate=lexemes[idx]?.value?.toLowerCase();(typeCandidate==="value"||typeCandidate==="scalar"||typeCandidate==="array"||typeCandidate==="object")&&(jsonType=typeCandidate,idx++);let uniqueKeys=null,uniqueCandidate=lexemes[idx]?.value?.toLowerCase();if(uniqueCandidate==="with"||uniqueCandidate==="without"){let uniqueToken=lexemes[idx+1]?.value?.toLowerCase(),keysToken=lexemes[idx+2]?.value?.toLowerCase();uniqueToken==="unique"&&keysToken==="keys"&&(uniqueKeys=uniqueCandidate,idx+=3)}return{value:new JsonPredicateExpression(expression,operator==="is not",jsonType,uniqueKeys),newIndex:idx}}static transferPositionedComments(lexeme,value){if(lexeme.positionedComments&&lexeme.positionedComments.length>0){let beforeComments=lexeme.positionedComments.filter(comment=>comment.position==="before"),afterComments=lexeme.positionedComments.filter(comment=>comment.position==="after");if(beforeComments.length>0){let clonedBefore=beforeComments.map(comment=>({position:comment.position,comments:[...comment.comments]}));value.positionedComments=value.positionedComments?[...clonedBefore,...value.positionedComments]:clonedBefore}if(afterComments.length>0){let clonedAfter=afterComments.map(comment=>({position:comment.position,comments:[...comment.comments]}));value.positionedComments=value.positionedComments?[...value.positionedComments,...clonedAfter]:clonedAfter}!beforeComments.length&&!afterComments.length&&!value.positionedComments&&(value.positionedComments=lexeme.positionedComments.map(comment=>({position:comment.position,comments:[...comment.comments]})));return}else 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&&this.isQualifiedSpecialValueIdentifier(lexemes,idx)){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx),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 isQualifiedSpecialValueIdentifier(lexemes,index){return SQL_SPECIAL_VALUE_KEYWORD_SET.has(lexemes[index].value.toLowerCase())&&index+1<lexemes.length&&(lexemes[index+1].type&32)!==0}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 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 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,this.returningClause=params.returningClause??null}};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(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(MergeQuery.kind,expr=>this.visitMergeQuery(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(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(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)}visitInsertQuery(query){query.selectQuery&&query.selectQuery.accept(this)}visitUpdateQuery(query){query.withClause&&query.withClause.accept(this),query.updateClause.source.accept(this),query.setClause.items.forEach(item=>item.value.accept(this)),query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.returningClause&&this.visitReturningClause(query.returningClause)}visitDeleteQuery(query){query.withClause&&query.withClause.accept(this),query.deleteClause.source.accept(this),query.usingClause&&query.usingClause.sources.forEach(source=>source.accept(this)),query.whereClause&&query.whereClause.accept(this),query.returningClause&&this.visitReturningClause(query.returningClause)}visitMergeQuery(query){query.withClause&&query.withClause.accept(this),query.target.accept(this),query.source.accept(this),query.onCondition.accept(this);for(let clause of query.whenClauses)if(clause.condition&&clause.condition.accept(this),clause.action instanceof MergeUpdateAction)clause.action.setClause.items.forEach(item=>item.value.accept(this)),clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeDeleteAction)clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeInsertAction&&clause.action.values)clause.action.values.accept(this);else if(!(clause.action instanceof MergeInsertAction)){let actionName=clause.action?.constructor?.name??"UnknownMergeAction";throw new Error(`[CTECollector] Unsupported MERGE action type: ${actionName}.`)}query.returningClause&&this.visitReturningClause(query.returningClause)}visitReturningClause(clause){for(let item of clause.items)item.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)}visitJsonPredicateExpression(expr){expr.expression.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(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(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(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(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)}visitInsertQuery(query){return query}visitUpdateQuery(query){return query}visitDeleteQuery(query){return query}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,clause.mode)}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)}visitJsonPredicateExpression(expr){let expression=this.visit(expr.expression);return new JsonPredicateExpression(expression,expr.negated,expr.jsonType,expr.uniqueKeys)}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,dedupe=!0){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.cteNames=new Set;this.isRootVisit=!0;this.selectableOnly=selectableOnly,this.dedupe=dedupe,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(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(MergeQuery.kind,expr=>this.visitMergeQuery(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(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(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)}visitInsertQuery(query){query.insertClause.source.accept(this),query.selectQuery&&query.selectQuery.accept(this),!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitUpdateQuery(query){!this.selectableOnly&&query.withClause&&query.withClause.accept(this),query.updateClause.source.accept(this),this.selectableOnly||query.setClause.items.forEach(item=>item.value.accept(this)),query.fromClause&&query.fromClause.accept(this),!this.selectableOnly&&query.whereClause&&query.whereClause.accept(this),!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitDeleteQuery(query){!this.selectableOnly&&query.withClause&&query.withClause.accept(this),query.deleteClause.source.accept(this),query.usingClause&&query.usingClause.sources.forEach(source=>source.accept(this)),!this.selectableOnly&&query.whereClause&&query.whereClause.accept(this),!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitMergeQuery(query){if(query.withClause&&this.registerCteNames(query.withClause),!this.selectableOnly&&query.withClause&&query.withClause.accept(this),query.target.accept(this),query.source.accept(this),!this.selectableOnly){query.onCondition.accept(this);for(let clause of query.whenClauses)if(clause.condition&&clause.condition.accept(this),clause.action instanceof MergeUpdateAction)clause.action.setClause.items.forEach(item=>item.value.accept(this)),clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeDeleteAction)clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeInsertAction&&clause.action.values)clause.action.values.accept(this);else if(!(clause.action instanceof MergeInsertAction)){let actionName=clause.action?.constructor?.name??"UnknownMergeAction";throw new Error(`[TableSourceCollector] Unsupported MERGE action type: ${actionName}.`)}}!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitReturningClause(clause){for(let item of clause.items)item.value.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);if(!this.isCTETable(source.table.name)){if(this.dedupe){if(this.tableNameMap.has(identifier))return;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)}registerCteNames(withClause){for(let table of withClause.tables)this.cteNames.add(table.aliasExpression.table.name)}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)}visitJsonPredicateExpression(expr){expr.expression.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.filterCondition&&func.filterCondition.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 SelectQueryWithClauseHelper=class{static getWithClause(selectQuery){let owner=this.findClauseOwner(selectQuery);return owner?owner.withClause:null}static setWithClause(selectQuery,withClause){let owner=this.findClauseOwner(selectQuery);if(!owner)throw new Error("Cannot attach WITH clause to the provided select query.");owner.withClause=withClause}static detachWithClause(selectQuery){let owner=this.findClauseOwner(selectQuery);if(!owner)return null;let clause=owner.withClause;return owner.withClause=null,clause}static findClauseOwner(selectQuery){if(!selectQuery)return null;if(selectQuery instanceof SimpleSelectQuery||selectQuery instanceof ValuesQuery)return selectQuery;if(selectQuery instanceof BinarySelectQuery)return this.findClauseOwner(selectQuery.left);throw new Error("Unsupported select query type for WITH clause management.")}};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??'"',this.target=identifierEscape?.target??"all"}decorate(text){return this.target==="minimal"&&this.canRenderBare(text)?text:this.start+this.escapeIdentifierText(text)+this.end}canRenderBare(text){return/^[a-z_][a-z0-9_]*$/.test(text)&&!UNSAFE_BARE_IDENTIFIERS.has(text)&&this.isPlainIdentifierToken(text)}isPlainIdentifierToken(text){let lexemes=new SqlTokenizer(text).readLexmes();return lexemes.length===1&&lexemes[0].type===64&&lexemes[0].value===text}escapeIdentifierText(text){return this.end?text.split(this.end).join(this.end+this.end):text}},UNSAFE_BARE_IDENTIFIERS=new Set(["all","and","any","as","between","by","case","cross","delete","distinct","else","end","except","exists","false","fetch","for","from","full","group","having","in","inner","insert","intersect","into","is","join","left","like","limit","not","null","offset","on","or","order","outer","right","select","set","table","then","true","union","update","using","values","when","where","with",...SQL_SPECIAL_VALUE_KEYWORDS]);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 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);this.collectValuesFromCteQuery(commonTable.query,innerCommonTables).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})}collectValuesFromCteQuery(query,commonTables){return this.isSelectQuery(query)?new _SelectValueCollector(this.tableColumnResolver,commonTables).collect(query):this.collectValuesFromReturning(query)}collectValuesFromReturning(query){return query instanceof InsertQuery||query instanceof UpdateQuery||query instanceof DeleteQuery||query instanceof MergeQuery?query.returningClause?this.extractValuesFromReturningClause(query.returningClause):[]:[]}extractValuesFromReturningClause(clause){let values=[];for(let item of clause.items){let name=item.identifier?.name??this.extractSelectItemName(item);name&&values.push({name,value:item.value})}return values}extractSelectItemName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}};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.isUnlogged=params.isUnlogged??!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)})}};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}},CreateSchemaStatement=class extends SqlComponent{static{this.kind=Symbol("CreateSchemaStatement")}constructor(params){super(),this.schemaName=new QualifiedName(params.schemaName.namespaces,params.schemaName.name),this.ifNotExists=params.ifNotExists??!1,this.authorization=params.authorization?cloneIdentifierWithComments(params.authorization):null}},DropSchemaStatement=class extends SqlComponent{static{this.kind=Symbol("DropSchemaStatement")}constructor(params){super(),this.schemaNames=params.schemaNames.map(schema=>new QualifiedName(schema.namespaces,schema.name)),this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},CommentOnStatement=class extends SqlComponent{static{this.kind=Symbol("CommentOnStatement")}constructor(params){super(),this.targetKind=params.targetKind,this.target=new QualifiedName(params.target.namespaces,params.target.name),this.comment=params.comment}},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}},AlterTableAddColumn=class extends SqlComponent{static{this.kind=Symbol("AlterTableAddColumn")}constructor(params){super(),this.column=params.column,this.ifNotExists=params.ifNotExists??!1}},AlterTableAlterColumnDefault=class extends SqlComponent{static{this.kind=Symbol("AlterTableAlterColumnDefault")}constructor(params){if(super(),this.columnName=params.columnName,this.setDefault=params.setDefault??null,this.dropDefault=params.dropDefault??!1,this.setDefault!==null&&this.dropDefault)throw new Error("[AlterTableAlterColumnDefault] Cannot set and drop a default at the same time.")}},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}},CreateSequenceStatement=class extends SqlComponent{static{this.kind=Symbol("CreateSequenceStatement")}constructor(params){super(),this.sequenceName=new QualifiedName(params.sequenceName.namespaces,params.sequenceName.name),this.ifNotExists=params.ifNotExists??!1,this.clauses=params.clauses?[...params.clauses]:[]}},AlterSequenceStatement=class extends SqlComponent{static{this.kind=Symbol("AlterSequenceStatement")}constructor(params){super(),this.sequenceName=new QualifiedName(params.sequenceName.namespaces,params.sequenceName.name),this.ifExists=params.ifExists??!1,this.clauses=params.clauses?[...params.clauses]:[]}},VacuumStatement=class extends SqlComponent{static{this.kind=Symbol("VacuumStatement")}constructor(params){super(),this.full=params?.full??!1,this.verbose=params?.verbose??!1,this.freeze=params?.freeze??!1,this.analyze=params?.analyze??!1,this.targets=params?.targets?[...params.targets]:[]}},ReindexStatement=class extends SqlComponent{static{this.kind=Symbol("ReindexStatement")}constructor(params){super(),this.concurrently=params?.concurrently??!1,this.targets=params?.targets?[...params.targets]:[],this.targetType=params?.targetType??null}},ClusterStatement=class extends SqlComponent{static{this.kind=Symbol("ClusterStatement")}constructor(params){super(),this.verbose=params?.verbose??!1,this.table=params?.table??null,this.index=params?.index??null}},CheckpointStatement=class extends SqlComponent{static{this.kind=Symbol("CheckpointStatement")}constructor(params){super(),this.options=params?.options?[...params.options]:[]}};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.listContinuationCommentComponents=new WeakSet;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??'"',target:options?.identifierEscape?.target}),this.castStyle=options?.castStyle??"standard",this.constraintStyle=options?.constraintStyle??"postgres",this.sourceAliasStyle=options?.sourceAliasStyle??"as",this.orderByDefaultDirectionStyle=options?.orderByDefaultDirectionStyle??"omit",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(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(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(OnConflictClause.kind,expr=>this.visitOnConflictClause(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(CreateSchemaStatement.kind,expr=>this.visitCreateSchemaStatement(expr)),this.handlers.set(IndexColumnDefinition.kind,expr=>this.visitIndexColumnDefinition(expr)),this.handlers.set(CreateSequenceStatement.kind,expr=>this.visitCreateSequenceStatement(expr)),this.handlers.set(AlterSequenceStatement.kind,expr=>this.visitAlterSequenceStatement(expr)),this.handlers.set(DropTableStatement.kind,expr=>this.visitDropTableStatement(expr)),this.handlers.set(DropIndexStatement.kind,expr=>this.visitDropIndexStatement(expr)),this.handlers.set(DropSchemaStatement.kind,expr=>this.visitDropSchemaStatement(expr)),this.handlers.set(CommentOnStatement.kind,expr=>this.visitCommentOnStatement(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(AlterTableAddColumn.kind,expr=>this.visitAlterTableAddColumn(expr)),this.handlers.set(AlterTableDropColumn.kind,expr=>this.visitAlterTableDropColumn(expr)),this.handlers.set(AlterTableAlterColumnDefault.kind,expr=>this.visitAlterTableAlterColumnDefault(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,OrderByItem.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}visitCreateSchemaStatement(arg){let keywordParts=["create","schema"];arg.ifNotExists&&keywordParts.push("if not exists");let token=new SqlPrintToken(1,keywordParts.join(" "),"CreateSchemaStatement");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.schemaName.accept(this)),arg.authorization&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"authorization")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.authorization.accept(this))),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"),hasOwnComments=this.hasPositionedComments(arg)||this.hasLegacyComments(arg);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,!hasOwnComments&&(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"))):this.orderByDefaultDirectionStyle==="explicit"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"asc"))),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")))),arg.comments&&arg.comments.length>0&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(...this.createInlineCommentSequence(arg.comments))),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(`
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 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 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{this.SQL_JSON_CONSTRUCTORS=new Set(["json_array","json_object","json_scalar","json_serialize"])}static{this.QUANTIFIED_COMPARISON_FUNCTIONS=new Set(["all","any","some"])}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.QUANTIFIED_COMPARISON_FUNCTIONS.has(functionName)&&this.isSubqueryArgumentStart(lexemes,idx)){let result=this.parseSubqueryArgumentWithComments(lexemes,idx);arg={value:result.value,newIndex:result.newIndex},closingComments=result.closingComments}else if(this.SQL_JSON_CONSTRUCTORS.has(functionName)){let result=this.parseRawFunctionArguments(lexemes,idx);arg={value:result.argument,newIndex:result.newIndex},closingComments=result.closingComments}else 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 filterCondition=null;if(idx<lexemes.length&&lexemes[idx].value==="filter"){let filterResult=this.parseFilterClause(lexemes,idx);filterCondition=filterResult.condition,idx=filterResult.newIndex}let withOrdinality=!1;idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++);let nullsTreatment=this.parseNullsTreatment(lexemes,idx);if(idx=nullsTreatment.newIndex,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,filterCondition,nullsTreatment.value);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,filterCondition,nullsTreatment.value);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 isSubqueryArgumentStart(lexemes,index){return index+1<lexemes.length&&(lexemes[index].type&4)!==0&&(lexemes[index+1].value==="select"||lexemes[index+1].value==="values"||lexemes[index+1].value==="with")}static parseSubqueryArgumentWithComments(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 queryResult=SelectQueryParser.parseFromLexeme(lexemes,idx);if(idx=queryResult.newIndex,idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis.");let closingComments=this.getClosingComments(lexemes[idx]);idx++;let value=new InlineQuery(queryResult.value),openingComments=openParenToken.positionedComments?.filter(comment=>comment.position==="after"&&comment.comments.length>0).map(comment=>({position:"before",comments:[...comment.comments]}))??[];return openingComments.length>0?value.positionedComments=openingComments:openParenToken.comments&&openParenToken.comments.length>0&&(value.positionedComments=[{position:"before",comments:[...openParenToken.comments]}]),{value,closingComments,newIndex:idx}}static parseRawFunctionArguments(lexemes,index){let idx=index;if(idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected opening parenthesis.");let contentStart=idx+1,depth=1;for(idx++;idx<lexemes.length&&depth>0;){if(lexemes[idx].type&4?depth++:lexemes[idx].type&8&&depth--,depth===0){let closingComments=this.getClosingComments(lexemes[idx]),rawText=joinLexemeValues(lexemes,contentStart,idx);return idx++,{argument:rawText.length>0?new RawString(rawText):new ValueList([]),closingComments,newIndex:idx}}idx++}throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis.")}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;idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++);let nullsTreatment=this.parseNullsTreatment(lexemes,idx);if(idx=nullsTreatment.newIndex,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,null,nullsTreatment.value),newIndex:idx}}else return{value:new FunctionCall(namespaces,name.name,arg,null,withinGroup,withOrdinality,null,null,nullsTreatment.value),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 parseNullsTreatment(lexemes,index){let value=lexemes[index]?.value;return value==="ignore nulls"||value==="respect nulls"?{value,newIndex:index+1}:{value:null,newIndex:index}}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 parseFilterClause(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].value!=="filter")throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected 'FILTER' keyword.");if(idx++,idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected '(' after FILTER.");if(idx++,idx>=lexemes.length||lexemes[idx].value!=="where")throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected 'WHERE' inside FILTER clause.");idx++;let conditionResult=ValueParser.parseFromLexeme(lexemes,idx);if(idx=conditionResult.newIndex,idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected ')' after FILTER predicate.");return idx++,{condition:conditionResult.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,"||":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 jsonPredicate=this.tryParseJsonPredicate(lexemes,idx,result);if(jsonPredicate){result=jsonPredicate.value,idx=jsonPredicate.newIndex;continue}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 tryParseJsonPredicate(lexemes,index,expression){let operator=lexemes[index]?.value?.toLowerCase();if(operator!=="is"&&operator!=="is not")return null;let idx=index+1;if(idx>=lexemes.length||lexemes[idx].value.toLowerCase()!=="json")return null;idx++;let jsonType=null,typeCandidate=lexemes[idx]?.value?.toLowerCase();(typeCandidate==="value"||typeCandidate==="scalar"||typeCandidate==="array"||typeCandidate==="object")&&(jsonType=typeCandidate,idx++);let uniqueKeys=null,uniqueCandidate=lexemes[idx]?.value?.toLowerCase();if(uniqueCandidate==="with"||uniqueCandidate==="without"){let uniqueToken=lexemes[idx+1]?.value?.toLowerCase(),keysToken=lexemes[idx+2]?.value?.toLowerCase();uniqueToken==="unique"&&keysToken==="keys"&&(uniqueKeys=uniqueCandidate,idx+=3)}return{value:new JsonPredicateExpression(expression,operator==="is not",jsonType,uniqueKeys),newIndex:idx}}static transferPositionedComments(lexeme,value){if(lexeme.positionedComments&&lexeme.positionedComments.length>0){let beforeComments=lexeme.positionedComments.filter(comment=>comment.position==="before"),afterComments=lexeme.positionedComments.filter(comment=>comment.position==="after");if(beforeComments.length>0){let clonedBefore=beforeComments.map(comment=>({position:comment.position,comments:[...comment.comments]}));value.positionedComments=value.positionedComments?[...clonedBefore,...value.positionedComments]:clonedBefore}if(afterComments.length>0){let clonedAfter=afterComments.map(comment=>({position:comment.position,comments:[...comment.comments]}));value.positionedComments=value.positionedComments?[...value.positionedComments,...clonedAfter]:clonedAfter}!beforeComments.length&&!afterComments.length&&!value.positionedComments&&(value.positionedComments=lexeme.positionedComments.map(comment=>({position:comment.position,comments:[...comment.comments]})));return}else 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&&this.isQualifiedSpecialValueIdentifier(lexemes,idx)){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx),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 isQualifiedSpecialValueIdentifier(lexemes,index){return SQL_SPECIAL_VALUE_KEYWORD_SET.has(lexemes[index].value.toLowerCase())&&index+1<lexemes.length&&(lexemes[index+1].type&32)!==0}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 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 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,this.returningClause=params.returningClause??null}};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(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(MergeQuery.kind,expr=>this.visitMergeQuery(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(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(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)}visitInsertQuery(query){query.selectQuery&&query.selectQuery.accept(this)}visitUpdateQuery(query){query.withClause&&query.withClause.accept(this),query.updateClause.source.accept(this),query.setClause.items.forEach(item=>item.value.accept(this)),query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.returningClause&&this.visitReturningClause(query.returningClause)}visitDeleteQuery(query){query.withClause&&query.withClause.accept(this),query.deleteClause.source.accept(this),query.usingClause&&query.usingClause.sources.forEach(source=>source.accept(this)),query.whereClause&&query.whereClause.accept(this),query.returningClause&&this.visitReturningClause(query.returningClause)}visitMergeQuery(query){query.withClause&&query.withClause.accept(this),query.target.accept(this),query.source.accept(this),query.onCondition.accept(this);for(let clause of query.whenClauses)if(clause.condition&&clause.condition.accept(this),clause.action instanceof MergeUpdateAction)clause.action.setClause.items.forEach(item=>item.value.accept(this)),clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeDeleteAction)clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeInsertAction&&clause.action.values)clause.action.values.accept(this);else if(!(clause.action instanceof MergeInsertAction)){let actionName=clause.action?.constructor?.name??"UnknownMergeAction";throw new Error(`[CTECollector] Unsupported MERGE action type: ${actionName}.`)}query.returningClause&&this.visitReturningClause(query.returningClause)}visitReturningClause(clause){for(let item of clause.items)item.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)}visitJsonPredicateExpression(expr){expr.expression.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(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(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(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(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)}visitInsertQuery(query){return query}visitUpdateQuery(query){return query}visitDeleteQuery(query){return query}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,clause.mode)}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)}visitJsonPredicateExpression(expr){let expression=this.visit(expr.expression);return new JsonPredicateExpression(expression,expr.negated,expr.jsonType,expr.uniqueKeys)}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,dedupe=!0){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.cteNames=new Set;this.isRootVisit=!0;this.selectableOnly=selectableOnly,this.dedupe=dedupe,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(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(MergeQuery.kind,expr=>this.visitMergeQuery(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(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(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)}visitInsertQuery(query){query.insertClause.source.accept(this),query.selectQuery&&query.selectQuery.accept(this),!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitUpdateQuery(query){!this.selectableOnly&&query.withClause&&query.withClause.accept(this),query.updateClause.source.accept(this),this.selectableOnly||query.setClause.items.forEach(item=>item.value.accept(this)),query.fromClause&&query.fromClause.accept(this),!this.selectableOnly&&query.whereClause&&query.whereClause.accept(this),!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitDeleteQuery(query){!this.selectableOnly&&query.withClause&&query.withClause.accept(this),query.deleteClause.source.accept(this),query.usingClause&&query.usingClause.sources.forEach(source=>source.accept(this)),!this.selectableOnly&&query.whereClause&&query.whereClause.accept(this),!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitMergeQuery(query){if(query.withClause&&this.registerCteNames(query.withClause),!this.selectableOnly&&query.withClause&&query.withClause.accept(this),query.target.accept(this),query.source.accept(this),!this.selectableOnly){query.onCondition.accept(this);for(let clause of query.whenClauses)if(clause.condition&&clause.condition.accept(this),clause.action instanceof MergeUpdateAction)clause.action.setClause.items.forEach(item=>item.value.accept(this)),clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeDeleteAction)clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeInsertAction&&clause.action.values)clause.action.values.accept(this);else if(!(clause.action instanceof MergeInsertAction)){let actionName=clause.action?.constructor?.name??"UnknownMergeAction";throw new Error(`[TableSourceCollector] Unsupported MERGE action type: ${actionName}.`)}}!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitReturningClause(clause){for(let item of clause.items)item.value.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);if(!this.isCTETable(source.table.name)){if(this.dedupe){if(this.tableNameMap.has(identifier))return;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)}registerCteNames(withClause){for(let table of withClause.tables)this.cteNames.add(table.aliasExpression.table.name)}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)}visitJsonPredicateExpression(expr){expr.expression.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.filterCondition&&func.filterCondition.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 SelectQueryWithClauseHelper=class{static getWithClause(selectQuery){let owner=this.findClauseOwner(selectQuery);return owner?owner.withClause:null}static setWithClause(selectQuery,withClause){let owner=this.findClauseOwner(selectQuery);if(!owner)throw new Error("Cannot attach WITH clause to the provided select query.");owner.withClause=withClause}static detachWithClause(selectQuery){let owner=this.findClauseOwner(selectQuery);if(!owner)return null;let clause=owner.withClause;return owner.withClause=null,clause}static findClauseOwner(selectQuery){if(!selectQuery)return null;if(selectQuery instanceof SimpleSelectQuery||selectQuery instanceof ValuesQuery)return selectQuery;if(selectQuery instanceof BinarySelectQuery)return this.findClauseOwner(selectQuery.left);throw new Error("Unsupported select query type for WITH clause management.")}};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??'"',this.target=identifierEscape?.target??"all"}decorate(text){return this.target==="minimal"&&this.canRenderBare(text)?text:this.start+this.escapeIdentifierText(text)+this.end}canRenderBare(text){return/^[a-z_][a-z0-9_]*$/.test(text)&&!UNSAFE_BARE_IDENTIFIERS.has(text)&&this.isPlainIdentifierToken(text)}isPlainIdentifierToken(text){let lexemes=new SqlTokenizer(text).readLexmes();return lexemes.length===1&&lexemes[0].type===64&&lexemes[0].value===text}escapeIdentifierText(text){return this.end?text.split(this.end).join(this.end+this.end):text}},UNSAFE_BARE_IDENTIFIERS=new Set(["all","and","any","as","between","by","case","cross","delete","distinct","else","end","except","exists","false","fetch","for","from","full","group","having","in","inner","insert","intersect","into","is","join","left","like","limit","not","null","offset","on","or","order","outer","right","select","set","table","then","true","union","update","using","values","when","where","with",...SQL_SPECIAL_VALUE_KEYWORDS]);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"||this.style==="original")&&(paramText=this.prefix+text+this.suffix),text=paramText,text}};var SelectValueCollector=class _SelectValueCollector{constructor(tableColumnResolver=null,initialCommonTables=null,preserveDuplicateSelectItems=!1){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=tableColumnResolver??null,this.commonTableCollector=new CTECollector,this.commonTables=[],this.initialCommonTables=initialCommonTables,this.preserveDuplicateSelectItems=preserveDuplicateSelectItems,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){if(this.commonTables.length===0&&this.initialCommonTables===null&&(this.commonTables=this.commonTableCollector.collect(query)),query.selectClause&&query.selectClause.accept(this),this.selectValues.filter(item=>item.name==="*").length===0)return;let expandedValues=[];for(let item of this.selectValues){if(item.name!=="*"||!(item.value instanceof ColumnReference)){expandedValues.push(item);continue}expandedValues.push(...this.expandWildcardValue(item.value,query.fromClause))}this.selectValues=expandedValues}processFromClause(clause,joinCascade){for(let item of this.collectFromClauseValues(clause,joinCascade))this.addSelectValue(item.name,item.value)}processJoinClause(clause){for(let item of this.collectJoinClauseValues(clause))this.addSelectValue(item.name,item.value)}processSourceExpression(sourceName,source){for(let item of this.collectSourceExpressionValues(sourceName,source))this.addSelectValue(item.name,item.value)}expandWildcardValue(value,fromClause){if(!fromClause)return[];if(value.namespaces===null)return this.collectFromClauseValues(fromClause,!0);let sourceName=value.getNamespace();if(fromClause.getSourceAliasName()===sourceName)return this.collectFromClauseValues(fromClause,!1);if(!fromClause.joins)return[];let join=fromClause.joins.find(item=>this.getJoinSourceName(item)===sourceName);return join?this.collectJoinClauseValues(join):[]}collectFromClauseValues(clause,joinCascade){let values=this.collectSourceExpressionValues(clause.getSourceAliasName(),clause.source);if(clause.joins&&joinCascade)for(let join of clause.joins)values.push(...this.collectJoinClauseValues(join));return values}collectJoinClauseValues(clause){return this.collectSourceExpressionValues(this.getJoinSourceName(clause),clause.source)}getJoinSourceName(clause){return clause.source.getAliasName()}collectSourceExpressionValues(sourceName,source){let tableSourceName=source.datasource instanceof TableSource?source.datasource.getSourceName():null,commonTable=tableSourceName?this.commonTables.find(item=>item.aliasExpression.table.name===tableSourceName):null;if(commonTable){let innerCommonTables=this.commonTables.filter(item=>item.aliasExpression.table.name!==commonTable.aliasExpression.table.name);return this.collectValuesFromCteQuery(commonTable.query,innerCommonTables).map(item=>({name:item.name,value:new ColumnReference(sourceName?[sourceName]:null,item.name)}))}return new _SelectValueCollector(this.tableColumnResolver,this.commonTables,!0).collect(source).map(item=>({name:item.name,value:new ColumnReference(sourceName?[sourceName]:null,item.name)}))}visitSelectClause(clause){for(let item of clause.items)this.processSelectItem(item)}processSelectItem(item){if(item.identifier)this.addSelectValueFromSelectItem(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.addSelectValueFromSelectItem(columnName,item.value)}}visitSourceExpression(source){if(source.aliasExpression&&source.aliasExpression.columns){let sourceName=source.getAliasName();source.aliasExpression.columns.forEach(column=>{this.addSelectValueFromSelectItem(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.addSelectValueFromSelectItem(column,new ColumnReference([sourceName],column))})}return}else if(source.datasource instanceof SubQuerySource){let sourceName=source.getAliasName();new _SelectValueCollector(this.tableColumnResolver,this.commonTables,!0).collect(source.datasource.query).forEach(item=>{this.addSelectValueFromSelectItem(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})}addSelectValue(name,value){this.selectValues.push({name,value})}addSelectValueFromSelectItem(name,value){if(this.preserveDuplicateSelectItems){this.addSelectValue(name,value);return}this.addSelectValueAsUnique(name,value)}collectValuesFromCteQuery(query,commonTables){return this.isSelectQuery(query)?new _SelectValueCollector(this.tableColumnResolver,commonTables,!0).collect(query):this.collectValuesFromReturning(query)}collectValuesFromReturning(query){return query instanceof InsertQuery||query instanceof UpdateQuery||query instanceof DeleteQuery||query instanceof MergeQuery?query.returningClause?this.extractValuesFromReturningClause(query.returningClause):[]:[]}extractValuesFromReturningClause(clause){let values=[];for(let item of clause.items){let name=item.identifier?.name??this.extractSelectItemName(item);name&&values.push({name,value:item.value})}return values}extractSelectItemName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}};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.isUnlogged=params.isUnlogged??!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)})}};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}},CreateSchemaStatement=class extends SqlComponent{static{this.kind=Symbol("CreateSchemaStatement")}constructor(params){super(),this.schemaName=new QualifiedName(params.schemaName.namespaces,params.schemaName.name),this.ifNotExists=params.ifNotExists??!1,this.authorization=params.authorization?cloneIdentifierWithComments(params.authorization):null}},DropSchemaStatement=class extends SqlComponent{static{this.kind=Symbol("DropSchemaStatement")}constructor(params){super(),this.schemaNames=params.schemaNames.map(schema=>new QualifiedName(schema.namespaces,schema.name)),this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},CommentOnStatement=class extends SqlComponent{static{this.kind=Symbol("CommentOnStatement")}constructor(params){super(),this.targetKind=params.targetKind,this.target=new QualifiedName(params.target.namespaces,params.target.name),this.comment=params.comment}},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}},AlterTableAddColumn=class extends SqlComponent{static{this.kind=Symbol("AlterTableAddColumn")}constructor(params){super(),this.column=params.column,this.ifNotExists=params.ifNotExists??!1}},AlterTableAlterColumnDefault=class extends SqlComponent{static{this.kind=Symbol("AlterTableAlterColumnDefault")}constructor(params){if(super(),this.columnName=params.columnName,this.setDefault=params.setDefault??null,this.dropDefault=params.dropDefault??!1,this.setDefault!==null&&this.dropDefault)throw new Error("[AlterTableAlterColumnDefault] Cannot set and drop a default at the same time.")}},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}},CreateSequenceStatement=class extends SqlComponent{static{this.kind=Symbol("CreateSequenceStatement")}constructor(params){super(),this.sequenceName=new QualifiedName(params.sequenceName.namespaces,params.sequenceName.name),this.ifNotExists=params.ifNotExists??!1,this.clauses=params.clauses?[...params.clauses]:[]}},AlterSequenceStatement=class extends SqlComponent{static{this.kind=Symbol("AlterSequenceStatement")}constructor(params){super(),this.sequenceName=new QualifiedName(params.sequenceName.namespaces,params.sequenceName.name),this.ifExists=params.ifExists??!1,this.clauses=params.clauses?[...params.clauses]:[]}},VacuumStatement=class extends SqlComponent{static{this.kind=Symbol("VacuumStatement")}constructor(params){super(),this.full=params?.full??!1,this.verbose=params?.verbose??!1,this.freeze=params?.freeze??!1,this.analyze=params?.analyze??!1,this.targets=params?.targets?[...params.targets]:[]}},ReindexStatement=class extends SqlComponent{static{this.kind=Symbol("ReindexStatement")}constructor(params){super(),this.concurrently=params?.concurrently??!1,this.targets=params?.targets?[...params.targets]:[],this.targetType=params?.targetType??null}},ClusterStatement=class extends SqlComponent{static{this.kind=Symbol("ClusterStatement")}constructor(params){super(),this.verbose=params?.verbose??!1,this.table=params?.table??null,this.index=params?.index??null}},CheckpointStatement=class extends SqlComponent{static{this.kind=Symbol("CheckpointStatement")}constructor(params){super(),this.options=params?.options?[...params.options]:[]}};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.listContinuationCommentComponents=new WeakSet;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??'"',target:options?.identifierEscape?.target}),this.castStyle=options?.castStyle??"standard",this.constraintStyle=options?.constraintStyle??"postgres",this.sourceAliasStyle=this.normalizeAliasKeywordStyle(options?.sourceAliasStyle),this.columnAliasStyle=this.normalizeAliasKeywordStyle(options?.columnAliasStyle),this.orderByDefaultDirectionStyle=options?.orderByDefaultDirectionStyle??"omit",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(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(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(OnConflictClause.kind,expr=>this.visitOnConflictClause(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(CreateSchemaStatement.kind,expr=>this.visitCreateSchemaStatement(expr)),this.handlers.set(IndexColumnDefinition.kind,expr=>this.visitIndexColumnDefinition(expr)),this.handlers.set(CreateSequenceStatement.kind,expr=>this.visitCreateSequenceStatement(expr)),this.handlers.set(AlterSequenceStatement.kind,expr=>this.visitAlterSequenceStatement(expr)),this.handlers.set(DropTableStatement.kind,expr=>this.visitDropTableStatement(expr)),this.handlers.set(DropIndexStatement.kind,expr=>this.visitDropIndexStatement(expr)),this.handlers.set(DropSchemaStatement.kind,expr=>this.visitDropSchemaStatement(expr)),this.handlers.set(CommentOnStatement.kind,expr=>this.visitCommentOnStatement(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(AlterTableAddColumn.kind,expr=>this.visitAlterTableAddColumn(expr)),this.handlers.set(AlterTableDropColumn.kind,expr=>this.visitAlterTableDropColumn(expr)),this.handlers.set(AlterTableAlterColumnDefault.kind,expr=>this.visitAlterTableAlterColumnDefault(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,OrderByItem.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}visitCreateSchemaStatement(arg){let keywordParts=["create","schema"];arg.ifNotExists&&keywordParts.push("if not exists");let token=new SqlPrintToken(1,keywordParts.join(" "),"CreateSchemaStatement");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.schemaName.accept(this)),arg.authorization&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"authorization")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.authorization.accept(this))),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"),hasOwnComments=this.hasPositionedComments(arg)||this.hasLegacyComments(arg);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,!hasOwnComments&&(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());let item=arg.order[i];token.innerTokens.push(this.visit(item)),!(item instanceof OrderByItem)&&this.orderByDefaultDirectionStyle==="explicit"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"asc")))}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"))):this.orderByDefaultDirectionStyle==="explicit"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"asc"))),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")))),arg.comments&&arg.comments.length>0&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(...this.createInlineCommentSequence(arg.comments))),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"||style==="original"){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
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"),hasOwnComments=this.hasPositionedComments(arg)||this.hasLegacyComments(arg),originalNamePositionedComments=arg.qualifiedName.name.positionedComments,originalNameComments=arg.qualifiedName.name.comments;return hasOwnComments&&(arg.qualifiedName.name.positionedComments=null,arg.qualifiedName.name.comments=null),token.innerTokens.push(arg.qualifiedName.accept(this)),hasOwnComments&&(arg.qualifiedName.name.positionedComments=originalNamePositionedComments,arg.qualifiedName.name.comments=originalNameComments),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&&(this.relocateGroupingSetComments(arg),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.filterCondition&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"filter")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"where")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.filterCondition)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)),arg.withOrdinality&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"with ordinality"))),arg.nullsTreatment&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.nullsTreatment))),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}relocateGroupingSetComments(arg){if(!this.isGroupingSetsFunction(arg))return;let argument=arg.argument;if(!(argument instanceof ValueList))return;let values=argument.values;for(let i=1;i<values.length;i++){let current=values[i],previous=values[i-1],leadingComments=this.extractPositionedComments(current,"before");if(leadingComments.length===0)continue;let trailingBlock=leadingComments.map(comment=>({position:"after",comments:[...comment.comments]}));previous.positionedComments=previous.positionedComments?[...previous.positionedComments,...trailingBlock]:trailingBlock}}isGroupingSetsFunction(arg){let nameComponent=arg.qualifiedName.name;return(nameComponent instanceof RawString?nameComponent.value:nameComponent.name).trim().toLowerCase()==="grouping sets"}extractPositionedComments(component,position){if(!component.positionedComments||component.positionedComments.length===0)return[];let kept=[],extracted=[];for(let comment of component.positionedComments)comment.position===position?extracted.push({position:comment.position,comments:[...comment.comments]}):kept.push(comment);return component.positionedComments=kept.length>0?kept:null,extracted}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),hasOwnComments&&innerBeforeComments.length>0){let innerBeforeSet=new Set(innerBeforeComments);arg.positionedComments=arg.positionedComments?.map(comment=>comment.position==="after"?{...comment,comments:comment.comments.filter(value=>!innerBeforeSet.has(value))}:comment).filter(comment=>comment.comments.length>0)??null}if(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.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"),duplicateCaseAfterComments=arg.value instanceof CaseExpression?this.collectCaseSelectItemDuplicateAfterComments(arg.value):new Set;if(beforeComments.length>0)if(arg.value instanceof CaseExpression||this.listContinuationCommentComponents.has(arg)){let commentBlocks=this.createCommentBlocks(beforeComments);token.innerTokens.push(...commentBlocks)}else{let commentTokens=this.createInlineCommentSequence(beforeComments);token.innerTokens.push(...commentTokens),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}token.innerTokens.push(this.visit(arg.value));let visibleAfterComments=arg.value instanceof CaseExpression?this.filterCaseSelectItemDuplicateAfterComments(afterComments,duplicateCaseAfterComments):afterComments;if(visibleAfterComments.length>0&&!isParenExpression){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(visibleAfterComments);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}collectCaseSelectItemDuplicateAfterComments(value){let promoted=new Set;if(value.comments)for(let comment of value.comments)promoted.add(comment);let firstCase=value.switchCase.cases[0];if(firstCase?.positionedComments){for(let positionedComment of firstCase.positionedComments)if(positionedComment.position==="before")for(let comment of positionedComment.comments)promoted.add(comment)}return promoted}filterCaseSelectItemDuplicateAfterComments(afterComments,promoted){return afterComments.length===0||promoted.size===0?afterComments:afterComments.filter(comment=>!promoted.has(comment))}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++){if(i>0){token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),this.listContinuationCommentComponents.add(arg.items[i]);try{token.innerTokens.push(this.visit(arg.items[i]))}finally{this.listContinuationCommentComponents.delete(arg.items[i])}continue}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),this.appendSourceAliasKeyword(token),token.innerTokens.push(arg.aliasExpression.accept(this))),token}else return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),this.appendSourceAliasKeyword(token),token.innerTokens.push(arg.aliasExpression.accept(this)),token}appendSourceAliasKeyword(token){this.sourceAliasStyle!=="implicit"&&(token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_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),arg.withOrdinality&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"with ordinality"))),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");if(arg.mode&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.mode))),arg.grouping.length===0)return token;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"),selectQuery=arg.selectQuery,extractedWithClause=selectQuery?SelectQueryWithClauseHelper.detachWithClause(selectQuery):null;return extractedWithClause&&token.innerTokens.push(extractedWithClause.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.onConflictClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.onConflictClause.accept(this))),arg.returningClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.returningClause.accept(this))),selectQuery&&extractedWithClause&&SelectQueryWithClauseHelper.setWithClause(selectQuery,extractedWithClause),token}visitJsonPredicateExpression(arg){let token=new SqlPrintToken(0,"","BinaryExpression");return token.innerTokens.push(this.visit(arg.expression)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(5,arg.negated?"is not":"is")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"json")),arg.jsonType&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.jsonType))),arg.uniqueKeys&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,`${arg.uniqueKeys} unique keys`))),token}visitOnConflictClause(arg){let token=new SqlPrintToken(1,"on conflict","OnConflictClause");return arg.target&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.targetKind==="constraint"&&(token.innerTokens.push(new SqlPrintToken(1,"on constraint")),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,this.formatOnConflictAction(arg))),arg.setClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.setClause.accept(this))),arg.forClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.forClause.accept(this))),arg.whereClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.whereClause.accept(this))),token}formatOnConflictAction(arg){switch(arg.action){case"nothing":return"do nothing";case"select":return"do select";case"update":return"do update"}}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 arg.returningClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.returningClause.accept(this))),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");if(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.aliases.length>0){token.innerTokens.push(new SqlPrintToken(1,"with")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);for(let i=0;i<arg.aliases.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(new SqlPrintToken(1,arg.aliases[i].kind)),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.aliases[i].alias));token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),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}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}visitCreateSequenceStatement(arg){let keywordParts=["create","sequence"];arg.ifNotExists&&keywordParts.push("if not exists");let token=new SqlPrintToken(1,keywordParts.join(" "),"CreateSequenceStatement");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.sequenceName.accept(this)),arg.clauses.length>0&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visitSequenceClauses(arg.clauses))),token}visitAlterSequenceStatement(arg){let keywordParts=["alter","sequence"];arg.ifExists&&keywordParts.push("if exists");let token=new SqlPrintToken(1,keywordParts.join(" "),"AlterSequenceStatement");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.sequenceName.accept(this)),arg.clauses.length>0&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visitSequenceClauses(arg.clauses))),token}visitSequenceClauses(clauses){let token=new SqlPrintToken(0,"","SequenceOptionList");for(let i=0;i<clauses.length;i++)i>0&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visitSequenceClause(clauses[i]));return token}visitSequenceClause(clause){let token=new SqlPrintToken(0,"","SequenceOptionClause");switch(clause.kind){case"increment":token.innerTokens.push(new SqlPrintToken(1,"increment")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"by")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.value.accept(this));break;case"start":token.innerTokens.push(new SqlPrintToken(1,"start")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"with")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.value.accept(this));break;case"minValue":clause.noValue?(token.innerTokens.push(new SqlPrintToken(1,"no")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"minvalue"))):clause.value&&(token.innerTokens.push(new SqlPrintToken(1,"minvalue")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.value.accept(this)));break;case"maxValue":clause.noValue?(token.innerTokens.push(new SqlPrintToken(1,"no")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"maxvalue"))):clause.value&&(token.innerTokens.push(new SqlPrintToken(1,"maxvalue")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.value.accept(this)));break;case"cache":clause.noValue?(token.innerTokens.push(new SqlPrintToken(1,"no")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"cache"))):clause.value&&(token.innerTokens.push(new SqlPrintToken(1,"cache")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.value.accept(this)));break;case"cycle":token.innerTokens.push(new SqlPrintToken(1,clause.enabled?"cycle":"no cycle"));break;case"restart":token.innerTokens.push(new SqlPrintToken(1,"restart")),clause.value&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"with")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.value.accept(this)));break;case"ownedBy":token.innerTokens.push(new SqlPrintToken(1,"owned")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"by")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),clause.none?token.innerTokens.push(new SqlPrintToken(1,"none")):clause.target&&token.innerTokens.push(clause.target.accept(this));break}return 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}visitDropSchemaStatement(arg){let keyword=arg.ifExists?"drop schema if exists":"drop schema",token=new SqlPrintToken(1,keyword,"DropSchemaStatement");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let schemaList=new SqlPrintToken(0,"","ValueList");for(let i=0;i<arg.schemaNames.length;i++)i>0&&schemaList.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),schemaList.innerTokens.push(arg.schemaNames[i].accept(this));return token.innerTokens.push(schemaList),arg.behavior&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.behavior))),token}visitCommentOnStatement(arg){let keyword=arg.targetKind==="table"?"comment on table":"comment on column",token=new SqlPrintToken(1,keyword,"CommentOnStatement");return 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,"is")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.comment===null?token.innerTokens.push(new SqlPrintToken(1,"null")):token.innerTokens.push(arg.comment.accept(this)),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}visitAlterTableAddColumn(arg){let keyword="add column";arg.ifNotExists&&(keyword+=" if not exists");let token=new SqlPrintToken(0,"","AlterTableAddColumn");return token.innerTokens.push(new SqlPrintToken(1,keyword)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.column.accept(this)),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}visitAlterTableAlterColumnDefault(arg){let token=new SqlPrintToken(0,"","AlterTableAlterColumnDefault");return token.innerTokens.push(new SqlPrintToken(1,"alter column")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.columnName.accept(this)),arg.dropDefault?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"drop default"))):arg.setDefault?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"set default")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.setDefault.accept(this))):(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"set default"))),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
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"),hasOwnComments=this.hasPositionedComments(arg)||this.hasLegacyComments(arg),originalNamePositionedComments=arg.qualifiedName.name.positionedComments,originalNameComments=arg.qualifiedName.name.comments;return hasOwnComments&&(arg.qualifiedName.name.positionedComments=null,arg.qualifiedName.name.comments=null),token.innerTokens.push(arg.qualifiedName.accept(this)),hasOwnComments&&(arg.qualifiedName.name.positionedComments=originalNamePositionedComments,arg.qualifiedName.name.comments=originalNameComments),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&&(this.relocateGroupingSetComments(arg),arg.argument instanceof InlineQuery&&this.isQuantifiedComparisonFunction(arg)?token.innerTokens.push(arg.argument.selectQuery.accept(this)):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.filterCondition&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"filter")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"where")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.filterCondition)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)),arg.withOrdinality&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"with ordinality"))),arg.nullsTreatment&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.nullsTreatment))),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}isQuantifiedComparisonFunction(arg){let nameComponent=arg.qualifiedName.name,rawName=(nameComponent instanceof RawString?nameComponent.value:nameComponent.name).toLowerCase();return rawName==="all"||rawName==="any"||rawName==="some"}relocateGroupingSetComments(arg){if(!this.isGroupingSetsFunction(arg))return;let argument=arg.argument;if(!(argument instanceof ValueList))return;let values=argument.values;for(let i=1;i<values.length;i++){let current=values[i],previous=values[i-1],leadingComments=this.extractPositionedComments(current,"before");if(leadingComments.length===0)continue;let trailingBlock=leadingComments.map(comment=>({position:"after",comments:[...comment.comments]}));previous.positionedComments=previous.positionedComments?[...previous.positionedComments,...trailingBlock]:trailingBlock}}isGroupingSetsFunction(arg){let nameComponent=arg.qualifiedName.name;return(nameComponent instanceof RawString?nameComponent.value:nameComponent.name).trim().toLowerCase()==="grouping sets"}extractPositionedComments(component,position){if(!component.positionedComments||component.positionedComments.length===0)return[];let kept=[],extracted=[];for(let comment of component.positionedComments)comment.position===position?extracted.push({position:comment.position,comments:[...comment.comments]}):kept.push(comment);return component.positionedComments=kept.length>0?kept:null,extracted}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.style==="original"&&arg.sourceText?arg.sourceText: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),hasOwnComments&&innerBeforeComments.length>0){let innerBeforeSet=new Set(innerBeforeComments);arg.positionedComments=arg.positionedComments?.map(comment=>comment.position==="after"?{...comment,comments:comment.comments.filter(value=>!innerBeforeSet.has(value))}:comment).filter(comment=>comment.comments.length>0)??null}if(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.removeCaseAfterCommentsDuplicatedOnFirstWhen(arg),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.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}removeCaseAfterCommentsDuplicatedOnFirstWhen(arg){if(!arg.positionedComments||arg.positionedComments.length===0)return;let firstWhenComments=new Set((arg.switchCase.cases[0]?.getPositionedComments("before")??[]).map(comment=>this.normalizeCommentSignature(comment)));if(firstWhenComments.size===0)return;let retained=[];for(let entry of arg.positionedComments){if(entry.position!=="after"){retained.push(entry);continue}let comments=entry.comments.filter(comment=>!firstWhenComments.has(this.normalizeCommentSignature(comment)));comments.length>0&&retained.push({...entry,comments})}arg.positionedComments=retained.length>0?retained:null}normalizeCommentSignature(comment){return comment.replace(/\s+/g," ").trim()}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"),duplicateCaseAfterComments=arg.value instanceof CaseExpression?this.collectCaseSelectItemDuplicateAfterComments(arg.value):new Set;if(beforeComments.length>0)if(arg.value instanceof CaseExpression||this.listContinuationCommentComponents.has(arg)){let commentBlocks=this.createCommentBlocks(beforeComments);token.innerTokens.push(...commentBlocks)}else{let commentTokens=this.createInlineCommentSequence(beforeComments);token.innerTokens.push(...commentTokens),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}token.innerTokens.push(this.visit(arg.value));let visibleAfterComments=arg.value instanceof CaseExpression?this.filterCaseSelectItemDuplicateAfterComments(afterComments,duplicateCaseAfterComments):afterComments;if(visibleAfterComments.length>0&&!isParenExpression){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(visibleAfterComments);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,asKeywordComments="asKeywordComments"in arg?arg.asKeywordComments:null,shouldPrintAsKeyword=this.shouldPrintColumnAliasKeyword(asKeywordPositionedComments,asKeywordComments);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(shouldPrintAsKeyword&&token.innerTokens.push(new SqlPrintToken(1,"as")),shouldPrintAsKeyword&&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)}}}if(asKeywordComments&&asKeywordComments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(asKeywordComments);token.innerTokens.push(...commentTokens)}shouldPrintAsKeyword&&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}collectCaseSelectItemDuplicateAfterComments(value){let promoted=new Set;if(value.comments)for(let comment of value.comments)promoted.add(comment);let firstCase=value.switchCase.cases[0];if(firstCase?.positionedComments){for(let positionedComment of firstCase.positionedComments)if(positionedComment.position==="before")for(let comment of positionedComment.comments)promoted.add(comment)}return promoted}filterCaseSelectItemDuplicateAfterComments(afterComments,promoted){return afterComments.length===0||promoted.size===0?afterComments:afterComments.filter(comment=>!promoted.has(comment))}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++){if(i>0){token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),this.listContinuationCommentComponents.add(arg.items[i]);try{token.innerTokens.push(this.visit(arg.items[i]))}finally{this.listContinuationCommentComponents.delete(arg.items[i])}continue}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),this.appendSourceAliasKeyword(token),token.innerTokens.push(arg.aliasExpression.accept(this))),token}else return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),this.appendSourceAliasKeyword(token),token.innerTokens.push(arg.aliasExpression.accept(this)),token}appendSourceAliasKeyword(token){this.sourceAliasStyle!=="omit"&&(token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN))}shouldPrintColumnAliasKeyword(asKeywordPositionedComments,asKeywordComments){if(this.columnAliasStyle==="explicit")return!0;let hasPositionedComments=Array.isArray(asKeywordPositionedComments)&&asKeywordPositionedComments.length>0,hasLegacyComments=Array.isArray(asKeywordComments)&&asKeywordComments.length>0;return hasPositionedComments||hasLegacyComments}normalizeAliasKeywordStyle(style){return style==="implicit"||style==="omit"?"omit":"explicit"}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),arg.withOrdinality&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"with ordinality"))),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");if(arg.mode&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.mode))),arg.grouping.length===0)return token;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"),selectQuery=arg.selectQuery,extractedWithClause=selectQuery?SelectQueryWithClauseHelper.detachWithClause(selectQuery):null;return extractedWithClause&&token.innerTokens.push(extractedWithClause.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.onConflictClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.onConflictClause.accept(this))),arg.returningClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.returningClause.accept(this))),selectQuery&&extractedWithClause&&SelectQueryWithClauseHelper.setWithClause(selectQuery,extractedWithClause),token}visitJsonPredicateExpression(arg){let token=new SqlPrintToken(0,"","BinaryExpression");return token.innerTokens.push(this.visit(arg.expression)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(5,arg.negated?"is not":"is")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"json")),arg.jsonType&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.jsonType))),arg.uniqueKeys&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,`${arg.uniqueKeys} unique keys`))),token}visitOnConflictClause(arg){let token=new SqlPrintToken(1,"on conflict","OnConflictClause");return arg.target&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.targetKind==="constraint"&&(token.innerTokens.push(new SqlPrintToken(1,"on constraint")),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,this.formatOnConflictAction(arg))),arg.setClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.setClause.accept(this))),arg.forClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.forClause.accept(this))),arg.whereClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.whereClause.accept(this))),token}formatOnConflictAction(arg){switch(arg.action){case"nothing":return"do nothing";case"select":return"do select";case"update":return"do update"}}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 arg.returningClause&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.returningClause.accept(this))),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");if(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.aliases.length>0){token.innerTokens.push(new SqlPrintToken(1,"with")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);for(let i=0;i<arg.aliases.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(new SqlPrintToken(1,arg.aliases[i].kind)),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.aliases[i].alias));token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),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}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}visitCreateSequenceStatement(arg){let keywordParts=["create","sequence"];arg.ifNotExists&&keywordParts.push("if not exists");let token=new SqlPrintToken(1,keywordParts.join(" "),"CreateSequenceStatement");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.sequenceName.accept(this)),arg.clauses.length>0&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visitSequenceClauses(arg.clauses))),token}visitAlterSequenceStatement(arg){let keywordParts=["alter","sequence"];arg.ifExists&&keywordParts.push("if exists");let token=new SqlPrintToken(1,keywordParts.join(" "),"AlterSequenceStatement");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.sequenceName.accept(this)),arg.clauses.length>0&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visitSequenceClauses(arg.clauses))),token}visitSequenceClauses(clauses){let token=new SqlPrintToken(0,"","SequenceOptionList");for(let i=0;i<clauses.length;i++)i>0&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visitSequenceClause(clauses[i]));return token}visitSequenceClause(clause){let token=new SqlPrintToken(0,"","SequenceOptionClause");switch(clause.kind){case"increment":token.innerTokens.push(new SqlPrintToken(1,"increment")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"by")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.value.accept(this));break;case"start":token.innerTokens.push(new SqlPrintToken(1,"start")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"with")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.value.accept(this));break;case"minValue":clause.noValue?(token.innerTokens.push(new SqlPrintToken(1,"no")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"minvalue"))):clause.value&&(token.innerTokens.push(new SqlPrintToken(1,"minvalue")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.value.accept(this)));break;case"maxValue":clause.noValue?(token.innerTokens.push(new SqlPrintToken(1,"no")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"maxvalue"))):clause.value&&(token.innerTokens.push(new SqlPrintToken(1,"maxvalue")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.value.accept(this)));break;case"cache":clause.noValue?(token.innerTokens.push(new SqlPrintToken(1,"no")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"cache"))):clause.value&&(token.innerTokens.push(new SqlPrintToken(1,"cache")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.value.accept(this)));break;case"cycle":token.innerTokens.push(new SqlPrintToken(1,clause.enabled?"cycle":"no cycle"));break;case"restart":token.innerTokens.push(new SqlPrintToken(1,"restart")),clause.value&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"with")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(clause.value.accept(this)));break;case"ownedBy":token.innerTokens.push(new SqlPrintToken(1,"owned")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"by")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),clause.none?token.innerTokens.push(new SqlPrintToken(1,"none")):clause.target&&token.innerTokens.push(clause.target.accept(this));break}return 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}visitDropSchemaStatement(arg){let keyword=arg.ifExists?"drop schema if exists":"drop schema",token=new SqlPrintToken(1,keyword,"DropSchemaStatement");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let schemaList=new SqlPrintToken(0,"","ValueList");for(let i=0;i<arg.schemaNames.length;i++)i>0&&schemaList.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),schemaList.innerTokens.push(arg.schemaNames[i].accept(this));return token.innerTokens.push(schemaList),arg.behavior&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.behavior))),token}visitCommentOnStatement(arg){let keyword=arg.targetKind==="table"?"comment on table":"comment on column",token=new SqlPrintToken(1,keyword,"CommentOnStatement");return 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,"is")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.comment===null?token.innerTokens.push(new SqlPrintToken(1,"null")):token.innerTokens.push(arg.comment.accept(this)),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}visitAlterTableAddColumn(arg){let keyword="add column";arg.ifNotExists&&(keyword+=" if not exists");let token=new SqlPrintToken(0,"","AlterTableAddColumn");return token.innerTokens.push(new SqlPrintToken(1,keyword)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.column.accept(this)),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}visitAlterTableAlterColumnDefault(arg){let token=new SqlPrintToken(0,"","AlterTableAlterColumnDefault");return token.innerTokens.push(new SqlPrintToken(1,"alter column")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.columnName.accept(this)),arg.dropDefault?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"drop default"))):arg.setDefault?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"set default")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.setDefault.accept(this))):(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"set default"))),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];if(current.text!==""){let lineText=this.endsWithAsciiWhitespace(current.text)?current.text.trimEnd():current.text;current.text=lineText+this.newline}}this.lines.push(new PrintLine(level,""))}appendText(text){if(text===","&&this.cleanupLine()){let previousLine=this.lines[this.lines.length-1],lineText=this.endsWithAsciiWhitespace(previousLine.text)?previousLine.text.trimEnd():previousLine.text;previousLine.text=lineText+text;return}let workLine=this.getCurrentLine();text===" "&&workLine.text===""||(workLine.text+=text)}endsWithAsciiWhitespace(text){if(text.length===0)return!1;let tail=text.charCodeAt(text.length-1);return tail===32||tail===9||tail===10||tail===13}trimTrailingWhitespaceFromPreviousLine(){if(this.lines.length<2)return;let previousLine=this.lines[this.lines.length-2],text=previousLine.text,lineEnd=this.findLineEndIndex(text),contentEnd=lineEnd;for(;contentEnd>0;){let code=text.charCodeAt(contentEnd-1);if(code!==32&&code!==9)break;contentEnd--}contentEnd!==lineEnd&&(previousLine.text=text.slice(0,contentEnd)+text.slice(lineEnd))}findLineEndIndex(text){return text.endsWith(`\r
21
21
  `)?text.length-2:text.endsWith(`
22
22
  `)?text.length-1:text.length}cleanupLine(){let workLine=this.getCurrentLine();if(this.isAsciiWhitespaceOnly(workLine.text)&&this.lines.length>1&&(this.commaBreak==="after"||this.commaBreak==="none")){let previousIndex=this.lines.length-2;for(;previousIndex>=0&&this.isAsciiWhitespaceOnly(this.lines[previousIndex].text);)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}isAsciiWhitespaceOnly(text){for(let i=0;i<text.length;i++){let code=text.charCodeAt(i);if(code!==32&&code!==9&&code!==10&&code!==13)return!1}return!0}lineHasTrailingComment(text){if(!text.includes("--"))return!1;if(!text.includes("'")&&!text.includes('"'))return!0;let quote=null;for(let i=0;i<text.length-1;i++){let current=text.charCodeAt(i),next=text.charCodeAt(i+1);if(quote===39){if(current===39){if(next===39){i++;continue}quote=null}continue}if(quote===34){if(current===34){if(next===34){i++;continue}quote=null}continue}if(current===39){quote=39;continue}if(current===34){quote=34;continue}if(current===45&&next===45)return!0}return!1}getCurrentLine(){if(this.lines.length>0)return this.lines[this.lines.length-1];throw new Error("No tokens to get current line from.")}isCurrentLineEmpty(){if(this.lines.length>0){let currentLine=this.lines[this.lines.length-1];return this.isAsciiWhitespaceOnly(currentLine.text)}return!0}},PrintLine=class{constructor(level,text){this.level=level,this.text=text}};var INDENT_CHAR_MAP={space:" ",tab:" "},NEWLINE_MAP={lf:`
23
23
  `,crlf:`\r
24
- `,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,target="all"){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,target}}let start=option.start??"",end=option.end??"";return{start,end,target}}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.joinOnClauseDepth=0;this.expandedOneLineFallbackTokens=new WeakSet;this.pendingLineCommentBreak=null;this.smartCommentBlockBuilder=null;this.commentedFunctionCallDepth=0;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.joinOnBreak=options?.joinOnBreak??"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,this.oneLineMaxLength=this.normalizeOneLineMaxLength(options?.oneLineMaxLength),this.joinConditionContinuationIndent=options?.joinConditionContinuationIndent??!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","ReturningClause","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.joinOnClauseDepth=0,this.pendingLineCommentBreak=null,this.smartCommentBlockBuilder=null,this.expandedOneLineFallbackTokens=new WeakSet,this.commentedFunctionCallDepth=0,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,void 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,previousSiblingWasOpenParen=!1){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),leadingCommentFollowsLogicalOperator=hasRenderableLeadingComment&&this.currentLineEndsWithLogicalOperator(),leadingCommentIndentLevel=hasRenderableLeadingComment?this.getLeadingCommentIndentLevel(token.containerType==="SelectItem"?token.containerType:parentContainerType,level):null;hasRenderableLeadingComment&&!this.isOnelineMode()&&this.shouldAddNewlineBeforeLeadingComments(parentContainerType)&&!this.shouldKeepLeadingCommentOnCommaLine()&&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,!1),token.containerType==="SelectItem"&&this.smartCommentBlockBuilder?.mode==="line"&&this.flushSmartCommentBlockBuilder());if(leadingCommentFollowsLogicalOperator&&this.pendingLineCommentBreak===null&&!this.isOnelineMode()&&this.linePrinter.getCurrentLine().text.trim().endsWith("*/")&&this.linePrinter.appendNewline(level+1),this.smartCommentBlockBuilder&&token.containerType!=="CommentBlock"&&token.type!==12&&this.flushSmartCommentBlockBuilder(),this.pendingLineCommentBreak!==null){if(!this.isOnelineMode()){let pendingBreakLevel=leadingCommentFollowsLogicalOperator?this.pendingLineCommentBreak+1:this.pendingLineCommentBreak;this.linePrinter.appendNewline(pendingBreakLevel)}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;this.shouldKeepLeadingCommentOnCommaLine()&&this.ensureTrailingSpace();let commentLevel=this.getCommentBaseIndentLevel(level,parentContainerType);parentContainerType==="SelectItem"&&effectiveCommentContext.position==="leading"&&this.linePrinter.getCurrentLine().text.trim()===""&&(this.linePrinter.getCurrentLine().level=commentLevel),this.handleCommentBlockContainer(token,commentLevel,effectiveCommentContext);return}let current=this.linePrinter.getCurrentLine(),nextCaseContextDepth=this.isCaseContext(token.containerType)?caseContextDepth+1:caseContextDepth,shouldIndentNested=this.shouldIndentNestedParentheses(token,previousSiblingWasOpenParen);if(token.type===1)this.handleKeywordToken(token,level,parentContainerType,caseContextDepth);else if(token.type===3)this.handleCommaToken(token,level,parentContainerType);else if(token.type===11)this.handleArgumentSplitterToken(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"){if(this.tryHandleCteOnelineToken(token,level))return}else{if(this.shouldFormatContainerAsOneline(token,shouldIndentNested)&&this.tryHandleOnelineToken(token,level))return;this.tryAppendInsertClauseTokenText(token.text,parentContainerType)||this.linePrinter.appendText(token.text)}if(token.containerType==="JoinOnClause"&&this.joinOnBreak==="before"&&!this.isOnelineMode()&&this.linePrinter.getCurrentLine().text.trim().length>0&&this.linePrinter.appendNewline(level+1),this.expandedOneLineFallbackTokens.has(token)&&(shouldIndentNested=!0),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,void 0,!1)}let innerLevel=level,increasedIndent=!1,shouldIncreaseIndent=this.indentIncrementContainers.has(token.containerType)||shouldIndentNested,delayIndentNewline=shouldIndentNested&&token.containerType==="ParenExpression",isAlterTableStatement=token.containerType==="AlterTableStatement",deferAlterTableIndent=!1;if(token.containerType==="JoinOnClause"&&this.joinOnBreak==="before"&&!this.isOnelineMode()&&(innerLevel=level+1),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,enteredJoinOnClause=token.containerType==="JoinOnClause";enteredJoinOnClause&&this.joinOnClauseDepth++;let enteredCommentedFunctionCall=this.shouldExpandCommentedFunctionCall(token);enteredCommentedFunctionCall&&this.commentedFunctionCallDepth++;let enteredLogicalOperatorWithComment=this.isLogicalOperatorWithComment(token);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 previousChildWasOpenParen=previousChild?.type===4&&previousChild.text.trim()==="(",childIndentParentActive=token.containerType==="ParenExpression"?shouldIndentNested:indentParentActive;inMergePredicate&&this.mergeWhenPredicateDepth++;let childCommentContext=child.containerType==="CommentBlock"?{position:"inline",isTopLevelContainer:containerIsTopLevel}:void 0,childLevel=enteredCommentedFunctionCall&&child.containerType==="ValueList"?innerLevel+1:innerLevel;this.appendToken(child,childLevel,token.containerType,nextCaseContextDepth,childIndentParentActive,childCommentContext,previousChildWasOpenParen),inMergePredicate&&this.mergeWhenPredicateDepth--,childIsAction&&isMergeWhenClause&&(mergePredicateActive=!1)}if(enteredLogicalOperatorWithComment&&!this.isOnelineMode()){let currentLine=this.linePrinter.getCurrentLine();currentLine.text.trim()===""?currentLine.level=level+1:this.linePrinter.appendNewline(level+1)}if(this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder(),enteredJoinOnClause&&this.joinOnClauseDepth--,enteredCommentedFunctionCall&&this.commentedFunctionCallDepth--,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}}shouldExpandCommentedFunctionCall(token){return this.commentExportMode!=="none"&&token.containerType==="FunctionCall"&&token.innerTokens.some(child=>child.containerType==="ValueList"&&this.containsCommentBlock(child))}containsCommentBlock(token){return token.containerType==="CommentBlock"?!0:token.innerTokens.some(child=>this.containsCommentBlock(child))}isLogicalOperatorWithComment(token){return this.containsCommentBlock(token)&&token.type===5&&["and","or"].includes(token.text.toLowerCase())}currentLineEndsWithLogicalOperator(){let trimmed=this.linePrinter.getCurrentLine().text.trim().toLowerCase();return trimmed==="and"||trimmed==="or"}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)}handleArgumentSplitterToken(token,level,parentContainerType){this.linePrinter.appendText(token.text),this.commentedFunctionCallDepth>0&&parentContainerType==="ValueList"&&!this.isOnelineMode()&&this.linePrinter.appendNewline(level)}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(this.getJoinConditionContinuationLevel(level)),this.linePrinter.appendText(text)):this.andBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(this.getJoinConditionContinuationLevel(level))):this.linePrinter.appendText(text)}handleParenthesisToken(token,level,indentParentActive,parentContainerType){if(token.text==="("){if(this.linePrinter.appendText(token.text),this.commentedFunctionCallDepth>0&&parentContainerType==="FunctionCall"&&!this.isOnelineMode()){this.linePrinter.appendNewline(level+1);return}if((parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction")&&this.insertColumnsOneLine)return;this.isOnelineMode()||(this.shouldBreakAfterOpeningParen(parentContainerType)?this.linePrinter.appendNewline(level+1):indentParentActive&&parentContainerType==="ParenExpression"&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&this.linePrinter.appendNewline(level));return}if(token.text===")"&&!this.isOnelineMode()){if(this.commentedFunctionCallDepth>0&&parentContainerType==="FunctionCall"){this.linePrinter.appendNewline(level),this.linePrinter.appendText(token.text);return}if(this.shouldBreakBeforeClosingParen(parentContainerType)){this.linePrinter.appendNewline(Math.max(level,0)),this.linePrinter.appendText(token.text);return}if(indentParentActive&&parentContainerType==="ParenExpression"&&!(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(this.getJoinConditionContinuationLevel(level)),this.linePrinter.appendText(text)):this.orBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(this.getJoinConditionContinuationLevel(level))):this.linePrinter.appendText(text)}getJoinConditionContinuationLevel(level){return this.joinOnClauseDepth===0||this.joinOnBreak==="before"?level:this.joinConditionContinuationIndent?level+1:level}shouldIndentNestedParentheses(token,previousSiblingWasOpenParen=!1){return!this.indentNestedParentheses||token.containerType!=="ParenExpression"?!1:this.expandedOneLineFallbackTokens.has(token)?!0:previousSiblingWasOpenParen||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){if(this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder(),this.commentedFunctionCallDepth>0&&parentContainerType==="ValueList"&&previousToken?.type===11&&!this.isOnelineMode())return;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:`
25
- `,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,!1)}return}let emptyBlockCommentText=this.getEmptyBlockCommentText(token);if(emptyBlockCommentText!==null){this.linePrinter.appendText(emptyBlockCommentText);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)}getEmptyBlockCommentText(token){let commentTokens=(token.innerTokens??[]).filter(child=>child.type===6);if(commentTokens.length!==1)return null;let trimmed=commentTokens[0].text.trim();return!trimmed.startsWith("/*")||!trimmed.endsWith("*/")?null:trimmed.slice(2,-2).trim()===""?trimmed:null}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&&(!content&&trimmed.startsWith("/*")&&trimmed.endsWith("*/")?lines.push(this.sanitizeCommentLine(this.escapeCommentDelimiters(trimmed))):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
+ `,cr:"\r",space:" "},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,target="all"){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,target}}let start=option.start??"",end=option.end??"";return{start,end,target}}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.joinOnClauseDepth=0;this.expandedOneLineFallbackTokens=new WeakSet;this.pendingLineCommentBreak=null;this.smartCommentBlockBuilder=null;this.commentedFunctionCallDepth=0;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.joinOnBreak=this.normalizeJoinOnBreak(options?.joinOnBreak),this.keywordCase=this.normalizeKeywordCase(options?.keywordCase),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.inOneLine=options?.inOneLine??!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,this.oneLineMaxLength=this.normalizeOneLineMaxLength(options?.oneLineMaxLength),this.joinConditionContinuationIndent=options?.joinConditionContinuationIndent??!1;let onelineOptions={parenthesesOneLine:this.parenthesesOneLine,betweenOneLine:this.betweenOneLine,valuesOneLine:this.valuesOneLine,inOneLine:this.inOneLine,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","ReturningClause","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.joinOnClauseDepth=0,this.pendingLineCommentBreak=null,this.smartCommentBlockBuilder=null,this.expandedOneLineFallbackTokens=new WeakSet,this.commentedFunctionCallDepth=0,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,void 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,previousSiblingWasOpenParen=!1){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),leadingCommentFollowsLogicalOperator=hasRenderableLeadingComment&&this.currentLineEndsWithLogicalOperator(),leadingCommentIndentLevel=hasRenderableLeadingComment?this.getLeadingCommentIndentLevel(token.containerType==="SelectItem"?token.containerType:parentContainerType,level):null;hasRenderableLeadingComment&&!this.isOnelineMode()&&this.shouldAddNewlineBeforeLeadingComments(parentContainerType)&&!this.shouldKeepLeadingCommentOnCommaLine()&&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,!1),token.containerType==="SelectItem"&&this.smartCommentBlockBuilder?.mode==="line"&&this.flushSmartCommentBlockBuilder(),containerIsTopLevel&&!this.isOnelineMode()&&this.pendingLineCommentBreak===null&&this.linePrinter.getCurrentLine().text.trim()!==""&&this.linePrinter.appendNewline(level));if(hasRenderableLeadingComment&&containerIsTopLevel&&!this.isOnelineMode()&&this.linePrinter.getCurrentLine().text.trim()!==""&&this.linePrinter.appendNewline(level),leadingCommentFollowsLogicalOperator&&this.pendingLineCommentBreak===null&&!this.isOnelineMode()&&this.linePrinter.getCurrentLine().text.trim().endsWith("*/")&&this.linePrinter.appendNewline(level+1),this.smartCommentBlockBuilder&&token.containerType!=="CommentBlock"&&token.type!==12&&this.flushSmartCommentBlockBuilder(),this.pendingLineCommentBreak!==null){if(!this.isOnelineMode()){let pendingBreakLevel=leadingCommentFollowsLogicalOperator?this.pendingLineCommentBreak+1:this.pendingLineCommentBreak;this.linePrinter.appendNewline(pendingBreakLevel)}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;this.shouldKeepLeadingCommentOnCommaLine()&&this.ensureTrailingSpace();let commentLevel=this.getCommentBaseIndentLevel(level,parentContainerType);parentContainerType==="SelectItem"&&effectiveCommentContext.position==="leading"&&this.linePrinter.getCurrentLine().text.trim()===""&&(this.linePrinter.getCurrentLine().level=commentLevel),this.handleCommentBlockContainer(token,commentLevel,effectiveCommentContext);return}let current=this.linePrinter.getCurrentLine(),nextCaseContextDepth=this.isCaseContext(token.containerType)?caseContextDepth+1:caseContextDepth,shouldIndentNested=this.shouldIndentNestedParentheses(token,previousSiblingWasOpenParen);if(token.type===1)this.handleKeywordToken(token,level,parentContainerType,caseContextDepth);else if(token.type===3)this.handleCommaToken(token,level,parentContainerType);else if(token.type===11)this.handleArgumentSplitterToken(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"){if(this.tryHandleCteOnelineToken(token,level))return}else{if(this.inOneLine&&this.isInValueListExpression(token)&&this.tryHandleInOneLineToken(token,level))return;if(this.shouldFormatContainerAsOneline(token,shouldIndentNested)&&this.tryHandleOnelineToken(token,level))return;this.tryAppendInsertClauseTokenText(token.text,parentContainerType)||this.linePrinter.appendText(token.text)}if(token.containerType==="JoinOnClause"&&this.joinOnBreak==="before"&&!this.isOnelineMode()&&this.linePrinter.getCurrentLine().text.trim().length>0&&this.linePrinter.appendNewline(level+1),this.expandedOneLineFallbackTokens.has(token)&&(shouldIndentNested=!0),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,void 0,!1)}let innerLevel=level,increasedIndent=!1,shouldIncreaseIndent=this.indentIncrementContainers.has(token.containerType)||shouldIndentNested,delayIndentNewline=shouldIndentNested&&token.containerType==="ParenExpression",isAlterTableStatement=token.containerType==="AlterTableStatement",deferAlterTableIndent=!1;if(token.containerType==="JoinOnClause"&&this.joinOnBreak==="before"&&!this.isOnelineMode()&&(innerLevel=level+1),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,enteredJoinOnClause=token.containerType==="JoinOnClause";enteredJoinOnClause&&this.joinOnClauseDepth++;let enteredCommentedFunctionCall=this.shouldExpandCommentedFunctionCall(token);enteredCommentedFunctionCall&&this.commentedFunctionCallDepth++;let enteredLogicalOperatorWithComment=this.isLogicalOperatorWithComment(token);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 previousChildWasOpenParen=previousChild?.type===4&&previousChild.text.trim()==="(",childIndentParentActive=token.containerType==="ParenExpression"?shouldIndentNested:indentParentActive;inMergePredicate&&this.mergeWhenPredicateDepth++;let childCommentContext=child.containerType==="CommentBlock"?{position:"inline",isTopLevelContainer:containerIsTopLevel}:void 0,childLevel=enteredCommentedFunctionCall&&child.containerType==="ValueList"?innerLevel+1:innerLevel;this.appendToken(child,childLevel,token.containerType,nextCaseContextDepth,childIndentParentActive,childCommentContext,previousChildWasOpenParen),inMergePredicate&&this.mergeWhenPredicateDepth--,childIsAction&&isMergeWhenClause&&(mergePredicateActive=!1)}if(enteredLogicalOperatorWithComment&&!this.isOnelineMode()){let currentLine=this.linePrinter.getCurrentLine();currentLine.text.trim()===""?currentLine.level=level+1:this.linePrinter.appendNewline(level+1)}if(this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder(),enteredJoinOnClause&&this.joinOnClauseDepth--,enteredCommentedFunctionCall&&this.commentedFunctionCallDepth--,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}}shouldExpandCommentedFunctionCall(token){return this.commentExportMode!=="none"&&token.containerType==="FunctionCall"&&token.innerTokens.some(child=>child.containerType==="ValueList"&&this.containsCommentBlock(child))}containsCommentBlock(token){return token.containerType==="CommentBlock"?!0:token.innerTokens.some(child=>this.containsCommentBlock(child))}containsRenderableCommentBlock(token,context){return token.containerType==="CommentBlock"?this.shouldRenderComment(token,context):token.innerTokens.some(child=>this.containsRenderableCommentBlock(child,context))}isLogicalOperatorWithComment(token){return this.containsCommentBlock(token)&&token.type===5&&["and","or"].includes(token.text.toLowerCase())}currentLineEndsWithLogicalOperator(){let trimmed=this.linePrinter.getCurrentLine().text.trim().toLowerCase();return trimmed==="and"||trimmed==="or"}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)}handleArgumentSplitterToken(token,level,parentContainerType){this.linePrinter.appendText(token.text),this.commentedFunctionCallDepth>0&&parentContainerType==="ValueList"&&!this.isOnelineMode()&&this.linePrinter.appendNewline(level)}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(this.getJoinConditionContinuationLevel(level)),this.linePrinter.appendText(text)):this.andBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(this.getJoinConditionContinuationLevel(level))):this.linePrinter.appendText(text)}handleParenthesisToken(token,level,indentParentActive,parentContainerType){if(token.text==="("){if(this.linePrinter.appendText(token.text),this.commentedFunctionCallDepth>0&&parentContainerType==="FunctionCall"&&!this.isOnelineMode()){this.linePrinter.appendNewline(level+1);return}if((parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction")&&this.insertColumnsOneLine)return;this.isOnelineMode()||(this.shouldBreakAfterOpeningParen(parentContainerType)?this.linePrinter.appendNewline(level+1):indentParentActive&&parentContainerType==="ParenExpression"&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&this.linePrinter.appendNewline(level));return}if(token.text===")"&&!this.isOnelineMode()){if(this.commentedFunctionCallDepth>0&&parentContainerType==="FunctionCall"){this.linePrinter.appendNewline(level),this.linePrinter.appendText(token.text);return}if(this.shouldBreakBeforeClosingParen(parentContainerType)){this.linePrinter.appendNewline(Math.max(level,0)),this.linePrinter.appendText(token.text);return}if(indentParentActive&&parentContainerType==="ParenExpression"&&!(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(this.getJoinConditionContinuationLevel(level)),this.linePrinter.appendText(text)):this.orBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(this.getJoinConditionContinuationLevel(level))):this.linePrinter.appendText(text)}getJoinConditionContinuationLevel(level){return this.joinOnClauseDepth===0||this.joinOnBreak==="before"?level:this.joinConditionContinuationIndent?level+1:level}shouldIndentNestedParentheses(token,previousSiblingWasOpenParen=!1){return!this.indentNestedParentheses||token.containerType!=="ParenExpression"?!1:this.expandedOneLineFallbackTokens.has(token)?!0:previousSiblingWasOpenParen||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)}isInValueListExpression(token){return this.getInValueListParts(token)!==null}getInValueListParts(token){if(token.containerType!=="BinaryExpression")return null;let significant=token.innerTokens.filter(child=>child.type!==10);if(significant.length!==3)return null;let[left,operator,right]=significant,operatorText=operator.text.trim().toLowerCase();if(operatorText!=="in"&&operatorText!=="not in"||right.containerType!=="ParenExpression")return null;let valueList=right.innerTokens.find(child=>child.containerType==="ValueList");return valueList?{left,operator,valueList}:null}isInsertClauseOneline(parentContainerType){return this.onelineHelper.isInsertClauseOneline(parentContainerType)}handleSpaceToken(token,parentContainerType,nextToken,previousToken,priorToken){if(this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder(),this.commentedFunctionCallDepth>0&&parentContainerType==="ValueList"&&previousToken?.type===11&&!this.isOnelineMode())return;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];if(this.shouldFallbackSmartLineCommentToBlock()){this.linePrinter.appendText(this.buildBlockComment([content],level)),this.ensureTrailingSpace();return}let lineText=this.buildSmartLineComment(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:`
25
+ `,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){if(context.position==="leading"&&context.isTopLevelContainer&&!this.isOnelineMode()){for(let line of rawLines)this.linePrinter.appendText(`/* ${line} */`),this.linePrinter.appendNewline(level);return}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}let directBlockComments=this.extractDirectBlockCommentTexts(token);if(directBlockComments.length>1&&context.position==="leading"&&context.isTopLevelContainer&&!this.isOnelineMode()){for(let comment of directBlockComments)this.linePrinter.appendText(comment),this.linePrinter.appendNewline(level);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,!1)}return}let emptyBlockCommentText=this.getEmptyBlockCommentText(token);if(emptyBlockCommentText!==null){this.linePrinter.appendText(emptyBlockCommentText);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)}getEmptyBlockCommentText(token){let commentTokens=(token.innerTokens??[]).filter(child=>child.type===6);if(commentTokens.length!==1)return null;let trimmed=commentTokens[0].text.trim();return!trimmed.startsWith("/*")||!trimmed.endsWith("*/")?null:trimmed.slice(2,-2).trim()===""?trimmed:null}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||this.shouldFallbackSmartLineCommentToBlock()){let blockText=this.buildBlockComment(lines,level);this.linePrinter.appendText(blockText),this.shouldFallbackSmartLineCommentToBlock()&&this.ensureTrailingSpace()}else{let content=lines[0]??"";this.linePrinter.appendText(this.buildSmartLineComment(content))}this.isOnelineMode()||this.linePrinter.appendNewline(level),this.pendingLineCommentBreak=null}this.smartCommentBlockBuilder=null}shouldFallbackSmartLineCommentToBlock(){return this.isOnelineMode()}buildSmartLineComment(content){return content?`-- ${content}`:"--"}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&&(!content&&trimmed.startsWith("/*")&&trimmed.endsWith("*/")?lines.push(this.sanitizeCommentLine(this.escapeCommentDelimiters(trimmed))):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}extractDirectBlockCommentTexts(token){let comments=[];for(let child of token.innerTokens??[]){if(child.type!==6)continue;let trimmed=child.text.trim();trimmed.startsWith("/*")&&trimmed.endsWith("*/")&&comments.push(trimmed)}return comments}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,`
26
26
  `).includes(`
27
27
  `)?(forceBlock=!0,source=inner):(source=inner,source.trim()||(source=trimmed))}let rawSegments=this.escapeCommentDelimiters(source).replace(/\r?\n/g,`
28
28
  `).split(`
29
29
  `),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===" "?`
30
- `: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==="OrderByItem"||parentType==="GroupByClause"||parentType==="ExplainStatement"||parentType==="ReturningClause":!1}getLeadingCommentIndentLevel(parentType,currentLevel){return parentType==="SelectItem"||parentType==="OrderByItem"||parentType==="GroupByClause"?currentLevel:parentType==="TupleExpression"||parentType==="InsertClause"||parentType==="MergeInsertAction"||parentType==="SelectClause"||parentType==="ReturningClause"||parentType==="SetClause"?currentLevel+1:currentLevel}shouldKeepLeadingCommentOnCommaLine(){return this.commaBreak!=="before"?!1:this.linePrinter.getCurrentLine().text.trim()===","}isOnelineMode(){return this.newline===" "}normalizeOneLineMaxLength(value){if(value===void 0||!Number.isFinite(value)||value<=0)return;let normalized=Math.floor(value);return normalized>0?normalized:void 0}fitsOneLineMaxLength(text){if(this.oneLineMaxLength===void 0)return!0;let currentLine=this.linePrinter.getCurrentLine();return currentLine.level*this.indentSize*String(this.indentChar).length+currentLine.text.length+text.length<=this.oneLineMaxLength}tryHandleCteOnelineToken(token,level){let onelineResult=this.createCteOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);cleanedResult=cleanedResult.replace(/\(\s+/g,"(").replace(/\s+\)/g," )");let trimmedResult=cleanedResult.trim();return this.fitsOneLineMaxLength(trimmedResult)?(this.linePrinter.appendText(trimmedResult),!0):!1}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})}tryHandleOnelineToken(token,level){let onelineResult=this.createOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);return this.fitsOneLineMaxLength(cleanedResult)?(this.linePrinter.appendText(cleanedResult),!0):(this.isBooleanParenExpression(token)&&this.expandedOneLineFallbackTokens.add(token),!1)}isBooleanParenExpression(token){return token.containerType!=="ParenExpression"?!1:this.containsLogicalOperator(token)}containsLogicalOperator(token){return(token.type===5||token.type===1)&&["and","or"].includes(token.text.toLowerCase())?!0:token.innerTokens.some(child=>this.containsLogicalOperator(child))}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"||parentType==="ReturningClause")?!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,options.identifierEscapeTarget??"all"),parserOptions={...presetConfig,identifierEscape:resolvedIdentifierEscape??presetConfig?.identifierEscape,parameterSymbol:options.parameterSymbol??presetConfig?.parameterSymbol,parameterStyle:options.parameterStyle??presetConfig?.parameterStyle,castStyle:options.castStyle??presetConfig?.castStyle,sourceAliasStyle:options.sourceAliasStyle??presetConfig?.sourceAliasStyle,orderByDefaultDirectionStyle:options.orderByDefaultDirectionStyle??presetConfig?.orderByDefaultDirectionStyle,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(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(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)}visitJsonPredicateExpression(expr){expr.expression.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 withOrdinality=!1;idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++);let functionName=name.name;return{value:new FunctionSource({namespaces,name:functionName},argument.value,withOrdinality),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);if(nextCteMap.delete(src.table.name),!this.isSelectQuery(cte.query))return null;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.collectColumnsFromCteQuery(cte.query);cteColumns.push(...columns)}return cteColumns}collectColumnsFromCteQuery(query){return this.isSelectQuery(query)?this.collectColumnsFromSelectQuery(query):this.collectColumnsFromReturning(query)}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[]}collectColumnsFromReturning(query){return query instanceof InsertQuery||query instanceof UpdateQuery||query instanceof DeleteQuery||query instanceof MergeQuery?this.extractReturningColumns(query.returningClause):[]}extractReturningColumns(returningClause){if(!returningClause)return[];let columns=[];for(let item of returningClause.items){let name=item.identifier?.name??this.extractColumnName(item);name&&columns.push(name)}return columns}extractColumnName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}};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.withClause=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 preservedWithClause=SelectQueryWithClauseHelper.getWithClause(valuesQuery),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 SelectQueryWithClauseHelper.setWithClause(combined,preservedWithClause),new InsertQuery({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 preservedWithClause=SelectQueryWithClauseHelper.getWithClause(insertQuery.selectQuery),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 SelectQueryWithClauseHelper.setWithClause(valuesQuery,preservedWithClause),new InsertQuery({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 TextPositionUtils=class{static lineColumnToCharOffset(text,position){if(position.line<1||position.column<1)return-1;let lines=text.split(`
30
+ `: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==="OrderByItem"||parentType==="GroupByClause"||parentType==="ExplainStatement"||parentType==="ReturningClause":!1}getLeadingCommentIndentLevel(parentType,currentLevel){return parentType==="SelectItem"||parentType==="OrderByItem"||parentType==="GroupByClause"?currentLevel:parentType==="TupleExpression"||parentType==="InsertClause"||parentType==="MergeInsertAction"||parentType==="SelectClause"||parentType==="ReturningClause"||parentType==="SetClause"?currentLevel+1:currentLevel}shouldKeepLeadingCommentOnCommaLine(){return this.commaBreak!=="before"?!1:this.linePrinter.getCurrentLine().text.trim()===","}isOnelineMode(){return this.newline===" "}normalizeOneLineMaxLength(value){if(value==null||!Number.isFinite(value)||value<=0)return;let normalized=Math.floor(value);return normalized>0?normalized:void 0}normalizeKeywordCase(value){return value==="preserve"?"none":value??"none"}normalizeJoinOnBreak(value){return value==="before"?"before":"none"}fitsOneLineMaxLength(text){if(this.oneLineMaxLength===void 0)return!0;let currentLine=this.linePrinter.getCurrentLine();return currentLine.level*this.indentSize*String(this.indentChar).length+currentLine.text.length+text.length<=this.oneLineMaxLength}tryHandleCteOnelineToken(token,level){if(this.shouldPreserveCteComments(token))return!1;let onelineResult=this.createCteOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);cleanedResult=cleanedResult.replace(/\(\s+/g,"(").replace(/\s+\)/g," )");let trimmedResult=cleanedResult.trim();return this.fitsOneLineMaxLength(trimmedResult)?(this.linePrinter.appendText(trimmedResult),!0):!1}shouldPreserveCteComments(token){return this.containsRenderableCommentBlock(token,{position:"inline",isTopLevelContainer:!1})}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})}tryHandleOnelineToken(token,level){let onelineResult=this.createOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);return this.fitsOneLineMaxLength(cleanedResult)?(this.linePrinter.appendText(cleanedResult),!0):(this.isBooleanParenExpression(token)&&this.expandedOneLineFallbackTokens.add(token),!1)}tryHandleInOneLineToken(token,level){let parts=this.getInValueListParts(token);if(!parts)return!1;if(this.containsRenderableCommentBlock(parts.valueList,{position:"inline",isTopLevelContainer:!1}))return this.appendExpandedInValueList(parts,token,level),!0;let onelineResult=this.createOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);return this.fitsOneLineMaxLength(cleanedResult)?(this.linePrinter.appendText(cleanedResult),!0):(this.appendExpandedInValueList(parts,token,level),!0)}appendExpandedInValueList(parts,token,level){this.appendToken(parts.left,level,token.containerType),this.ensureTrailingSpace(),this.linePrinter.appendText(this.applyKeywordCase(parts.operator.text)),this.ensureTrailingSpace(),this.linePrinter.appendText("(");let valueGroups=this.splitValueListItems(parts.valueList);for(let i=0;i<valueGroups.length;i++){this.linePrinter.appendNewline(level+1),i>0&&(this.linePrinter.appendText(","),this.ensureTrailingSpace());for(let valueToken of valueGroups[i])this.appendToken(valueToken,level+1,"ValueList")}this.linePrinter.appendNewline(level),this.linePrinter.appendText(")")}splitValueListItems(valueList){let groups=[[]];for(let child of valueList.innerTokens){if(child.type===11){groups.push([]);continue}child.type===10&&groups[groups.length-1].length===0||groups[groups.length-1].push(child)}return groups.filter(group=>group.length>0)}isBooleanParenExpression(token){return token.containerType!=="ParenExpression"?!1:this.containsLogicalOperator(token)}containsLogicalOperator(token){return(token.type===5||token.type===1)&&["and","or"].includes(token.text.toLowerCase())?!0:token.innerTokens.some(child=>this.containsLogicalOperator(child))}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"||parentType==="ReturningClause")?!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,inOneLine:!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,options.identifierEscapeTarget??"all"),parserOptions={...presetConfig,identifierEscape:resolvedIdentifierEscape??presetConfig?.identifierEscape,parameterSymbol:options.parameterSymbol??presetConfig?.parameterSymbol,parameterStyle:options.parameterStyle??presetConfig?.parameterStyle,castStyle:options.castStyle??presetConfig?.castStyle,sourceAliasStyle:options.sourceAliasStyle??presetConfig?.sourceAliasStyle,columnAliasStyle:options.columnAliasStyle??presetConfig?.columnAliasStyle,orderByDefaultDirectionStyle:options.orderByDefaultDirectionStyle??presetConfig?.orderByDefaultDirectionStyle,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,inOneLine:options.inOneLine,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(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(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)}visitJsonPredicateExpression(expr){expr.expression.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 withOrdinality=!1;idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++);let functionName=name.name;return{value:new FunctionSource({namespaces,name:functionName},argument.value,withOrdinality),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);if(nextCteMap.delete(src.table.name),!this.isSelectQuery(cte.query))return null;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.collectColumnsFromCteQuery(cte.query);cteColumns.push(...columns)}return cteColumns}collectColumnsFromCteQuery(query){return this.isSelectQuery(query)?this.collectColumnsFromSelectQuery(query):this.collectColumnsFromReturning(query)}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[]}collectColumnsFromReturning(query){return query instanceof InsertQuery||query instanceof UpdateQuery||query instanceof DeleteQuery||query instanceof MergeQuery?this.extractReturningColumns(query.returningClause):[]}extractReturningColumns(returningClause){if(!returningClause)return[];let columns=[];for(let item of returningClause.items){let name=item.identifier?.name??this.extractColumnName(item);name&&columns.push(name)}return columns}extractColumnName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}};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.withClause=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 preservedWithClause=SelectQueryWithClauseHelper.getWithClause(valuesQuery),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 SelectQueryWithClauseHelper.setWithClause(combined,preservedWithClause),new InsertQuery({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 preservedWithClause=SelectQueryWithClauseHelper.getWithClause(insertQuery.selectQuery),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 SelectQueryWithClauseHelper.setWithClause(valuesQuery,preservedWithClause),new InsertQuery({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 TextPositionUtils=class{static lineColumnToCharOffset(text,position){if(position.line<1||position.column<1)return-1;let lines=text.split(`
31
31
  `);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(text,charOffset){if(charOffset<0||charOffset>text.length)return null;let lines=text.split(`
32
32
  `),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===text.length){let lastLine=lines[lines.length-1];return{line:lines.length,column:lastLine.length+1}}return null}static isValidPosition(text,position){return this.lineColumnToCharOffset(text,position)!==-1}static getLine(text,lineNumber){if(lineNumber<1)return null;let lines=text.split(`
33
33
  `);return lineNumber>lines.length?null:lines[lineNumber-1]}static getLineCount(text){return text.split(`
@@ -42,11 +42,11 @@ ${lines.map(line=>` ${line}`).join(`
42
42
  `))}};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(`
43
43
  `)}
44
44
  ${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(`
45
- `)+sql}getAllCTENames(ctes){return ctes.map(cte=>this.getCTEName(cte))}getCTEName(cte){return cte.aliasExpression.table.name}};var ColumnReferenceCollector=class{constructor(){this.columnReferences=[];this.visitedNodes=new Set;this.handlers=new Map,this.handlers.set(WithClause.kind,clause=>this.visitWithClause(clause)),this.handlers.set(CommonTable.kind,table=>this.visitCommonTable(table)),this.handlers.set(SelectClause.kind,clause=>this.visitSelectClause(clause)),this.handlers.set(FromClause.kind,clause=>this.visitFromClause(clause)),this.handlers.set(WhereClause.kind,clause=>this.visitWhereClause(clause)),this.handlers.set(GroupByClause.kind,clause=>this.visitGroupByClause(clause)),this.handlers.set(HavingClause.kind,clause=>this.visitHavingClause(clause)),this.handlers.set(OrderByClause.kind,clause=>this.visitOrderByClause(clause)),this.handlers.set(WindowsClause.kind,clause=>this.visitWindowsClause(clause)),this.handlers.set(LimitClause.kind,clause=>this.visitLimitClause(clause)),this.handlers.set(OffsetClause.kind,clause=>this.visitOffsetClause(clause)),this.handlers.set(FetchClause.kind,clause=>this.visitFetchClause(clause)),this.handlers.set(ForClause.kind,clause=>this.visitForClause(clause)),this.handlers.set(JoinClause.kind,clause=>this.visitJoinClause(clause)),this.handlers.set(JoinOnClause.kind,clause=>this.visitJoinOnClause(clause)),this.handlers.set(JoinUsingClause.kind,clause=>this.visitJoinUsingClause(clause)),this.handlers.set(SourceExpression.kind,source=>this.visitSourceExpression(source)),this.handlers.set(SubQuerySource.kind,source=>this.visitSubQuerySource(source)),this.handlers.set(InsertQuery.kind,query=>this.visitInsertQuery(query)),this.handlers.set(UpdateQuery.kind,query=>this.visitUpdateQuery(query)),this.handlers.set(DeleteQuery.kind,query=>this.visitDeleteQuery(query)),this.handlers.set(MergeQuery.kind,query=>this.visitMergeQuery(query)),this.handlers.set(ColumnReference.kind,ref=>this.visitColumnReference(ref)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(FunctionCall.kind,func=>this.visitFunctionCall(func)),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(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(InlineQuery.kind,query=>this.visitInlineQuery(query)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ValueList.kind,list=>this.visitValueList(list)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr))}collect(query){return this.columnReferences=[],this.visitedNodes.clear(),query instanceof SimpleSelectQuery?this.collectFromSimpleQuery(query):query instanceof BinarySelectQuery?this.collectFromSimpleQuery(query.toSimpleQuery()):query.accept(this),[...this.columnReferences]}collectFromSimpleQuery(query){if(query.withClause&&query.withClause.tables)for(let cte of query.withClause.tables){let cteQuery=cte.query;cteQuery instanceof SimpleSelectQuery?this.collectFromSimpleQuery(cteQuery):cteQuery instanceof BinarySelectQuery?this.collectFromSimpleQuery(cteQuery.toSimpleQuery()):cteQuery.accept(this)}if(this.collectFromSelectClause(query.selectClause),query.fromClause&&this.collectFromFromClause(query.fromClause),query.whereClause&&this.collectFromValueComponent(query.whereClause.condition),query.groupByClause&&query.groupByClause.grouping)for(let item of query.groupByClause.grouping)this.collectFromValueComponent(item);if(query.havingClause&&this.collectFromValueComponent(query.havingClause.condition),query.orderByClause&&query.orderByClause.order)for(let item of query.orderByClause.order)typeof item=="object"&&"value"in item&&item.value?this.collectFromValueComponent(item.value):this.collectFromValueComponent(item)}collectFromSelectClause(clause){for(let item of clause.items)this.collectFromValueComponent(item.value)}collectFromFromClause(clause){if(this.collectFromSourceExpression(clause.source),clause.joins)for(let join of clause.joins)this.collectFromSourceExpression(join.source),join.condition&&this.collectFromValueComponent(join.condition.condition)}collectFromSourceExpression(source){source.datasource instanceof SubQuerySource&&(source.datasource.query instanceof SimpleSelectQuery?this.collectFromSimpleQuery(source.datasource.query):source.datasource.query instanceof BinarySelectQuery&&this.collectFromSimpleQuery(source.datasource.query.toSimpleQuery()))}collectFromValueComponent(value){if(value instanceof ColumnReference)this.columnReferences.push(value);else if(value instanceof JsonPredicateExpression)this.collectFromValueComponent(value.expression);else if(value instanceof BinaryExpression)this.collectFromValueComponent(value.left),this.collectFromValueComponent(value.right);else if(value instanceof UnaryExpression)this.collectFromValueComponent(value.expression);else if(value instanceof FunctionCall)value.argument&&this.collectFromValueComponent(value.argument),value.filterCondition&&this.collectFromValueComponent(value.filterCondition);else if(value instanceof CaseExpression){if(value.condition&&this.collectFromValueComponent(value.condition),value.switchCase&&value.switchCase.cases)for(let pair of value.switchCase.cases)this.collectFromValueComponent(pair.key),this.collectFromValueComponent(pair.value);value.switchCase&&value.switchCase.elseValue&&this.collectFromValueComponent(value.switchCase.elseValue)}else value instanceof ParenExpression?this.collectFromValueComponent(value.expression):value instanceof InlineQuery&&(value.selectQuery instanceof SimpleSelectQuery?this.collectFromSimpleQuery(value.selectQuery):value.selectQuery instanceof BinarySelectQuery&&this.collectFromSimpleQuery(value.selectQuery.toSimpleQuery()))}visit(component){if(this.visitedNodes.has(component))return;this.visitedNodes.add(component);let handler=this.handlers.get(component.getKind());handler&&handler(component)}visitSimpleSelectQuery(query){query.withClause&&query.withClause.accept(this),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.orderByClause&&query.orderByClause.accept(this),query.windowClause&&query.windowClause.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)}visitWithClause(clause){for(let table of clause.tables)table.accept(this)}visitCommonTable(table){table.query.accept(this)}visitSelectClause(clause){for(let item of clause.items)item.value.accept(this)}visitFromClause(clause){if(clause.source.accept(this),clause.joins)for(let join of clause.joins)join.accept(this)}visitWhereClause(clause){clause.condition.accept(this)}visitGroupByClause(clause){if(clause.grouping)for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition.accept(this)}visitOrderByClause(clause){if(clause.order)for(let item of clause.order)typeof item=="object"&&"value"in item&&item.value?typeof item.value=="object"&&"accept"in item.value&&item.value.accept(this):typeof item=="object"&&"accept"in item&&item.accept(this)}visitWindowsClause(clause){for(let window of clause.windows)window.expression.accept(this)}visitLimitClause(clause){clause.value.accept(this)}visitOffsetClause(clause){clause.value.accept(this)}visitFetchClause(clause){clause.expression.accept(this)}visitForClause(clause){}visitJoinClause(clause){clause.source.accept(this),clause.condition&&clause.condition.accept(this)}visitJoinOnClause(clause){clause.condition.accept(this)}visitJoinUsingClause(clause){clause.condition.accept(this)}visitSourceExpression(source){source.datasource.accept(this)}visitSubQuerySource(source){source.query.accept(this)}visitInsertQuery(query){query.selectQuery&&(query.selectQuery instanceof SimpleSelectQuery?this.collectFromSimpleQuery(query.selectQuery):query.selectQuery instanceof BinarySelectQuery?this.collectFromSimpleQuery(query.selectQuery.toSimpleQuery()):query.selectQuery.accept(this)),query.returningClause&&this.visitReturningClause(query.returningClause)}visitUpdateQuery(query){query.withClause&&query.withClause.accept(this),query.setClause.items.forEach(item=>item.value.accept(this)),query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.returningClause&&this.visitReturningClause(query.returningClause)}visitDeleteQuery(query){query.withClause&&query.withClause.accept(this),query.usingClause&&query.usingClause.sources.forEach(source=>source.accept(this)),query.whereClause&&query.whereClause.accept(this),query.returningClause&&this.visitReturningClause(query.returningClause)}visitMergeQuery(query){query.withClause&&query.withClause.accept(this),query.target.accept(this),query.source.accept(this),query.onCondition.accept(this);for(let clause of query.whenClauses)clause.condition&&clause.condition.accept(this),clause.action instanceof MergeUpdateAction?(clause.action.setClause.items.forEach(item=>item.value.accept(this)),clause.action.whereClause&&clause.action.whereClause.accept(this)):clause.action instanceof MergeDeleteAction?clause.action.whereClause&&clause.action.whereClause.accept(this):clause.action instanceof MergeInsertAction&&clause.action.values&&clause.action.values.accept(this);query.returningClause&&this.visitReturningClause(query.returningClause)}visitReturningClause(clause){for(let item of clause.items)item.value.accept(this)}visitColumnReference(ref){this.columnReferences.push(ref)}visitBinaryExpression(expr){expr.left.accept(this),expr.right.accept(this)}visitJsonPredicateExpression(expr){expr.expression.accept(this)}visitUnaryExpression(expr){expr.expression.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.filterCondition&&func.filterCondition.accept(this)}visitCaseExpression(expr){if(expr.condition&&expr.condition.accept(this),expr.switchCase&&expr.switchCase.cases)for(let pair of expr.switchCase.cases)pair.key.accept(this),pair.value.accept(this);expr.switchCase&&expr.switchCase.elseValue&&expr.switchCase.elseValue.accept(this)}visitCastExpression(expr){expr.input.accept(this)}visitBetweenExpression(expr){expr.expression.accept(this),expr.lower.accept(this),expr.upper.accept(this)}visitParenExpression(expr){expr.expression.accept(this)}visitInlineQuery(query){query.selectQuery.accept(this)}visitArrayExpression(expr){expr.expression&&expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitValueList(list){if(list.values)for(let item of list.values)item.accept(this)}visitWindowFrameExpression(expr){expr.partition&&expr.partition.accept(this),expr.order&&expr.order.accept(this)}};var ERROR_MESSAGES={nullQuery:"Query cannot be null or undefined",invalidOldName:"Old CTE name must be a non-empty string",invalidNewName:"New CTE name must be a non-empty string",sameNames:"Old and new CTE names cannot be the same",unsupportedQuery:"Unsupported query type for CTE renaming",cteNotExists:name=>`CTE '${name}' does not exist`,cteAlreadyExists:name=>`CTE '${name}' already exists`,cteNotFound:name=>`CTE '${name}' not found`},CTERenamer=class{constructor(){this.dependencyAnalyzer=new CTEDependencyAnalyzer,this.columnReferenceCollector=new ColumnReferenceCollector,this.tableSourceCollector=new TableSourceCollector,this.keywordParser=new KeywordParser(keywordTrie)}renameCTE(query,oldName,newName){this.validateInputs(query,oldName,newName);let sanitizedOldName=oldName.trim(),sanitizedNewName=newName.trim();if(query instanceof SimpleSelectQuery)this.renameInSimpleQuery(query,sanitizedOldName,sanitizedNewName);else if(query instanceof BinarySelectQuery)this.renameInBinaryQuery(query,sanitizedOldName,sanitizedNewName);else throw new Error(ERROR_MESSAGES.unsupportedQuery)}validateInputs(query,oldName,newName){if(!query)throw new Error(ERROR_MESSAGES.nullQuery);if(!oldName||typeof oldName!="string"||oldName.trim()==="")throw new Error(ERROR_MESSAGES.invalidOldName);if(!newName||typeof newName!="string"||newName.trim()==="")throw new Error(ERROR_MESSAGES.invalidNewName);if(oldName.trim()===newName.trim())throw new Error(ERROR_MESSAGES.sameNames)}renameInSimpleQuery(query,oldName,newName){let availableCTEs=query.getCTENames();if(!availableCTEs.includes(oldName))throw new Error(ERROR_MESSAGES.cteNotExists(oldName));if(availableCTEs.includes(newName))throw new Error(ERROR_MESSAGES.cteAlreadyExists(newName));this.renameCTEDefinition(query,oldName,newName),this.updateAllReferences(query,oldName,newName)}renameInBinaryQuery(query,oldName,newName){let withClauseQuery=query.toSimpleQuery(),availableCTEs=[];if(withClauseQuery.withClause&&withClauseQuery.withClause.tables&&(availableCTEs=withClauseQuery.withClause.tables.map(cte=>cte.aliasExpression.table.name)),!availableCTEs.includes(oldName))throw new Error(ERROR_MESSAGES.cteNotExists(oldName));if(availableCTEs.includes(newName))throw new Error(ERROR_MESSAGES.cteAlreadyExists(newName));this.renameCTEDefinition(withClauseQuery,oldName,newName),withClauseQuery.withClause&&(query.withClause=withClauseQuery.withClause,query.left instanceof SimpleSelectQuery&&(query.left.withClause=withClauseQuery.withClause)),this.renameInSelectQuery(query.left,oldName,newName),this.renameInSelectQuery(query.right,oldName,newName)}renameInSelectQuery(query,oldName,newName){query instanceof SimpleSelectQuery?this.updateAllReferences(query,oldName,newName):query instanceof BinarySelectQuery&&(this.renameInSelectQuery(query.left,oldName,newName),this.renameInSelectQuery(query.right,oldName,newName))}renameCTEDefinition(query,oldName,newName){if(!query.withClause||!query.withClause.tables)throw new Error(ERROR_MESSAGES.cteNotFound(oldName));let cteToRename=query.withClause.tables.find(cte=>cte.aliasExpression.table.name===oldName);if(!cteToRename)throw new Error(ERROR_MESSAGES.cteNotFound(oldName));cteToRename.aliasExpression.table.name=newName}updateAllReferences(query,oldName,newName){let columnReferences=this.columnReferenceCollector.collect(query);for(let columnRef of columnReferences)if(columnRef.namespaces&&columnRef.namespaces.length>0){for(let namespace of columnRef.namespaces)if(namespace.name===oldName){namespace.name=newName;break}}let tableSources=this.tableSourceCollector.collect(query);for(let tableSource of tableSources)tableSource.getSourceName()===oldName&&(tableSource.qualifiedName.name instanceof ColumnReference||("name"in tableSource.qualifiedName.name?tableSource.qualifiedName.name.name=newName:tableSource.qualifiedName.name.value=newName));this.updateTableSourcesInCTEs(query,oldName,newName)}updateTableSourcesInCTEs(query,oldName,newName){if(!(!query.withClause||!query.withClause.tables))for(let cte of query.withClause.tables)cte.query instanceof SimpleSelectQuery&&this.updateTableSourcesInQuery(cte.query,oldName,newName)}updateTableSourcesInQuery(query,oldName,newName){if(query.fromClause&&query.fromClause.source.datasource&&this.updateTableSource(query.fromClause.source.datasource,oldName,newName),query.fromClause&&query.fromClause.joins)for(let join of query.fromClause.joins)join.source.datasource&&this.updateTableSource(join.source.datasource,oldName,newName)}updateTableSource(datasource,oldName,newName){if(!datasource||typeof datasource!="object")return;let source=datasource;if(typeof source.getSourceName=="function")try{if(source.getSourceName()===oldName&&source.qualifiedName&&typeof source.qualifiedName=="object"){let qualifiedName=source.qualifiedName;if(qualifiedName.name&&typeof qualifiedName.name=="object"){let nameObj=qualifiedName.name;"name"in nameObj&&typeof nameObj.name=="string"?nameObj.name=newName:"value"in nameObj&&typeof nameObj.value=="string"&&(nameObj.value=newName)}}}catch(error){console.warn("Warning: Failed to update table source:",error)}}renameCTEAtPosition(sql,position,newName){if(!sql?.trim())throw new Error("SQL cannot be empty");if(!position||position.line<1||position.column<1)throw new Error("Position must be a valid line/column (1-based)");if(!newName?.trim())throw new Error("New CTE name cannot be empty");let lexeme=LexemeCursor.findLexemeAtLineColumn(sql,position);if(!lexeme)throw new Error(`No CTE name found at line ${position.line}, column ${position.column}`);let cteName=lexeme.value,query=SelectQueryParser.parse(sql);if(!this.isCTENameInQuery(query,cteName))throw new Error(`'${cteName}' is not a CTE name in this query`);if(!(lexeme.type&2112))throw new Error(`Token at position is not a CTE name: '${lexeme.value}'`);let conflicts=this.checkNameConflicts(query,newName,cteName);if(conflicts.length>0)throw new Error(conflicts.join(", "));return this.renameCTE(query,cteName,newName),new SqlFormatter().format(query).formattedSql}checkNameConflicts(query,newName,currentName){let conflicts=[];return currentName===newName||(conflicts.push(...this.checkKeywordConflicts(newName)),this.isCTENameInQuery(query,newName)&&conflicts.push(`CTE name '${newName}' already exists`)),conflicts}checkKeywordConflicts(newName){let conflicts=[];try{let keywordResult=this.keywordParser.parse(newName,0);keywordResult!==null&&keywordResult.keyword.toLowerCase()===newName.toLowerCase()&&conflicts.push(`'${newName}' is a reserved SQL keyword and should not be used as a CTE name`)}catch(error){console.warn(`Failed to check keyword conflicts for '${newName}':`,error),this.isBasicReservedKeyword(newName)&&conflicts.push(`'${newName}' is a reserved SQL keyword and should not be used as a CTE name`)}return conflicts}isBasicReservedKeyword(name){return["select","from","where","with","as","union","join","table","null"].includes(name.toLowerCase())}isCTENameInQuery(query,cteName){return query instanceof SimpleSelectQuery&&query.withClause?query.withClause.tables.some(cte=>cte.aliasExpression&&cte.aliasExpression.table&&cte.aliasExpression.table.name===cteName):query instanceof BinarySelectQuery?this.isCTENameInQuery(query.left,cteName)||this.isCTENameInQuery(query.right,cteName):!1}};var ERROR_MESSAGES2={invalidSql:"Invalid SQL: unable to parse query",invalidPosition:"Invalid position: line or column out of bounds",noLexemeAtPosition:"No lexeme found at the specified position",notAnAlias:"Selected lexeme is not a valid alias",invalidNewName:"New alias name must be a non-empty string",sameNames:"Old and new alias names cannot be the same",nameConflict:name=>`Alias '${name}' already exists in this scope`,aliasNotFound:name=>`Alias '${name}' not found in current scope`},AliasRenamer=class{constructor(){this.keywordParser=new KeywordParser(keywordTrie)}renameAlias(sql,position,newName,options={}){try{this.validateInputs(sql,position,newName);let lexeme=LexemeCursor.findLexemeAtLineColumn(sql,position);if(!lexeme)throw new Error(ERROR_MESSAGES2.noLexemeAtPosition);this.validateLexemeIsAlias(lexeme);let query=SelectQueryParser.parse(sql),scope=this.detectAliasScope(sql,query,lexeme,options.scopeType),references=this.collectAliasReferences(scope,lexeme.value),conflicts=this.checkNameConflicts(scope,newName,lexeme.value);if(conflicts.length>0)return{success:!1,originalSql:sql,changes:[],conflicts,scope};let changes=this.prepareChanges(references,newName);if(options.dryRun)return{success:!0,originalSql:sql,changes,conflicts,scope};let newSql=this.performLexemeBasedRename(sql,lexeme.value,newName,scope);return{success:!0,originalSql:sql,newSql,changes,scope}}catch(error){return{success:!1,originalSql:sql,changes:[],conflicts:[error instanceof Error?error.message:String(error)]}}}validateInputs(sql,position,newName){if(!sql||typeof sql!="string"||sql.trim()==="")throw new Error(ERROR_MESSAGES2.invalidSql);if(!position||typeof position.line!="number"||typeof position.column!="number"||position.line<1||position.column<1)throw new Error(ERROR_MESSAGES2.invalidPosition);if(!newName||typeof newName!="string"||newName.trim()==="")throw new Error(ERROR_MESSAGES2.invalidNewName)}validateLexemeIsAlias(lexeme){if(!(lexeme.type&64))throw new Error(ERROR_MESSAGES2.notAnAlias)}detectAliasScope(sql,query,lexeme,scopeType){if(!lexeme.position)return{type:"main",query,startPosition:0,endPosition:sql.length};let lexemePosition=lexeme.position.startPosition;return scopeType&&scopeType!=="auto"?this.createScopeForType(scopeType,sql,query,lexemePosition):this.autoDetectScope(sql,query,lexemePosition)}createScopeForType(scopeType,sql,query,position){switch(scopeType){case"cte":return this.detectCTEScope(sql,query,position);case"subquery":return this.detectSubqueryScope(sql,query,position);case"main":default:return{type:"main",query,startPosition:0,endPosition:sql.length}}}autoDetectScope(sql,query,position){let cteScope=this.detectCTEScope(sql,query,position);if(cteScope.type==="cte")return cteScope;let subqueryScope=this.detectSubqueryScope(sql,query,position);return subqueryScope.type==="subquery"?subqueryScope:{type:"main",query,startPosition:0,endPosition:sql.length}}detectCTEScope(sql,query,position){try{let analysis=CTERegionDetector.analyzeCursorPosition(sql,position);if(analysis.isInCTE&&analysis.cteRegion){let cteQuery=this.findCTEQueryByName(query,analysis.cteRegion.name);return{type:"cte",name:analysis.cteRegion.name,query:cteQuery||query,startPosition:analysis.cteRegion.startPosition,endPosition:analysis.cteRegion.endPosition}}}catch(error){console.warn("CTE scope detection failed:",error)}return{type:"main",query,startPosition:0,endPosition:sql.length}}detectSubqueryScope(sql,query,position){return{type:"main",query,startPosition:0,endPosition:sql.length}}findCTEQueryByName(query,cteName){if(query instanceof SimpleSelectQuery&&query.withClause?.tables){for(let cte of query.withClause.tables)if(cte.aliasExpression.table.name===cteName)return this.isSelectQuery(cte.query)?cte.query:null}else if(query instanceof BinarySelectQuery){let leftResult=this.findCTEQueryByName(query.left,cteName);if(leftResult)return leftResult;let rightResult=this.findCTEQueryByName(query.right,cteName);if(rightResult)return rightResult}return null}isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}collectAliasReferences(scope,aliasName){let references=[];try{let tableReferences=this.collectTableAliasReferences(scope,aliasName);references.push(...tableReferences);let columnReferences=this.collectColumnAliasReferences(scope,aliasName);references.push(...columnReferences)}catch(error){console.warn(`Failed to collect alias references for '${aliasName}':`,error)}return references}collectTableAliasReferences(scope,aliasName){let references=[];try{let tableSources=new TableSourceCollector(!0).collect(scope.query);for(let tableSource of tableSources)if(tableSource.getSourceName()===aliasName){let lexeme=this.createLexemeFromTableSource(tableSource,aliasName);lexeme&&references.push({lexeme,scope,referenceType:"definition",context:"table"})}}catch(error){console.warn(`Failed to collect table alias references for '${aliasName}':`,error)}return references}collectColumnAliasReferences(scope,aliasName){let references=[];try{let columnRefs=new ColumnReferenceCollector().collect(scope.query);for(let columnRef of columnRefs)if(columnRef.namespaces&&columnRef.namespaces.length>0){for(let namespace of columnRef.namespaces)if(namespace.name===aliasName){let lexeme=this.createLexemeFromNamespace(namespace,aliasName);lexeme&&references.push({lexeme,scope,referenceType:"usage",context:"column"})}}}catch(error){console.warn(`Failed to collect column alias references for '${aliasName}':`,error)}return references}createLexemeFromTableSource(tableSource,aliasName){try{return{type:64,value:aliasName,comments:null,position:{startPosition:0,endPosition:aliasName.length}}}catch(error){return console.warn("Failed to create lexeme from table source:",error),null}}createLexemeFromNamespace(namespace,aliasName){try{return{type:64,value:aliasName,comments:null,position:{startPosition:0,endPosition:aliasName.length}}}catch(error){return console.warn("Failed to create lexeme from namespace:",error),null}}checkNameConflicts(scope,newName,currentName){let conflicts=[];if(newName.toLowerCase()===currentName.toLowerCase())return conflicts.push(ERROR_MESSAGES2.sameNames),conflicts;try{let tableConflicts=this.checkTableAliasConflicts(scope,newName);conflicts.push(...tableConflicts);let keywordConflicts=this.checkKeywordConflicts(newName);conflicts.push(...keywordConflicts)}catch(error){console.warn(`Error during conflict detection for '${newName}':`,error),conflicts.push(`Unable to verify conflicts for name '${newName}'`)}return conflicts}checkTableAliasConflicts(scope,newName){let conflicts=[];try{let tableSources=new TableSourceCollector(!0).collect(scope.query);for(let tableSource of tableSources){let aliasName=tableSource.getSourceName();if(aliasName&&aliasName.toLowerCase()===newName.toLowerCase()){conflicts.push(ERROR_MESSAGES2.nameConflict(newName));continue}let tableName=this.extractTableName(tableSource);tableName&&tableName.toLowerCase()===newName.toLowerCase()&&conflicts.push(`'${newName}' conflicts with table name in this scope`)}}catch(error){console.warn(`Failed to check table alias conflicts for '${newName}':`,error)}return conflicts}extractTableName(tableSource){try{if(tableSource.qualifiedName&&tableSource.qualifiedName.name){let name=tableSource.qualifiedName.name;if(typeof name=="string")return name;if(name.name&&typeof name.name=="string")return name.name;if(name.value&&typeof name.value=="string")return name.value}return tableSource.table&&typeof tableSource.table=="string"?tableSource.table:null}catch(error){return console.warn("Failed to extract table name from table source:",error),null}}checkKeywordConflicts(newName){let conflicts=[];if(this.isBasicReservedKeyword(newName))return conflicts.push(`'${newName}' is a reserved SQL keyword and should not be used as an alias`),conflicts;try{let keywordResult=this.keywordParser.parse(newName,0);keywordResult!==null&&keywordResult.keyword.toLowerCase()===newName.toLowerCase()&&conflicts.push(`'${newName}' is a reserved SQL keyword and should not be used as an alias`)}catch(error){console.warn(`Failed to check keyword conflicts for '${newName}':`,error)}return conflicts}isBasicReservedKeyword(name){return["select","from","where","join","table","null","and","or"].includes(name.toLowerCase())}prepareChanges(references,newName){return references.map(ref=>({oldName:ref.lexeme.value,newName,position:LexemeCursor.charOffsetToLineColumn("",ref.lexeme.position?.startPosition||0)||{line:1,column:1},context:ref.context,referenceType:ref.referenceType}))}performLexemeBasedRename(sql,aliasName,newName,scope){try{let targetLexemes=LexemeCursor.getAllLexemesWithPosition(sql).filter(lexeme=>lexeme.value===aliasName&&lexeme.position&&lexeme.position.startPosition>=scope.startPosition&&lexeme.position.endPosition<=scope.endPosition&&lexeme.type&64);if(targetLexemes.length===0)return sql;targetLexemes.sort((a,b)=>b.position.startPosition-a.position.startPosition);let modifiedSql=sql;for(let lexeme of targetLexemes){let pos=lexeme.position;modifiedSql=modifiedSql.substring(0,pos.startPosition)+newName+modifiedSql.substring(pos.endPosition)}return modifiedSql}catch(error){throw console.error("Failed to perform lexeme-based rename:",error),new Error(`Unable to rename alias using lexeme approach: ${error instanceof Error?error.message:String(error)}`)}}};var SqlIdentifierRenamer=class{renameIdentifiers(sql,renames){if(renames.size===0)return sql;let result=sql;for(let[originalValue,newValue]of renames)result=this.replaceIdentifierSafely(result,originalValue,newValue);return result}renameIdentifier(sql,oldIdentifier,newIdentifier){return this.replaceIdentifierSafely(sql,oldIdentifier,newIdentifier)}renameIdentifierInScope(sql,oldIdentifier,newIdentifier,scopeRange){if(!scopeRange)return this.replaceIdentifierSafely(sql,oldIdentifier,newIdentifier);let beforeScope=sql.slice(0,scopeRange.start),scopeContent=sql.slice(scopeRange.start,scopeRange.end),afterScope=sql.slice(scopeRange.end),modifiedScopeContent=this.replaceIdentifierSafely(scopeContent,oldIdentifier,newIdentifier);return beforeScope+modifiedScopeContent+afterScope}checkRenameability(sql,position){let charPosition=this.positionToCharIndex(sql,position);if(this.isInsideStringLiteral(sql,charPosition))return{canRename:!1,reason:"Cannot rename identifiers inside string literal"};let identifier=this.getIdentifierAtPosition(sql,charPosition);if(!identifier)return{canRename:!1,reason:"No identifier found at position"};let type=this.determineIdentifierType(sql,charPosition,identifier),scopeRange=this.calculateScopeRange(sql,charPosition,type);return{canRename:!0,currentName:identifier,type,scopeRange}}renameAtPosition(sql,position,newName){let renameability=this.checkRenameability(sql,position);if(!renameability.canRename||!renameability.currentName)throw new Error(renameability.reason||"Cannot rename at this position");return this.renameIdentifierInScope(sql,renameability.currentName,newName,renameability.scopeRange)}positionToCharIndex(sql,position){let lines=sql.split(`
45
+ `)+sql}getAllCTENames(ctes){return ctes.map(cte=>this.getCTEName(cte))}getCTEName(cte){return cte.aliasExpression.table.name}};var NamedQueryDefinitionExtractor=class _NamedQueryDefinitionExtractor{constructor(){this.definitions=[];this.visited=new Set}static extract(input){if(!input)return[];let extractor=new _NamedQueryDefinitionExtractor;return extractor.visit(input),extractor.definitions}visit(value){if(!(!value||typeof value!="object")&&!this.visited.has(value)){if(this.visited.add(value),value instanceof WithClause){this.visitWithClause(value);return}if(value instanceof CommonTable){this.visitCommonTable(value);return}if(value instanceof SimpleSelectQuery||value instanceof BinarySelectQuery||value instanceof ValuesQuery){this.visitSelectQuery(value);return}if(value instanceof InsertQuery){this.visitInsertQuery(value);return}if(value instanceof UpdateQuery){this.visitUpdateQuery(value);return}if(value instanceof DeleteQuery){this.visitDeleteQuery(value);return}if(value instanceof MergeQuery){this.visitMergeQuery(value);return}if(!this.visitKnownValueComponent(value)&&!this.visitKnownSqlComponent(value)){if(Array.isArray(value)){for(let item of value)this.visit(item);return}for(let key of Object.keys(value))this.visit(value[key])}}}visitSelectQuery(query,includeWith=!0){if(query instanceof SimpleSelectQuery){this.visitSimpleSelectQuery(query,includeWith);return}if(query instanceof BinarySelectQuery){this.visitSelectQuery(query.left,includeWith),this.visitSelectQuery(query.right);return}query instanceof ValuesQuery&&(includeWith&&this.visit(query.withClause),this.visit(query.tuples))}visitSimpleSelectQuery(query,includeWith){includeWith&&this.visit(query.withClause),this.visit(query.selectClause),this.visit(query.fromClause),this.visit(query.whereClause),this.visit(query.groupByClause),this.visit(query.havingClause),this.visit(query.windowClause),this.visit(query.orderByClause),this.visit(query.limitClause),this.visit(query.offsetClause),this.visit(query.fetchClause),this.visit(query.forClause)}visitInsertQuery(query){let withClause=SelectQueryWithClauseHelper.getWithClause(query.selectQuery);this.visit(withClause),this.visit(query.insertClause),query.selectQuery&&this.visitSelectQuery(query.selectQuery,!1),this.visit(query.onConflictClause),this.visit(query.returningClause)}visitUpdateQuery(query){this.visit(query.withClause),this.visit(query.updateClause),this.visit(query.setClause),this.visit(query.fromClause),this.visit(query.whereClause),this.visit(query.returningClause)}visitDeleteQuery(query){this.visit(query.withClause),this.visit(query.deleteClause),this.visit(query.usingClause),this.visit(query.whereClause),this.visit(query.returningClause)}visitMergeQuery(query){this.visit(query.withClause),this.visit(query.target),this.visit(query.source),this.visit(query.onCondition),this.visit(query.whenClauses),this.visit(query.returningClause)}visitWithClause(withClause){for(let commonTable of withClause.tables)this.visitCommonTable(commonTable,withClause.recursive)}visitCommonTable(commonTable,recursive){let definition={name:commonTable.getSourceAliasName(),query:commonTable.query,range:null,nameRange:null};recursive!==void 0&&(definition.recursive=recursive),this.definitions.push(definition),this.visit(commonTable.query)}visitKnownSqlComponent(value){if(value instanceof SelectClause)return this.visit(value.distinct),this.visit(value.hints),this.visit(value.items),!0;if(value instanceof SelectItem)return this.visit(value.value),!0;if(value instanceof FromClause)return this.visit(value.source),this.visit(value.joins),!0;if(value instanceof JoinClause)return this.visit(value.source),this.visit(value.condition),!0;if(value instanceof JoinOnClause||value instanceof JoinUsingClause)return this.visit(value.condition),!0;if(value instanceof SourceExpression)return this.visit(value.datasource),!0;if(value instanceof SubQuerySource)return this.visitSelectQuery(value.query),!0;if(value instanceof FunctionSource)return this.visit(value.argument),!0;if(value instanceof ParenSource)return this.visit(value.source),!0;if(value instanceof WhereClause||value instanceof HavingClause)return this.visit(value.condition),!0;if(value instanceof LimitClause)return this.visit(value.value),!0;if(value instanceof GroupByClause)return this.visit(value.grouping),!0;if(value instanceof WindowsClause)return this.visit(value.windows),!0;if(value instanceof WindowFrameClause)return this.visit(value.expression),!0;if(value instanceof OrderByClause)return this.visit(value.order),!0;if(value instanceof OrderByItem)return this.visit(value.value),!0;if(value instanceof ReturningClause)return this.visit(value.items),!0;if(value instanceof OnConflictClause)return this.visit(value.setClause),this.visit(value.whereClause),this.visit(value.forClause),!0;if(value instanceof SetClause){for(let item of value.items)this.visit(item.value);return!0}return value instanceof UpdateClause||value instanceof DeleteClause||value instanceof InsertClause?(this.visit(value.source),!0):value instanceof UsingClause?(this.visit(value.sources),!0):value instanceof MergeWhenClause?(this.visit(value.condition),this.visit(value.action),!0):value instanceof MergeUpdateAction?(this.visit(value.setClause),this.visit(value.whereClause),!0):value instanceof MergeDeleteAction?(this.visit(value.whereClause),!0):value instanceof MergeInsertAction?(this.visit(value.values),!0):!1}visitKnownValueComponent(value){return value instanceof ValueList||value instanceof TupleExpression?(this.visit(value.values),!0):value instanceof FunctionCall?(this.visit(value.argument),this.visit(value.internalOrderBy),this.visit(value.withinGroup),this.visit(value.filterCondition),this.visit(value.over),!0):value instanceof WindowFrameExpression?(this.visit(value.partition),this.visit(value.order),this.visit(value.frameSpec),!0):value instanceof WindowFrameSpec?(this.visit(value.startBound),this.visit(value.endBound),!0):value instanceof WindowFrameBoundaryValue?(this.visit(value.value),!0):value instanceof UnaryExpression||value instanceof ParenExpression||value instanceof ArrayExpression||value instanceof JsonPredicateExpression?(this.visit(value.expression),!0):value instanceof BinaryExpression?(this.visit(value.left),this.visit(value.right),!0):value instanceof SwitchCaseArgument?(this.visit(value.cases),this.visit(value.elseValue),!0):value instanceof CaseKeyValuePair?(this.visit(value.key),this.visit(value.value),!0):value instanceof CastExpression?(this.visit(value.input),this.visit(value.castType),!0):value instanceof CaseExpression?(this.visit(value.condition),this.visit(value.switchCase),!0):value instanceof ArrayQueryExpression?(this.visitSelectQuery(value.query),!0):value instanceof InlineQuery?(this.visitSelectQuery(value.selectQuery),!0):value instanceof BetweenExpression?(this.visit(value.expression),this.visit(value.lower),this.visit(value.upper),!0):value instanceof TypeValue?(this.visit(value.argument),!0):value instanceof ArraySliceExpression?(this.visit(value.array),this.visit(value.startIndex),this.visit(value.endIndex),!0):value instanceof ArrayIndexExpression?(this.visit(value.array),this.visit(value.index),!0):!1}};var AstCommentAttachmentExtractor=class _AstCommentAttachmentExtractor{constructor(){this.attachments=[];this.visited=new Set;this.suppressedDetachedCommentArrays=new WeakSet}static extract(input){if(!input)return[];let extractor=new _AstCommentAttachmentExtractor;return extractor.visit(input),extractor.attachments}visit(value){if(!(!value||typeof value!="object")&&!this.visited.has(value)){if(this.visited.add(value),Array.isArray(value)){for(let item of value)this.visit(item);return}if(value instanceof SqlComponent){this.visitSqlComponent(value);return}}}visitSqlComponent(component){if(this.emitHeaderComments(component),this.emitPositionedComments(component,"before"),component instanceof SimpleSelectQuery||this.emitLegacyComments(component),component instanceof SelectItem){this.emitPositionedComments(component,"after"),this.emitSelectItemKeywordComments(component),this.visit(component.value),this.visit(component.identifier);return}if(component instanceof CommonTable){this.visit(component.aliasExpression),this.visit(component.query),this.emitPositionedComments(component,"after");return}if(component instanceof WithClause){this.visit(component.tables),this.emitDetachedComments(component.trailingComments),this.emitDetachedComments(component.globalComments),this.emitPositionedComments(component,"after");return}if(component instanceof SimpleSelectQuery){this.suppressWithClauseTrailingCommentsAlreadyCopiedToQuery(component),this.visit(component.withClause),this.emitLegacyComments(component),this.visit(component.selectClause),this.visit(component.fromClause),this.visit(component.whereClause),this.visit(component.groupByClause),this.visit(component.havingClause),this.visit(component.windowClause),this.visit(component.orderByClause),this.visit(component.limitClause),this.visit(component.offsetClause),this.visit(component.fetchClause),this.visit(component.forClause),this.emitPositionedComments(component,"after");return}if(component instanceof BinarySelectQuery){this.visit(component.left),this.visit(component.right),this.emitPositionedComments(component,"after");return}if(component instanceof ValuesQuery){this.visit(component.withClause),this.visit(component.tuples),this.emitPositionedComments(component,"after");return}if(component instanceof SelectClause){this.visit(component.distinct),this.visit(component.hints),this.visit(component.items),this.emitPositionedComments(component,"after");return}if(component instanceof SourceAliasExpression){this.visit(component.table),this.visit(component.columns),this.emitPositionedComments(component,"after");return}this.visitFallbackProperties(component),this.emitPositionedComments(component,"after")}visitFallbackProperties(component){for(let key of Object.keys(component))this.shouldSkipProperty(key)||this.visit(component[key])}shouldSkipProperty(key){return key==="comments"||key==="positionedComments"||key==="headerComments"||key==="trailingComments"||key==="globalComments"||key==="asKeywordPositionedComments"||key==="asKeywordComments"||key==="aliasPositionedComments"||key==="aliasComments"||key==="cteNameCache"}emitHeaderComments(component){this.isSelectQuery(component)&&this.emitComments(component.headerComments,"leading",component)}emitLegacyComments(component){this.emitComments(component.comments,"detached")}emitPositionedComments(component,position){if(component.positionedComments)for(let positionedComment of component.positionedComments)positionedComment.position===position&&this.emitComments(positionedComment.comments,position==="before"?"leading":"trailing",component)}emitSelectItemKeywordComments(selectItem){let itemWithCommentFields=selectItem;this.emitKeywordPositionedComments(itemWithCommentFields.asKeywordPositionedComments,selectItem,"inner"),this.emitComments(itemWithCommentFields.asKeywordComments,"inner",selectItem),this.emitKeywordPositionedComments(itemWithCommentFields.aliasPositionedComments,selectItem),this.emitComments(itemWithCommentFields.aliasComments,"trailing",selectItem)}emitKeywordPositionedComments(positionedComments,targetNode,placementOverride){if(positionedComments)for(let positionedComment of positionedComments){let placement=placementOverride??(positionedComment.position==="before"?"leading":"trailing");this.emitComments(positionedComment.comments,placement,targetNode)}}emitDetachedComments(comments){comments&&this.suppressedDetachedCommentArrays.has(comments)||this.emitComments(comments,"detached")}emitComments(comments,placement,targetNode){if(comments)for(let text of comments)this.attachments.push({text,sourceOrder:this.attachments.length,placement,...targetNode?{targetNode}:{}})}isSelectQuery(component){return"__selectQueryType"in component&&component.__selectQueryType==="SelectQuery"}suppressWithClauseTrailingCommentsAlreadyCopiedToQuery(query){let trailingComments=query.withClause?.trailingComments;!trailingComments||!query.comments||this.containsCommentSequence(query.comments,trailingComments)&&this.suppressedDetachedCommentArrays.add(trailingComments)}containsCommentSequence(source,candidate){if(candidate.length===0)return!0;for(let start=0;start<=source.length-candidate.length;start++)if(candidate.every((comment,index)=>source[start+index]===comment))return!0;return!1}};function extractAstCommentAttachments(input){return AstCommentAttachmentExtractor.extract(input)}var ColumnReferenceCollector=class{constructor(){this.columnReferences=[];this.visitedNodes=new Set;this.handlers=new Map,this.handlers.set(WithClause.kind,clause=>this.visitWithClause(clause)),this.handlers.set(CommonTable.kind,table=>this.visitCommonTable(table)),this.handlers.set(SelectClause.kind,clause=>this.visitSelectClause(clause)),this.handlers.set(FromClause.kind,clause=>this.visitFromClause(clause)),this.handlers.set(WhereClause.kind,clause=>this.visitWhereClause(clause)),this.handlers.set(GroupByClause.kind,clause=>this.visitGroupByClause(clause)),this.handlers.set(HavingClause.kind,clause=>this.visitHavingClause(clause)),this.handlers.set(OrderByClause.kind,clause=>this.visitOrderByClause(clause)),this.handlers.set(WindowsClause.kind,clause=>this.visitWindowsClause(clause)),this.handlers.set(LimitClause.kind,clause=>this.visitLimitClause(clause)),this.handlers.set(OffsetClause.kind,clause=>this.visitOffsetClause(clause)),this.handlers.set(FetchClause.kind,clause=>this.visitFetchClause(clause)),this.handlers.set(ForClause.kind,clause=>this.visitForClause(clause)),this.handlers.set(JoinClause.kind,clause=>this.visitJoinClause(clause)),this.handlers.set(JoinOnClause.kind,clause=>this.visitJoinOnClause(clause)),this.handlers.set(JoinUsingClause.kind,clause=>this.visitJoinUsingClause(clause)),this.handlers.set(SourceExpression.kind,source=>this.visitSourceExpression(source)),this.handlers.set(SubQuerySource.kind,source=>this.visitSubQuerySource(source)),this.handlers.set(InsertQuery.kind,query=>this.visitInsertQuery(query)),this.handlers.set(UpdateQuery.kind,query=>this.visitUpdateQuery(query)),this.handlers.set(DeleteQuery.kind,query=>this.visitDeleteQuery(query)),this.handlers.set(MergeQuery.kind,query=>this.visitMergeQuery(query)),this.handlers.set(ColumnReference.kind,ref=>this.visitColumnReference(ref)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(FunctionCall.kind,func=>this.visitFunctionCall(func)),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(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(InlineQuery.kind,query=>this.visitInlineQuery(query)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ValueList.kind,list=>this.visitValueList(list)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr))}collect(query){return this.columnReferences=[],this.visitedNodes.clear(),query instanceof SimpleSelectQuery?this.collectFromSimpleQuery(query):query instanceof BinarySelectQuery?this.collectFromSimpleQuery(query.toSimpleQuery()):query.accept(this),[...this.columnReferences]}collectFromSimpleQuery(query){if(query.withClause&&query.withClause.tables)for(let cte of query.withClause.tables){let cteQuery=cte.query;cteQuery instanceof SimpleSelectQuery?this.collectFromSimpleQuery(cteQuery):cteQuery instanceof BinarySelectQuery?this.collectFromSimpleQuery(cteQuery.toSimpleQuery()):cteQuery.accept(this)}if(this.collectFromSelectClause(query.selectClause),query.fromClause&&this.collectFromFromClause(query.fromClause),query.whereClause&&this.collectFromValueComponent(query.whereClause.condition),query.groupByClause&&query.groupByClause.grouping)for(let item of query.groupByClause.grouping)this.collectFromValueComponent(item);if(query.havingClause&&this.collectFromValueComponent(query.havingClause.condition),query.orderByClause&&query.orderByClause.order)for(let item of query.orderByClause.order)typeof item=="object"&&"value"in item&&item.value?this.collectFromValueComponent(item.value):this.collectFromValueComponent(item)}collectFromSelectClause(clause){for(let item of clause.items)this.collectFromValueComponent(item.value)}collectFromFromClause(clause){if(this.collectFromSourceExpression(clause.source),clause.joins)for(let join of clause.joins)this.collectFromSourceExpression(join.source),join.condition&&this.collectFromValueComponent(join.condition.condition)}collectFromSourceExpression(source){source.datasource instanceof SubQuerySource&&(source.datasource.query instanceof SimpleSelectQuery?this.collectFromSimpleQuery(source.datasource.query):source.datasource.query instanceof BinarySelectQuery&&this.collectFromSimpleQuery(source.datasource.query.toSimpleQuery()))}collectFromValueComponent(value){if(value instanceof ColumnReference)this.columnReferences.push(value);else if(value instanceof JsonPredicateExpression)this.collectFromValueComponent(value.expression);else if(value instanceof BinaryExpression)this.collectFromValueComponent(value.left),this.collectFromValueComponent(value.right);else if(value instanceof UnaryExpression)this.collectFromValueComponent(value.expression);else if(value instanceof FunctionCall)value.argument&&this.collectFromValueComponent(value.argument),value.filterCondition&&this.collectFromValueComponent(value.filterCondition);else if(value instanceof CaseExpression){if(value.condition&&this.collectFromValueComponent(value.condition),value.switchCase&&value.switchCase.cases)for(let pair of value.switchCase.cases)this.collectFromValueComponent(pair.key),this.collectFromValueComponent(pair.value);value.switchCase&&value.switchCase.elseValue&&this.collectFromValueComponent(value.switchCase.elseValue)}else value instanceof ParenExpression?this.collectFromValueComponent(value.expression):value instanceof InlineQuery&&(value.selectQuery instanceof SimpleSelectQuery?this.collectFromSimpleQuery(value.selectQuery):value.selectQuery instanceof BinarySelectQuery&&this.collectFromSimpleQuery(value.selectQuery.toSimpleQuery()))}visit(component){if(this.visitedNodes.has(component))return;this.visitedNodes.add(component);let handler=this.handlers.get(component.getKind());handler&&handler(component)}visitSimpleSelectQuery(query){query.withClause&&query.withClause.accept(this),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.orderByClause&&query.orderByClause.accept(this),query.windowClause&&query.windowClause.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)}visitWithClause(clause){for(let table of clause.tables)table.accept(this)}visitCommonTable(table){table.query.accept(this)}visitSelectClause(clause){for(let item of clause.items)item.value.accept(this)}visitFromClause(clause){if(clause.source.accept(this),clause.joins)for(let join of clause.joins)join.accept(this)}visitWhereClause(clause){clause.condition.accept(this)}visitGroupByClause(clause){if(clause.grouping)for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition.accept(this)}visitOrderByClause(clause){if(clause.order)for(let item of clause.order)typeof item=="object"&&"value"in item&&item.value?typeof item.value=="object"&&"accept"in item.value&&item.value.accept(this):typeof item=="object"&&"accept"in item&&item.accept(this)}visitWindowsClause(clause){for(let window of clause.windows)window.expression.accept(this)}visitLimitClause(clause){clause.value.accept(this)}visitOffsetClause(clause){clause.value.accept(this)}visitFetchClause(clause){clause.expression.accept(this)}visitForClause(clause){}visitJoinClause(clause){clause.source.accept(this),clause.condition&&clause.condition.accept(this)}visitJoinOnClause(clause){clause.condition.accept(this)}visitJoinUsingClause(clause){clause.condition.accept(this)}visitSourceExpression(source){source.datasource.accept(this)}visitSubQuerySource(source){source.query.accept(this)}visitInsertQuery(query){query.selectQuery&&(query.selectQuery instanceof SimpleSelectQuery?this.collectFromSimpleQuery(query.selectQuery):query.selectQuery instanceof BinarySelectQuery?this.collectFromSimpleQuery(query.selectQuery.toSimpleQuery()):query.selectQuery.accept(this)),query.returningClause&&this.visitReturningClause(query.returningClause)}visitUpdateQuery(query){query.withClause&&query.withClause.accept(this),query.setClause.items.forEach(item=>item.value.accept(this)),query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.returningClause&&this.visitReturningClause(query.returningClause)}visitDeleteQuery(query){query.withClause&&query.withClause.accept(this),query.usingClause&&query.usingClause.sources.forEach(source=>source.accept(this)),query.whereClause&&query.whereClause.accept(this),query.returningClause&&this.visitReturningClause(query.returningClause)}visitMergeQuery(query){query.withClause&&query.withClause.accept(this),query.target.accept(this),query.source.accept(this),query.onCondition.accept(this);for(let clause of query.whenClauses)clause.condition&&clause.condition.accept(this),clause.action instanceof MergeUpdateAction?(clause.action.setClause.items.forEach(item=>item.value.accept(this)),clause.action.whereClause&&clause.action.whereClause.accept(this)):clause.action instanceof MergeDeleteAction?clause.action.whereClause&&clause.action.whereClause.accept(this):clause.action instanceof MergeInsertAction&&clause.action.values&&clause.action.values.accept(this);query.returningClause&&this.visitReturningClause(query.returningClause)}visitReturningClause(clause){for(let item of clause.items)item.value.accept(this)}visitColumnReference(ref){this.columnReferences.push(ref)}visitBinaryExpression(expr){expr.left.accept(this),expr.right.accept(this)}visitJsonPredicateExpression(expr){expr.expression.accept(this)}visitUnaryExpression(expr){expr.expression.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.filterCondition&&func.filterCondition.accept(this)}visitCaseExpression(expr){if(expr.condition&&expr.condition.accept(this),expr.switchCase&&expr.switchCase.cases)for(let pair of expr.switchCase.cases)pair.key.accept(this),pair.value.accept(this);expr.switchCase&&expr.switchCase.elseValue&&expr.switchCase.elseValue.accept(this)}visitCastExpression(expr){expr.input.accept(this)}visitBetweenExpression(expr){expr.expression.accept(this),expr.lower.accept(this),expr.upper.accept(this)}visitParenExpression(expr){expr.expression.accept(this)}visitInlineQuery(query){query.selectQuery.accept(this)}visitArrayExpression(expr){expr.expression&&expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitValueList(list){if(list.values)for(let item of list.values)item.accept(this)}visitWindowFrameExpression(expr){expr.partition&&expr.partition.accept(this),expr.order&&expr.order.accept(this)}};var ERROR_MESSAGES={nullQuery:"Query cannot be null or undefined",invalidOldName:"Old CTE name must be a non-empty string",invalidNewName:"New CTE name must be a non-empty string",sameNames:"Old and new CTE names cannot be the same",unsupportedQuery:"Unsupported query type for CTE renaming",cteNotExists:name=>`CTE '${name}' does not exist`,cteAlreadyExists:name=>`CTE '${name}' already exists`,cteNotFound:name=>`CTE '${name}' not found`},CTERenamer=class{constructor(){this.dependencyAnalyzer=new CTEDependencyAnalyzer,this.columnReferenceCollector=new ColumnReferenceCollector,this.tableSourceCollector=new TableSourceCollector,this.keywordParser=new KeywordParser(keywordTrie)}renameCTE(query,oldName,newName){this.validateInputs(query,oldName,newName);let sanitizedOldName=oldName.trim(),sanitizedNewName=newName.trim();if(query instanceof SimpleSelectQuery)this.renameInSimpleQuery(query,sanitizedOldName,sanitizedNewName);else if(query instanceof BinarySelectQuery)this.renameInBinaryQuery(query,sanitizedOldName,sanitizedNewName);else throw new Error(ERROR_MESSAGES.unsupportedQuery)}validateInputs(query,oldName,newName){if(!query)throw new Error(ERROR_MESSAGES.nullQuery);if(!oldName||typeof oldName!="string"||oldName.trim()==="")throw new Error(ERROR_MESSAGES.invalidOldName);if(!newName||typeof newName!="string"||newName.trim()==="")throw new Error(ERROR_MESSAGES.invalidNewName);if(oldName.trim()===newName.trim())throw new Error(ERROR_MESSAGES.sameNames)}renameInSimpleQuery(query,oldName,newName){let availableCTEs=query.getCTENames();if(!availableCTEs.includes(oldName))throw new Error(ERROR_MESSAGES.cteNotExists(oldName));if(availableCTEs.includes(newName))throw new Error(ERROR_MESSAGES.cteAlreadyExists(newName));this.renameCTEDefinition(query,oldName,newName),this.updateAllReferences(query,oldName,newName)}renameInBinaryQuery(query,oldName,newName){let withClauseQuery=query.toSimpleQuery(),availableCTEs=[];if(withClauseQuery.withClause&&withClauseQuery.withClause.tables&&(availableCTEs=withClauseQuery.withClause.tables.map(cte=>cte.aliasExpression.table.name)),!availableCTEs.includes(oldName))throw new Error(ERROR_MESSAGES.cteNotExists(oldName));if(availableCTEs.includes(newName))throw new Error(ERROR_MESSAGES.cteAlreadyExists(newName));this.renameCTEDefinition(withClauseQuery,oldName,newName),withClauseQuery.withClause&&(query.withClause=withClauseQuery.withClause,query.left instanceof SimpleSelectQuery&&(query.left.withClause=withClauseQuery.withClause)),this.renameInSelectQuery(query.left,oldName,newName),this.renameInSelectQuery(query.right,oldName,newName)}renameInSelectQuery(query,oldName,newName){query instanceof SimpleSelectQuery?this.updateAllReferences(query,oldName,newName):query instanceof BinarySelectQuery&&(this.renameInSelectQuery(query.left,oldName,newName),this.renameInSelectQuery(query.right,oldName,newName))}renameCTEDefinition(query,oldName,newName){if(!query.withClause||!query.withClause.tables)throw new Error(ERROR_MESSAGES.cteNotFound(oldName));let cteToRename=query.withClause.tables.find(cte=>cte.aliasExpression.table.name===oldName);if(!cteToRename)throw new Error(ERROR_MESSAGES.cteNotFound(oldName));cteToRename.aliasExpression.table.name=newName}updateAllReferences(query,oldName,newName){let columnReferences=this.columnReferenceCollector.collect(query);for(let columnRef of columnReferences)if(columnRef.namespaces&&columnRef.namespaces.length>0){for(let namespace of columnRef.namespaces)if(namespace.name===oldName){namespace.name=newName;break}}let tableSources=this.tableSourceCollector.collect(query);for(let tableSource of tableSources)tableSource.getSourceName()===oldName&&(tableSource.qualifiedName.name instanceof ColumnReference||("name"in tableSource.qualifiedName.name?tableSource.qualifiedName.name.name=newName:tableSource.qualifiedName.name.value=newName));this.updateTableSourcesInCTEs(query,oldName,newName)}updateTableSourcesInCTEs(query,oldName,newName){if(!(!query.withClause||!query.withClause.tables))for(let cte of query.withClause.tables)cte.query instanceof SimpleSelectQuery&&this.updateTableSourcesInQuery(cte.query,oldName,newName)}updateTableSourcesInQuery(query,oldName,newName){if(query.fromClause&&query.fromClause.source.datasource&&this.updateTableSource(query.fromClause.source.datasource,oldName,newName),query.fromClause&&query.fromClause.joins)for(let join of query.fromClause.joins)join.source.datasource&&this.updateTableSource(join.source.datasource,oldName,newName)}updateTableSource(datasource,oldName,newName){if(!datasource||typeof datasource!="object")return;let source=datasource;if(typeof source.getSourceName=="function")try{if(source.getSourceName()===oldName&&source.qualifiedName&&typeof source.qualifiedName=="object"){let qualifiedName=source.qualifiedName;if(qualifiedName.name&&typeof qualifiedName.name=="object"){let nameObj=qualifiedName.name;"name"in nameObj&&typeof nameObj.name=="string"?nameObj.name=newName:"value"in nameObj&&typeof nameObj.value=="string"&&(nameObj.value=newName)}}}catch(error){console.warn("Warning: Failed to update table source:",error)}}renameCTEAtPosition(sql,position,newName){if(!sql?.trim())throw new Error("SQL cannot be empty");if(!position||position.line<1||position.column<1)throw new Error("Position must be a valid line/column (1-based)");if(!newName?.trim())throw new Error("New CTE name cannot be empty");let lexeme=LexemeCursor.findLexemeAtLineColumn(sql,position);if(!lexeme)throw new Error(`No CTE name found at line ${position.line}, column ${position.column}`);let cteName=lexeme.value,query=SelectQueryParser.parse(sql);if(!this.isCTENameInQuery(query,cteName))throw new Error(`'${cteName}' is not a CTE name in this query`);if(!(lexeme.type&2112))throw new Error(`Token at position is not a CTE name: '${lexeme.value}'`);let conflicts=this.checkNameConflicts(query,newName,cteName);if(conflicts.length>0)throw new Error(conflicts.join(", "));return this.renameCTE(query,cteName,newName),new SqlFormatter().format(query).formattedSql}checkNameConflicts(query,newName,currentName){let conflicts=[];return currentName===newName||(conflicts.push(...this.checkKeywordConflicts(newName)),this.isCTENameInQuery(query,newName)&&conflicts.push(`CTE name '${newName}' already exists`)),conflicts}checkKeywordConflicts(newName){let conflicts=[];try{let keywordResult=this.keywordParser.parse(newName,0);keywordResult!==null&&keywordResult.keyword.toLowerCase()===newName.toLowerCase()&&conflicts.push(`'${newName}' is a reserved SQL keyword and should not be used as a CTE name`)}catch(error){console.warn(`Failed to check keyword conflicts for '${newName}':`,error),this.isBasicReservedKeyword(newName)&&conflicts.push(`'${newName}' is a reserved SQL keyword and should not be used as a CTE name`)}return conflicts}isBasicReservedKeyword(name){return["select","from","where","with","as","union","join","table","null"].includes(name.toLowerCase())}isCTENameInQuery(query,cteName){return query instanceof SimpleSelectQuery&&query.withClause?query.withClause.tables.some(cte=>cte.aliasExpression&&cte.aliasExpression.table&&cte.aliasExpression.table.name===cteName):query instanceof BinarySelectQuery?this.isCTENameInQuery(query.left,cteName)||this.isCTENameInQuery(query.right,cteName):!1}};var ERROR_MESSAGES2={invalidSql:"Invalid SQL: unable to parse query",invalidPosition:"Invalid position: line or column out of bounds",noLexemeAtPosition:"No lexeme found at the specified position",notAnAlias:"Selected lexeme is not a valid alias",invalidNewName:"New alias name must be a non-empty string",sameNames:"Old and new alias names cannot be the same",nameConflict:name=>`Alias '${name}' already exists in this scope`,aliasNotFound:name=>`Alias '${name}' not found in current scope`},AliasRenamer=class{constructor(){this.keywordParser=new KeywordParser(keywordTrie)}renameAlias(sql,position,newName,options={}){try{this.validateInputs(sql,position,newName);let lexeme=LexemeCursor.findLexemeAtLineColumn(sql,position);if(!lexeme)throw new Error(ERROR_MESSAGES2.noLexemeAtPosition);this.validateLexemeIsAlias(lexeme);let query=SelectQueryParser.parse(sql),scope=this.detectAliasScope(sql,query,lexeme,options.scopeType),references=this.collectAliasReferences(scope,lexeme.value),conflicts=this.checkNameConflicts(scope,newName,lexeme.value);if(conflicts.length>0)return{success:!1,originalSql:sql,changes:[],conflicts,scope};let changes=this.prepareChanges(references,newName);if(options.dryRun)return{success:!0,originalSql:sql,changes,conflicts,scope};let newSql=this.performLexemeBasedRename(sql,lexeme.value,newName,scope);return{success:!0,originalSql:sql,newSql,changes,scope}}catch(error){return{success:!1,originalSql:sql,changes:[],conflicts:[error instanceof Error?error.message:String(error)]}}}validateInputs(sql,position,newName){if(!sql||typeof sql!="string"||sql.trim()==="")throw new Error(ERROR_MESSAGES2.invalidSql);if(!position||typeof position.line!="number"||typeof position.column!="number"||position.line<1||position.column<1)throw new Error(ERROR_MESSAGES2.invalidPosition);if(!newName||typeof newName!="string"||newName.trim()==="")throw new Error(ERROR_MESSAGES2.invalidNewName)}validateLexemeIsAlias(lexeme){if(!(lexeme.type&64))throw new Error(ERROR_MESSAGES2.notAnAlias)}detectAliasScope(sql,query,lexeme,scopeType){if(!lexeme.position)return{type:"main",query,startPosition:0,endPosition:sql.length};let lexemePosition=lexeme.position.startPosition;return scopeType&&scopeType!=="auto"?this.createScopeForType(scopeType,sql,query,lexemePosition):this.autoDetectScope(sql,query,lexemePosition)}createScopeForType(scopeType,sql,query,position){switch(scopeType){case"cte":return this.detectCTEScope(sql,query,position);case"subquery":return this.detectSubqueryScope(sql,query,position);default:return{type:"main",query,startPosition:0,endPosition:sql.length}}}autoDetectScope(sql,query,position){let cteScope=this.detectCTEScope(sql,query,position);if(cteScope.type==="cte")return cteScope;let subqueryScope=this.detectSubqueryScope(sql,query,position);return subqueryScope.type==="subquery"?subqueryScope:{type:"main",query,startPosition:0,endPosition:sql.length}}detectCTEScope(sql,query,position){try{let analysis=CTERegionDetector.analyzeCursorPosition(sql,position);if(analysis.isInCTE&&analysis.cteRegion){let cteQuery=this.findCTEQueryByName(query,analysis.cteRegion.name);return{type:"cte",name:analysis.cteRegion.name,query:cteQuery||query,startPosition:analysis.cteRegion.startPosition,endPosition:analysis.cteRegion.endPosition}}}catch(error){console.warn("CTE scope detection failed:",error)}return{type:"main",query,startPosition:0,endPosition:sql.length}}detectSubqueryScope(sql,query,position){return{type:"main",query,startPosition:0,endPosition:sql.length}}findCTEQueryByName(query,cteName){if(query instanceof SimpleSelectQuery&&query.withClause?.tables){for(let cte of query.withClause.tables)if(cte.aliasExpression.table.name===cteName)return this.isSelectQuery(cte.query)?cte.query:null}else if(query instanceof BinarySelectQuery){let leftResult=this.findCTEQueryByName(query.left,cteName);if(leftResult)return leftResult;let rightResult=this.findCTEQueryByName(query.right,cteName);if(rightResult)return rightResult}return null}isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}collectAliasReferences(scope,aliasName){let references=[];try{let tableReferences=this.collectTableAliasReferences(scope,aliasName);references.push(...tableReferences);let columnReferences=this.collectColumnAliasReferences(scope,aliasName);references.push(...columnReferences)}catch(error){console.warn(`Failed to collect alias references for '${aliasName}':`,error)}return references}collectTableAliasReferences(scope,aliasName){let references=[];try{let tableSources=new TableSourceCollector(!0).collect(scope.query);for(let tableSource of tableSources)if(tableSource.getSourceName()===aliasName){let lexeme=this.createLexemeFromTableSource(tableSource,aliasName);lexeme&&references.push({lexeme,scope,referenceType:"definition",context:"table"})}}catch(error){console.warn(`Failed to collect table alias references for '${aliasName}':`,error)}return references}collectColumnAliasReferences(scope,aliasName){let references=[];try{let columnRefs=new ColumnReferenceCollector().collect(scope.query);for(let columnRef of columnRefs)if(columnRef.namespaces&&columnRef.namespaces.length>0){for(let namespace of columnRef.namespaces)if(namespace.name===aliasName){let lexeme=this.createLexemeFromNamespace(namespace,aliasName);lexeme&&references.push({lexeme,scope,referenceType:"usage",context:"column"})}}}catch(error){console.warn(`Failed to collect column alias references for '${aliasName}':`,error)}return references}createLexemeFromTableSource(tableSource,aliasName){try{return{type:64,value:aliasName,comments:null,position:{startPosition:0,endPosition:aliasName.length}}}catch(error){return console.warn("Failed to create lexeme from table source:",error),null}}createLexemeFromNamespace(namespace,aliasName){try{return{type:64,value:aliasName,comments:null,position:{startPosition:0,endPosition:aliasName.length}}}catch(error){return console.warn("Failed to create lexeme from namespace:",error),null}}checkNameConflicts(scope,newName,currentName){let conflicts=[];if(newName.toLowerCase()===currentName.toLowerCase())return conflicts.push(ERROR_MESSAGES2.sameNames),conflicts;try{let tableConflicts=this.checkTableAliasConflicts(scope,newName);conflicts.push(...tableConflicts);let keywordConflicts=this.checkKeywordConflicts(newName);conflicts.push(...keywordConflicts)}catch(error){console.warn(`Error during conflict detection for '${newName}':`,error),conflicts.push(`Unable to verify conflicts for name '${newName}'`)}return conflicts}checkTableAliasConflicts(scope,newName){let conflicts=[];try{let tableSources=new TableSourceCollector(!0).collect(scope.query);for(let tableSource of tableSources){let aliasName=tableSource.getSourceName();if(aliasName&&aliasName.toLowerCase()===newName.toLowerCase()){conflicts.push(ERROR_MESSAGES2.nameConflict(newName));continue}let tableName=this.extractTableName(tableSource);tableName&&tableName.toLowerCase()===newName.toLowerCase()&&conflicts.push(`'${newName}' conflicts with table name in this scope`)}}catch(error){console.warn(`Failed to check table alias conflicts for '${newName}':`,error)}return conflicts}extractTableName(tableSource){try{if(tableSource.qualifiedName&&tableSource.qualifiedName.name){let name=tableSource.qualifiedName.name;if(typeof name=="string")return name;if(name.name&&typeof name.name=="string")return name.name;if(name.value&&typeof name.value=="string")return name.value}return tableSource.table&&typeof tableSource.table=="string"?tableSource.table:null}catch(error){return console.warn("Failed to extract table name from table source:",error),null}}checkKeywordConflicts(newName){let conflicts=[];if(this.isBasicReservedKeyword(newName))return conflicts.push(`'${newName}' is a reserved SQL keyword and should not be used as an alias`),conflicts;try{let keywordResult=this.keywordParser.parse(newName,0);keywordResult!==null&&keywordResult.keyword.toLowerCase()===newName.toLowerCase()&&conflicts.push(`'${newName}' is a reserved SQL keyword and should not be used as an alias`)}catch(error){console.warn(`Failed to check keyword conflicts for '${newName}':`,error)}return conflicts}isBasicReservedKeyword(name){return["select","from","where","join","table","null","and","or"].includes(name.toLowerCase())}prepareChanges(references,newName){return references.map(ref=>({oldName:ref.lexeme.value,newName,position:LexemeCursor.charOffsetToLineColumn("",ref.lexeme.position?.startPosition||0)||{line:1,column:1},context:ref.context,referenceType:ref.referenceType}))}performLexemeBasedRename(sql,aliasName,newName,scope){try{let targetLexemes=LexemeCursor.getAllLexemesWithPosition(sql).filter(lexeme=>lexeme.value===aliasName&&lexeme.position&&lexeme.position.startPosition>=scope.startPosition&&lexeme.position.endPosition<=scope.endPosition&&lexeme.type&64);if(targetLexemes.length===0)return sql;targetLexemes.sort((a,b)=>b.position.startPosition-a.position.startPosition);let modifiedSql=sql;for(let lexeme of targetLexemes){let pos=lexeme.position;modifiedSql=modifiedSql.substring(0,pos.startPosition)+newName+modifiedSql.substring(pos.endPosition)}return modifiedSql}catch(error){throw console.error("Failed to perform lexeme-based rename:",error),new Error(`Unable to rename alias using lexeme approach: ${error instanceof Error?error.message:String(error)}`)}}};var SqlIdentifierRenamer=class{renameIdentifiers(sql,renames){if(renames.size===0)return sql;let result=sql;for(let[originalValue,newValue]of renames)result=this.replaceIdentifierSafely(result,originalValue,newValue);return result}renameIdentifier(sql,oldIdentifier,newIdentifier){return this.replaceIdentifierSafely(sql,oldIdentifier,newIdentifier)}renameIdentifierInScope(sql,oldIdentifier,newIdentifier,scopeRange){if(!scopeRange)return this.replaceIdentifierSafely(sql,oldIdentifier,newIdentifier);let beforeScope=sql.slice(0,scopeRange.start),scopeContent=sql.slice(scopeRange.start,scopeRange.end),afterScope=sql.slice(scopeRange.end),modifiedScopeContent=this.replaceIdentifierSafely(scopeContent,oldIdentifier,newIdentifier);return beforeScope+modifiedScopeContent+afterScope}checkRenameability(sql,position){let charPosition=this.positionToCharIndex(sql,position);if(this.isInsideStringLiteral(sql,charPosition))return{canRename:!1,reason:"Cannot rename identifiers inside string literal"};let identifier=this.getIdentifierAtPosition(sql,charPosition);if(!identifier)return{canRename:!1,reason:"No identifier found at position"};let type=this.determineIdentifierType(sql,charPosition,identifier),scopeRange=this.calculateScopeRange(sql,charPosition,type);return{canRename:!0,currentName:identifier,type,scopeRange}}renameAtPosition(sql,position,newName){let renameability=this.checkRenameability(sql,position);if(!renameability.canRename||!renameability.currentName)throw new Error(renameability.reason||"Cannot rename at this position");return this.renameIdentifierInScope(sql,renameability.currentName,newName,renameability.scopeRange)}positionToCharIndex(sql,position){let lines=sql.split(`
46
46
  `),charIndex=0;for(let i=0;i<position.line-1&&i<lines.length;i++)charIndex+=lines[i].length+1;return charIndex+=position.column-1,Math.min(charIndex,sql.length-1)}isInsideStringLiteral(sql,charPosition){let inString=!1;for(let i=0;i<charPosition&&i<sql.length;i++)sql[i]==="'"&&(inString=!inString);return inString}getIdentifierAtPosition(sql,charPosition){if(charPosition>=sql.length)return null;let start=charPosition;for(;start>0&&this.isIdentifierChar(sql.charCodeAt(start-1));)start--;let end=charPosition;for(;end<sql.length&&this.isIdentifierChar(sql.charCodeAt(end));)end++;return start===end?null:sql.slice(start,end)}determineIdentifierType(sql,charPosition,identifier){let beforePosition=sql.slice(0,charPosition),afterPosition=sql.slice(charPosition),beforeUpper=beforePosition.toUpperCase(),afterUpper=afterPosition.toUpperCase();if(beforeUpper.lastIndexOf("WITH")!==-1){let start=charPosition;for(;start>0&&this.isIdentifierChar(sql.charCodeAt(start-1));)start--;let end=charPosition;for(;end<sql.length&&this.isIdentifierChar(sql.charCodeAt(end));)end++;if(sql.slice(end).toUpperCase().trim().startsWith("AS ("))return"cte"}let beforeLines=beforePosition.split(`
47
47
  `),currentLine=beforeLines[beforeLines.length-1].toUpperCase();if(currentLine.includes("FROM ")||currentLine.includes("JOIN "))return"table_alias";let contextBefore=beforePosition.slice(Math.max(0,charPosition-50)),contextAfter=afterPosition.slice(0,50),fullContext=(contextBefore+identifier+contextAfter).toUpperCase();return fullContext.includes(" AS "+identifier.toUpperCase())||fullContext.includes(" "+identifier.toUpperCase()+" ON")||fullContext.includes(" "+identifier.toUpperCase()+`
48
48
  `),"table_alias"}calculateScopeRange(sql,charPosition,type){if(type==="cte")return{start:0,end:sql.length};let beforePosition=sql.slice(0,charPosition),afterPosition=sql.slice(charPosition),lastSelect=beforePosition.toUpperCase().lastIndexOf("SELECT"),start=lastSelect!==-1?lastSelect:0,nextMajorClause=afterPosition.search(/\b(SELECT|WITH|UNION)\b/i),end=nextMajorClause!==-1?charPosition+nextMajorClause:sql.length;return{start,end}}replaceIdentifierSafely(sql,oldIdentifier,newIdentifier){if(oldIdentifier===newIdentifier||oldIdentifier.length===0)return sql;let result=[],position=0,sqlLength=sql.length,oldIdLength=oldIdentifier.length;for(;position<sqlLength;){let char=sql[position],charCode=char.charCodeAt(0);if(charCode===34||charCode===96||charCode===91){let{content,nextPosition}=this.extractAndReplaceQuotedIdentifier(sql,position,char,oldIdentifier,newIdentifier);result.push(content),position=nextPosition;continue}if(charCode===39){let{content,nextPosition}=this.extractQuotedString(sql,position,char);result.push(content),position=nextPosition;continue}if(charCode===45&&position+1<sqlLength&&sql.charCodeAt(position+1)===45){let{content,nextPosition}=this.extractLineComment(sql,position);result.push(content),position=nextPosition;continue}if(charCode===47&&position+1<sqlLength&&sql.charCodeAt(position+1)===42){let{content,nextPosition}=this.extractBlockComment(sql,position);result.push(content),position=nextPosition;continue}if(this.isIdentifierStartChar(charCode)&&this.matchesIdentifierAt(sql,position,oldIdentifier)){let beforePosition=position-1,afterPosition=position+oldIdLength,beforeChar=beforePosition>=0?sql[beforePosition]:null,afterChar=afterPosition<sqlLength?sql[afterPosition]:null;if(this.hasValidWordBoundaries(beforeChar,afterChar)){result.push(newIdentifier),position+=oldIdLength;continue}}result.push(char),position++}return result.join("")}validateRename(originalSql,modifiedSql,oldIdentifier,newIdentifier){if(originalSql===modifiedSql||!modifiedSql.includes(newIdentifier))return!1;let originalOccurrences=this.countWordOccurrences(originalSql,oldIdentifier);return this.countWordOccurrences(modifiedSql,oldIdentifier)<originalOccurrences}extractAndReplaceQuotedIdentifier(sql,startPosition,quoteChar,oldIdentifier,newIdentifier){if(quoteChar==="[")return this.extractAndReplaceBracketedIdentifier(sql,startPosition,oldIdentifier,newIdentifier);let result=[quoteChar],position=startPosition+1,identifierStart=position;for(;position<sql.length;){let char=sql[position];if(char===quoteChar){if(position+1<sql.length&&sql[position+1]===quoteChar){result.push(char),result.push(sql[position+1]),position+=2;continue}let quotedContent=sql.slice(identifierStart,position);quotedContent.toLowerCase()===oldIdentifier.toLowerCase()?result.push(newIdentifier):result.push(quotedContent),result.push(char);break}position++}return{content:result.join(""),nextPosition:position+1}}extractAndReplaceBracketedIdentifier(sql,startPosition,oldIdentifier,newIdentifier){let result=["["],position=startPosition+1,identifierStart=position;for(;position<sql.length;){let char=sql[position];if(char==="]"){let bracketedContent=sql.slice(identifierStart,position);bracketedContent.toLowerCase()===oldIdentifier.toLowerCase()?result.push(newIdentifier):result.push(bracketedContent),result.push(char);break}position++}return{content:result.join(""),nextPosition:position+1}}extractQuotedString(sql,startPosition,quoteChar){let result=[quoteChar],position=startPosition+1;for(;position<sql.length;){let char=sql[position];if(result.push(char),char===quoteChar){if(position+1<sql.length&&sql[position+1]===quoteChar){result.push(sql[position+1]),position+=2;continue}break}position++}return{content:result.join(""),nextPosition:position+1}}extractLineComment(sql,startPosition){let result=[],position=startPosition;for(;position<sql.length&&sql.charCodeAt(position)!==10&&sql.charCodeAt(position)!==13;)result.push(sql[position]),position++;return position<sql.length&&(sql.charCodeAt(position)===10||sql.charCodeAt(position)===13)&&(result.push(sql[position]),position++),{content:result.join(""),nextPosition:position}}extractBlockComment(sql,startPosition){let result=["/","*"],position=startPosition+2;for(;position<sql.length-1;){let char=sql[position];if(result.push(char),char==="*"&&sql[position+1]==="/"){result.push("/"),position+=2;break}position++}return{content:result.join(""),nextPosition:position}}isIdentifierStartChar(charCode){return charCode>=65&&charCode<=90||charCode>=97&&charCode<=122||charCode===95}isIdentifierChar(charCode){return charCode>=65&&charCode<=90||charCode>=97&&charCode<=122||charCode>=48&&charCode<=57||charCode===95}matchesIdentifierAt(sql,position,identifier){if(position+identifier.length>sql.length)return!1;for(let i=0;i<identifier.length;i++){let sqlChar=sql.charCodeAt(position+i),idChar=identifier.charCodeAt(i),sqlLower=sqlChar>=65&&sqlChar<=90?sqlChar+32:sqlChar,idLower=idChar>=65&&idChar<=90?idChar+32:idChar;if(sqlLower!==idLower)return!1}return!0}hasValidWordBoundaries(beforeChar,afterChar){let isValidBefore=beforeChar===null||!this.isIdentifierChar(beforeChar.charCodeAt(0)),isValidAfter=afterChar===null||!this.isIdentifierChar(afterChar.charCodeAt(0));return isValidBefore&&isValidAfter}countWordOccurrences(sql,identifier){let count=0,position=0,sqlLength=sql.length,idLength=identifier.length;for(;position<=sqlLength-idLength;){if(this.matchesIdentifierAt(sql,position,identifier)){let beforePosition=position-1,afterPosition=position+idLength,beforeChar=beforePosition>=0?sql[beforePosition]:null,afterChar=afterPosition<sqlLength?sql[afterPosition]:null;this.hasValidWordBoundaries(beforeChar,afterChar)&&count++}position++}return count}};var SmartRenamer=class{constructor(){this.cteRenamer=new CTERenamer,this.aliasRenamer=new AliasRenamer,this.identifierRenamer=new SqlIdentifierRenamer}isRenameable(sql,position){try{if(!sql?.trim())return{renameable:!1,renamerType:"none",reason:"Empty SQL"};if(!position||position.line<1||position.column<1)return{renameable:!1,renamerType:"none",reason:"Invalid position"};let lexeme=LexemeCursor.findLexemeAtLineColumn(sql,position);if(!lexeme)return{renameable:!1,renamerType:"none",reason:"No token found"};if(!(lexeme.type&2112))return{renameable:!1,renamerType:"none",tokenName:lexeme.value,reason:`Token '${lexeme.value}' is not an identifier`};let tokenName=lexeme.value,renamerType=this.detectRenamerType(sql,tokenName);return renamerType==="unknown"?{renameable:!1,renamerType:"none",tokenName,reason:`Cannot determine if '${tokenName}' is renameable`}:{renameable:!0,renamerType,tokenName}}catch(error){return{renameable:!1,renamerType:"none",reason:`Error: ${error instanceof Error?error.message:String(error)}`}}}rename(sql,position,newName,options){try{if(!sql?.trim())return this.createErrorResult(sql,newName,"unknown","","SQL cannot be empty");if(!position||position.line<1||position.column<1)return this.createErrorResult(sql,newName,"unknown","","Position must be valid line/column (1-based)");if(!newName?.trim())return this.createErrorResult(sql,newName,"unknown","","New name cannot be empty");let lexeme=LexemeCursor.findLexemeAtLineColumn(sql,position);if(!lexeme)return this.createErrorResult(sql,newName,"unknown","",`No identifier found at line ${position.line}, column ${position.column}`);if(!(lexeme.type&64))return this.createErrorResult(sql,newName,"unknown",lexeme.value,`Token '${lexeme.value}' is not renameable`);let originalName=lexeme.value,preserveFormatting=options?.preserveFormatting??!1,renamerType=this.detectRenamerType(sql,originalName);if(preserveFormatting)try{let formatPreservedResult=this.attemptFormattingPreservationRename(sql,position,newName,originalName,renamerType);if(formatPreservedResult.success)return formatPreservedResult}catch(error){console.warn("Formatting preservation failed, falling back to standard rename:",error)}try{let newSql;if(renamerType==="cte")newSql=this.cteRenamer.renameCTEAtPosition(sql,position,newName);else if(renamerType==="alias"){let result=this.aliasRenamer.renameAlias(sql,position,newName);if(!result.success)return{success:!1,originalSql:sql,renamerType:"alias",originalName,newName,error:result.conflicts?.join(", ")||"Alias rename failed",formattingPreserved:!1,formattingMethod:"smart-renamer-only"};newSql=result.newSql}else return this.createErrorResult(sql,newName,"unknown",originalName,`Cannot determine if '${originalName}' is a CTE name or table alias`);return{success:!0,originalSql:sql,newSql,renamerType,originalName,newName,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}catch(error){return this.createErrorResult(sql,newName,renamerType,originalName,`${renamerType.toUpperCase()} rename failed: ${error instanceof Error?error.message:String(error)}`)}}catch(error){return this.createErrorResult(sql,newName,"unknown","",`Unexpected error: ${error instanceof Error?error.message:String(error)}`)}}detectRenamerType(sql,identifierName){try{let query=SelectQueryParser.parse(sql);return this.isCTEName(query,identifierName)?"cte":"alias"}catch{return"unknown"}}isCTEName(query,name){return query instanceof SimpleSelectQuery&&query.withClause?query.withClause.tables.some(cte=>cte.aliasExpression&&cte.aliasExpression.table&&cte.aliasExpression.table.name===name):query instanceof BinarySelectQuery?this.isCTEName(query.left,name)||this.isCTEName(query.right,name):!1}attemptFormattingPreservationRename(sql,position,newName,originalName,renamerType){let standardResult=this.performStandardRename(sql,position,newName,originalName,renamerType);if(!standardResult.success)return{...standardResult,formattingPreserved:!1,formattingMethod:"smart-renamer-only"};let renameMap=new Map([[originalName,newName]]);try{let formattedSql=this.identifierRenamer.renameIdentifiers(sql,renameMap);if(this.validateRenameResult(sql,formattedSql,originalName,newName))return{success:!0,originalSql:sql,newSql:formattedSql,renamerType,originalName,newName,formattingPreserved:!0,formattingMethod:"sql-identifier-renamer"};throw new Error("Validation failed: rename may not have been applied correctly")}catch{return{...standardResult,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}}performStandardRename(sql,position,newName,originalName,renamerType){try{let newSql;if(renamerType==="cte")newSql=this.cteRenamer.renameCTEAtPosition(sql,position,newName);else if(renamerType==="alias"){let result=this.aliasRenamer.renameAlias(sql,position,newName);if(!result.success)return{success:!1,originalSql:sql,renamerType:"alias",originalName,newName,error:result.conflicts?.join(", ")||"Alias rename failed"};newSql=result.newSql}else return{success:!1,originalSql:sql,renamerType:"unknown",originalName,newName,error:`Cannot determine if '${originalName}' is a CTE name or table alias`};return{success:!0,originalSql:sql,newSql,renamerType,originalName,newName}}catch(error){return{success:!1,originalSql:sql,renamerType,originalName,newName,error:`${renamerType.toUpperCase()} rename failed: ${error instanceof Error?error.message:String(error)}`}}}validateRenameResult(originalSql,newSql,oldName,newName){if(originalSql===newSql||!newSql.includes(newName))return!1;let originalOccurrences=this.countWordOccurrences(originalSql,oldName);return this.countWordOccurrences(newSql,oldName)<originalOccurrences}countWordOccurrences(sql,name){let regex=new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"gi"),matches=sql.match(regex);return matches?matches.length:0}createErrorResult(sql,newName,renamerType,originalName,error){return{success:!1,originalSql:sql,renamerType,originalName,newName,error,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}batchRename(sql,renames,options){if(options?.preserveFormatting??!1)try{let renameMap=new Map(Object.entries(renames)),formattedSql=this.identifierRenamer.renameIdentifiers(sql,renameMap),originalNames=Object.keys(renames),newNames=Object.values(renames);return{success:!0,originalSql:sql,newSql:formattedSql,renamerType:"alias",originalName:originalNames.join(", "),newName:newNames.join(", "),formattingPreserved:!0,formattingMethod:"sql-identifier-renamer"}}catch(error){return{success:!1,originalSql:sql,renamerType:"unknown",originalName:Object.keys(renames).join(", "),newName:Object.values(renames).join(", "),error:`Batch rename failed: ${error instanceof Error?error.message:String(error)}`,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}else return{success:!1,originalSql:sql,renamerType:"unknown",originalName:Object.keys(renames).join(", "),newName:Object.values(renames).join(", "),error:"Batch rename without formatting preservation not implemented. Use individual renames or enable formatting preservation.",formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}};var OriginalFormatRestorer=class{restore(lexemes){if(lexemes.length===0)return"";let result="";for(let lexeme of lexemes)result+=lexeme.value,lexeme.followingWhitespace&&(result+=lexeme.followingWhitespace);return result}restoreWithComments(lexemes,includeComments=!0){if(lexemes.length===0)return"";let result="";for(let lexeme of lexemes){if(result+=lexeme.value,includeComments&&lexeme.inlineComments&&lexeme.inlineComments.length>0)for(let comment of lexeme.inlineComments)comment.trim().length>0&&(result+=` -- ${comment}`);lexeme.followingWhitespace&&(result+=lexeme.followingWhitespace)}return result}analyzeFormatting(lexemes){let totalWhitespace=0,totalComments=0,spaceCount=0,tabCount=0,indentLines=0,totalIndentSize=0;for(let lexeme of lexemes){if(lexeme.followingWhitespace){totalWhitespace+=lexeme.followingWhitespace.length;let lines=lexeme.followingWhitespace.split(`
49
- `);for(let i=1;i<lines.length;i++){let line=lines[i],leadingSpaces=line.match(/^ */)?.[0].length||0,leadingTabs=line.match(/^\t*/)?.[0].length||0;(leadingSpaces>0||leadingTabs>0)&&(indentLines++,totalIndentSize+=leadingSpaces+leadingTabs*4,spaceCount+=leadingSpaces,tabCount+=leadingTabs)}}lexeme.inlineComments&&(totalComments+=lexeme.inlineComments.length)}let indentationStyle="none";return spaceCount>0&&tabCount>0?indentationStyle="mixed":spaceCount>0?indentationStyle="spaces":tabCount>0&&(indentationStyle="tabs"),{totalWhitespace,totalComments,indentationStyle,averageIndentSize:indentLines>0?totalIndentSize/indentLines:0}}validateFormattingLexemes(lexemes){let issues=[];for(let i=0;i<lexemes.length;i++){let lexeme=lexemes[i];lexeme.position||issues.push(`Lexeme ${i} missing position information`),lexeme.followingWhitespace===void 0&&issues.push(`Lexeme ${i} missing followingWhitespace property`),lexeme.inlineComments===void 0&&issues.push(`Lexeme ${i} missing inlineComments property`),lexeme.position&&lexeme.position.startPosition>=lexeme.position.endPosition&&issues.push(`Lexeme ${i} has invalid position range`)}return{isValid:issues.length===0,issues}}};var SelectResultSelectConverter=class{static toSelectQuery(query,options){let fixtureTables=options?.fixtureTables??[];if(fixtureTables.length===0)return query;let sources=new TableSourceCollector(!1).collect(query),referencedTables=new Set;sources.forEach(s=>referencedTables.add(s.getSourceName().toLowerCase()));let neededFixtures=fixtureTables.filter(f=>referencedTables.has(f.tableName.toLowerCase()));if(neededFixtures.length===0)return query;let fixtureCtes=FixtureCteBuilder.buildFixtures(neededFixtures);return query instanceof SimpleSelectQuery&&(query.withClause?query.withClause.tables=[...fixtureCtes,...query.withClause.tables]:query.appendWith(fixtureCtes)),query}};var SimulatedSelectConverter=class{static convert(ast,options){if(ast instanceof InsertQuery)return InsertResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof UpdateQuery)return UpdateResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof DeleteQuery)return DeleteResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof MergeQuery)return MergeResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof SimpleSelectQuery||ast instanceof BinarySelectQuery||ast instanceof ValuesQuery)return SelectResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof CreateTableQuery){if(ast.isTemporary&&ast.asSelectQuery){let processedSelect=SelectResultSelectConverter.toSelectQuery(ast.asSelectQuery,options);return ast.asSelectQuery=processedSelect,ast}return null}return null}};var DDLGeneralizer=class{static generalize(ast){let result=[];for(let component of ast)if(component instanceof CreateTableQuery){let{createTable,alterTables}=this.splitCreateTable(component);result.push(createTable),result.push(...alterTables)}else result.push(component);return result}static splitCreateTable(query){let newColumns=[],alterTables=[],tableQualifiedName=new QualifiedName(query.namespaces||[],query.tableName.name);for(let col of query.columns){let newConstraints=[];for(let constraint of col.constraints)if(["primary-key","unique","references","check"].includes(constraint.kind)){let tableConstraint=this.columnToTableConstraint(col.name,constraint);alterTables.push(new AlterTableStatement({table:tableQualifiedName,actions:[new AlterTableAddConstraint({constraint:tableConstraint})]}))}else newConstraints.push(constraint);newColumns.push(new TableColumnDefinition({name:col.name,dataType:col.dataType,constraints:newConstraints}))}if(query.tableConstraints)for(let constraint of query.tableConstraints)alterTables.push(new AlterTableStatement({table:tableQualifiedName,actions:[new AlterTableAddConstraint({constraint})]}));return{createTable:new CreateTableQuery({tableName:query.tableName.name,namespaces:query.namespaces,columns:newColumns,ifNotExists:query.ifNotExists,isTemporary:query.isTemporary,tableOptions:query.tableOptions,asSelectQuery:query.asSelectQuery,withDataOption:query.withDataOption,tableConstraints:[]}),alterTables}}static columnToTableConstraint(columnName,constraint){let baseParams={constraintName:constraint.constraintName,deferrable:constraint.reference?.deferrable,initially:constraint.reference?.initially};switch(constraint.kind){case"primary-key":return new TableConstraintDefinition({kind:"primary-key",columns:[columnName],...baseParams});case"unique":return new TableConstraintDefinition({kind:"unique",columns:[columnName],...baseParams});case"references":return new TableConstraintDefinition({kind:"foreign-key",columns:[columnName],reference:constraint.reference,...baseParams});case"check":return new TableConstraintDefinition({kind:"check",checkExpression:constraint.checkExpression,...baseParams});default:throw new Error(`Unsupported constraint kind for generalization: ${constraint.kind}`)}}};var DDLDiffGenerator=class{static generateDiff(currentSql,expectedSql,options={}){let currentAst=this.parseAndGeneralize(currentSql),expectedAst=this.parseAndGeneralize(expectedSql),currentSchema=this.buildSchema(currentAst),expectedSchema=this.buildSchema(expectedAst),diffAsts=[];for(let[tableName,expectedTable]of expectedSchema.tables){let currentTable=currentSchema.tables.get(tableName);if(currentTable)this.compareColumns(currentTable,expectedTable,diffAsts,options),this.compareConstraints(currentTable,expectedTable,diffAsts,options),this.compareIndexes(currentTable,expectedTable,diffAsts,options);else{let columns=Array.from(expectedTable.columns.values()).map(c=>c.definition),tableNameStr=expectedTable.qualifiedName.name instanceof RawString?expectedTable.qualifiedName.name.value:expectedTable.qualifiedName.name.name,namespaces=expectedTable.qualifiedName.namespaces?expectedTable.qualifiedName.namespaces.map(ns=>ns.name):null,createTable=new CreateTableQuery({tableName:tableNameStr,namespaces,columns});diffAsts.push(createTable);for(let constraint of expectedTable.constraints)diffAsts.push(new AlterTableStatement({table:expectedTable.qualifiedName,actions:[new AlterTableAddConstraint({constraint:constraint.definition})]}));for(let index of expectedTable.indexes)diffAsts.push(index.definition)}}if(options.dropTables)for(let[tableName,currentTable]of currentSchema.tables)expectedSchema.tables.has(tableName)||diffAsts.push(new DropTableStatement({tables:[currentTable.qualifiedName],ifExists:!1}));let formatter2=new SqlFormatter(options.formatOptions||{keywordCase:"upper"});return diffAsts.map(ast=>formatter2.format(ast).formattedSql+";")}static parseAndGeneralize(sql){let split=MultiQuerySplitter.split(sql),asts=[];for(let q of split.queries)if(!q.isEmpty)try{let ast=SqlParser.parse(q.sql);asts.push(ast)}catch(e){console.warn("Failed to parse SQL for diff:",q.sql,e)}return DDLGeneralizer.generalize(asts)}static buildSchema(asts){let tables=new Map,formatter2=new SqlFormatter({keywordCase:"none"});for(let ast of asts)if(ast instanceof CreateTableQuery){let qName=new QualifiedName(ast.namespaces||[],ast.tableName),key=this.getQualifiedNameKey(qName),tableModel={name:key,qualifiedName:qName,columns:new Map,constraints:[],indexes:[]};for(let col of ast.columns)tableModel.columns.set(col.name.name,{name:col.name.name,definition:col});tables.set(key,tableModel)}else if(ast instanceof AlterTableStatement){let key=this.getQualifiedNameKey(ast.table),tableModel=tables.get(key);if(tableModel)for(let action of ast.actions)if(action instanceof AlterTableAddConstraint){let formatted=formatter2.format(action.constraint).formattedSql;tableModel.constraints.push({name:action.constraint.constraintName?.name,kind:action.constraint.kind,definition:action.constraint,formatted})}else action instanceof AlterTableAddColumn&&tableModel.columns.set(action.column.name.name,{name:action.column.name.name,definition:action.column})}else if(ast instanceof CreateIndexStatement){let key=this.getQualifiedNameKey(ast.tableName),tableModel=tables.get(key);if(tableModel){let formatted=formatter2.format(ast).formattedSql;tableModel.indexes.push({name:ast.indexName.toString(),definition:ast,formatted})}}return{tables}}static compareColumns(current,expected,diffs,options){for(let[name,col]of expected.columns)current.columns.has(name)||diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableAddColumn({column:col.definition})]}));if(options.dropColumns)for(let[name,col]of current.columns)expected.columns.has(name)||diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableDropColumn({columnName:col.definition.name})]}))}static compareConstraints(current,expected,diffs,options){let formatter2=new SqlFormatter({keywordCase:"none"}),getConstraintSignature=c=>options.checkConstraintNames?c.kind==="primary-key"?c.formatted.replace(/^constraint\s+("[^"]+"|[^\s]+)\s+/i,"").trim():c.name||c.formatted:c.formatted.replace(/^constraint\s+("[^"]+"|[^\s]+)\s+/i,"").trim(),currentSignatures=new Set(current.constraints.map(getConstraintSignature));for(let expectedC of expected.constraints){let sig=getConstraintSignature(expectedC);currentSignatures.has(sig)||diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableAddConstraint({constraint:expectedC.definition})]}))}if(options.dropConstraints){let expectedSignatures=new Set(expected.constraints.map(getConstraintSignature));for(let currentC of current.constraints){let sig=getConstraintSignature(currentC);expectedSignatures.has(sig)||(currentC.name?diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableDropConstraint({constraintName:new IdentifierString(currentC.name)})]})):console.warn("Cannot drop unnamed constraint:",currentC.formatted))}}}static compareIndexes(current,expected,diffs,options){let getIndexSignature=idx=>{if(options.checkConstraintNames)return idx.name;let def=idx.definition,parts=[];parts.push(def.tableName.toString()),def.unique&&parts.push("UNIQUE"),def.usingMethod&&parts.push(`USING:${def.usingMethod.toString()}`);let columnSigs=def.columns.map(col=>{let expr=col.expression.toString(),sort=col.sortOrder||"",nulls=col.nullsOrder||"";return`${expr}${sort}${nulls}`});return parts.push(`COLS:${columnSigs.join(",")}`),def.include&&def.include.length>0&&parts.push(`INCLUDE:${def.include.map(i=>i.toString()).join(",")}`),def.where&&parts.push(`WHERE:${def.where.toString()}`),parts.join("|")},currentSignatures=new Set(current.indexes.map(getIndexSignature));for(let expectedIdx of expected.indexes){let sig=getIndexSignature(expectedIdx);currentSignatures.has(sig)||diffs.push(expectedIdx.definition)}if(options.checkConstraintNames||options.dropIndexes){let expectedSignatures=new Set(expected.indexes.map(getIndexSignature));for(let currentIdx of current.indexes){let sig=getIndexSignature(currentIdx);expectedSignatures.has(sig)||diffs.push(new DropIndexStatement({indexNames:[currentIdx.definition.indexName],ifExists:!1}))}}}static getQualifiedNameKey(qName){return qName.toString()}};var ParameterDetector=class{static extractParameterNames(query){return ParameterCollector.collect(query).map(p=>p.name.value)}static hasParameter(query,parameterName){return this.extractParameterNames(query).includes(parameterName)}static separateFilters(query,filter){let hardcodedParamNames=this.extractParameterNames(query),hardcodedParams={},dynamicFilters={};for(let[key,value]of Object.entries(filter))hardcodedParamNames.includes(key)?hardcodedParams[key]=value:dynamicFilters[key]=value;return{hardcodedParams,dynamicFilters}}};var FilterableItem=class{constructor(name,type,tableName){this.name=name;this.type=type;this.tableName=tableName}},FilterableItemCollector=class{constructor(tableColumnResolver,options){this.tableColumnResolver=tableColumnResolver,this.options={qualified:!1,upstream:!0,...options}}collect(query){let items=[],columnItems=this.collectColumns(query);items.push(...columnItems);let parameterItems=this.collectParameters(query);return items.push(...parameterItems),this.removeDuplicates(items)}collectColumns(query){let items=[];try{let columns=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:this.options.upstream}).collect(query);for(let column of columns){let tableName,realTableName;if(column.value&&typeof column.value.getNamespace=="function"){let namespace=column.value.getNamespace();namespace&&namespace.trim()!==""&&(tableName=namespace,this.options.qualified&&(realTableName=this.getRealTableName(query,namespace)))}tableName||(tableName=this.inferTableNameFromQuery(query),tableName&&this.options.qualified&&(realTableName=tableName));let columnName=column.name;this.options.qualified&&(realTableName||tableName)&&(columnName=`${realTableName||tableName}.${column.name}`),items.push(new FilterableItem(columnName,"column",tableName))}}catch(error){console.warn("Failed to collect columns with SelectableColumnCollector, using fallback:",error);try{let schemas=new SchemaCollector(this.tableColumnResolver,!0).collect(query);for(let schema of schemas)for(let columnName of schema.columns){let finalColumnName=columnName;this.options.qualified&&(finalColumnName=`${schema.name}.${columnName}`),items.push(new FilterableItem(finalColumnName,"column",schema.name))}}catch(fallbackError){console.warn("Failed to collect columns with both approaches:",error,fallbackError)}}return items}inferTableNameFromQuery(query){if(query instanceof SimpleSelectQuery&&query.fromClause&&query.fromClause.source){let datasource=query.fromClause.source.datasource;if(datasource&&typeof datasource.table=="object"){let table=datasource.table;if(table&&typeof table.name=="string")return table.name}}}getRealTableName(query,aliasOrName){try{let simpleQuery=query.type==="WITH"?query.toSimpleQuery():query;if(simpleQuery instanceof SimpleSelectQuery&&simpleQuery.fromClause){if(simpleQuery.fromClause.source?.datasource){let mainSource=simpleQuery.fromClause.source,realName=this.extractRealTableName(mainSource,aliasOrName);if(realName)return realName}let fromClause=simpleQuery.fromClause;if(fromClause.joinClauses&&Array.isArray(fromClause.joinClauses)){for(let joinClause of fromClause.joinClauses)if(joinClause.source?.datasource){let realName=this.extractRealTableName(joinClause.source,aliasOrName);if(realName)return realName}}}}catch(error){console.warn("Error resolving real table name:",error)}return aliasOrName}extractRealTableName(source,aliasOrName){try{let datasource=source.datasource;if(!datasource)return;let alias=source.alias||source.aliasExpression?.table?.name,realTableName=datasource.table?.name;if(alias===aliasOrName&&realTableName||!alias&&realTableName===aliasOrName)return realTableName}catch{}}collectParameters(query){let items=[];try{let parameterNames=ParameterDetector.extractParameterNames(query);for(let paramName of parameterNames)items.push(new FilterableItem(paramName,"parameter"))}catch(error){console.warn("Failed to collect parameters:",error)}return items}removeDuplicates(items){let seen=new Set,result=[];for(let item of items){let key=`${item.type}:${item.name}:${item.tableName||"none"}`;seen.has(key)||(seen.add(key),result.push(item))}return result.sort((a,b)=>{if(a.type!==b.type)return a.type==="column"?-1:1;if(a.type==="column"){let tableA=a.tableName||"",tableB=b.tableName||"";if(tableA!==tableB)return tableA.localeCompare(tableB)}return a.name.localeCompare(b.name)})}};var SqlSortInjector=class{constructor(tableColumnResolver){this.tableColumnResolver=tableColumnResolver}static removeOrderBy(query){if(typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for ORDER BY removal");return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:null,windowClause:query.windowClause,limitClause:query.limitClause,offsetClause:query.offsetClause,fetchClause:query.fetchClause,forClause:query.forClause})}inject(query,sortConditions){if(typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for sorting");let availableColumns=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query);for(let columnName of Object.keys(sortConditions))if(!availableColumns.find(item=>item.name===columnName))throw new Error(`Column or alias '${columnName}' not found in current query`);let newOrderByItems=[];for(let[columnName,condition]of Object.entries(sortConditions)){let columnEntry=availableColumns.find(item=>item.name===columnName);if(!columnEntry)continue;let columnRef=columnEntry.value;this.validateSortCondition(columnName,condition);let sortDirection;condition.desc?sortDirection="desc":sortDirection="asc";let nullsPosition=null;condition.nullsFirst?nullsPosition="first":condition.nullsLast&&(nullsPosition="last");let orderByItem=new OrderByItem(columnRef,sortDirection,nullsPosition);newOrderByItems.push(orderByItem)}let finalOrderByItems=[];query.orderByClause?finalOrderByItems=[...query.orderByClause.order,...newOrderByItems]:finalOrderByItems=newOrderByItems;let newOrderByClause=finalOrderByItems.length>0?new OrderByClause(finalOrderByItems):null;return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:newOrderByClause,windowClause:query.windowClause,limitClause:query.limitClause,offsetClause:query.offsetClause,fetchClause:query.fetchClause,forClause:query.forClause})}validateSortCondition(columnName,condition){if(condition.asc&&condition.desc)throw new Error(`Conflicting sort directions for column '${columnName}': both asc and desc specified`);if(condition.nullsFirst&&condition.nullsLast)throw new Error(`Conflicting nulls positions for column '${columnName}': both nullsFirst and nullsLast specified`);if(!condition.asc&&!condition.desc&&!condition.nullsFirst&&!condition.nullsLast)throw new Error(`Empty sort condition for column '${columnName}': at least one sort option must be specified`)}};var SqlPaginationInjector=class{inject(query,pagination){if(this.validatePaginationOptions(pagination),typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for pagination");if(query.limitClause||query.offsetClause)throw new Error("Query already contains LIMIT or OFFSET clause. Use removePagination() first if you want to override existing pagination.");let offset=(pagination.page-1)*pagination.pageSize,limitClause=new LimitClause(new ParameterExpression("paging_limit",pagination.pageSize)),offsetClause=new OffsetClause(new ParameterExpression("paging_offset",offset));return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:query.orderByClause,windowClause:query.windowClause,limitClause,offsetClause,fetchClause:query.fetchClause,forClause:query.forClause})}static removePagination(query){if(typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for pagination removal");return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:query.orderByClause,windowClause:query.windowClause,limitClause:null,offsetClause:null,fetchClause:query.fetchClause,forClause:query.forClause})}validatePaginationOptions(pagination){if(!pagination)throw new Error("Pagination options are required");if(typeof pagination.page!="number"||pagination.page<1)throw new Error("Page number must be a positive integer (1 or greater)");if(typeof pagination.pageSize!="number"||pagination.pageSize<1)throw new Error("Page size must be a positive integer (1 or greater)");if(pagination.pageSize>1e3)throw new Error("Page size cannot exceed 1000 items")}};var SqlParameterBinder=class{constructor(options={}){this.options={requireAllParameters:!0,...options}}bind(query,parameterValues){let modifiedQuery=query,existingParams=ParameterDetector.extractParameterNames(modifiedQuery);if(this.options.requireAllParameters){let missingParams=existingParams.filter(paramName=>!(paramName in parameterValues)||parameterValues[paramName]===void 0);if(missingParams.length>0)throw new Error(`Missing values for required parameters: ${missingParams.join(", ")}`)}for(let[paramName,value]of Object.entries(parameterValues))if(existingParams.includes(paramName))try{ParameterHelper.set(modifiedQuery,paramName,value)}catch(error){throw new Error(`Failed to bind parameter '${paramName}': ${error instanceof Error?error.message:"Unknown error"}`)}return modifiedQuery}bindToSimpleQuery(query,parameterValues){return this.bind(query,parameterValues)}};var NAMESPACE_SEPARATOR="|",normalizeIdentifier=input=>{let value=input?.trim()??"";return value===""?"":value.toLowerCase()},normalizeColumnSetKey=columns=>columns.map(column=>normalizeIdentifier(column)).filter(Boolean).sort().join(NAMESPACE_SEPARATOR),buildSchemaMap=schemaInfo=>{let map=new Map;for(let table of schemaInfo){let normalizedName=normalizeIdentifier(table.name);if(!normalizedName)continue;let columnSet=new Set(table.columns.map(normalizeIdentifier).filter(Boolean)),uniqueSetKeys=new Set;for(let uniqueKey of table.uniqueKeys){let normalizedKey=normalizeColumnSetKey(uniqueKey);normalizedKey&&uniqueSetKeys.add(normalizedKey)}columnSet.size===0&&uniqueSetKeys.size===0||map.set(normalizedName,{columnSet,uniqueSetKeys})}return map},collectReferenceMetadata=query=>{let collector=new ColumnReferenceCollector,namespaceCounts=new Map,unqualifiedColumns=new Set;for(let ref of collector.collect(query)){let namespace=normalizeIdentifier(ref.getNamespace());if(namespace)namespaceCounts.set(namespace,(namespaceCounts.get(namespace)??0)+1);else{let column=normalizeIdentifier(ref.column.name);column&&unqualifiedColumns.add(column)}}let joinConditionCounts=new Map;if(query.fromClause?.joins)for(let join of query.fromClause.joins){let counts=new Map;if(join.condition&&join.condition instanceof JoinOnClause){let joinCollector=new ColumnReferenceCollector;for(let ref of joinCollector.collect(join.condition.condition)){let namespace=normalizeIdentifier(ref.getNamespace());namespace&&counts.set(namespace,(counts.get(namespace)??0)+1)}}joinConditionCounts.set(join,counts)}return{namespaceCounts,unqualifiedColumns,joinConditionCounts}},isLeftJoin=join=>join.joinType.value.toLowerCase().includes("left"),getJoinIdentifiers=join=>{let identifiers=new Set,alias=normalizeIdentifier(join.source.getAliasName());if(alias&&identifiers.add(alias),join.source.datasource instanceof TableSource){let rawName=join.source.datasource.getSourceName();rawName&&identifiers.add(normalizeIdentifier(rawName));let shortName=normalizeIdentifier(join.source.datasource.table.name);shortName&&identifiers.add(shortName)}return[...identifiers]},hasExternalReferences=(identifiers,metadata,join)=>{let local=metadata.joinConditionCounts.get(join)??new Map;for(let identifier of identifiers){let total=metadata.namespaceCounts.get(identifier)??0,localCount=local.get(identifier)??0;if(total-localCount>0)return!0}return!1},getJoinColumnInfo=(join,identifiers)=>{if(!(join.condition instanceof JoinOnClause))return null;let expression=join.condition.condition;if(!(expression instanceof BinaryExpression)||expression.operator.value.trim().toLowerCase()!=="=")return null;let resolveColumn=component=>component instanceof ColumnReference?component:null,leftRef=resolveColumn(expression.left),rightRef=resolveColumn(expression.right);if(!leftRef||!rightRef)return null;let normalizedLeftNamespace=normalizeIdentifier(leftRef.getNamespace()),normalizedRightNamespace=normalizeIdentifier(rightRef.getNamespace());return identifiers.has(normalizedLeftNamespace)?normalizeIdentifier(leftRef.column.name):identifiers.has(normalizedRightNamespace)?normalizeIdentifier(rightRef.column.name):null},shouldRemoveJoin=(join,schemaMap,metadata)=>{if(!isLeftJoin(join)||join.lateral||!(join.source.datasource instanceof TableSource))return!1;let candidates=[normalizeIdentifier(join.source.datasource.getSourceName()),normalizeIdentifier(join.source.datasource.table.name)].filter(Boolean),tableInfo;for(let candidate of candidates){let info=schemaMap.get(candidate);if(info){tableInfo=info;break}}if(!tableInfo)return!1;let identifiers=new Set(getJoinIdentifiers(join));if(identifiers.size===0||hasExternalReferences([...identifiers],metadata,join))return!1;let joinColumn=getJoinColumnInfo(join,identifiers);if(!joinColumn||metadata.unqualifiedColumns.has(joinColumn)||tableInfo.columnSet.size>0&&!tableInfo.columnSet.has(joinColumn))return!1;let uniqueKey=normalizeColumnSetKey([joinColumn]);return!!tableInfo.uniqueSetKeys.has(uniqueKey)},optimizeSimpleQuery=(query,schemaMap)=>{if(!query.fromClause?.joins?.length)return!1;let metadata=collectReferenceMetadata(query),retainedJoins=[],removed=!1;for(let join of query.fromClause.joins){if(shouldRemoveJoin(join,schemaMap,metadata)){removed=!0;continue}retainedJoins.push(join)}return query.fromClause.joins=retainedJoins.length>0?retainedJoins:null,removed},traverseSelectQuery=(query,schemaMap)=>{if(query instanceof SimpleSelectQuery)return optimizeSimpleQuery(query,schemaMap);if(query instanceof BinarySelectQuery){let leftChanged=traverseSelectQuery(query.left,schemaMap),rightChanged=traverseSelectQuery(query.right,schemaMap);return leftChanged||rightChanged}return!1},optimizeUnusedLeftJoinsOnce=(query,schemaMap)=>schemaMap.size===0?!1:traverseSelectQuery(query,schemaMap),optimizeUnusedLeftJoins=(query,schemaInfo)=>(optimizeUnusedLeftJoinsOnce(query,buildSchemaMap(schemaInfo)),query),optimizeUnusedLeftJoinsToFixedPoint=(query,schemaInfo)=>{let schemaMap=buildSchemaMap(schemaInfo),changed=!0;for(;changed;)changed=optimizeUnusedLeftJoinsOnce(query,schemaMap);return query},collectTableSourceNames=component=>{let collector=new CTETableReferenceCollector,names=new Set;for(let source of collector.collect(component)){let normalizedName=normalizeIdentifier(source.table.name);normalizedName&&names.add(normalizedName)}return names},isReferencedByOthers=(cteName,mainReferences,cteReferenceMap)=>{if(mainReferences.has(cteName))return!0;for(let[otherName,references]of cteReferenceMap)if(otherName!==cteName&&references.has(cteName))return!0;return!1},optimizeSimpleQueryCtes=query=>{let withClause=query.withClause;if(!withClause||withClause.recursive||withClause.tables.length===0)return!1;let mainReferences=collectTableSourceNames(query),cteReferenceMap=new Map;for(let table of withClause.tables){let normalizedName=normalizeIdentifier(table.aliasExpression.table.name);normalizedName&&cteReferenceMap.set(normalizedName,collectTableSourceNames(table.query))}let removableNames=[];for(let table of withClause.tables){let normalizedName=normalizeIdentifier(table.aliasExpression.table.name);if(!normalizedName)continue;let body=table.query;!(body instanceof SimpleSelectQuery)&&!(body instanceof BinarySelectQuery)||isReferencedByOthers(normalizedName,mainReferences,cteReferenceMap)||removableNames.push(normalizedName)}if(removableNames.length===0)return!1;for(let name of removableNames)query.removeCTE(name);return!0},optimizeCtesInSelectQuery=query=>{if(query instanceof SimpleSelectQuery)return optimizeSimpleQueryCtes(query);if(query instanceof BinarySelectQuery){let leftChanged=optimizeCtesInSelectQuery(query.left),rightChanged=optimizeCtesInSelectQuery(query.right);return leftChanged||rightChanged}return!1},optimizeUnusedCtesOnce=query=>optimizeCtesInSelectQuery(query),optimizeUnusedCtes=query=>(optimizeUnusedCtesOnce(query),query),optimizeUnusedCtesToFixedPoint=query=>{let changed=!0;for(;changed;)changed=optimizeUnusedCtesOnce(query);return query};var isBinaryOperator=(expression,operator)=>expression instanceof BinaryExpression&&expression.operator.value.trim().toLowerCase()===operator,unwrapSingleOuterParen=expression=>{let candidate=expression;for(;candidate instanceof ParenExpression;)candidate=candidate.expression;return candidate},unwrapOptionalGuardParameter=expression=>{let candidate=unwrapSingleOuterParen(expression);for(;candidate instanceof CastExpression;)candidate=unwrapSingleOuterParen(candidate.input);if(candidate instanceof FunctionCall&&getFunctionCallName(candidate)==="cast"&&candidate.argument){let argument=unwrapSingleOuterParen(candidate.argument);if(isBinaryOperator(argument,"as"))return unwrapOptionalGuardParameter(argument.left)}return candidate},getFunctionCallName=expression=>{let name=expression.qualifiedName.name;return"value"in name?name.value.toLowerCase():name.name.toLowerCase()},collectTopLevelAndTerms=expression=>{let candidate=unwrapSingleOuterParen(expression);return isBinaryOperator(candidate,"and")?[...collectTopLevelAndTerms(candidate.left),...collectTopLevelAndTerms(candidate.right)]:[expression]},collectTopLevelOrTerms=expression=>{let candidate=unwrapSingleOuterParen(expression);return isBinaryOperator(candidate,"or")?[...collectTopLevelOrTerms(candidate.left),...collectTopLevelOrTerms(candidate.right)]:[expression]},isNullLiteral=expression=>expression instanceof LiteralValue&&expression.value===null||expression instanceof RawString&&expression.value.trim().toLowerCase()==="null",isTrueSentinel=expression=>{let candidate=unwrapSingleOuterParen(expression);return candidate instanceof LiteralValue?candidate.value===!0:isBinaryOperator(candidate,"=")?candidate.left instanceof LiteralValue&&candidate.right instanceof LiteralValue&&candidate.left.value===1&&candidate.right.value===1:!1},getGuardedParameterName=expression=>{let candidate=unwrapSingleOuterParen(expression);if(!isBinaryOperator(candidate,"is"))return null;let left=unwrapOptionalGuardParameter(candidate.left);return!(left instanceof ParameterExpression)||!isNullLiteral(candidate.right)?null:left.name.value},getUniqueParameterNames=expression=>new Set(ParameterCollector.collect(expression).map(parameter=>parameter.name.value)),isSupportedMeaningfulBranch=(expression,parameterName)=>{let candidate=unwrapSingleOuterParen(expression);if(candidate instanceof ParameterExpression)return!1;let parameterNames=getUniqueParameterNames(candidate);return parameterNames.size!==1||!parameterNames.has(parameterName)?!1:!(candidate instanceof LiteralValue||candidate instanceof RawString)},isExplicitPruningTarget=(pruningParameters,parameterName)=>Object.prototype.hasOwnProperty.call(pruningParameters,parameterName),isKnownAbsentTarget=(pruningParameters,parameterName)=>{if(!isExplicitPruningTarget(pruningParameters,parameterName))return!1;let parameterValue=pruningParameters[parameterName];return parameterValue==null},shouldPruneOptionalBranch=(expression,pruningParameters)=>{let branch=getSupportedOptionalConditionBranch(expression);return branch!==null&&isKnownAbsentTarget(pruningParameters,branch.parameterName)},rebuildAndCondition=terms=>{if(terms.length===0)return null;let condition=terms[0];for(let index=1;index<terms.length;index+=1)condition=new BinaryExpression(condition,"and",terms[index]);return condition},pruneSimpleQueryWhereClause=(query,pruningParameters)=>{if(!query.whereClause)return!1;let topLevelTerms=collectTopLevelAndTerms(query.whereClause.condition),retainedTerms=[],prunedAnyBranch=!1;for(let term of topLevelTerms){if(shouldPruneOptionalBranch(term,pruningParameters)){prunedAnyBranch=!0;continue}retainedTerms.push(term)}if(!prunedAnyBranch)return!1;let cleanedTerms=retainedTerms.filter(term=>!isTrueSentinel(term)),rebuiltCondition=rebuildAndCondition(cleanedTerms);return query.whereClause=rebuiltCondition?new WhereClause(rebuiltCondition):null,!0},isSelectQueryNode=value=>value instanceof SimpleSelectQuery||value instanceof BinarySelectQuery,traverseNestedSelectQueries=(root,pruningParameters)=>{let changed=!1,visited=new WeakSet,walk=value=>{if(!(!value||typeof value!="object")&&!visited.has(value)){if(visited.add(value),value!==root&&isSelectQueryNode(value)){changed=traverseSelectQuery2(value,pruningParameters)||changed;return}if(Array.isArray(value)){value.forEach(walk);return}for(let child of Object.values(value))walk(child)}};return walk(root),changed},traverseSelectQuery2=(query,pruningParameters)=>{if(query instanceof SimpleSelectQuery){let selfChanged=pruneSimpleQueryWhereClause(query,pruningParameters),nestedChanged=traverseNestedSelectQueries(query,pruningParameters);return selfChanged||nestedChanged}if(query instanceof BinarySelectQuery){let leftChanged=traverseSelectQuery2(query.left,pruningParameters),rightChanged=traverseSelectQuery2(query.right,pruningParameters);return leftChanged||rightChanged}return!1},getSupportedOptionalConditionBranch=expression=>{let orTerms=collectTopLevelOrTerms(expression);if(orTerms.length<2)return null;let guardTerms=orTerms.map(term=>({term,parameterName:getGuardedParameterName(term)})).filter(candidate=>candidate.parameterName!==null);if(guardTerms.length!==1)return null;let[{term:guardTerm,parameterName}]=guardTerms,meaningfulTerms=orTerms.filter(term=>term!==guardTerm);return meaningfulTerms.length===0||!meaningfulTerms.every(term=>isSupportedMeaningfulBranch(term,parameterName))?null:{parameterName,kind:"expression"}},collectSupportedBranchesFromSimpleQuery=(query,branches)=>{if(!query.whereClause)return;let topLevelTerms=collectTopLevelAndTerms(query.whereClause.condition);for(let term of topLevelTerms){let branch=getSupportedOptionalConditionBranch(term);branch&&branches.push({query,parameterName:branch.parameterName,expression:term,kind:branch.kind})}},collectSupportedBranchesFromSelectQuery=(query,branches)=>{if(query instanceof SimpleSelectQuery){collectSupportedBranchesFromSimpleQuery(query,branches),traverseNestedSelectQueriesForCollection(query,branches);return}query instanceof BinarySelectQuery&&(collectSupportedBranchesFromSelectQuery(query.left,branches),collectSupportedBranchesFromSelectQuery(query.right,branches))},traverseNestedSelectQueriesForCollection=(root,branches)=>{let visited=new WeakSet,walk=value=>{if(!(!value||typeof value!="object")&&!visited.has(value)){if(visited.add(value),value!==root&&isSelectQueryNode(value)){collectSupportedBranchesFromSelectQuery(value,branches);return}if(Array.isArray(value)){value.forEach(walk);return}for(let child of Object.values(value))walk(child)}};walk(root)},pruneOptionalConditionBranches=(query,pruningParameters)=>(Object.keys(pruningParameters).length===0||traverseSelectQuery2(query,pruningParameters),query),collectSupportedOptionalConditionBranches=query=>{let branches=[];return collectSupportedBranchesFromSelectQuery(query,branches),branches},collectSupportedOptionalConditionBranchSpans=sql=>{let parsed=SelectQueryParser.parse(sql),supportedBranches=collectSupportedOptionalConditionBranches(parsed);if(supportedBranches.length===0)return[];let candidates=collectOptionalConditionSpanCandidates(sql),remainingSupportedCounts=countSupportedBranchesByKey(supportedBranches);assertUnambiguousCandidateCounts(candidates,remainingSupportedCounts);let spans=[];for(let candidate of candidates){let key=getSupportedBranchKey(candidate),remainingCount=remainingSupportedCounts.get(key)??0;remainingCount<=0||(spans.push(candidate),remainingSupportedCounts.set(key,remainingCount-1))}return assertNoMissingSupportedBranches(remainingSupportedCounts),spans},getSupportedBranchKey=branch=>`${branch.kind}:${branch.parameterName}`,countSupportedBranchesByKey=branches=>{let counts=new Map;for(let branch of branches){let key=getSupportedBranchKey(branch);counts.set(key,(counts.get(key)??0)+1)}return counts},assertUnambiguousCandidateCounts=(candidates,supportedCounts)=>{let candidateCounts=countSupportedBranchesByKey(candidates);for(let[key,supportedCount]of supportedCounts){let candidateCount=candidateCounts.get(key)??0;if(candidateCount<supportedCount)throw new Error(`Could not locate source range for supported optional condition branch '${key}'.`);if(candidateCount>supportedCount)throw new Error(`Ambiguous source ranges for supported optional condition branch '${key}'.`)}},assertNoMissingSupportedBranches=supportedCounts=>{let missingKeys=[...supportedCounts.entries()].filter(([,count])=>count>0).map(([key])=>key);if(missingKeys.length>0)throw new Error(`Could not locate source ranges for supported optional condition branches: ${missingKeys.join(", ")}.`)},collectOptionalConditionSpanCandidates=sql=>{let lexemes=new SqlTokenizer(sql).readLexemes(),candidates=[],stack=[];for(let index=0;index<lexemes.length;index+=1){let lexeme=lexemes[index];if(isOpenParen(lexeme)){stack.push(index);continue}if(!isCloseParen(lexeme))continue;let openParenIndex=stack.pop();if(openParenIndex===void 0)continue;let candidate=buildOptionalConditionSpanCandidate(sql,lexemes,openParenIndex,index);candidate&&candidates.push(candidate)}return candidates.sort((left,right)=>left.sourceRange.start-right.sourceRange.start)},buildOptionalConditionSpanCandidate=(sql,lexemes,openParenIndex,closeParenIndex)=>{let inside=lexemes.slice(openParenIndex+1,closeParenIndex),orTermRanges=splitTopLevelTermsByKeyword(inside,"or");if(orTermRanges.length<2)return null;let guardTerms=orTermRanges.map(range=>({range,parameterName:getGuardedParameterNameFromLexemes(inside.slice(range.start,range.end))})).filter(candidate=>candidate.parameterName!==null);if(guardTerms.length!==1)return null;let[{range:guardRange,parameterName}]=guardTerms,meaningfulTerms=orTermRanges.filter(range=>range!==guardRange);if(meaningfulTerms.length===0||!meaningfulTerms.every(range=>isSupportedMeaningfulBranchFromLexemes(inside.slice(range.start,range.end),parameterName)))return null;let expandedRange=expandWrappingParenRange(lexemes,openParenIndex,closeParenIndex),sourceStart=requiredPosition(lexemes[expandedRange.openParenIndex]).startPosition,sourceEnd=requiredPosition(lexemes[expandedRange.closeParenIndex]).endPosition,removalRange=getRemovalRange(sql,lexemes,expandedRange.openParenIndex,expandedRange.closeParenIndex);return{parameterName,kind:"expression",sourceRange:{start:sourceStart,end:sourceEnd,text:sql.slice(sourceStart,sourceEnd)},removalRange,openParenIndex:expandedRange.openParenIndex,closeParenIndex:expandedRange.closeParenIndex}},expandWrappingParenRange=(lexemes,openParenIndex,closeParenIndex)=>{let expandedOpenParenIndex=openParenIndex,expandedCloseParenIndex=closeParenIndex;for(;isOpenParen(lexemes[expandedOpenParenIndex-1])&&isCloseParen(lexemes[expandedCloseParenIndex+1]);)expandedOpenParenIndex-=1,expandedCloseParenIndex+=1;return{openParenIndex:expandedOpenParenIndex,closeParenIndex:expandedCloseParenIndex}},splitTopLevelTermsByKeyword=(lexemes,keyword)=>{let ranges=[],depth=0,start=0;for(let index=0;index<lexemes.length;index+=1){let lexeme=lexemes[index];if(isOpenParen(lexeme)){depth+=1;continue}if(isCloseParen(lexeme)){depth-=1;continue}depth===0&&isKeyword(lexeme,keyword)&&(ranges.push({start,end:index}),start=index+1)}return ranges.push({start,end:lexemes.length}),ranges},getGuardedParameterNameFromLexemes=lexemes=>{let compact=lexemes.filter(lexeme=>!isWrappingParen(lexeme)),isIndexKeyword=(index,keyword)=>{let lexeme=compact[index];return lexeme!==void 0&&isKeyword(lexeme,keyword)};if(compact.length===3)return!isParameter(compact[0])||!isIndexKeyword(1,"is")||!isIndexKeyword(2,"null")?null:normalizeParameterName(compact[0].value);if(compact.length===5&&isParameter(compact[0])&&compact[1]?.value==="::"&&isIndexKeyword(3,"is")&&isIndexKeyword(4,"null"))return normalizeParameterName(compact[0].value);if(compact.length>=6&&isIndexKeyword(0,"cast")&&isParameter(compact[1])&&isIndexKeyword(2,"as")){let isIndex=compact.findIndex((lexeme,index)=>index>2&&isKeyword(lexeme,"is"));if(isIndex>=0&&isIndexKeyword(isIndex+1,"null"))return normalizeParameterName(compact[1].value)}return null},isSupportedMeaningfulBranchFromLexemes=(lexemes,parameterName)=>{try{let parsed=ValueParser.parseFromLexeme(lexemes,0);return parsed.newIndex!==lexemes.length?!1:isSupportedMeaningfulBranch(parsed.value,parameterName)}catch{return!1}},getRemovalRange=(sql,lexemes,openParenIndex,closeParenIndex)=>{let previous=lexemes[openParenIndex-1],next=lexemes[closeParenIndex+1],start=requiredPosition(lexemes[openParenIndex]).startPosition,end=requiredPosition(lexemes[closeParenIndex]).endPosition;return previous&&isKeyword(previous,"and")?start=requiredPosition(previous).startPosition:next&&isKeyword(next,"and")?end=requiredPosition(next).endPosition:previous&&isKeyword(previous,"where")&&(start=requiredPosition(previous).startPosition),{start,end,text:sql.slice(start,end)}},isParameter=lexeme=>(lexeme.type&256)!==0,isOpenParen=lexeme=>(lexeme.type&4)!==0,isCloseParen=lexeme=>(lexeme.type&8)!==0,isKeyword=(lexeme,keyword)=>lexeme.value.toLowerCase()===keyword,isWrappingParen=lexeme=>isOpenParen(lexeme)||isCloseParen(lexeme),normalizeParameterName=value=>value.startsWith("${")&&value.endsWith("}")?value.slice(2,-1):value.replace(/^[:@$]/,""),requiredPosition=lexeme=>{if(!lexeme.position)throw new Error(`Lexeme '${lexeme.value}' is missing source position metadata.`);return lexeme.position};var DynamicQueryBuilder=class{constructor(resolverOrOptions){typeof resolverOrOptions=="function"?this.tableColumnResolver=resolverOrOptions:resolverOrOptions&&(this.tableColumnResolver=resolverOrOptions.tableColumnResolver,this.defaultSchemaInfo=resolverOrOptions.schemaInfo)}buildQuery(sqlContent,options={}){let removedOptions=options;if("serialize"in removedOptions||"jsonb"in removedOptions)throw new Error("DynamicQueryBuilder SQL-result JSON shaping has been removed. Keep SQL results as rows and use generated AOT mappers so the executed SQL remains debuggable.");let parsedQuery;try{parsedQuery=SelectQueryParser.parse(sqlContent)}catch(error){throw new Error(`Failed to parse SQL: ${error instanceof Error?error.message:"Unknown error"}`)}let modifiedQuery=parsedQuery;if(options.filter&&Object.keys(options.filter).length>0){let{hardcodedParams,dynamicFilters}=ParameterDetector.separateFilters(modifiedQuery,options.filter);if(Object.keys(hardcodedParams).length>0&&(modifiedQuery=new SqlParameterBinder({requireAllParameters:!1}).bind(modifiedQuery,hardcodedParams)),Object.keys(dynamicFilters).length>0)throw new Error("DynamicQueryBuilder no longer injects runtime filter predicates. Use `ashiba query optional add` to author optional filters, `ashiba query optional refresh` to refresh them, and `optionalConditionParameters` at runtime for pruning only.")}if(options.sort&&Object.keys(options.sort).length>0){let sortInjector=new SqlSortInjector(this.tableColumnResolver),simpleQuery=QueryBuilder.buildSimpleQuery(modifiedQuery);modifiedQuery=sortInjector.inject(simpleQuery,options.sort)}if(options.paging){let{page=1,pageSize}=options.paging;if(pageSize!==void 0){let paginationInjector=new SqlPaginationInjector,paginationOptions={page,pageSize},simpleQuery=QueryBuilder.buildSimpleQuery(modifiedQuery);modifiedQuery=paginationInjector.inject(simpleQuery,paginationOptions)}}modifiedQuery=this.applyColumnFilters(modifiedQuery,options);let optionalConditionParameters=this.resolveOptionalConditionPruningParameters(options);Object.keys(optionalConditionParameters).length>0&&(modifiedQuery=pruneOptionalConditionBranches(modifiedQuery,optionalConditionParameters));let effectiveSchemaInfo=options.schemaInfo??this.defaultSchemaInfo;return options.removeUnusedLeftJoins&&effectiveSchemaInfo?.length&&(modifiedQuery=optimizeUnusedLeftJoinsToFixedPoint(modifiedQuery,effectiveSchemaInfo)),options.removeUnusedCtes&&(modifiedQuery=optimizeUnusedCtesToFixedPoint(modifiedQuery)),modifiedQuery}resolveOptionalConditionPruningParameters(options){if(options.optionalConditionParameters)return options.optionalConditionParameters;if(!options.optionalConditionParameterStates)return{};let legacyParameters={};for(let[parameterName,state]of Object.entries(options.optionalConditionParameterStates))legacyParameters[parameterName]=state==="absent"?null:"__RAWSQL_OPTIONAL_CONDITION_PRESENT__";return legacyParameters}applyColumnFilters(query,options){let hasIncludeFilters=Array.isArray(options.includeColumns)&&options.includeColumns.length>0,hasExcludeFilters=Array.isArray(options.excludeColumns)&&options.excludeColumns.length>0;if(!hasIncludeFilters&&!hasExcludeFilters)return query;if(hasIncludeFilters&&hasExcludeFilters)throw new Error("includeColumns and excludeColumns cannot be used together.");let simpleQuery=QueryBuilder.buildSimpleQuery(query),metadata=simpleQuery.selectClause.items.map(item=>{let name=this.getSelectItemName(item);return{item,normalized:name?this.normalizeColumnIdentifier(name):null}}),availableColumns=new Set(metadata.map(entry=>entry.normalized).filter(name=>name!==null)),includeFilters=hasIncludeFilters?this.normalizeColumnList(options.includeColumns):null,excludeFilters=hasExcludeFilters?this.normalizeColumnList(options.excludeColumns):null,includeSet=includeFilters?new Set(includeFilters.map(entry=>entry.normalized)):null,excludeSet=excludeFilters?new Set(excludeFilters.map(entry=>entry.normalized)):null;if(includeFilters){let missing=includeFilters.filter(entry=>!availableColumns.has(entry.normalized));if(missing.length>0)throw new Error(`Column${missing.length===1?"":"s"} not found in SELECT clause: ${missing.map(entry=>`'${entry.original}'`).join(", ")}.`)}if(excludeFilters){let missing=excludeFilters.filter(entry=>!availableColumns.has(entry.normalized));if(missing.length>0)throw new Error(`Column${missing.length===1?"":"s"} not found in SELECT clause: ${missing.map(entry=>`'${entry.original}'`).join(", ")}.`)}let filteredItems=metadata.filter(entry=>entry.normalized?includeSet?includeSet.has(entry.normalized):excludeSet?!excludeSet.has(entry.normalized):!0:!0).map(entry=>entry.item);if(filteredItems.length===0)throw new Error("Column filtering removed every SELECT item.");return simpleQuery.selectClause.items=filteredItems,simpleQuery}normalizeColumnList(columns){return columns.map(column=>{if(typeof column!="string")throw new Error("Column filters must be strings.");let trimmed=column.trim();if(trimmed==="")throw new Error("Column filters must not be empty.");return{normalized:this.normalizeColumnIdentifier(trimmed),original:trimmed}})}normalizeColumnIdentifier(value){return value.trim().toLowerCase()}getSelectItemName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}buildFilteredQuery(sqlContent,filter){return this.buildQuery(sqlContent,{filter})}buildSortedQuery(sqlContent,sort){return this.buildQuery(sqlContent,{sort})}buildPaginatedQuery(sqlContent,paging){return this.buildQuery(sqlContent,{paging})}validateSql(sqlContent){try{return SelectQueryParser.parse(sqlContent),!0}catch(error){throw new Error(`Invalid SQL: ${error instanceof Error?error.message:"Unknown error"}`)}}};var SUPPORTED_SCALAR_OPERATORS=new Set(["=","<>","<","<=",">",">=","like","ilike"]),formatter=null,normalizeIdentifier2=value=>value.trim().toLowerCase(),normalizeSql=value=>value.replace(/\s+/g," ").trim().toLowerCase(),normalizeRewriteTokenType=lexeme=>(lexeme.type&128)!==0?128:(lexeme.type&64)!==0?64:lexeme.type,normalizeRewriteTokenValue=lexeme=>(lexeme.type&128)!==0?lexeme.value.toLowerCase():lexeme.value,tokenizeForRewritePlan=sql=>new SqlTokenizer(sql).tokenize().map(lexeme=>({type:normalizeRewriteTokenType(lexeme),value:normalizeRewriteTokenValue(lexeme)})),tokenSequencesEqual=(left,right)=>left.length!==right.length?!1:left.every((token,index)=>{let other=right[index];return other!==void 0&&token.type===other.type&&token.value===other.value}),collectCommentFragments=sql=>new SqlTokenizer(sql).tokenize().flatMap(lexeme=>lexeme.positionedComments?lexeme.positionedComments.flatMap(positioned=>positioned.comments):lexeme.comments?[...lexeme.comments]:[]),commentsPreservedInOrder=(before,after)=>{let cursor=0;for(let comment of before){let foundAt=after.indexOf(comment,cursor);if(foundAt<0)return!1;cursor=foundAt+1}return!0},countCommandToken=(tokens,value)=>tokens.filter(token=>token.type===128&&token.value===value).length,applyRewriteEdits=(sql,edits)=>[...edits].sort((left,right)=>right.start-left.start).reduce((current,edit)=>current.slice(0,edit.start)+edit.after+current.slice(edit.end),sql),getStatementEndPosition=sql=>{let end=sql.length;for(;end>0&&/\s/.test(sql[end-1]);)end--;if(end>0&&sql[end-1]===";")for(end--;end>0&&/\s/.test(sql[end-1]);)end--;return end},clauseBoundaryCommands=new Set(["group by","having","order by","limit","offset","fetch","for"]),isClauseBoundary=lexeme=>(lexeme.type&128)!==0&&clauseBoundaryCommands.has(lexeme.value.toLowerCase()),findMinimalWhereInsertPosition=sql=>{let lexemes=new SqlTokenizer(sql).tokenize(),statementEnd=getStatementEndPosition(sql),topLevelLexemes=[],depth=0;for(let index=0;index<lexemes.length;index+=1){let lexeme=lexemes[index];(lexeme.type&8)!==0&&(depth=Math.max(0,depth-1)),depth===0&&topLevelLexemes.push({lexeme,index}),(lexeme.type&4)!==0&&(depth+=1)}let where=topLevelLexemes.find(entry=>(entry.lexeme.type&128)!==0&&entry.lexeme.value.toLowerCase()==="where");return where?{position:topLevelLexemes.filter(entry=>entry.index>where.index).map(entry=>entry.lexeme).find(isClauseBoundary)?.position?.startPosition??statementEnd,hasWhere:!0}:{position:topLevelLexemes.map(entry=>entry.lexeme).find(isClauseBoundary)?.position?.startPosition??statementEnd,hasWhere:!1}},findMatchingParenEnd=(sql,start)=>{let depth=0,quote=null;for(let index=start;index<sql.length;index++){let char=sql[index];if(quote){if(char===quote){if(quote==="'"&&sql[index+1]==="'"){index++;continue}quote=null}continue}if(char==="'"||char==='"'){quote=char;continue}if(char==="("&&depth++,char===")"&&(depth--,depth===0))return index+1}return-1},findOptionalBranchSpans=(sql,parameterName)=>{let spans=[],parameterNeedle=`:${parameterName.toLowerCase()}`,lowerSql=sql.toLowerCase();for(let index=0;index<sql.length;index++){if(sql[index]!=="(")continue;let end=findMatchingParenEnd(sql,index);if(end<0)break;let text=sql.slice(index,end),normalized=lowerSql.slice(index,end);normalized.includes(parameterNeedle)&&normalized.includes(" is null")&&normalized.includes(" or ")&&spans.push({start:index,end,text}),index=end-1}return spans},findBooleanOperatorBefore=(sql,start)=>{let prefix=sql.slice(0,start),match=/(\s+)(and|or)(\s*)$/i.exec(prefix);return!match||match.index===void 0?null:{start:match.index,end:start,value:match[2].toLowerCase()}},findBooleanOperatorAfter=(sql,end)=>{let suffix=sql.slice(end),match=/^(\s*)(and|or)(\s+)/i.exec(suffix);return match?{start:end,end:end+match[0].length,value:match[2].toLowerCase()}:null},findWhereBefore=(sql,position)=>{let lexemes=new SqlTokenizer(sql).tokenize(),found=null;for(let lexeme of lexemes){if((lexeme.position?.startPosition??0)>=position)break;(lexeme.type&128)!==0&&lexeme.value.toLowerCase()==="where"&&(found=lexeme)}return found?.position?{start:found.position.startPosition,end:found.position.endPosition}:null},findSourceColumnReferenceText=(sql,reference)=>{let namespace=normalizeIdentifier2(reference.getNamespace()),column=normalizeIdentifier2(reference.column.name),lexemes=new SqlTokenizer(sql).tokenize();for(let index=0;index<lexemes.length-2;index++){let first=lexemes[index],dot=lexemes[index+1],last=lexemes[index+2];if(!((first.type&64)===0||dot.value!=="."||(last.type&64)===0)&&!(normalizeIdentifier2(first.value)!==namespace||normalizeIdentifier2(last.value)!==column)&&!(!first.position||!last.position))return sql.slice(first.position.startPosition,last.position.endPosition)}return normalizeColumnReferenceText(reference)},normalizeColumnReferenceKey=reference=>`${normalizeIdentifier2(reference.getNamespace())}.${normalizeIdentifier2(reference.column.name)}`,normalizeColumnReferenceText=reference=>{let namespace=reference.getNamespace();return namespace?`${namespace}.${reference.column.name}`:reference.column.name},normalizeScalarOperator=value=>{if(!value)return"=";let normalized=value.trim().toLowerCase();if(normalized==="!=")return"<>";if(SUPPORTED_SCALAR_OPERATORS.has(normalized))return normalized;throw new Error(`Unsupported SSSQL operator '${value}'.`)},isExplicitEqualityScaffoldValue=value=>{if(value==null)return!0;if(Array.isArray(value))return!1;if(typeof value!="object")return!0;let entries=Object.entries(value).filter(([,entry])=>entry!==void 0);return entries.length===1&&entries[0]?.[0]==="="},parseQualifiedFilterName=filterName=>{let segments=filterName.split(".");if(segments.length!==2)return null;let[table,column]=segments.map(segment=>segment.trim());return!table||!column?null:{table,column}},makeParameterName=filterName=>filterName.trim().replace(/\./g,"_").replace(/[^a-zA-Z0-9_]/g,"_"),unwrapParens=expression=>{let candidate=expression;for(;candidate instanceof ParenExpression;)candidate=candidate.expression;return candidate},isBinaryOperator2=(expression,operator)=>expression instanceof BinaryExpression&&expression.operator.value.trim().toLowerCase()===operator,collectTopLevelAndTerms2=expression=>{let candidate=unwrapParens(expression);return isBinaryOperator2(candidate,"and")?[...collectTopLevelAndTerms2(candidate.left),...collectTopLevelAndTerms2(candidate.right)]:[expression]},collectTopLevelOrTerms2=expression=>{let candidate=unwrapParens(expression);return isBinaryOperator2(candidate,"or")?[...collectTopLevelOrTerms2(candidate.left),...collectTopLevelOrTerms2(candidate.right)]:[expression]},getGuardedParameterName2=expression=>{let candidate=unwrapParens(expression);if(!isBinaryOperator2(candidate,"is"))return null;let left=unwrapOptionalGuardParameter2(candidate.left);if(!(left instanceof ParameterExpression))return null;let right=unwrapParens(candidate.right);return right instanceof LiteralValue&&right.value===null||right instanceof RawString&&right.value.trim().toLowerCase()==="null"?left.name.value:null},unwrapOptionalGuardParameter2=expression=>{let candidate=unwrapParens(expression);for(;candidate instanceof CastExpression;)candidate=unwrapParens(candidate.input);if(candidate instanceof FunctionCall&&getFunctionCallName2(candidate)==="cast"&&candidate.argument){let argument=unwrapParens(candidate.argument);if(isBinaryOperator2(argument,"as"))return unwrapOptionalGuardParameter2(argument.left)}return candidate},getFunctionCallName2=expression=>{let name=expression.qualifiedName.name;return"value"in name?name.value.toLowerCase():name.name.toLowerCase()},buildOptionalScalarBranch=(column,parameterName,operator)=>{let guard=new BinaryExpression(new ParameterExpression(parameterName),"is",new LiteralValue(null)),predicate=new BinaryExpression(new ColumnReference(column.getNamespace()||null,column.column.name),operator,new ParameterExpression(parameterName));return new ParenExpression(new BinaryExpression(guard,"or",predicate))},buildOptionalExistsBranch=(parameterName,subquery,kind)=>{let guard=new BinaryExpression(new ParameterExpression(parameterName),"is",new LiteralValue(null)),existsExpression=new UnaryExpression("exists",new InlineQuery(subquery)),predicate=kind==="exists"?existsExpression:new UnaryExpression("not",existsExpression);return new ParenExpression(new BinaryExpression(guard,"or",predicate))},rebuildWhereWithoutTerm=(query,termToRemove)=>{if(!query.whereClause)return;let terms=collectTopLevelAndTerms2(query.whereClause.condition).filter(term=>term!==termToRemove);if(terms.length===0){query.whereClause=null;return}let rebuilt=terms[0];for(let index=1;index<terms.length;index+=1)rebuilt=new BinaryExpression(rebuilt,"and",terms[index]);query.whereClause=new WhereClause(rebuilt)},formatSqlComponent=component=>(formatter??=new SqlFormatter,formatter.format(component).formattedSql),enforceSubqueryConstraints=sql=>{if(!sql.trim())throw new Error("SSSQL EXISTS/NOT EXISTS scaffold query must not be empty.");if(sql.includes(";"))throw new Error("SSSQL EXISTS/NOT EXISTS scaffold query must not contain semicolons or multiple statements.");if(/\blateral\b/i.test(sql))throw new Error("LATERAL is not supported in SSSQL EXISTS/NOT EXISTS scaffold.")},substituteAnchorPlaceholders=(sql,formattedColumns)=>{let usedIndexes=new Set,replaced=sql.replace(/\$c(\d+)/g,(_,indexDigits)=>{let index=Number(indexDigits);if(!Number.isInteger(index))throw new Error(`Invalid placeholder '$c${indexDigits}' in SSSQL scaffold query.`);if(index<0||index>=formattedColumns.length)throw new Error(`Placeholder '$c${index}' references a missing SSSQL scaffold anchor column.`);return usedIndexes.add(index),formattedColumns[index]});if(formattedColumns.length===0)return replaced;for(let index=0;index<formattedColumns.length;index+=1)if(!usedIndexes.has(index))throw new Error(`Missing placeholder '$c${index}' for SSSQL scaffold anchor column.`);return replaced},getScalarBranchDetails=(expression,parameterName)=>{let meaningfulTerms=collectTopLevelOrTerms2(expression).filter(term=>getGuardedParameterName2(term)!==parameterName);if(meaningfulTerms.length!==1)return null;let predicate=unwrapParens(meaningfulTerms[0]);if(!(predicate instanceof BinaryExpression))return null;let left=unwrapParens(predicate.left),right=unwrapParens(predicate.right);if(left instanceof ColumnReference&&right instanceof ParameterExpression&&right.name.value===parameterName)try{return{operator:normalizeScalarOperator(predicate.operator.value),target:normalizeColumnReferenceText(left)}}catch{return null}if(right instanceof ColumnReference&&left instanceof ParameterExpression&&left.name.value===parameterName)try{return{operator:normalizeScalarOperator(predicate.operator.value),target:normalizeColumnReferenceText(right)}}catch{return null}return null},hasSelectQuery=value=>typeof value=="object"&&value!==null&&"selectQuery"in value,collectColumnReferencesDeep=value=>{let references=[],visited=new WeakSet,walk=candidate=>{if(!(!candidate||typeof candidate!="object")){if(candidate instanceof ColumnReference){references.push(candidate);return}if(!visited.has(candidate)){if(visited.add(candidate),Array.isArray(candidate)){for(let item of candidate)walk(item);return}for(let child of Object.values(candidate))walk(child)}}};return walk(value),references},getExistsBranchKind=(expression,parameterName)=>{let meaningfulTerms=collectTopLevelOrTerms2(expression).filter(term=>getGuardedParameterName2(term)!==parameterName);if(meaningfulTerms.length!==1)return null;let predicate=unwrapParens(meaningfulTerms[0]),isInlineQueryValue=value=>value instanceof InlineQuery||hasSelectQuery(value);if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="exists")return isInlineQueryValue(unwrapParens(predicate.expression))?"exists":null;if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not exists")return isInlineQueryValue(unwrapParens(predicate.expression))?"not-exists":null;if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not"&&unwrapParens(predicate.expression)instanceof UnaryExpression){let nested=unwrapParens(predicate.expression);if(nested.operator.value.trim().toLowerCase()==="exists"&&isInlineQueryValue(unwrapParens(nested.expression)))return"not-exists"}return null},getExistsPredicateDetails=(expression,parameterName)=>{let meaningfulTerms=collectTopLevelOrTerms2(expression).filter(term=>getGuardedParameterName2(term)!==parameterName);if(meaningfulTerms.length!==1)return null;let predicate=unwrapParens(meaningfulTerms[0]),isInlineQueryValue=value=>value instanceof InlineQuery||hasSelectQuery(value);if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="exists"){let candidate=unwrapParens(predicate.expression);return isInlineQueryValue(candidate)?{kind:"exists",subquery:candidate.selectQuery}:null}if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not exists"){let candidate=unwrapParens(predicate.expression);return isInlineQueryValue(candidate)?{kind:"not-exists",subquery:candidate.selectQuery}:null}if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not"&&unwrapParens(predicate.expression)instanceof UnaryExpression){let nested=unwrapParens(predicate.expression),candidate=unwrapParens(nested.expression);if(nested.operator.value.trim().toLowerCase()==="exists"&&isInlineQueryValue(candidate))return{kind:"not-exists",subquery:candidate.selectQuery}}return null},getBranchInfo=branch=>{let scalar=getScalarBranchDetails(branch.expression,branch.parameterName);if(scalar)return{parameterName:branch.parameterName,kind:"scalar",operator:scalar.operator,target:scalar.target,query:branch.query,expression:branch.expression,sql:formatSqlComponent(branch.expression)};let existsKind=getExistsBranchKind(branch.expression,branch.parameterName);return existsKind?{parameterName:branch.parameterName,kind:existsKind,query:branch.query,expression:branch.expression,sql:formatSqlComponent(branch.expression)}:{parameterName:branch.parameterName,kind:"expression",query:branch.query,expression:branch.expression,sql:formatSqlComponent(branch.expression)}},isEquivalentScalarBranch=(branch,query,parameterName,operator,targetColumnText)=>branch.query===query&&branch.kind==="scalar"&&branch.parameterName===parameterName&&branch.operator===operator&&branch.target!==void 0&&normalizeIdentifier2(branch.target)===normalizeIdentifier2(targetColumnText),SSSQLFilterBuilder=class{constructor(tableColumnResolver){this.tableColumnResolver=tableColumnResolver;this.finder=new UpstreamSelectQueryFinder(this.tableColumnResolver)}list(query){let parsed=this.parseQuery(query);return collectSupportedOptionalConditionBranches(parsed).map(getBranchInfo)}planScaffold(query,filters){if(typeof query=="string"){let entries=Object.entries(filters);if(entries.length===1){let[filterName,filterValue]=entries[0];if(isExplicitEqualityScaffoldValue(filterValue))try{return this.planScalarInsert(query,{target:filterName,parameterName:makeParameterName(filterName),operator:"="})}catch{}}}return this.planRewrite(query,parsed=>this.scaffold(parsed,filters))}dryRunScaffold(query,filters){return this.planScaffold(query,filters)}planScaffoldBranch(query,spec){if(typeof query=="string"&&(spec.kind==="exists"||spec.kind==="not-exists"))try{return this.planExistsInsert(query,spec)}catch{}if(typeof query=="string"&&spec.kind!=="exists"&&spec.kind!=="not-exists")try{return this.planScalarInsert(query,spec)}catch{}return this.planRewrite(query,parsed=>this.scaffoldBranch(parsed,spec))}dryRunScaffoldBranch(query,spec){return this.planScaffoldBranch(query,spec)}planRefresh(query,filters){if(typeof query=="string")try{let parsed=SelectQueryParser.parse(query);if(!this.refreshParsed(parsed,filters).changed)return this.buildPlanFromEdits(query,[],[],[])}catch{}return this.planRewrite(query,parsed=>this.refresh(parsed,filters))}dryRunRefresh(query,filters){return this.planRefresh(query,filters)}planRemove(query,spec){if(typeof query=="string")try{return this.planBranchRemoval(query,spec)}catch{}return this.planRewrite(query,parsed=>this.remove(parsed,spec))}dryRunRemove(query,spec){return this.planRemove(query,spec)}planRemoveAll(query){return this.planRewrite(query,parsed=>this.removeAll(parsed))}dryRunRemoveAll(query){return this.planRemoveAll(query)}scaffold(query,filters){let parsed=this.parseQuery(query);for(let[filterName,filterValue]of Object.entries(filters)){if(!isExplicitEqualityScaffoldValue(filterValue))throw new Error(`SSSQL scaffold only supports equality filters in v1. Use structured scaffold or refresh for pre-authored branches: '${filterName}'.`);this.scaffoldBranch(parsed,{target:filterName,parameterName:makeParameterName(filterName),operator:"="})}return parsed}scaffoldBranch(query,spec){let parsed=this.parseQuery(query);return spec.kind==="exists"||spec.kind==="not-exists"?(this.scaffoldExistsBranch(parsed,spec),parsed):(this.scaffoldScalarBranch(parsed,spec),parsed)}refresh(query,filters){let parsed=this.parseQuery(query);return this.refreshParsed(parsed,filters),parsed}refreshParsed(parsed,filters){let changed=!1;for(let[filterName,filterValue]of Object.entries(filters)){let parameterName=filterName,target=null,matches=collectSupportedOptionalConditionBranches(parsed).filter(branch=>branch.parameterName===parameterName);if(matches.length===0&&(target=this.resolveTarget(parsed,filterName),parameterName=target.parameterName,matches=collectSupportedOptionalConditionBranches(parsed).filter(branch=>branch.parameterName===parameterName)),matches.length===0){if(target||(target=this.resolveTarget(parsed,filterName),parameterName=target.parameterName),!isExplicitEqualityScaffoldValue(filterValue))throw new Error(`No existing SSSQL branch was found for '${filterName}', and v1 scaffold only supports equality filters.`);this.scaffoldScalarBranch(parsed,{target:filterName,parameterName:target.parameterName,operator:"="}),changed=!0;continue}if(matches.length>1)throw new Error(`Multiple SSSQL branches matched parameter ':${parameterName}'. Refresh is ambiguous.`);let[match]=matches;if(!match)continue;let correlatedPlan=this.buildCorrelatedRefreshPlan(parsed,match);if(correlatedPlan){if(correlatedPlan.target.query===match.query)continue;this.rebaseMovedBranchByAlias(match.expression,correlatedPlan.sourceAlias,correlatedPlan.target.column),rebuildWhereWithoutTerm(match.query,match.expression),correlatedPlan.target.query.appendWhere(match.expression),changed=!0;continue}!target&&(target=this.tryResolveTarget(parsed,filterName),!target)||match.query!==target.query&&(this.rebaseMovedBranch(match.expression,match.query,target.column),rebuildWhereWithoutTerm(match.query,match.expression),target.query.appendWhere(match.expression),changed=!0)}return{query:parsed,changed}}remove(query,spec){let parsed=this.parseQuery(query),matches=this.findMatchingBranchInfos(parsed,spec);if(matches.length===0)return parsed;if(matches.length>1)throw new Error(`Multiple SSSQL branches matched parameter ':${spec.parameterName}'. Remove is ambiguous.`);let[match]=matches;return match&&rebuildWhereWithoutTerm(match.query,match.expression),parsed}removeAll(query){let parsed=this.parseQuery(query),matches=this.list(parsed);for(let match of matches)rebuildWhereWithoutTerm(match.query,match.expression);return parsed}parseQuery(query){return typeof query=="string"?SelectQueryParser.parse(query):query}planScalarInsert(sourceSql,spec){let parsed=SelectQueryParser.parse(sourceSql),target=this.resolveTarget(parsed,spec.target);if(target.query!==parsed)return this.planRewrite(sourceSql,query=>this.scaffoldBranch(query,spec));let parameterName=spec.parameterName?.trim()||target.parameterName,operator=normalizeScalarOperator(spec.operator),targetColumnText=findSourceColumnReferenceText(sourceSql,target.column),branchSql=`(:${parameterName} is null or ${targetColumnText} ${operator} :${parameterName})`,normalizedBranch=normalizeSql(branchSql);return this.list(parsed).find(existing=>existing.query===target.query&&normalizeSql(existing.sql)===normalizedBranch||isEquivalentScalarBranch(existing,target.query,parameterName,operator,targetColumnText))?this.buildPlanFromEdits(sourceSql,[],[],[]):this.buildMinimalInsertPlan(sourceSql,branchSql,{branchKind:"scalar",parameterName,column:targetColumnText})}planExistsInsert(sourceSql,spec){let parameterName=spec.parameterName.trim();if(!parameterName)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires parameterName.");if(spec.anchorColumns.length===0)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires at least one anchorColumn.");let parsed=SelectQueryParser.parse(sourceSql),anchorTargets=spec.anchorColumns.map(anchorColumn=>this.resolveTarget(parsed,anchorColumn)),targetQueries=[...new Set(anchorTargets.map(target=>target.query))];if(targetQueries.length!==1)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold anchor columns must resolve within one query scope.");let targetQuery=targetQueries[0];if(targetQuery!==parsed)return this.planRewrite(sourceSql,query=>this.scaffoldBranch(query,spec));let sourceColumns=anchorTargets.map(target=>findSourceColumnReferenceText(sourceSql,target.column)),substitutedSql=substituteAnchorPlaceholders(spec.query,sourceColumns).trim();enforceSubqueryConstraints(substitutedSql);let subquery=SelectQueryParser.parse(substitutedSql),parameterNames=new Set(ParameterCollector.collect(subquery).map(parameter=>parameter.name.value));if(parameterNames.size!==1||!parameterNames.has(parameterName))throw new Error(`SSSQL ${spec.kind.toUpperCase()} scaffold query must reference only parameter ':${parameterName}'.`);let branchSql=`(:${parameterName} is null or ${spec.kind==="not-exists"?"not exists":"exists"} (${substitutedSql}))`;return this.list(parsed).find(existing=>existing.query===targetQuery&&normalizeSql(existing.sql)===normalizeSql(branchSql))?this.buildPlanFromEdits(sourceSql,[],[],[]):this.buildMinimalInsertPlan(sourceSql,branchSql,{branchKind:spec.kind,parameterName,column:sourceColumns.join(", ")})}buildMinimalInsertPlan(sourceSql,branchSql,target){let insertPosition=findMinimalWhereInsertPosition(sourceSql),prefix=`${insertPosition.position===0||!/\s/.test(sourceSql[insertPosition.position-1])?" ":""}${insertPosition.hasWhere?"and":"where"} `,suffix=insertPosition.position<getStatementEndPosition(sourceSql)?" ":"",branchLabel=target.branchKind==="scalar"?"scalar":target.branchKind,edit={start:insertPosition.position,end:insertPosition.position,before:"",after:`${prefix}${branchSql}${suffix}`,kind:"insert",reason:insertPosition.hasWhere?`Append SSSQL ${branchLabel} branch to the existing WHERE clause.`:`Create a WHERE clause for the SSSQL ${branchLabel} branch.`,target},changedRegions=[{kind:"target-branch",start:edit.start+prefix.length,end:edit.start+edit.after.length-suffix.length,message:`Inserted SSSQL ${branchLabel} optional branch.`}];return insertPosition.hasWhere?changedRegions.unshift({kind:"boolean-operator",start:edit.start,end:edit.start+prefix.length,message:`Inserted AND before the SSSQL ${branchLabel} branch.`}):changedRegions.unshift({kind:"where-keyword",start:edit.start,end:edit.start+prefix.length,message:`Inserted WHERE before the SSSQL ${branchLabel} branch.`}),this.buildPlanFromEdits(sourceSql,[edit],changedRegions,[])}planBranchRemoval(sourceSql,spec){let parsed=SelectQueryParser.parse(sourceSql),matches=this.findMatchingBranchInfos(parsed,spec);if(matches.length>1)return this.buildPlanFromEdits(sourceSql,[],[],[],[{code:"REWRITE_FAILED",message:"SSSQL remove planning found multiple matching branches.",detail:`Multiple SSSQL branches matched parameter ':${spec.parameterName}'. Remove is ambiguous.`}]);if(matches.length===0)return this.buildPlanFromEdits(sourceSql,[],[],[]);let branchSpans=findOptionalBranchSpans(sourceSql,spec.parameterName);if(branchSpans.length>1)return this.planRewrite(sourceSql,query=>this.remove(query,spec));let span=branchSpans[0];if(!span)return this.planRewrite(sourceSql,query=>this.remove(query,spec));let beforeOperator=findBooleanOperatorBefore(sourceSql,span.start),afterOperator=findBooleanOperatorAfter(sourceSql,span.end),where=findWhereBefore(sourceSql,span.start),start=span.start,end=span.end,changedRegions=[{kind:"target-branch",start:span.start,end:span.end,message:"Removed SSSQL optional branch."}];if(beforeOperator)start=beforeOperator.start,changedRegions.unshift({kind:"boolean-operator",start:beforeOperator.start,end:beforeOperator.end,message:`Removed adjacent ${beforeOperator.value.toUpperCase()} before the SSSQL branch.`});else if(afterOperator)end=afterOperator.end,changedRegions.push({kind:"boolean-operator",start:afterOperator.start,end:afterOperator.end,message:`Removed adjacent ${afterOperator.value.toUpperCase()} after the SSSQL branch.`});else if(where){for(start=where.start;end<sourceSql.length&&/\s/.test(sourceSql[end]);)end++;changedRegions.unshift({kind:"where-keyword",start:where.start,end:where.end,message:"Removed WHERE because the SSSQL branch was the only condition."})}let edit={start,end,before:sourceSql.slice(start,end),after:"",kind:"delete",reason:"Remove the targeted SSSQL optional branch from the source SQL.",target:{branchKind:matches[0].kind,parameterName:matches[0].parameterName,column:matches[0].target}};return this.buildPlanFromEdits(sourceSql,[edit],changedRegions,[])}buildPlanFromEdits(sourceSql,edits,changedRegions,warnings,errors=[]){let plannedSql=errors.length===0?applyRewriteEdits(sourceSql,edits):void 0,beforeTokens=tokenizeForRewritePlan(sourceSql),beforeComments=collectCommentFragments(sourceSql),afterTokens=plannedSql!==void 0?tokenizeForRewritePlan(plannedSql):[],afterComments=plannedSql!==void 0?collectCommentFragments(plannedSql):[],commentsPreserved=plannedSql!==void 0?commentsPreservedInOrder(beforeComments,afterComments):!1,changedOnlyTargetBranches=errors.length===0&&changedRegions.every(region=>region.kind==="target-branch"||region.kind==="where-keyword"||region.kind==="boolean-operator"||region.kind==="parentheses")&&commentsPreserved,planWarnings=[...warnings];if(plannedSql!==void 0&&applyRewriteEdits(sourceSql,edits)!==plannedSql&&(errors=[...errors,{code:"APPLY_PLAN_MISMATCH",message:"Applying SSSQL rewrite plan edits did not reproduce the planned SQL."}]),plannedSql!==void 0)try{SelectQueryParser.parse(plannedSql)}catch(error){errors=[...errors,{code:"PARSE_AFTER_FAILED",message:"The SQL produced by SSSQL rewrite planning could not be parsed.",detail:error instanceof Error?error.message:error}]}return plannedSql!==void 0&&!commentsPreserved&&planWarnings.push({code:"COMMENTS_NOT_PRESERVED",message:"One or more input SQL comments are missing or reordered after the SSSQL rewrite."}),{ok:errors.length===0,requiresFullReformat:!1,edits,sql:plannedSql,safety:{tokenCountBefore:beforeTokens.length,tokenCountAfter:afterTokens.length,tokenSequencePreserved:plannedSql!==void 0?tokenSequencesEqual(beforeTokens,afterTokens):!1,commentsPreserved,changedOnlyTargetBranches,changedRegions},warnings:planWarnings,errors}}planRewrite(query,rewrite){let warnings=[],errors=[],sourceSql=typeof query=="string"?query:formatSqlComponent(query);typeof query!="string"&&warnings.push({code:"SOURCE_SQL_UNAVAILABLE",message:"SSSQL rewrite planning received an AST, so the source SQL had to be formatter-generated before analysis."});let beforeTokens=[],beforeComments=[];try{beforeTokens=tokenizeForRewritePlan(sourceSql),beforeComments=collectCommentFragments(sourceSql)}catch(error){errors.push({code:"TOKENIZE_BEFORE_FAILED",message:"Could not tokenize the input SQL before SSSQL rewrite planning.",detail:error instanceof Error?error.message:error})}let plannedSql,afterTokens=[],afterComments=[];if(errors.length===0)try{let parsed=SelectQueryParser.parse(sourceSql),rewritten=rewrite(parsed);plannedSql=formatSqlComponent(rewritten)}catch(error){errors.push({code:"REWRITE_FAILED",message:"SSSQL rewrite planning could not produce a rewritten query.",detail:error instanceof Error?error.message:error})}if(plannedSql!==void 0){try{SelectQueryParser.parse(plannedSql)}catch(error){errors.push({code:"PARSE_AFTER_FAILED",message:"The SQL produced by SSSQL rewrite planning could not be parsed.",detail:error instanceof Error?error.message:error})}try{afterTokens=tokenizeForRewritePlan(plannedSql),afterComments=collectCommentFragments(plannedSql)}catch(error){errors.push({code:"TOKENIZE_AFTER_FAILED",message:"Could not tokenize the SQL produced by SSSQL rewrite planning.",detail:error instanceof Error?error.message:error})}}let edits=plannedSql!==void 0&&plannedSql!==sourceSql?[{start:0,end:sourceSql.length,before:sourceSql,after:plannedSql,kind:"replace",reason:"Current SSSQL rewrite planning is backed by AST rewrite plus formatter output."}]:[],changedRegions=edits.length>0?[{kind:"formatter-rewrite",start:0,end:sourceSql.length,message:"The conservative SSSQL rewrite plan requires replacing formatter output for the full SQL text."}]:[],requiresFullReformat=edits.length>0,tokenSequencePreserved=plannedSql!==void 0?tokenSequencesEqual(beforeTokens,afterTokens):!1,commentsPreserved=plannedSql!==void 0?commentsPreservedInOrder(beforeComments,afterComments):!1,changedOnlyTargetBranches=edits.length===0;return requiresFullReformat&&warnings.push({code:"FULL_REFORMAT_REQUIRED",message:"The current SSSQL rewrite plan can only represent the change as a full SQL replacement."}),plannedSql!==void 0&&!tokenSequencePreserved&&warnings.push({code:"TOKEN_SEQUENCE_CHANGED",message:"The SQL token sequence changes after the SSSQL rewrite. The conservative planner cannot prove that only target branches changed.",detail:{tokenCountBefore:beforeTokens.length,tokenCountAfter:afterTokens.length}}),plannedSql!==void 0&&!commentsPreserved&&warnings.push({code:"COMMENTS_NOT_PRESERVED",message:"One or more input SQL comments are missing or reordered after the SSSQL rewrite."}),plannedSql!==void 0&&countCommandToken(afterTokens,"as")>countCommandToken(beforeTokens,"as")&&warnings.push({code:"OPTIONAL_ALIAS_AS_ADDED",message:"The rewrite output contains more AS tokens than the input, which may indicate formatter-added aliases."}),plannedSql!==void 0&&!sourceSql.includes('"')&&plannedSql.includes('"')&&warnings.push({code:"IDENTIFIER_QUOTES_ADDED",message:"The rewrite output contains double-quoted identifiers that were not present in the input SQL."}),{ok:errors.length===0,requiresFullReformat,edits,sql:plannedSql,safety:{tokenCountBefore:beforeTokens.length,tokenCountAfter:afterTokens.length,tokenSequencePreserved,commentsPreserved,changedOnlyTargetBranches,changedRegions},warnings,errors}}findMatchingBranchInfos(root,spec){let normalizedOperator=spec.operator?normalizeScalarOperator(spec.operator):void 0,normalizedTarget=spec.target?normalizeIdentifier2(spec.target):void 0;return this.list(root).filter(branch=>!(branch.parameterName!==spec.parameterName||spec.kind&&branch.kind!==spec.kind||normalizedOperator&&branch.operator!==normalizedOperator||normalizedTarget&&(!branch.target||normalizeIdentifier2(branch.target)!==normalizedTarget)))}scaffoldScalarBranch(root,spec){let target=this.resolveTarget(root,spec.target),parameterName=spec.parameterName?.trim()||target.parameterName,operator=normalizeScalarOperator(spec.operator),branch=buildOptionalScalarBranch(target.column,parameterName,operator),branchSql=normalizeSql(formatSqlComponent(branch));this.list(root).find(existing=>existing.query===target.query&&normalizeSql(existing.sql)===branchSql)||target.query.appendWhere(branch)}scaffoldExistsBranch(root,spec){let parameterName=spec.parameterName.trim();if(!parameterName)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires parameterName.");if(spec.anchorColumns.length===0)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires at least one anchorColumn.");let anchorTargets=spec.anchorColumns.map(anchorColumn=>this.resolveTarget(root,anchorColumn)),targetQueries=[...new Set(anchorTargets.map(target=>target.query))];if(targetQueries.length!==1)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold anchor columns must resolve within one query scope.");let targetQuery=targetQueries[0],formattedColumns=anchorTargets.map(target=>formatSqlComponent(target.column)),substitutedSql=substituteAnchorPlaceholders(spec.query,formattedColumns).trim();enforceSubqueryConstraints(substitutedSql);let subquery=SelectQueryParser.parse(substitutedSql),parameterNames=new Set(ParameterCollector.collect(subquery).map(parameter=>parameter.name.value));if(parameterNames.size!==1||!parameterNames.has(parameterName))throw new Error(`SSSQL ${spec.kind.toUpperCase()} scaffold query must reference only parameter ':${parameterName}'.`);let branch=buildOptionalExistsBranch(parameterName,subquery,spec.kind),branchSql=normalizeSql(formatSqlComponent(branch));this.list(root).find(existing=>existing.query===targetQuery&&normalizeSql(existing.sql)===branchSql)||targetQuery.appendWhere(branch)}resolveTarget(root,filterName){let qualified=parseQualifiedFilterName(filterName),lookupColumn=qualified?.column??filterName.trim(),matches=[...new Set(this.finder.find(root,lookupColumn))].map(query=>this.resolveTargetInQuery(query,filterName,qualified)).filter(target=>target!==null);if(matches.length===0)throw new Error(`Could not resolve SSSQL filter target '${filterName}' in the current query graph.`);if(matches.length>1)throw new Error(`SSSQL filter target '${filterName}' is ambiguous across multiple query scopes.`);return matches[0]}resolveTargetInQuery(query,filterName,qualified){return qualified?this.resolveQualifiedTarget(query,qualified):this.resolveUnqualifiedTarget(query,filterName)}resolveQualifiedTarget(query,filterName){let alias=this.findAliasForTable(query,filterName.table);if(!alias)return null;let matches=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query).filter(entry=>entry.value instanceof ColumnReference).filter(entry=>normalizeColumnReferenceKey(entry.value)===`${normalizeIdentifier2(alias)}.${normalizeIdentifier2(filterName.column)}`);if(matches.length===0)return null;if(matches.length>1)throw new Error(`SSSQL scaffold target '${filterName.table}.${filterName.column}' resolved to multiple columns.`);return{query,column:matches[0].value,parameterName:makeParameterName(`${filterName.table}.${filterName.column}`)}}resolveUnqualifiedTarget(query,filterName){let matches=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query).filter(entry=>entry.value instanceof ColumnReference).filter(entry=>normalizeIdentifier2(entry.name)===normalizeIdentifier2(filterName));if(matches.length===0)return null;if(matches.length>1)throw new Error(`SSSQL scaffold target '${filterName}' is ambiguous. Use a qualified table.column reference.`);return{query,column:matches[0].value,parameterName:makeParameterName(filterName)}}tryResolveTarget(root,filterName){try{return this.resolveTarget(root,filterName)}catch{return null}}findAliasForTable(query,tableName){let normalizedTable=normalizeIdentifier2(tableName),matchingAliases=(query.fromClause?.getSources()??[]).map(source=>this.resolveAliasForSource(source,normalizedTable)).filter(alias=>alias!==null);if(matchingAliases.length===0)return null;if(matchingAliases.length>1)throw new Error(`SSSQL scaffold target table '${tableName}' is ambiguous in the selected query scope.`);return matchingAliases[0]}resolveAliasForSource(source,normalizedTable){if(!(source.datasource instanceof TableSource))return null;let sourceName=normalizeIdentifier2(source.datasource.getSourceName()),shortName=normalizeIdentifier2(source.datasource.table.name);return sourceName!==normalizedTable&&shortName!==normalizedTable?null:source.getAliasName()??source.datasource.table.name}buildCorrelatedRefreshPlan(root,branch){let details=getExistsPredicateDetails(branch.expression,branch.parameterName);if(!details)return null;let sourceAliases=this.collectSourceAliases(branch.query),candidatesByKey=new Map;for(let reference of new ColumnReferenceCollector().collect(details.subquery)){let namespace=normalizeIdentifier2(reference.getNamespace());if(!namespace||!sourceAliases.has(namespace))continue;let column=normalizeIdentifier2(reference.column.name),key=`${namespace}.${column}`;candidatesByKey.has(key)||candidatesByKey.set(key,{namespace,column})}let candidates=[...candidatesByKey.values()];if(candidates.length===0)throw new Error(`SSSQL refresh could not infer a correlated anchor for ':${branch.parameterName}'.`);if(candidates.length>1){let listed=candidates.map(candidate=>`${candidate.namespace}.${candidate.column}`).join(", ");throw new Error(`SSSQL refresh found multiple correlated anchor candidates for ':${branch.parameterName}' (${listed}).`)}let[anchor]=candidates;if(!anchor)throw new Error(`SSSQL refresh could not infer a correlated anchor for ':${branch.parameterName}'.`);return{target:this.resolveCorrelatedAnchorTarget(root,branch.query,anchor,branch.parameterName),sourceAlias:anchor.namespace}}collectSourceAliases(query){let aliases=new Set;for(let source of query.fromClause?.getSources()??[]){let sourceAlias=this.getSourceAlias(source);sourceAlias&&aliases.add(sourceAlias)}return aliases}resolveCorrelatedAnchorTarget(root,sourceQuery,anchor,parameterName){let sourceExpression=this.findSourceExpressionByAlias(sourceQuery,anchor.namespace,parameterName),upstreamQuery=this.resolveSourceExpressionToUpstreamQuery(root,sourceExpression,parameterName);return upstreamQuery?this.resolveAnchorTargetInQuery(upstreamQuery,anchor,parameterName):{query:sourceQuery,column:new ColumnReference(anchor.namespace,anchor.column),parameterName}}findSourceExpressionByAlias(query,alias,parameterName){let matches=(query.fromClause?.getSources()??[]).filter(source=>this.getSourceAlias(source)===alias);if(matches.length===0)throw new Error(`SSSQL refresh could not resolve correlated alias '${alias}' for ':${parameterName}'.`);if(matches.length>1)throw new Error(`SSSQL refresh found multiple correlated sources for alias '${alias}' and ':${parameterName}'.`);return matches[0]}resolveSourceExpressionToUpstreamQuery(root,source,parameterName){if(source.datasource instanceof SubQuerySource){if(source.datasource.query instanceof SimpleSelectQuery)return source.datasource.query;throw new Error(`SSSQL refresh requires a simple query anchor for ':${parameterName}'.`)}if(!(source.datasource instanceof TableSource))return null;let cteName=normalizeIdentifier2(source.datasource.table.name),cteMatches=new CTECollector().collect(root).filter(cte2=>normalizeIdentifier2(cte2.getSourceAliasName())===cteName);if(cteMatches.length===0)return null;if(cteMatches.length>1)throw new Error(`SSSQL refresh found multiple CTE anchors for ':${parameterName}' (${source.datasource.table.name}).`);let[cte]=cteMatches;if(!cte)return null;let cteQuery=cte.query;if(!(cteQuery instanceof SimpleSelectQuery))throw new Error(`SSSQL refresh requires a simple CTE anchor for ':${parameterName}'.`);return cteQuery}resolveAnchorTargetInQuery(query,anchor,parameterName){let matches=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query).filter(entry=>entry.value instanceof ColumnReference).filter(entry=>normalizeIdentifier2(entry.name)===anchor.column);if(matches.length===0)throw new Error(`SSSQL refresh could not resolve correlated anchor column '${anchor.column}' for ':${parameterName}'.`);if(matches.length>1)throw new Error(`SSSQL refresh found multiple correlated anchor columns '${anchor.column}' for ':${parameterName}'.`);return{query,column:matches[0].value,parameterName}}getSourceAlias(source){let explicitAlias=source.getAliasName();return explicitAlias?normalizeIdentifier2(explicitAlias):source.datasource instanceof TableSource?normalizeIdentifier2(source.datasource.table.name):null}rebaseMovedBranch(expression,sourceQuery,targetColumn){let targetNamespace=targetColumn.qualifiedName.namespaces?targetColumn.qualifiedName.namespaces.map(namespace=>namespace.name):null,targetColumnName=normalizeIdentifier2(targetColumn.column.name),sourceAliases=new Set(collectColumnReferencesDeep(expression).filter(reference=>normalizeIdentifier2(reference.column.name)===targetColumnName).map(reference=>normalizeIdentifier2(reference.getNamespace())).filter(namespace=>namespace.length>0));if(sourceAliases.size===0)return;if(sourceAliases.size>1){let aliases=[...sourceAliases].join(", ");throw new Error(`SSSQL refresh cannot safely rebase '${targetColumn.column.name}' across multiple aliases (${aliases}).`)}let[sourceAlias]=[...sourceAliases];if(new Set((sourceQuery.fromClause?.getSources()??[]).map(source=>source.getAliasName()).filter(alias=>typeof alias=="string").map(alias=>normalizeIdentifier2(alias))).has(sourceAlias))for(let reference of collectColumnReferencesDeep(expression))normalizeIdentifier2(reference.getNamespace())===sourceAlias&&(reference.qualifiedName.namespaces=targetNamespace?.map(namespace=>new IdentifierString(namespace))??null)}rebaseMovedBranchByAlias(expression,sourceAlias,targetColumn){let normalizedSourceAlias=normalizeIdentifier2(sourceAlias);if(!normalizedSourceAlias)return;let targetNamespace=targetColumn.qualifiedName.namespaces?targetColumn.qualifiedName.namespaces.map(namespace=>namespace.name):null;for(let reference of collectColumnReferencesDeep(expression))normalizeIdentifier2(reference.getNamespace())===normalizedSourceAlias&&(reference.qualifiedName.namespaces=targetNamespace?.map(namespace=>new IdentifierString(namespace))??null)}},scaffoldSssqlQuery=(sqlContent,filters)=>({query:new SSSQLFilterBuilder().scaffold(sqlContent,filters)}),refreshSssqlQuery=(sqlContent,filters)=>({query:new SSSQLFilterBuilder().refresh(sqlContent,filters)});var BaseDataFlowNode=class{constructor(id,label,type,shape,details){this.id=id;this.label=label;this.type=type;this.shape=shape;this.details=details}},DataSourceNode=class _DataSourceNode extends BaseDataFlowNode{constructor(id,label,type){super(id,label,type,type==="subquery"?"hexagon":"cylinder");this.annotations=new Set}addAnnotation(annotation){this.annotations.add(annotation)}hasAnnotation(annotation){return this.annotations.has(annotation)}getMermaidRepresentation(){return this.shape==="hexagon"?`${this.id}{{${this.label}}}`:`${this.id}[(${this.label})]`}static createTable(tableName){return new _DataSourceNode(`table_${tableName}`,tableName,"table")}static createCTE(cteName){return new _DataSourceNode(`cte_${cteName}`,`CTE:${cteName}`,"cte")}static createSubquery(alias){return new _DataSourceNode(`subquery_${alias}`,`SubQuery:${alias}`,"subquery")}},ProcessNode=class _ProcessNode extends BaseDataFlowNode{constructor(id,operation,context=""){let nodeId=context?`${context}_${operation.toLowerCase().replace(/\s+/g,"_")}`:operation.toLowerCase().replace(/\s+/g,"_");super(nodeId,operation,"process","hexagon")}getMermaidRepresentation(){return`${this.id}{{${this.label}}}`}static createWhere(context){return new _ProcessNode(`${context}_where`,"WHERE",context)}static createGroupBy(context){return new _ProcessNode(`${context}_group_by`,"GROUP BY",context)}static createHaving(context){return new _ProcessNode(`${context}_having`,"HAVING",context)}static createSelect(context){return new _ProcessNode(`${context}_select`,"SELECT",context)}static createOrderBy(context){return new _ProcessNode(`${context}_order_by`,"ORDER BY",context)}static createLimit(context,hasOffset=!1){let label=hasOffset?"LIMIT/OFFSET":"LIMIT";return new _ProcessNode(`${context}_limit`,label,context)}},OperationNode=class _OperationNode extends BaseDataFlowNode{constructor(id,operation,shape="diamond"){super(id,operation,"operation",shape)}getMermaidRepresentation(){switch(this.shape){case"rounded":return`${this.id}(${this.label})`;case"rectangle":return`${this.id}[${this.label}]`;case"hexagon":return`${this.id}{{${this.label}}}`;case"stadium":return`${this.id}([${this.label}])`;case"diamond":default:return`${this.id}{${this.label}}`}}static createJoin(joinId,joinType){let label,normalizedType=joinType.trim().toLowerCase();return normalizedType==="join"?label="INNER JOIN":normalizedType.endsWith(" join")?label=normalizedType.toUpperCase():label=normalizedType.toUpperCase()+" JOIN",new _OperationNode(`join_${joinId}`,label,"rectangle")}static createUnion(unionId,unionType="UNION ALL"){return new _OperationNode(`${unionType.toLowerCase().replace(/\s+/g,"_")}_${unionId}`,unionType.toUpperCase(),"rectangle")}static createSetOperation(operationId,operation){let normalizedOp=operation.toUpperCase(),id=`${normalizedOp.toLowerCase().replace(/\s+/g,"_")}_${operationId}`;return new _OperationNode(id,normalizedOp,"rectangle")}},OutputNode=class extends BaseDataFlowNode{constructor(context="main"){let label=context==="main"?"Final Result":`${context} Result`;super(`${context}_output`,label,"output","stadium")}getMermaidRepresentation(){return`${this.id}([${this.label}])`}};var DataFlowConnection=class _DataFlowConnection{constructor(from,to,label){this.from=from;this.to=to;this.label=label}getMermaidRepresentation(){let arrow=this.label?` -->|${this.label}| `:" --> ";return`${this.from}${arrow}${this.to}`}static create(from,to,label){return new _DataFlowConnection(from,to,label)}static createWithNullability(from,to,isNullable){let label=isNullable?"NULLABLE":"NOT NULL";return new _DataFlowConnection(from,to,label)}},DataFlowEdgeCollection=class{constructor(){this.edges=[];this.connectionSet=new Set}add(edge){let key=`${edge.from}->${edge.to}`;this.connectionSet.has(key)||(this.edges.push(edge),this.connectionSet.add(key))}addConnection(from,to,label){this.add(DataFlowConnection.create(from,to,label))}addJoinConnection(from,to,isNullable){this.add(DataFlowConnection.createWithNullability(from,to,isNullable))}hasConnection(from,to){return this.connectionSet.has(`${from}->${to}`)}getAll(){return[...this.edges]}getMermaidRepresentation(){return this.edges.map(edge=>edge.getMermaidRepresentation()).join(`
49
+ `);for(let i=1;i<lines.length;i++){let line=lines[i],leadingSpaces=line.match(/^ */)?.[0].length||0,leadingTabs=line.match(/^\t*/)?.[0].length||0;(leadingSpaces>0||leadingTabs>0)&&(indentLines++,totalIndentSize+=leadingSpaces+leadingTabs*4,spaceCount+=leadingSpaces,tabCount+=leadingTabs)}}lexeme.inlineComments&&(totalComments+=lexeme.inlineComments.length)}let indentationStyle="none";return spaceCount>0&&tabCount>0?indentationStyle="mixed":spaceCount>0?indentationStyle="spaces":tabCount>0&&(indentationStyle="tabs"),{totalWhitespace,totalComments,indentationStyle,averageIndentSize:indentLines>0?totalIndentSize/indentLines:0}}validateFormattingLexemes(lexemes){let issues=[];for(let i=0;i<lexemes.length;i++){let lexeme=lexemes[i];lexeme.position||issues.push(`Lexeme ${i} missing position information`),lexeme.followingWhitespace===void 0&&issues.push(`Lexeme ${i} missing followingWhitespace property`),lexeme.inlineComments===void 0&&issues.push(`Lexeme ${i} missing inlineComments property`),lexeme.position&&lexeme.position.startPosition>=lexeme.position.endPosition&&issues.push(`Lexeme ${i} has invalid position range`)}return{isValid:issues.length===0,issues}}};var ClauseScopedColumnReferenceCollector=class{collect(query){if(!(query instanceof SimpleSelectQuery))throw new Error("ClauseScopedColumnReferenceCollector requires a SimpleSelectQuery.");let result=this.createEmptyResult();return this.collectFromSelectClause(query.selectClause,result),this.collectFromJoinClauses(query,result),query.whereClause&&this.collectFromWhereClause(query.whereClause,result),query.groupByClause&&this.collectFromGroupByClause(query.groupByClause,result),query.havingClause&&this.collectFromHavingClause(query.havingClause,result),query.orderByClause&&this.collectFromOrderByClause(query.orderByClause,"orderBy",result),query.windowClause&&this.collectFromWindowsClause(query.windowClause,result),query.limitClause&&this.collectFromLimitClause(query.limitClause,result),query.offsetClause&&this.collectFromOffsetClause(query.offsetClause,result),query.fetchClause&&this.collectFromFetchClause(query.fetchClause,result),result}createEmptyResult(){return{select:[],where:[],joinOn:[],groupBy:[],having:[],orderBy:[],window:[],limitOffset:[]}}collectFromSelectClause(clause,result){clause.distinct instanceof DistinctOn&&this.collectFromValueComponent(clause.distinct.value,"select",result);for(let item of clause.items)this.collectFromValueComponent(item.value,"select",result)}collectFromJoinClauses(query,result){if(query.fromClause?.joins)for(let join of query.fromClause.joins)(join.condition instanceof JoinOnClause||join.condition instanceof JoinUsingClause)&&this.collectFromValueComponent(join.condition.condition,"joinOn",result)}collectFromWhereClause(clause,result){this.collectFromValueComponent(clause.condition,"where",result)}collectFromGroupByClause(clause,result){for(let item of clause.grouping)this.collectFromValueComponent(item,"groupBy",result)}collectFromHavingClause(clause,result){this.collectFromValueComponent(clause.condition,"having",result)}collectFromOrderByClause(clause,target,result){for(let item of clause.order)item instanceof OrderByItem?this.collectFromValueComponent(item.value,target,result):this.collectFromValueComponent(item,target,result)}collectFromLimitClause(clause,result){this.collectFromValueComponent(clause.value,"limitOffset",result)}collectFromOffsetClause(clause,result){this.collectFromValueComponent(clause.value,"limitOffset",result)}collectFromFetchClause(clause,result){this.collectFromValueComponent(clause.expression.count,"limitOffset",result)}collectFromWindowsClause(clause,result){for(let window of clause.windows)this.collectFromWindowFrameExpression(window.expression,"window",result)}collectFromValueComponent(value,target,result,expression=value){if(value instanceof ColumnReference){result[target].push(this.createInfo(value,target,expression));return}if(value instanceof BinaryExpression)this.collectFromValueComponent(value.left,target,result,value),this.collectFromValueComponent(value.right,target,result,value);else if(value instanceof UnaryExpression)this.collectFromValueComponent(value.expression,target,result,value);else if(value instanceof FunctionCall)this.collectFromFunctionCall(value,target,result);else if(value instanceof CaseExpression){value.condition&&this.collectFromValueComponent(value.condition,target,result,value);for(let pair of value.switchCase.cases)this.collectFromValueComponent(pair.key,target,result,value),this.collectFromValueComponent(pair.value,target,result,value);value.switchCase.elseValue&&this.collectFromValueComponent(value.switchCase.elseValue,target,result,value)}else if(value instanceof ParenExpression)this.collectFromValueComponent(value.expression,target,result,value);else if(value instanceof CastExpression)this.collectFromValueComponent(value.input,target,result,value);else if(value instanceof BetweenExpression)this.collectFromValueComponent(value.expression,target,result,value),this.collectFromValueComponent(value.lower,target,result,value),this.collectFromValueComponent(value.upper,target,result,value);else if(value instanceof JsonPredicateExpression)this.collectFromValueComponent(value.expression,target,result,value);else if(value instanceof ArrayExpression)this.collectFromValueComponent(value.expression,target,result,value);else if(value instanceof ArraySliceExpression)this.collectFromValueComponent(value.array,target,result,value),value.startIndex&&this.collectFromValueComponent(value.startIndex,target,result,value),value.endIndex&&this.collectFromValueComponent(value.endIndex,target,result,value);else if(value instanceof ArrayIndexExpression)this.collectFromValueComponent(value.array,target,result,value),this.collectFromValueComponent(value.index,target,result,value);else if(value instanceof ValueList)for(let item of value.values)this.collectFromValueComponent(item,target,result,value);else if(value instanceof TupleExpression)for(let item of value.values)this.collectFromValueComponent(item,target,result,value);else if(value instanceof TypeValue&&value.argument)this.collectFromValueComponent(value.argument,target,result,value);else if(value instanceof InlineQuery||value instanceof ArrayQueryExpression)return}collectFromFunctionCall(value,target,result){value.argument&&this.collectFromValueComponent(value.argument,target,result,value),value.filterCondition&&this.collectFromValueComponent(value.filterCondition,target,result,value),value.withinGroup&&this.collectFromOrderByClause(value.withinGroup,target,result),value.internalOrderBy&&this.collectFromOrderByClause(value.internalOrderBy,target,result),value.over instanceof WindowFrameExpression&&this.collectFromWindowFrameExpression(value.over,target,result)}collectFromWindowFrameExpression(value,target,result){value.partition&&this.collectFromValueComponent(value.partition.value,target,result),value.order&&this.collectFromOrderByClause(value.order,target,result),value.frameSpec&&(value.frameSpec.startBound instanceof WindowFrameBoundaryValue&&this.collectFromValueComponent(value.frameSpec.startBound.value,target,result),value.frameSpec.endBound instanceof WindowFrameBoundaryValue&&this.collectFromValueComponent(value.frameSpec.endBound.value,target,result))}createInfo(reference,clause,expression){let namespaces=reference.namespaces?.map(namespace=>namespace.name)??[],columnName=this.getNameText(reference.qualifiedName.name);return{clause,reference,qualifiedName:reference.qualifiedName.toString(),namespaces,namespace:namespaces.length>0?namespaces.join("."):null,column:columnName,expression}}getNameText(name){return name instanceof IdentifierString?name.name:name.value}};var SelectResultSelectConverter=class{static toSelectQuery(query,options){let fixtureTables=options?.fixtureTables??[];if(fixtureTables.length===0)return query;let sources=new TableSourceCollector(!1).collect(query),referencedTables=new Set;sources.forEach(s=>referencedTables.add(s.getSourceName().toLowerCase()));let neededFixtures=fixtureTables.filter(f=>referencedTables.has(f.tableName.toLowerCase()));if(neededFixtures.length===0)return query;let fixtureCtes=FixtureCteBuilder.buildFixtures(neededFixtures);return query instanceof SimpleSelectQuery&&(query.withClause?query.withClause.tables=[...fixtureCtes,...query.withClause.tables]:query.appendWith(fixtureCtes)),query}};var SimulatedSelectConverter=class{static convert(ast,options){if(ast instanceof InsertQuery)return InsertResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof UpdateQuery)return UpdateResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof DeleteQuery)return DeleteResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof MergeQuery)return MergeResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof SimpleSelectQuery||ast instanceof BinarySelectQuery||ast instanceof ValuesQuery)return SelectResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof CreateTableQuery){if(ast.isTemporary&&ast.asSelectQuery){let processedSelect=SelectResultSelectConverter.toSelectQuery(ast.asSelectQuery,options);return ast.asSelectQuery=processedSelect,ast}return null}return null}};var DDLGeneralizer=class{static generalize(ast){let result=[];for(let component of ast)if(component instanceof CreateTableQuery){let{createTable,alterTables}=this.splitCreateTable(component);result.push(createTable),result.push(...alterTables)}else result.push(component);return result}static splitCreateTable(query){let newColumns=[],alterTables=[],tableQualifiedName=new QualifiedName(query.namespaces||[],query.tableName.name);for(let col of query.columns){let newConstraints=[];for(let constraint of col.constraints)if(["primary-key","unique","references","check"].includes(constraint.kind)){let tableConstraint=this.columnToTableConstraint(col.name,constraint);alterTables.push(new AlterTableStatement({table:tableQualifiedName,actions:[new AlterTableAddConstraint({constraint:tableConstraint})]}))}else newConstraints.push(constraint);newColumns.push(new TableColumnDefinition({name:col.name,dataType:col.dataType,constraints:newConstraints}))}if(query.tableConstraints)for(let constraint of query.tableConstraints)alterTables.push(new AlterTableStatement({table:tableQualifiedName,actions:[new AlterTableAddConstraint({constraint})]}));return{createTable:new CreateTableQuery({tableName:query.tableName.name,namespaces:query.namespaces,columns:newColumns,ifNotExists:query.ifNotExists,isTemporary:query.isTemporary,tableOptions:query.tableOptions,asSelectQuery:query.asSelectQuery,withDataOption:query.withDataOption,tableConstraints:[]}),alterTables}}static columnToTableConstraint(columnName,constraint){let baseParams={constraintName:constraint.constraintName,deferrable:constraint.reference?.deferrable,initially:constraint.reference?.initially};switch(constraint.kind){case"primary-key":return new TableConstraintDefinition({kind:"primary-key",columns:[columnName],...baseParams});case"unique":return new TableConstraintDefinition({kind:"unique",columns:[columnName],...baseParams});case"references":return new TableConstraintDefinition({kind:"foreign-key",columns:[columnName],reference:constraint.reference,...baseParams});case"check":return new TableConstraintDefinition({kind:"check",checkExpression:constraint.checkExpression,...baseParams});default:throw new Error(`Unsupported constraint kind for generalization: ${constraint.kind}`)}}};var DDLDiffGenerator=class{static generateDiff(currentSql,expectedSql,options={}){let currentAst=this.parseAndGeneralize(currentSql),expectedAst=this.parseAndGeneralize(expectedSql),currentSchema=this.buildSchema(currentAst),expectedSchema=this.buildSchema(expectedAst),diffAsts=[];for(let[tableName,expectedTable]of expectedSchema.tables){let currentTable=currentSchema.tables.get(tableName);if(currentTable)this.compareColumns(currentTable,expectedTable,diffAsts,options),this.compareConstraints(currentTable,expectedTable,diffAsts,options),this.compareIndexes(currentTable,expectedTable,diffAsts,options);else{let columns=Array.from(expectedTable.columns.values()).map(c=>c.definition),tableNameStr=expectedTable.qualifiedName.name instanceof RawString?expectedTable.qualifiedName.name.value:expectedTable.qualifiedName.name.name,namespaces=expectedTable.qualifiedName.namespaces?expectedTable.qualifiedName.namespaces.map(ns=>ns.name):null,createTable=new CreateTableQuery({tableName:tableNameStr,namespaces,columns});diffAsts.push(createTable);for(let constraint of expectedTable.constraints)diffAsts.push(new AlterTableStatement({table:expectedTable.qualifiedName,actions:[new AlterTableAddConstraint({constraint:constraint.definition})]}));for(let index of expectedTable.indexes)diffAsts.push(index.definition)}}if(options.dropTables)for(let[tableName,currentTable]of currentSchema.tables)expectedSchema.tables.has(tableName)||diffAsts.push(new DropTableStatement({tables:[currentTable.qualifiedName],ifExists:!1}));let formatter2=new SqlFormatter(options.formatOptions||{keywordCase:"upper"});return diffAsts.map(ast=>formatter2.format(ast).formattedSql+";")}static parseAndGeneralize(sql){let split=MultiQuerySplitter.split(sql),asts=[];for(let q of split.queries)if(!q.isEmpty)try{let ast=SqlParser.parse(q.sql);asts.push(ast)}catch(e){console.warn("Failed to parse SQL for diff:",q.sql,e)}return DDLGeneralizer.generalize(asts)}static buildSchema(asts){let tables=new Map,formatter2=new SqlFormatter({keywordCase:"none"});for(let ast of asts)if(ast instanceof CreateTableQuery){let qName=new QualifiedName(ast.namespaces||[],ast.tableName),key=this.getQualifiedNameKey(qName),tableModel={name:key,qualifiedName:qName,columns:new Map,constraints:[],indexes:[]};for(let col of ast.columns)tableModel.columns.set(col.name.name,{name:col.name.name,definition:col});tables.set(key,tableModel)}else if(ast instanceof AlterTableStatement){let key=this.getQualifiedNameKey(ast.table),tableModel=tables.get(key);if(tableModel)for(let action of ast.actions)if(action instanceof AlterTableAddConstraint){let formatted=formatter2.format(action.constraint).formattedSql;tableModel.constraints.push({name:action.constraint.constraintName?.name,kind:action.constraint.kind,definition:action.constraint,formatted})}else action instanceof AlterTableAddColumn&&tableModel.columns.set(action.column.name.name,{name:action.column.name.name,definition:action.column})}else if(ast instanceof CreateIndexStatement){let key=this.getQualifiedNameKey(ast.tableName),tableModel=tables.get(key);if(tableModel){let formatted=formatter2.format(ast).formattedSql;tableModel.indexes.push({name:ast.indexName.toString(),definition:ast,formatted})}}return{tables}}static compareColumns(current,expected,diffs,options){for(let[name,col]of expected.columns)current.columns.has(name)||diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableAddColumn({column:col.definition})]}));if(options.dropColumns)for(let[name,col]of current.columns)expected.columns.has(name)||diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableDropColumn({columnName:col.definition.name})]}))}static compareConstraints(current,expected,diffs,options){let formatter2=new SqlFormatter({keywordCase:"none"}),getConstraintSignature=c=>options.checkConstraintNames?c.kind==="primary-key"?c.formatted.replace(/^constraint\s+("[^"]+"|[^\s]+)\s+/i,"").trim():c.name||c.formatted:c.formatted.replace(/^constraint\s+("[^"]+"|[^\s]+)\s+/i,"").trim(),currentSignatures=new Set(current.constraints.map(getConstraintSignature));for(let expectedC of expected.constraints){let sig=getConstraintSignature(expectedC);currentSignatures.has(sig)||diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableAddConstraint({constraint:expectedC.definition})]}))}if(options.dropConstraints){let expectedSignatures=new Set(expected.constraints.map(getConstraintSignature));for(let currentC of current.constraints){let sig=getConstraintSignature(currentC);expectedSignatures.has(sig)||(currentC.name?diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableDropConstraint({constraintName:new IdentifierString(currentC.name)})]})):console.warn("Cannot drop unnamed constraint:",currentC.formatted))}}}static compareIndexes(current,expected,diffs,options){let getIndexSignature=idx=>{if(options.checkConstraintNames)return idx.name;let def=idx.definition,parts=[];parts.push(def.tableName.toString()),def.unique&&parts.push("UNIQUE"),def.usingMethod&&parts.push(`USING:${def.usingMethod.toString()}`);let columnSigs=def.columns.map(col=>{let expr=col.expression.toString(),sort=col.sortOrder||"",nulls=col.nullsOrder||"";return`${expr}${sort}${nulls}`});return parts.push(`COLS:${columnSigs.join(",")}`),def.include&&def.include.length>0&&parts.push(`INCLUDE:${def.include.map(i=>i.toString()).join(",")}`),def.where&&parts.push(`WHERE:${def.where.toString()}`),parts.join("|")},currentSignatures=new Set(current.indexes.map(getIndexSignature));for(let expectedIdx of expected.indexes){let sig=getIndexSignature(expectedIdx);currentSignatures.has(sig)||diffs.push(expectedIdx.definition)}if(options.checkConstraintNames||options.dropIndexes){let expectedSignatures=new Set(expected.indexes.map(getIndexSignature));for(let currentIdx of current.indexes){let sig=getIndexSignature(currentIdx);expectedSignatures.has(sig)||diffs.push(new DropIndexStatement({indexNames:[currentIdx.definition.indexName],ifExists:!1}))}}}static getQualifiedNameKey(qName){return qName.toString()}};var SelectBodyExtractor=class{static extract(input){return typeof input=="string"?this.extractFromSql(input):this.extractFromStatement(input)}static extractFromSql(sql){let lexemes=new SqlTokenizer(sql).readLexemes();return this.isCreateViewStatement(lexemes)?this.extractCreateViewFromLexemes(lexemes):this.extractFromStatement(SqlParser.parse(sql))}static extractFromStatement(statement){if(statement instanceof CreateTableQuery){let targetName=this.createTableTargetName(statement);return statement.asSelectQuery?{supported:!0,kind:"create-table-as",targetName,selectQuery:statement.asSelectQuery}:this.unsupported(targetName)}if(statement instanceof InsertQuery){let targetName=this.insertTargetName(statement);return!statement.selectQuery||statement.selectQuery instanceof ValuesQuery?this.unsupported(targetName):{supported:!0,kind:"insert-select",targetName,selectQuery:statement.selectQuery}}return{supported:!1,kind:null,targetName:null,selectQuery:null,reason:"Statement type is not supported."}}static extractCreateViewFromLexemes(lexemes){let idx=0;idx++;let materialized=lexemes[idx]?.value.toLowerCase()==="materialized";if(materialized&&idx++,lexemes[idx]?.value.toLowerCase()!=="view")return this.unsupported(null,"Statement type is not supported.");idx++,lexemes[idx]?.value.toLowerCase()==="if not exists"&&idx++;let targetResult=FullNameParser.parseFromLexeme(lexemes,idx);idx=targetResult.newIndex;let targetName=[...targetResult.namespaces??[],targetResult.name.name].join(".");if(lexemes[idx]?.type===4&&(idx=this.consumeBalancedParentheses(lexemes,idx)),lexemes[idx]?.value.toLowerCase()!=="as")return this.unsupported(targetName);idx++;let selectResult=SelectQueryParser.parseFromLexeme(lexemes,idx);return{supported:!0,kind:materialized?"create-materialized-view":"create-view",targetName,selectQuery:selectResult.value}}static isCreateViewStatement(lexemes){if(lexemes[0]?.value.toLowerCase()!=="create")return!1;let second=lexemes[1]?.value.toLowerCase(),third=lexemes[2]?.value.toLowerCase();return second==="view"||second==="materialized"&&third==="view"}static consumeBalancedParentheses(lexemes,index){let idx=index,depth=0;for(;idx<lexemes.length;){if(lexemes[idx].type===4)depth++;else if(lexemes[idx].type===8&&(depth--,depth===0))return idx+1;idx++}return idx}static createTableTargetName(query){return[...query.namespaces??[],query.tableName.name].join(".")}static insertTargetName(query){let source=query.insertClause.source;return source.datasource instanceof TableSource?source.datasource.getSourceName():source.getAliasName()}static unsupported(targetName,reason="No embedded SELECT body found."){return{supported:!1,kind:null,targetName,selectQuery:null,reason}}};var SelectOutputCollector=class _SelectOutputCollector{constructor(tableColumnResolver=null,initialCommonTables=null){this.tableColumnResolver=tableColumnResolver;this.commonTableCollector=new CTECollector;this.commonTables=initialCommonTables??[]}collect(arg){return this.collectRaw(arg).map((item,outputIndex)=>({...item,outputIndex}))}collectRaw(arg){return arg instanceof SimpleSelectQuery?this.collectSimpleSelectQuery(arg):arg instanceof SourceExpression?this.collectSourceExpression(arg.getAliasName(),arg):arg instanceof FromClause?this.collectFromClause(arg,!0):[]}collectSimpleSelectQuery(query){let previousCommonTables=this.commonTables;this.commonTables.length===0&&(this.commonTables=this.commonTableCollector.collect(query));try{let outputs=[];for(let item of query.selectClause.items)outputs.push(...this.collectSelectItem(item,query.fromClause));return outputs}finally{this.commonTables=previousCommonTables}}collectSelectItem(item,fromClause){if(item.identifier)return[this.createExplicitOutput(item.identifier.name,item.value,fromClause)];if(!(item.value instanceof ColumnReference))return[];let columnName=item.value.column.name;return columnName==="*"?this.expandWildcard(item.value,fromClause):[this.createExplicitOutput(columnName,item.value,fromClause)]}expandWildcard(value,fromClause){if(!fromClause)return[];if(value.namespaces===null)return this.collectFromClause(fromClause,!0);let sourceName=value.getNamespace();if(fromClause.getSourceAliasName()===sourceName)return this.collectFromClause(fromClause,!1);let join=fromClause.joins?.find(item=>this.getJoinSourceName(item)===sourceName);return join?this.collectJoinClause(join):[]}collectFromClause(clause,joinCascade){let outputs=this.collectSourceExpression(clause.getSourceAliasName(),clause.source);if(clause.joins&&joinCascade)for(let join of clause.joins)outputs.push(...this.collectJoinClause(join));return outputs}collectJoinClause(clause){return this.collectSourceExpression(this.getJoinSourceName(clause),clause.source)}getJoinSourceName(clause){return clause.source.getAliasName()}collectSourceExpression(sourceName,source){if(source.aliasExpression?.columns)return source.aliasExpression.columns.map(column=>({name:column.name,value:new ColumnReference(sourceName?[sourceName]:null,column.name),sourceAlias:sourceName,sourceName:null,sourceColumnName:column.name}));let cte=this.findCommonTable(source);if(cte){let innerCommonTables=this.commonTables.filter(item=>item.getSourceAliasName()!==cte.getSourceAliasName()),innerOutputs=this.collectCteQuery(cte.query,innerCommonTables);return this.qualifyOutputs(innerOutputs,sourceName,cte.getSourceAliasName())}if(source.datasource instanceof TableSource)return this.collectTableSource(sourceName,source.datasource);if(source.datasource instanceof SubQuerySource){let innerOutputs=this.collectNestedSelectQuery(source.datasource.query);return this.qualifyOutputs(innerOutputs,sourceName,null)}return source.datasource instanceof ParenSource?[]:[]}findCommonTable(source){if(!(source.datasource instanceof TableSource))return null;let tableName=source.datasource.getSourceName();return this.commonTables.find(item=>item.getSourceAliasName()===tableName)??null}collectTableSource(sourceName,source){if(!this.tableColumnResolver)return[];let tableName=source.getSourceName(),qualifier=sourceName??tableName;return this.tableColumnResolver(tableName).map(column=>({name:column,value:new ColumnReference([qualifier],column),sourceAlias:sourceName,sourceName:tableName,sourceColumnName:column}))}collectNestedSelectQuery(query){return new _SelectOutputCollector(this.tableColumnResolver,this.commonTables).collect(query).map(({name,value,sourceAlias,sourceName,sourceColumnName})=>({name,value,sourceAlias,sourceName,sourceColumnName}))}collectCteQuery(query,commonTables){return this.isSelectQuery(query)?new _SelectOutputCollector(this.tableColumnResolver,commonTables).collect(query).map(({name,value,sourceAlias,sourceName,sourceColumnName})=>({name,value,sourceAlias,sourceName,sourceColumnName})):this.collectReturningOutputs(query)}collectReturningOutputs(query){return query instanceof InsertQuery||query instanceof UpdateQuery||query instanceof DeleteQuery||query instanceof MergeQuery?query.returningClause?this.extractReturningOutputs(query.returningClause):[]:[]}extractReturningOutputs(clause){let outputs=[];for(let item of clause.items){let name=item.identifier?.name??this.extractSelectItemName(item);name&&outputs.push(this.createExplicitOutput(name,item.value))}return outputs}extractSelectItemName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}qualifyOutputs(outputs,sourceAlias,sourceName){return outputs.map(item=>({name:item.name,value:new ColumnReference(sourceAlias?[sourceAlias]:null,item.name),sourceAlias,sourceName,sourceColumnName:item.name}))}createExplicitOutput(name,value,fromClause=null){if(value instanceof ColumnReference&&value.column.name!=="*"){let sourceMetadata=this.resolveColumnSourceMetadata(value,fromClause);if(sourceMetadata)return{name,value,...sourceMetadata}}return{name,value,sourceAlias:null,sourceName:null,sourceColumnName:null}}resolveColumnSourceMetadata(value,fromClause){if(!fromClause||value.namespaces===null)return null;let namespace=value.getNamespace(),matches=fromClause.getSources().filter(source2=>this.getSourceMatchNames(source2).includes(namespace));if(matches.length!==1)return null;let source=matches[0];return{sourceAlias:this.getColumnReferenceSourceAlias(source,namespace),sourceName:this.getColumnReferenceSourceName(source),sourceColumnName:value.column.name}}getSourceMatchNames(source){let names=new Set;if(source.aliasExpression)return names.add(source.aliasExpression.table.name),[...names];let aliasName=source.getAliasName();return aliasName&&names.add(aliasName),source.datasource instanceof TableSource&&(names.add(source.datasource.table.name),names.add(source.datasource.getSourceName())),[...names]}getColumnReferenceSourceAlias(source,namespace){return source.aliasExpression?source.aliasExpression.table.name:namespace}getColumnReferenceSourceName(source){let cte=this.findCommonTable(source);return cte?cte.getSourceAliasName():source.aliasExpression?.columns?null:source.datasource instanceof TableSource?source.datasource.getSourceName():null}isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}};var clauseOrder=["select","where","joinOn","groupBy","having","orderBy","window","limitOffset"],WildcardColumnInferenceCollector=class{constructor(){this.clauseCollector=new ClauseScopedColumnReferenceCollector;this.requirements=new Map;this.visitedQueries=new Set;this.nextObjectId=0;this.objectIds=new WeakMap}collect(query){return this.requirements.clear(),this.visitedQueries.clear(),this.nextObjectId=0,this.objectIds=new WeakMap,this.collectFromSelectQuery(query,[]),[...this.requirements.values()].map(item=>this.inferTarget(item))}collectFromSelectQuery(query,commonTables){if(this.visitedQueries.has(query))return;if(this.visitedQueries.add(query),query instanceof BinarySelectQuery){let rightCommonTables=this.mergeCommonTables(commonTables,this.collectLeadingCommonTables(query.left));this.collectFromSelectQuery(query.left,commonTables),this.collectFromSelectQuery(query.right,rightCommonTables);return}if(!(query instanceof SimpleSelectQuery))return;let scopedCommonTables=this.mergeCommonTables(commonTables,query.withClause?.tables??[]);this.collectConsumerRequirements(query,scopedCommonTables),this.collectNestedSources(query.fromClause,scopedCommonTables);for(let commonTable of query.withClause?.tables??[])this.collectCteQuery(commonTable.query,scopedCommonTables)}collectCteQuery(query,commonTables){this.isSelectQuery(query)&&this.collectFromSelectQuery(query,commonTables)}collectConsumerRequirements(query,commonTables){if(!query.fromClause)return;let targets=this.collectConsumerTargets(query.fromClause,commonTables);if(targets.length===0)return;let targetByMatchName=new Map;for(let target of targets)for(let name of this.getTargetMatchNames(target)){let existing=targetByMatchName.get(name)??[];existing.push(target),targetByMatchName.set(name,existing)}let singleUnqualifiedTarget=query.fromClause.getSources().length===1&&targets.length===1?targets[0]:null;for(let reference of this.flattenReferences(this.clauseCollector.collect(query))){if(reference.column==="*")continue;let matchedTarget=reference.namespace?this.getUniqueTarget(targetByMatchName.get(reference.namespace)??[]):singleUnqualifiedTarget;matchedTarget&&this.addRequirement(matchedTarget,reference.column,this.createRequiredBy(reference))}}collectConsumerTargets(fromClause,commonTables){let targets=[];for(let source of fromClause.getSources()){let cteTarget=this.createCteTarget(source,commonTables);if(cteTarget){targets.push(cteTarget);continue}let derivedTarget=this.createDerivedTableTarget(source);derivedTarget&&targets.push(derivedTarget)}return targets}createCteTarget(source,commonTables){if(!(source.datasource instanceof TableSource))return null;let tableName=source.datasource.getSourceName(),commonTable=commonTables.find(item=>item.getSourceAliasName()===tableName);return!commonTable||!this.isSelectQuery(commonTable.query)?null:{key:`cte:${this.getObjectId(commonTable)}`,targetKind:"cte",targetName:commonTable.getSourceAliasName(),targetAlias:source.aliasExpression?source.getAliasName():commonTable.getSourceAliasName(),query:commonTable.query}}createDerivedTableTarget(source){return source.datasource instanceof SubQuerySource?{key:`derived:${this.getObjectId(source.datasource.query)}`,targetKind:"derivedTable",targetName:null,targetAlias:source.getAliasName(),query:source.datasource.query}:null}collectNestedSources(fromClause,commonTables){if(fromClause)for(let source of fromClause.getSources())source.datasource instanceof SubQuerySource&&this.collectFromSelectQuery(source.datasource.query,commonTables)}addRequirement(target,column,requiredBy){let requirement=this.requirements.get(target.key);requirement||(requirement={descriptor:target,requiredByColumn:new Map},this.requirements.set(target.key,requirement));let existing=requirement.requiredByColumn.get(column)??[];existing.push(requiredBy),requirement.requiredByColumn.set(column,existing)}inferTarget(requirement){let descriptor=requirement.descriptor,baseResult={targetKind:descriptor.targetKind,targetName:descriptor.targetName,targetAlias:descriptor.targetAlias,wildcards:[],explicitColumns:[],requiredColumns:[],unresolvedColumns:[]};if(!(descriptor.query instanceof SimpleSelectQuery)){for(let[outputName,requiredBy]of requirement.requiredByColumn)baseResult.unresolvedColumns.push(this.createUnresolved(outputName,"unsupportedQueryShape",[],requiredBy));return baseResult}let outputMetadata=this.collectTargetOutputMetadata(descriptor.query);baseResult.wildcards=outputMetadata.wildcards,baseResult.explicitColumns=outputMetadata.explicitColumns;for(let[outputName,requiredBy]of requirement.requiredByColumn){let explicitMatches=outputMetadata.explicitColumns.filter(item=>item.outputName===outputName),candidateWildcards=outputMetadata.wildcards;if(explicitMatches.length>0&&candidateWildcards.length>0){baseResult.unresolvedColumns.push(this.createUnresolved(outputName,"duplicateOutputOwnership",candidateWildcards,requiredBy));continue}if(explicitMatches.length>0)continue;if(outputMetadata.unqualifiedWildcardWithMultipleSources){baseResult.unresolvedColumns.push(this.createUnresolved(outputName,"unqualifiedWildcardMultipleSources",candidateWildcards,requiredBy));continue}if(candidateWildcards.length===0){baseResult.unresolvedColumns.push(this.createUnresolved(outputName,"noWildcardSupplier",[],requiredBy));continue}if(candidateWildcards.length>1){baseResult.unresolvedColumns.push(this.createUnresolved(outputName,"multipleWildcardSuppliers",candidateWildcards,requiredBy));continue}let wildcard=candidateWildcards[0];baseResult.requiredColumns.push({outputName,sourceAlias:wildcard.sourceAlias,sourceName:wildcard.sourceName,sourceColumnName:outputName,wildcard,requiredByClause:this.collectRequiredByClauses(requiredBy),requiredBy})}return baseResult}collectTargetOutputMetadata(query){let wildcards=[],unqualifiedWildcardWithMultipleSources=!1;query.selectClause.items.forEach((item,outputIndex)=>{let wildcard=this.collectWildcardMetadata(item,outputIndex,query.fromClause);if(wildcard==="unqualifiedWildcardMultipleSources"){unqualifiedWildcardWithMultipleSources=!0,wildcards.push({kind:"unqualified",outputIndex,sourceAlias:null,sourceName:null});return}wildcard&&wildcards.push(wildcard)});let explicitColumns=new SelectOutputCollector().collect(query).filter(item=>!(item.value instanceof ColumnReference&&item.value.column.name==="*")).map(item=>({outputName:item.name,sourceAlias:item.sourceAlias,sourceName:item.sourceName,sourceColumnName:item.sourceColumnName}));return{wildcards,explicitColumns,unqualifiedWildcardWithMultipleSources}}collectWildcardMetadata(item,outputIndex,fromClause){if(!(item.value instanceof ColumnReference)||item.value.column.name!=="*"||!fromClause)return null;if(item.value.namespaces===null){let sources=fromClause.getSources();return sources.length!==1?"unqualifiedWildcardMultipleSources":{kind:"unqualified",outputIndex,sourceAlias:sources[0].getAliasName(),sourceName:this.getSourceName(sources[0])}}let namespace=item.value.getNamespace(),source=this.getUniqueSource(fromClause.getSources().filter(candidate=>this.getSourceMatchNames(candidate).includes(namespace)));return{kind:"qualified",outputIndex,sourceAlias:namespace,sourceName:source?this.getSourceName(source):null}}createUnresolved(outputName,reason,candidateWildcards,requiredBy){return{outputName,reason,candidateWildcards,requiredByClause:this.collectRequiredByClauses(requiredBy),requiredBy}}flattenReferences(references){return clauseOrder.flatMap(clause=>references[clause])}createRequiredBy(reference){return{clause:reference.clause,qualifiedName:reference.qualifiedName,namespace:reference.namespace,column:reference.column}}collectRequiredByClauses(requiredBy){let clauses=new Set(requiredBy.map(item=>item.clause));return clauseOrder.filter(clause=>clauses.has(clause))}getTargetMatchNames(target){return target.targetAlias?[target.targetAlias]:target.targetName?[target.targetName]:[]}getUniqueTarget(targets){return targets.length===1?targets[0]:null}getUniqueSource(sources){return sources.length===1?sources[0]:null}getSourceMatchNames(source){let names=new Set,aliasName=source.getAliasName();return aliasName&&names.add(aliasName),source.datasource instanceof TableSource&&(names.add(source.datasource.table.name),names.add(source.datasource.getSourceName())),[...names]}getSourceName(source){return source.datasource instanceof TableSource?source.datasource.getSourceName():null}collectLeadingCommonTables(query){return query instanceof SimpleSelectQuery?query.withClause?.tables??[]:query instanceof BinarySelectQuery?this.collectLeadingCommonTables(query.left):[]}mergeCommonTables(left,right){let merged=[...left];for(let table of right){let existingIndex=merged.findIndex(item=>item.getSourceAliasName()===table.getSourceAliasName());existingIndex===-1?merged.push(table):merged[existingIndex]=table}return merged}getObjectId(value){let existing=this.objectIds.get(value);if(existing!==void 0)return existing;let id=this.nextObjectId++;return this.objectIds.set(value,id),id}isSelectQuery(query){return!!query&&typeof query=="object"&&"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}};var ParameterDetector=class{static extractParameterNames(query){return ParameterCollector.collect(query).map(p=>p.name.value)}static hasParameter(query,parameterName){return this.extractParameterNames(query).includes(parameterName)}static separateFilters(query,filter){let hardcodedParamNames=this.extractParameterNames(query),hardcodedParams={},dynamicFilters={};for(let[key,value]of Object.entries(filter))hardcodedParamNames.includes(key)?hardcodedParams[key]=value:dynamicFilters[key]=value;return{hardcodedParams,dynamicFilters}}};var FilterableItem=class{constructor(name,type,tableName){this.name=name;this.type=type;this.tableName=tableName}},FilterableItemCollector=class{constructor(tableColumnResolver,options){this.tableColumnResolver=tableColumnResolver,this.options={qualified:!1,upstream:!0,...options}}collect(query){let items=[],columnItems=this.collectColumns(query);items.push(...columnItems);let parameterItems=this.collectParameters(query);return items.push(...parameterItems),this.removeDuplicates(items)}collectColumns(query){let items=[];try{let columns=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:this.options.upstream}).collect(query);for(let column of columns){let tableName,realTableName;if(column.value&&typeof column.value.getNamespace=="function"){let namespace=column.value.getNamespace();namespace&&namespace.trim()!==""&&(tableName=namespace,this.options.qualified&&(realTableName=this.getRealTableName(query,namespace)))}tableName||(tableName=this.inferTableNameFromQuery(query),tableName&&this.options.qualified&&(realTableName=tableName));let columnName=column.name;this.options.qualified&&(realTableName||tableName)&&(columnName=`${realTableName||tableName}.${column.name}`),items.push(new FilterableItem(columnName,"column",tableName))}}catch(error){console.warn("Failed to collect columns with SelectableColumnCollector, using fallback:",error);try{let schemas=new SchemaCollector(this.tableColumnResolver,!0).collect(query);for(let schema of schemas)for(let columnName of schema.columns){let finalColumnName=columnName;this.options.qualified&&(finalColumnName=`${schema.name}.${columnName}`),items.push(new FilterableItem(finalColumnName,"column",schema.name))}}catch(fallbackError){console.warn("Failed to collect columns with both approaches:",error,fallbackError)}}return items}inferTableNameFromQuery(query){if(query instanceof SimpleSelectQuery&&query.fromClause&&query.fromClause.source){let datasource=query.fromClause.source.datasource;if(datasource&&typeof datasource.table=="object"){let table=datasource.table;if(table&&typeof table.name=="string")return table.name}}}getRealTableName(query,aliasOrName){try{let simpleQuery=query.type==="WITH"?query.toSimpleQuery():query;if(simpleQuery instanceof SimpleSelectQuery&&simpleQuery.fromClause){if(simpleQuery.fromClause.source?.datasource){let mainSource=simpleQuery.fromClause.source,realName=this.extractRealTableName(mainSource,aliasOrName);if(realName)return realName}let fromClause=simpleQuery.fromClause;if(fromClause.joinClauses&&Array.isArray(fromClause.joinClauses)){for(let joinClause of fromClause.joinClauses)if(joinClause.source?.datasource){let realName=this.extractRealTableName(joinClause.source,aliasOrName);if(realName)return realName}}}}catch(error){console.warn("Error resolving real table name:",error)}return aliasOrName}extractRealTableName(source,aliasOrName){try{let datasource=source.datasource;if(!datasource)return;let alias=source.alias||source.aliasExpression?.table?.name,realTableName=datasource.table?.name;if(alias===aliasOrName&&realTableName||!alias&&realTableName===aliasOrName)return realTableName}catch{}}collectParameters(query){let items=[];try{let parameterNames=ParameterDetector.extractParameterNames(query);for(let paramName of parameterNames)items.push(new FilterableItem(paramName,"parameter"))}catch(error){console.warn("Failed to collect parameters:",error)}return items}removeDuplicates(items){let seen=new Set,result=[];for(let item of items){let key=`${item.type}:${item.name}:${item.tableName||"none"}`;seen.has(key)||(seen.add(key),result.push(item))}return result.sort((a,b)=>{if(a.type!==b.type)return a.type==="column"?-1:1;if(a.type==="column"){let tableA=a.tableName||"",tableB=b.tableName||"";if(tableA!==tableB)return tableA.localeCompare(tableB)}return a.name.localeCompare(b.name)})}};var SqlSortInjector=class{constructor(tableColumnResolver){this.tableColumnResolver=tableColumnResolver}static removeOrderBy(query){if(typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for ORDER BY removal");return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:null,windowClause:query.windowClause,limitClause:query.limitClause,offsetClause:query.offsetClause,fetchClause:query.fetchClause,forClause:query.forClause})}inject(query,sortConditions){if(typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for sorting");let availableColumns=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query);for(let columnName of Object.keys(sortConditions))if(!availableColumns.find(item=>item.name===columnName))throw new Error(`Column or alias '${columnName}' not found in current query`);let newOrderByItems=[];for(let[columnName,condition]of Object.entries(sortConditions)){let columnEntry=availableColumns.find(item=>item.name===columnName);if(!columnEntry)continue;let columnRef=columnEntry.value;this.validateSortCondition(columnName,condition);let sortDirection;condition.desc?sortDirection="desc":sortDirection="asc";let nullsPosition=null;condition.nullsFirst?nullsPosition="first":condition.nullsLast&&(nullsPosition="last");let orderByItem=new OrderByItem(columnRef,sortDirection,nullsPosition);newOrderByItems.push(orderByItem)}let finalOrderByItems=[];query.orderByClause?finalOrderByItems=[...query.orderByClause.order,...newOrderByItems]:finalOrderByItems=newOrderByItems;let newOrderByClause=finalOrderByItems.length>0?new OrderByClause(finalOrderByItems):null;return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:newOrderByClause,windowClause:query.windowClause,limitClause:query.limitClause,offsetClause:query.offsetClause,fetchClause:query.fetchClause,forClause:query.forClause})}validateSortCondition(columnName,condition){if(condition.asc&&condition.desc)throw new Error(`Conflicting sort directions for column '${columnName}': both asc and desc specified`);if(condition.nullsFirst&&condition.nullsLast)throw new Error(`Conflicting nulls positions for column '${columnName}': both nullsFirst and nullsLast specified`);if(!condition.asc&&!condition.desc&&!condition.nullsFirst&&!condition.nullsLast)throw new Error(`Empty sort condition for column '${columnName}': at least one sort option must be specified`)}};var SqlPaginationInjector=class{inject(query,pagination){if(this.validatePaginationOptions(pagination),typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for pagination");if(query.limitClause||query.offsetClause)throw new Error("Query already contains LIMIT or OFFSET clause. Use removePagination() first if you want to override existing pagination.");let offset=(pagination.page-1)*pagination.pageSize,limitClause=new LimitClause(new ParameterExpression("paging_limit",pagination.pageSize)),offsetClause=new OffsetClause(new ParameterExpression("paging_offset",offset));return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:query.orderByClause,windowClause:query.windowClause,limitClause,offsetClause,fetchClause:query.fetchClause,forClause:query.forClause})}static removePagination(query){if(typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for pagination removal");return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:query.orderByClause,windowClause:query.windowClause,limitClause:null,offsetClause:null,fetchClause:query.fetchClause,forClause:query.forClause})}validatePaginationOptions(pagination){if(!pagination)throw new Error("Pagination options are required");if(typeof pagination.page!="number"||pagination.page<1)throw new Error("Page number must be a positive integer (1 or greater)");if(typeof pagination.pageSize!="number"||pagination.pageSize<1)throw new Error("Page size must be a positive integer (1 or greater)");if(pagination.pageSize>1e3)throw new Error("Page size cannot exceed 1000 items")}};var SqlParameterBinder=class{constructor(options={}){this.options={requireAllParameters:!0,...options}}bind(query,parameterValues){let modifiedQuery=query,existingParams=ParameterDetector.extractParameterNames(modifiedQuery);if(this.options.requireAllParameters){let missingParams=existingParams.filter(paramName=>!(paramName in parameterValues)||parameterValues[paramName]===void 0);if(missingParams.length>0)throw new Error(`Missing values for required parameters: ${missingParams.join(", ")}`)}for(let[paramName,value]of Object.entries(parameterValues))if(existingParams.includes(paramName))try{ParameterHelper.set(modifiedQuery,paramName,value)}catch(error){throw new Error(`Failed to bind parameter '${paramName}': ${error instanceof Error?error.message:"Unknown error"}`)}return modifiedQuery}bindToSimpleQuery(query,parameterValues){return this.bind(query,parameterValues)}};var NAMESPACE_SEPARATOR="|",normalizeIdentifier=input=>{let value=input?.trim()??"";return value===""?"":value.toLowerCase()},normalizeColumnSetKey=columns=>columns.map(column=>normalizeIdentifier(column)).filter(Boolean).sort().join(NAMESPACE_SEPARATOR),buildSchemaMap=schemaInfo=>{let map=new Map;for(let table of schemaInfo){let normalizedName=normalizeIdentifier(table.name);if(!normalizedName)continue;let columnSet=new Set(table.columns.map(normalizeIdentifier).filter(Boolean)),uniqueSetKeys=new Set;for(let uniqueKey of table.uniqueKeys){let normalizedKey=normalizeColumnSetKey(uniqueKey);normalizedKey&&uniqueSetKeys.add(normalizedKey)}columnSet.size===0&&uniqueSetKeys.size===0||map.set(normalizedName,{columnSet,uniqueSetKeys})}return map},collectReferenceMetadata=query=>{let collector=new ColumnReferenceCollector,namespaceCounts=new Map,unqualifiedColumns=new Set;for(let ref of collector.collect(query)){let namespace=normalizeIdentifier(ref.getNamespace());if(namespace)namespaceCounts.set(namespace,(namespaceCounts.get(namespace)??0)+1);else{let column=normalizeIdentifier(ref.column.name);column&&unqualifiedColumns.add(column)}}let joinConditionCounts=new Map;if(query.fromClause?.joins)for(let join of query.fromClause.joins){let counts=new Map;if(join.condition&&join.condition instanceof JoinOnClause){let joinCollector=new ColumnReferenceCollector;for(let ref of joinCollector.collect(join.condition.condition)){let namespace=normalizeIdentifier(ref.getNamespace());namespace&&counts.set(namespace,(counts.get(namespace)??0)+1)}}joinConditionCounts.set(join,counts)}return{namespaceCounts,unqualifiedColumns,joinConditionCounts}},isLeftJoin=join=>join.joinType.value.toLowerCase().includes("left"),getJoinIdentifiers=join=>{let identifiers=new Set,alias=normalizeIdentifier(join.source.getAliasName());if(alias&&identifiers.add(alias),join.source.datasource instanceof TableSource){let rawName=join.source.datasource.getSourceName();rawName&&identifiers.add(normalizeIdentifier(rawName));let shortName=normalizeIdentifier(join.source.datasource.table.name);shortName&&identifiers.add(shortName)}return[...identifiers]},hasExternalReferences=(identifiers,metadata,join)=>{let local=metadata.joinConditionCounts.get(join)??new Map;for(let identifier of identifiers){let total=metadata.namespaceCounts.get(identifier)??0,localCount=local.get(identifier)??0;if(total-localCount>0)return!0}return!1},getJoinColumnInfo=(join,identifiers)=>{if(!(join.condition instanceof JoinOnClause))return null;let expression=join.condition.condition;if(!(expression instanceof BinaryExpression)||expression.operator.value.trim().toLowerCase()!=="=")return null;let resolveColumn=component=>component instanceof ColumnReference?component:null,leftRef=resolveColumn(expression.left),rightRef=resolveColumn(expression.right);if(!leftRef||!rightRef)return null;let normalizedLeftNamespace=normalizeIdentifier(leftRef.getNamespace()),normalizedRightNamespace=normalizeIdentifier(rightRef.getNamespace());return identifiers.has(normalizedLeftNamespace)?normalizeIdentifier(leftRef.column.name):identifiers.has(normalizedRightNamespace)?normalizeIdentifier(rightRef.column.name):null},shouldRemoveJoin=(join,schemaMap,metadata)=>{if(!isLeftJoin(join)||join.lateral||!(join.source.datasource instanceof TableSource))return!1;let candidates=[normalizeIdentifier(join.source.datasource.getSourceName()),normalizeIdentifier(join.source.datasource.table.name)].filter(Boolean),tableInfo;for(let candidate of candidates){let info=schemaMap.get(candidate);if(info){tableInfo=info;break}}if(!tableInfo)return!1;let identifiers=new Set(getJoinIdentifiers(join));if(identifiers.size===0||hasExternalReferences([...identifiers],metadata,join))return!1;let joinColumn=getJoinColumnInfo(join,identifiers);if(!joinColumn||metadata.unqualifiedColumns.has(joinColumn)||tableInfo.columnSet.size>0&&!tableInfo.columnSet.has(joinColumn))return!1;let uniqueKey=normalizeColumnSetKey([joinColumn]);return!!tableInfo.uniqueSetKeys.has(uniqueKey)},optimizeSimpleQuery=(query,schemaMap)=>{if(!query.fromClause?.joins?.length)return!1;let metadata=collectReferenceMetadata(query),retainedJoins=[],removed=!1;for(let join of query.fromClause.joins){if(shouldRemoveJoin(join,schemaMap,metadata)){removed=!0;continue}retainedJoins.push(join)}return query.fromClause.joins=retainedJoins.length>0?retainedJoins:null,removed},traverseSelectQuery=(query,schemaMap)=>{if(query instanceof SimpleSelectQuery)return optimizeSimpleQuery(query,schemaMap);if(query instanceof BinarySelectQuery){let leftChanged=traverseSelectQuery(query.left,schemaMap),rightChanged=traverseSelectQuery(query.right,schemaMap);return leftChanged||rightChanged}return!1},optimizeUnusedLeftJoinsOnce=(query,schemaMap)=>schemaMap.size===0?!1:traverseSelectQuery(query,schemaMap),optimizeUnusedLeftJoins=(query,schemaInfo)=>(optimizeUnusedLeftJoinsOnce(query,buildSchemaMap(schemaInfo)),query),optimizeUnusedLeftJoinsToFixedPoint=(query,schemaInfo)=>{let schemaMap=buildSchemaMap(schemaInfo),changed=!0;for(;changed;)changed=optimizeUnusedLeftJoinsOnce(query,schemaMap);return query},collectTableSourceNames=component=>{let collector=new CTETableReferenceCollector,names=new Set;for(let source of collector.collect(component)){let normalizedName=normalizeIdentifier(source.table.name);normalizedName&&names.add(normalizedName)}return names},isReferencedByOthers=(cteName,mainReferences,cteReferenceMap)=>{if(mainReferences.has(cteName))return!0;for(let[otherName,references]of cteReferenceMap)if(otherName!==cteName&&references.has(cteName))return!0;return!1},optimizeSimpleQueryCtes=query=>{let withClause=query.withClause;if(!withClause||withClause.recursive||withClause.tables.length===0)return!1;let mainReferences=collectTableSourceNames(query),cteReferenceMap=new Map;for(let table of withClause.tables){let normalizedName=normalizeIdentifier(table.aliasExpression.table.name);normalizedName&&cteReferenceMap.set(normalizedName,collectTableSourceNames(table.query))}let removableNames=[];for(let table of withClause.tables){let normalizedName=normalizeIdentifier(table.aliasExpression.table.name);if(!normalizedName)continue;let body=table.query;!(body instanceof SimpleSelectQuery)&&!(body instanceof BinarySelectQuery)||isReferencedByOthers(normalizedName,mainReferences,cteReferenceMap)||removableNames.push(normalizedName)}if(removableNames.length===0)return!1;for(let name of removableNames)query.removeCTE(name);return!0},optimizeCtesInSelectQuery=query=>{if(query instanceof SimpleSelectQuery)return optimizeSimpleQueryCtes(query);if(query instanceof BinarySelectQuery){let leftChanged=optimizeCtesInSelectQuery(query.left),rightChanged=optimizeCtesInSelectQuery(query.right);return leftChanged||rightChanged}return!1},optimizeUnusedCtesOnce=query=>optimizeCtesInSelectQuery(query),optimizeUnusedCtes=query=>(optimizeUnusedCtesOnce(query),query),optimizeUnusedCtesToFixedPoint=query=>{let changed=!0;for(;changed;)changed=optimizeUnusedCtesOnce(query);return query};var isBinaryOperator=(expression,operator)=>expression instanceof BinaryExpression&&expression.operator.value.trim().toLowerCase()===operator,unwrapSingleOuterParen=expression=>{let candidate=expression;for(;candidate instanceof ParenExpression;)candidate=candidate.expression;return candidate},unwrapOptionalGuardParameter=expression=>{let candidate=unwrapSingleOuterParen(expression);for(;candidate instanceof CastExpression;)candidate=unwrapSingleOuterParen(candidate.input);if(candidate instanceof FunctionCall&&getFunctionCallName(candidate)==="cast"&&candidate.argument){let argument=unwrapSingleOuterParen(candidate.argument);if(isBinaryOperator(argument,"as"))return unwrapOptionalGuardParameter(argument.left)}return candidate},getFunctionCallName=expression=>{let name=expression.qualifiedName.name;return"value"in name?name.value.toLowerCase():name.name.toLowerCase()},collectTopLevelAndTerms=expression=>{let candidate=unwrapSingleOuterParen(expression);return isBinaryOperator(candidate,"and")?[...collectTopLevelAndTerms(candidate.left),...collectTopLevelAndTerms(candidate.right)]:[expression]},collectTopLevelOrTerms=expression=>{let candidate=unwrapSingleOuterParen(expression);return isBinaryOperator(candidate,"or")?[...collectTopLevelOrTerms(candidate.left),...collectTopLevelOrTerms(candidate.right)]:[expression]},isNullLiteral=expression=>expression instanceof LiteralValue&&expression.value===null||expression instanceof RawString&&expression.value.trim().toLowerCase()==="null",isTrueSentinel=expression=>{let candidate=unwrapSingleOuterParen(expression);return candidate instanceof LiteralValue?candidate.value===!0:isBinaryOperator(candidate,"=")?candidate.left instanceof LiteralValue&&candidate.right instanceof LiteralValue&&candidate.left.value===1&&candidate.right.value===1:!1},getGuardedParameterName=expression=>{let candidate=unwrapSingleOuterParen(expression);if(!isBinaryOperator(candidate,"is"))return null;let left=unwrapOptionalGuardParameter(candidate.left);return!(left instanceof ParameterExpression)||!isNullLiteral(candidate.right)?null:left.name.value},getUniqueParameterNames=expression=>new Set(ParameterCollector.collect(expression).map(parameter=>parameter.name.value)),isSupportedMeaningfulBranch=(expression,parameterName)=>{let candidate=unwrapSingleOuterParen(expression);if(candidate instanceof ParameterExpression)return!1;let parameterNames=getUniqueParameterNames(candidate);return parameterNames.size!==1||!parameterNames.has(parameterName)?!1:!(candidate instanceof LiteralValue||candidate instanceof RawString)},isExplicitPruningTarget=(pruningParameters,parameterName)=>Object.prototype.hasOwnProperty.call(pruningParameters,parameterName),isKnownAbsentTarget=(pruningParameters,parameterName)=>{if(!isExplicitPruningTarget(pruningParameters,parameterName))return!1;let parameterValue=pruningParameters[parameterName];return parameterValue==null},shouldPruneOptionalBranch=(expression,pruningParameters)=>{let branch=getSupportedOptionalConditionBranch(expression);return branch!==null&&isKnownAbsentTarget(pruningParameters,branch.parameterName)},rebuildAndCondition=terms=>{if(terms.length===0)return null;let condition=terms[0];for(let index=1;index<terms.length;index+=1)condition=new BinaryExpression(condition,"and",terms[index]);return condition},pruneSimpleQueryWhereClause=(query,pruningParameters)=>{if(!query.whereClause)return!1;let topLevelTerms=collectTopLevelAndTerms(query.whereClause.condition),retainedTerms=[],prunedAnyBranch=!1;for(let term of topLevelTerms){if(shouldPruneOptionalBranch(term,pruningParameters)){prunedAnyBranch=!0;continue}retainedTerms.push(term)}if(!prunedAnyBranch)return!1;let cleanedTerms=retainedTerms.filter(term=>!isTrueSentinel(term)),rebuiltCondition=rebuildAndCondition(cleanedTerms);return query.whereClause=rebuiltCondition?new WhereClause(rebuiltCondition):null,!0},isSelectQueryNode=value=>value instanceof SimpleSelectQuery||value instanceof BinarySelectQuery,traverseNestedSelectQueries=(root,pruningParameters)=>{let changed=!1,visited=new WeakSet,walk=value=>{if(!(!value||typeof value!="object")&&!visited.has(value)){if(visited.add(value),value!==root&&isSelectQueryNode(value)){changed=traverseSelectQuery2(value,pruningParameters)||changed;return}if(Array.isArray(value)){value.forEach(walk);return}for(let child of Object.values(value))walk(child)}};return walk(root),changed},traverseSelectQuery2=(query,pruningParameters)=>{if(query instanceof SimpleSelectQuery){let selfChanged=pruneSimpleQueryWhereClause(query,pruningParameters),nestedChanged=traverseNestedSelectQueries(query,pruningParameters);return selfChanged||nestedChanged}if(query instanceof BinarySelectQuery){let leftChanged=traverseSelectQuery2(query.left,pruningParameters),rightChanged=traverseSelectQuery2(query.right,pruningParameters);return leftChanged||rightChanged}return!1},getSupportedOptionalConditionBranch=expression=>{let orTerms=collectTopLevelOrTerms(expression);if(orTerms.length<2)return null;let guardTerms=orTerms.map(term=>({term,parameterName:getGuardedParameterName(term)})).filter(candidate=>candidate.parameterName!==null);if(guardTerms.length!==1)return null;let[{term:guardTerm,parameterName}]=guardTerms,meaningfulTerms=orTerms.filter(term=>term!==guardTerm);return meaningfulTerms.length===0||!meaningfulTerms.every(term=>isSupportedMeaningfulBranch(term,parameterName))?null:{parameterName,kind:"expression"}},collectSupportedBranchesFromSimpleQuery=(query,branches)=>{if(!query.whereClause)return;let topLevelTerms=collectTopLevelAndTerms(query.whereClause.condition);for(let term of topLevelTerms){let branch=getSupportedOptionalConditionBranch(term);branch&&branches.push({query,parameterName:branch.parameterName,expression:term,kind:branch.kind})}},collectSupportedBranchesFromSelectQuery=(query,branches)=>{if(query instanceof SimpleSelectQuery){collectSupportedBranchesFromSimpleQuery(query,branches),traverseNestedSelectQueriesForCollection(query,branches);return}query instanceof BinarySelectQuery&&(collectSupportedBranchesFromSelectQuery(query.left,branches),collectSupportedBranchesFromSelectQuery(query.right,branches))},traverseNestedSelectQueriesForCollection=(root,branches)=>{let visited=new WeakSet,walk=value=>{if(!(!value||typeof value!="object")&&!visited.has(value)){if(visited.add(value),value!==root&&isSelectQueryNode(value)){collectSupportedBranchesFromSelectQuery(value,branches);return}if(Array.isArray(value)){value.forEach(walk);return}for(let child of Object.values(value))walk(child)}};walk(root)},pruneOptionalConditionBranches=(query,pruningParameters)=>(Object.keys(pruningParameters).length===0||traverseSelectQuery2(query,pruningParameters),query),collectSupportedOptionalConditionBranches=query=>{let branches=[];return collectSupportedBranchesFromSelectQuery(query,branches),branches},collectSupportedOptionalConditionBranchSpans=sql=>{let parsed=SelectQueryParser.parse(sql),supportedBranches=collectSupportedOptionalConditionBranches(parsed);if(supportedBranches.length===0)return[];let candidates=collectOptionalConditionSpanCandidates(sql),remainingSupportedCounts=countSupportedBranchesByKey(supportedBranches);assertUnambiguousCandidateCounts(candidates,remainingSupportedCounts);let spans=[];for(let candidate of candidates){let key=getSupportedBranchKey(candidate),remainingCount=remainingSupportedCounts.get(key)??0;remainingCount<=0||(spans.push(candidate),remainingSupportedCounts.set(key,remainingCount-1))}return assertNoMissingSupportedBranches(remainingSupportedCounts),spans},getSupportedBranchKey=branch=>`${branch.kind}:${branch.parameterName}`,countSupportedBranchesByKey=branches=>{let counts=new Map;for(let branch of branches){let key=getSupportedBranchKey(branch);counts.set(key,(counts.get(key)??0)+1)}return counts},assertUnambiguousCandidateCounts=(candidates,supportedCounts)=>{let candidateCounts=countSupportedBranchesByKey(candidates);for(let[key,supportedCount]of supportedCounts){let candidateCount=candidateCounts.get(key)??0;if(candidateCount<supportedCount)throw new Error(`Could not locate source range for supported optional condition branch '${key}'.`);if(candidateCount>supportedCount)throw new Error(`Ambiguous source ranges for supported optional condition branch '${key}'.`)}},assertNoMissingSupportedBranches=supportedCounts=>{let missingKeys=[...supportedCounts.entries()].filter(([,count])=>count>0).map(([key])=>key);if(missingKeys.length>0)throw new Error(`Could not locate source ranges for supported optional condition branches: ${missingKeys.join(", ")}.`)},collectOptionalConditionSpanCandidates=sql=>{let lexemes=new SqlTokenizer(sql).readLexemes(),candidates=[],stack=[];for(let index=0;index<lexemes.length;index+=1){let lexeme=lexemes[index];if(isOpenParen(lexeme)){stack.push(index);continue}if(!isCloseParen(lexeme))continue;let openParenIndex=stack.pop();if(openParenIndex===void 0)continue;let candidate=buildOptionalConditionSpanCandidate(sql,lexemes,openParenIndex,index);candidate&&candidates.push(candidate)}return candidates.sort((left,right)=>left.sourceRange.start-right.sourceRange.start)},buildOptionalConditionSpanCandidate=(sql,lexemes,openParenIndex,closeParenIndex)=>{let inside=lexemes.slice(openParenIndex+1,closeParenIndex),orTermRanges=splitTopLevelTermsByKeyword(inside,"or");if(orTermRanges.length<2)return null;let guardTerms=orTermRanges.map(range=>({range,parameterName:getGuardedParameterNameFromLexemes(inside.slice(range.start,range.end))})).filter(candidate=>candidate.parameterName!==null);if(guardTerms.length!==1)return null;let[{range:guardRange,parameterName}]=guardTerms,meaningfulTerms=orTermRanges.filter(range=>range!==guardRange);if(meaningfulTerms.length===0||!meaningfulTerms.every(range=>isSupportedMeaningfulBranchFromLexemes(inside.slice(range.start,range.end),parameterName)))return null;let expandedRange=expandWrappingParenRange(lexemes,openParenIndex,closeParenIndex),sourceStart=requiredPosition(lexemes[expandedRange.openParenIndex]).startPosition,sourceEnd=requiredPosition(lexemes[expandedRange.closeParenIndex]).endPosition,removalRange=getRemovalRange(sql,lexemes,expandedRange.openParenIndex,expandedRange.closeParenIndex);return{parameterName,kind:"expression",sourceRange:{start:sourceStart,end:sourceEnd,text:sql.slice(sourceStart,sourceEnd)},removalRange,openParenIndex:expandedRange.openParenIndex,closeParenIndex:expandedRange.closeParenIndex}},expandWrappingParenRange=(lexemes,openParenIndex,closeParenIndex)=>{let expandedOpenParenIndex=openParenIndex,expandedCloseParenIndex=closeParenIndex;for(;isOpenParen(lexemes[expandedOpenParenIndex-1])&&isCloseParen(lexemes[expandedCloseParenIndex+1]);)expandedOpenParenIndex-=1,expandedCloseParenIndex+=1;return{openParenIndex:expandedOpenParenIndex,closeParenIndex:expandedCloseParenIndex}},splitTopLevelTermsByKeyword=(lexemes,keyword)=>{let ranges=[],depth=0,start=0;for(let index=0;index<lexemes.length;index+=1){let lexeme=lexemes[index];if(isOpenParen(lexeme)){depth+=1;continue}if(isCloseParen(lexeme)){depth-=1;continue}depth===0&&isKeyword(lexeme,keyword)&&(ranges.push({start,end:index}),start=index+1)}return ranges.push({start,end:lexemes.length}),ranges},getGuardedParameterNameFromLexemes=lexemes=>{let compact=lexemes.filter(lexeme=>!isWrappingParen(lexeme)),isIndexKeyword=(index,keyword)=>{let lexeme=compact[index];return lexeme!==void 0&&isKeyword(lexeme,keyword)};if(compact.length===3)return!isParameter(compact[0])||!isIndexKeyword(1,"is")||!isIndexKeyword(2,"null")?null:normalizeParameterName(compact[0].value);if(compact.length===5&&isParameter(compact[0])&&compact[1]?.value==="::"&&isIndexKeyword(3,"is")&&isIndexKeyword(4,"null"))return normalizeParameterName(compact[0].value);if(compact.length>=6&&isIndexKeyword(0,"cast")&&isParameter(compact[1])&&isIndexKeyword(2,"as")){let isIndex=compact.findIndex((lexeme,index)=>index>2&&isKeyword(lexeme,"is"));if(isIndex>=0&&isIndexKeyword(isIndex+1,"null"))return normalizeParameterName(compact[1].value)}return null},isSupportedMeaningfulBranchFromLexemes=(lexemes,parameterName)=>{try{let parsed=ValueParser.parseFromLexeme(lexemes,0);return parsed.newIndex!==lexemes.length?!1:isSupportedMeaningfulBranch(parsed.value,parameterName)}catch{return!1}},getRemovalRange=(sql,lexemes,openParenIndex,closeParenIndex)=>{let previous=lexemes[openParenIndex-1],next=lexemes[closeParenIndex+1],start=requiredPosition(lexemes[openParenIndex]).startPosition,end=requiredPosition(lexemes[closeParenIndex]).endPosition;return previous&&isKeyword(previous,"and")?start=requiredPosition(previous).startPosition:next&&isKeyword(next,"and")?end=requiredPosition(next).endPosition:previous&&isKeyword(previous,"where")&&(start=requiredPosition(previous).startPosition),{start,end,text:sql.slice(start,end)}},isParameter=lexeme=>(lexeme.type&256)!==0,isOpenParen=lexeme=>(lexeme.type&4)!==0,isCloseParen=lexeme=>(lexeme.type&8)!==0,isKeyword=(lexeme,keyword)=>lexeme.value.toLowerCase()===keyword,isWrappingParen=lexeme=>isOpenParen(lexeme)||isCloseParen(lexeme),normalizeParameterName=value=>value.startsWith("${")&&value.endsWith("}")?value.slice(2,-1):value.replace(/^[:@$]/,""),requiredPosition=lexeme=>{if(!lexeme.position)throw new Error(`Lexeme '${lexeme.value}' is missing source position metadata.`);return lexeme.position};var DynamicQueryBuilder=class{constructor(resolverOrOptions){typeof resolverOrOptions=="function"?this.tableColumnResolver=resolverOrOptions:resolverOrOptions&&(this.tableColumnResolver=resolverOrOptions.tableColumnResolver,this.defaultSchemaInfo=resolverOrOptions.schemaInfo)}buildQuery(sqlContent,options={}){let removedOptions=options;if("serialize"in removedOptions||"jsonb"in removedOptions)throw new Error("DynamicQueryBuilder SQL-result JSON shaping has been removed. Keep SQL results as rows and use generated AOT mappers so the executed SQL remains debuggable.");let parsedQuery;try{parsedQuery=SelectQueryParser.parse(sqlContent)}catch(error){throw new Error(`Failed to parse SQL: ${error instanceof Error?error.message:"Unknown error"}`)}let modifiedQuery=parsedQuery;if(options.filter&&Object.keys(options.filter).length>0){let{hardcodedParams,dynamicFilters}=ParameterDetector.separateFilters(modifiedQuery,options.filter);if(Object.keys(hardcodedParams).length>0&&(modifiedQuery=new SqlParameterBinder({requireAllParameters:!1}).bind(modifiedQuery,hardcodedParams)),Object.keys(dynamicFilters).length>0)throw new Error("DynamicQueryBuilder no longer injects runtime filter predicates. Use `ashiba query optional add` to author optional filters, `ashiba query optional refresh` to refresh them, and `optionalConditionParameters` at runtime for pruning only.")}if(options.sort&&Object.keys(options.sort).length>0){let sortInjector=new SqlSortInjector(this.tableColumnResolver),simpleQuery=QueryBuilder.buildSimpleQuery(modifiedQuery);modifiedQuery=sortInjector.inject(simpleQuery,options.sort)}if(options.paging){let{page=1,pageSize}=options.paging;if(pageSize!==void 0){let paginationInjector=new SqlPaginationInjector,paginationOptions={page,pageSize},simpleQuery=QueryBuilder.buildSimpleQuery(modifiedQuery);modifiedQuery=paginationInjector.inject(simpleQuery,paginationOptions)}}modifiedQuery=this.applyColumnFilters(modifiedQuery,options);let optionalConditionParameters=this.resolveOptionalConditionPruningParameters(options);Object.keys(optionalConditionParameters).length>0&&(modifiedQuery=pruneOptionalConditionBranches(modifiedQuery,optionalConditionParameters));let effectiveSchemaInfo=options.schemaInfo??this.defaultSchemaInfo;return options.removeUnusedLeftJoins&&effectiveSchemaInfo?.length&&(modifiedQuery=optimizeUnusedLeftJoinsToFixedPoint(modifiedQuery,effectiveSchemaInfo)),options.removeUnusedCtes&&(modifiedQuery=optimizeUnusedCtesToFixedPoint(modifiedQuery)),modifiedQuery}resolveOptionalConditionPruningParameters(options){if(options.optionalConditionParameters)return options.optionalConditionParameters;if(!options.optionalConditionParameterStates)return{};let legacyParameters={};for(let[parameterName,state]of Object.entries(options.optionalConditionParameterStates))legacyParameters[parameterName]=state==="absent"?null:"__RAWSQL_OPTIONAL_CONDITION_PRESENT__";return legacyParameters}applyColumnFilters(query,options){let hasIncludeFilters=Array.isArray(options.includeColumns)&&options.includeColumns.length>0,hasExcludeFilters=Array.isArray(options.excludeColumns)&&options.excludeColumns.length>0;if(!hasIncludeFilters&&!hasExcludeFilters)return query;if(hasIncludeFilters&&hasExcludeFilters)throw new Error("includeColumns and excludeColumns cannot be used together.");let simpleQuery=QueryBuilder.buildSimpleQuery(query),metadata=simpleQuery.selectClause.items.map(item=>{let name=this.getSelectItemName(item);return{item,normalized:name?this.normalizeColumnIdentifier(name):null}}),availableColumns=new Set(metadata.map(entry=>entry.normalized).filter(name=>name!==null)),includeFilters=hasIncludeFilters?this.normalizeColumnList(options.includeColumns):null,excludeFilters=hasExcludeFilters?this.normalizeColumnList(options.excludeColumns):null,includeSet=includeFilters?new Set(includeFilters.map(entry=>entry.normalized)):null,excludeSet=excludeFilters?new Set(excludeFilters.map(entry=>entry.normalized)):null;if(includeFilters){let missing=includeFilters.filter(entry=>!availableColumns.has(entry.normalized));if(missing.length>0)throw new Error(`Column${missing.length===1?"":"s"} not found in SELECT clause: ${missing.map(entry=>`'${entry.original}'`).join(", ")}.`)}if(excludeFilters){let missing=excludeFilters.filter(entry=>!availableColumns.has(entry.normalized));if(missing.length>0)throw new Error(`Column${missing.length===1?"":"s"} not found in SELECT clause: ${missing.map(entry=>`'${entry.original}'`).join(", ")}.`)}let filteredItems=metadata.filter(entry=>entry.normalized?includeSet?includeSet.has(entry.normalized):excludeSet?!excludeSet.has(entry.normalized):!0:!0).map(entry=>entry.item);if(filteredItems.length===0)throw new Error("Column filtering removed every SELECT item.");return simpleQuery.selectClause.items=filteredItems,simpleQuery}normalizeColumnList(columns){return columns.map(column=>{if(typeof column!="string")throw new Error("Column filters must be strings.");let trimmed=column.trim();if(trimmed==="")throw new Error("Column filters must not be empty.");return{normalized:this.normalizeColumnIdentifier(trimmed),original:trimmed}})}normalizeColumnIdentifier(value){return value.trim().toLowerCase()}getSelectItemName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}buildFilteredQuery(sqlContent,filter){return this.buildQuery(sqlContent,{filter})}buildSortedQuery(sqlContent,sort){return this.buildQuery(sqlContent,{sort})}buildPaginatedQuery(sqlContent,paging){return this.buildQuery(sqlContent,{paging})}validateSql(sqlContent){try{return SelectQueryParser.parse(sqlContent),!0}catch(error){throw new Error(`Invalid SQL: ${error instanceof Error?error.message:"Unknown error"}`)}}};var SUPPORTED_SCALAR_OPERATORS=new Set(["=","<>","<","<=",">",">=","like","ilike"]),formatter=null,normalizeIdentifier2=value=>value.trim().toLowerCase(),normalizeSql=value=>value.replace(/\s+/g," ").trim().toLowerCase(),normalizeRewriteTokenType=lexeme=>(lexeme.type&128)!==0?128:(lexeme.type&64)!==0?64:lexeme.type,normalizeRewriteTokenValue=lexeme=>(lexeme.type&128)!==0?lexeme.value.toLowerCase():lexeme.value,tokenizeForRewritePlan=sql=>new SqlTokenizer(sql).tokenize().map(lexeme=>({type:normalizeRewriteTokenType(lexeme),value:normalizeRewriteTokenValue(lexeme)})),tokenSequencesEqual=(left,right)=>left.length!==right.length?!1:left.every((token,index)=>{let other=right[index];return other!==void 0&&token.type===other.type&&token.value===other.value}),collectCommentFragments=sql=>new SqlTokenizer(sql).tokenize().flatMap(lexeme=>lexeme.positionedComments?lexeme.positionedComments.flatMap(positioned=>positioned.comments):lexeme.comments?[...lexeme.comments]:[]),commentsPreservedInOrder=(before,after)=>{let cursor=0;for(let comment of before){let foundAt=after.indexOf(comment,cursor);if(foundAt<0)return!1;cursor=foundAt+1}return!0},countCommandToken=(tokens,value)=>tokens.filter(token=>token.type===128&&token.value===value).length,applyRewriteEdits=(sql,edits)=>[...edits].sort((left,right)=>right.start-left.start).reduce((current,edit)=>current.slice(0,edit.start)+edit.after+current.slice(edit.end),sql),getStatementEndPosition=sql=>{let end=sql.length;for(;end>0&&/\s/.test(sql[end-1]);)end--;if(end>0&&sql[end-1]===";")for(end--;end>0&&/\s/.test(sql[end-1]);)end--;return end},clauseBoundaryCommands=new Set(["group by","having","order by","limit","offset","fetch","for"]),isClauseBoundary=lexeme=>(lexeme.type&128)!==0&&clauseBoundaryCommands.has(lexeme.value.toLowerCase()),findMinimalWhereInsertPosition=sql=>{let lexemes=new SqlTokenizer(sql).tokenize(),statementEnd=getStatementEndPosition(sql),topLevelLexemes=[],depth=0;for(let index=0;index<lexemes.length;index+=1){let lexeme=lexemes[index];(lexeme.type&8)!==0&&(depth=Math.max(0,depth-1)),depth===0&&topLevelLexemes.push({lexeme,index}),(lexeme.type&4)!==0&&(depth+=1)}let where=topLevelLexemes.find(entry=>(entry.lexeme.type&128)!==0&&entry.lexeme.value.toLowerCase()==="where");return where?{position:topLevelLexemes.filter(entry=>entry.index>where.index).map(entry=>entry.lexeme).find(isClauseBoundary)?.position?.startPosition??statementEnd,hasWhere:!0}:{position:topLevelLexemes.map(entry=>entry.lexeme).find(isClauseBoundary)?.position?.startPosition??statementEnd,hasWhere:!1}},findMatchingParenEnd=(sql,start)=>{let depth=0,quote=null;for(let index=start;index<sql.length;index++){let char=sql[index];if(quote){if(char===quote){if(quote==="'"&&sql[index+1]==="'"){index++;continue}quote=null}continue}if(char==="'"||char==='"'){quote=char;continue}if(char==="("&&depth++,char===")"&&(depth--,depth===0))return index+1}return-1},findOptionalBranchSpans=(sql,parameterName)=>{let spans=[],parameterNeedle=`:${parameterName.toLowerCase()}`,lowerSql=sql.toLowerCase();for(let index=0;index<sql.length;index++){if(sql[index]!=="(")continue;let end=findMatchingParenEnd(sql,index);if(end<0)break;let text=sql.slice(index,end),normalized=lowerSql.slice(index,end);normalized.includes(parameterNeedle)&&normalized.includes(" is null")&&normalized.includes(" or ")&&spans.push({start:index,end,text}),index=end-1}return spans},findBooleanOperatorBefore=(sql,start)=>{let prefix=sql.slice(0,start),match=/(\s+)(and|or)(\s*)$/i.exec(prefix);return!match||match.index===void 0?null:{start:match.index,end:start,value:match[2].toLowerCase()}},findBooleanOperatorAfter=(sql,end)=>{let suffix=sql.slice(end),match=/^(\s*)(and|or)(\s+)/i.exec(suffix);return match?{start:end,end:end+match[0].length,value:match[2].toLowerCase()}:null},findWhereBefore=(sql,position)=>{let lexemes=new SqlTokenizer(sql).tokenize(),found=null;for(let lexeme of lexemes){if((lexeme.position?.startPosition??0)>=position)break;(lexeme.type&128)!==0&&lexeme.value.toLowerCase()==="where"&&(found=lexeme)}return found?.position?{start:found.position.startPosition,end:found.position.endPosition}:null},findSourceColumnReferenceText=(sql,reference)=>{let namespace=normalizeIdentifier2(reference.getNamespace()),column=normalizeIdentifier2(reference.column.name),lexemes=new SqlTokenizer(sql).tokenize();for(let index=0;index<lexemes.length-2;index++){let first=lexemes[index],dot=lexemes[index+1],last=lexemes[index+2];if(!((first.type&64)===0||dot.value!=="."||(last.type&64)===0)&&!(normalizeIdentifier2(first.value)!==namespace||normalizeIdentifier2(last.value)!==column)&&!(!first.position||!last.position))return sql.slice(first.position.startPosition,last.position.endPosition)}return normalizeColumnReferenceText(reference)},normalizeColumnReferenceKey=reference=>`${normalizeIdentifier2(reference.getNamespace())}.${normalizeIdentifier2(reference.column.name)}`,normalizeColumnReferenceText=reference=>{let namespace=reference.getNamespace();return namespace?`${namespace}.${reference.column.name}`:reference.column.name},normalizeScalarOperator=value=>{if(!value)return"=";let normalized=value.trim().toLowerCase();if(normalized==="!=")return"<>";if(SUPPORTED_SCALAR_OPERATORS.has(normalized))return normalized;throw new Error(`Unsupported SSSQL operator '${value}'.`)},isExplicitEqualityScaffoldValue=value=>{if(value==null)return!0;if(Array.isArray(value))return!1;if(typeof value!="object")return!0;let entries=Object.entries(value).filter(([,entry])=>entry!==void 0);return entries.length===1&&entries[0]?.[0]==="="},parseQualifiedFilterName=filterName=>{let segments=filterName.split(".");if(segments.length!==2)return null;let[table,column]=segments.map(segment=>segment.trim());return!table||!column?null:{table,column}},makeParameterName=filterName=>filterName.trim().replace(/\./g,"_").replace(/[^a-zA-Z0-9_]/g,"_"),unwrapParens=expression=>{let candidate=expression;for(;candidate instanceof ParenExpression;)candidate=candidate.expression;return candidate},isBinaryOperator2=(expression,operator)=>expression instanceof BinaryExpression&&expression.operator.value.trim().toLowerCase()===operator,collectTopLevelAndTerms2=expression=>{let candidate=unwrapParens(expression);return isBinaryOperator2(candidate,"and")?[...collectTopLevelAndTerms2(candidate.left),...collectTopLevelAndTerms2(candidate.right)]:[expression]},collectTopLevelOrTerms2=expression=>{let candidate=unwrapParens(expression);return isBinaryOperator2(candidate,"or")?[...collectTopLevelOrTerms2(candidate.left),...collectTopLevelOrTerms2(candidate.right)]:[expression]},getGuardedParameterName2=expression=>{let candidate=unwrapParens(expression);if(!isBinaryOperator2(candidate,"is"))return null;let left=unwrapOptionalGuardParameter2(candidate.left);if(!(left instanceof ParameterExpression))return null;let right=unwrapParens(candidate.right);return right instanceof LiteralValue&&right.value===null||right instanceof RawString&&right.value.trim().toLowerCase()==="null"?left.name.value:null},unwrapOptionalGuardParameter2=expression=>{let candidate=unwrapParens(expression);for(;candidate instanceof CastExpression;)candidate=unwrapParens(candidate.input);if(candidate instanceof FunctionCall&&getFunctionCallName2(candidate)==="cast"&&candidate.argument){let argument=unwrapParens(candidate.argument);if(isBinaryOperator2(argument,"as"))return unwrapOptionalGuardParameter2(argument.left)}return candidate},getFunctionCallName2=expression=>{let name=expression.qualifiedName.name;return"value"in name?name.value.toLowerCase():name.name.toLowerCase()},buildOptionalScalarBranch=(column,parameterName,operator)=>{let guard=new BinaryExpression(new ParameterExpression(parameterName),"is",new LiteralValue(null)),predicate=new BinaryExpression(new ColumnReference(column.getNamespace()||null,column.column.name),operator,new ParameterExpression(parameterName));return new ParenExpression(new BinaryExpression(guard,"or",predicate))},buildOptionalExistsBranch=(parameterName,subquery,kind)=>{let guard=new BinaryExpression(new ParameterExpression(parameterName),"is",new LiteralValue(null)),existsExpression=new UnaryExpression("exists",new InlineQuery(subquery)),predicate=kind==="exists"?existsExpression:new UnaryExpression("not",existsExpression);return new ParenExpression(new BinaryExpression(guard,"or",predicate))},rebuildWhereWithoutTerm=(query,termToRemove)=>{if(!query.whereClause)return;let terms=collectTopLevelAndTerms2(query.whereClause.condition).filter(term=>term!==termToRemove);if(terms.length===0){query.whereClause=null;return}let rebuilt=terms[0];for(let index=1;index<terms.length;index+=1)rebuilt=new BinaryExpression(rebuilt,"and",terms[index]);query.whereClause=new WhereClause(rebuilt)},formatSqlComponent=component=>(formatter??=new SqlFormatter,formatter.format(component).formattedSql),enforceSubqueryConstraints=sql=>{if(!sql.trim())throw new Error("SSSQL EXISTS/NOT EXISTS scaffold query must not be empty.");if(sql.includes(";"))throw new Error("SSSQL EXISTS/NOT EXISTS scaffold query must not contain semicolons or multiple statements.");if(/\blateral\b/i.test(sql))throw new Error("LATERAL is not supported in SSSQL EXISTS/NOT EXISTS scaffold.")},substituteAnchorPlaceholders=(sql,formattedColumns)=>{let usedIndexes=new Set,replaced=sql.replace(/\$c(\d+)/g,(_,indexDigits)=>{let index=Number(indexDigits);if(!Number.isInteger(index))throw new Error(`Invalid placeholder '$c${indexDigits}' in SSSQL scaffold query.`);if(index<0||index>=formattedColumns.length)throw new Error(`Placeholder '$c${index}' references a missing SSSQL scaffold anchor column.`);return usedIndexes.add(index),formattedColumns[index]});if(formattedColumns.length===0)return replaced;for(let index=0;index<formattedColumns.length;index+=1)if(!usedIndexes.has(index))throw new Error(`Missing placeholder '$c${index}' for SSSQL scaffold anchor column.`);return replaced},getScalarBranchDetails=(expression,parameterName)=>{let meaningfulTerms=collectTopLevelOrTerms2(expression).filter(term=>getGuardedParameterName2(term)!==parameterName);if(meaningfulTerms.length!==1)return null;let predicate=unwrapParens(meaningfulTerms[0]);if(!(predicate instanceof BinaryExpression))return null;let left=unwrapParens(predicate.left),right=unwrapParens(predicate.right);if(left instanceof ColumnReference&&right instanceof ParameterExpression&&right.name.value===parameterName)try{return{operator:normalizeScalarOperator(predicate.operator.value),target:normalizeColumnReferenceText(left)}}catch{return null}if(right instanceof ColumnReference&&left instanceof ParameterExpression&&left.name.value===parameterName)try{return{operator:normalizeScalarOperator(predicate.operator.value),target:normalizeColumnReferenceText(right)}}catch{return null}return null},hasSelectQuery=value=>typeof value=="object"&&value!==null&&"selectQuery"in value,collectColumnReferencesDeep=value=>{let references=[],visited=new WeakSet,walk=candidate=>{if(!(!candidate||typeof candidate!="object")){if(candidate instanceof ColumnReference){references.push(candidate);return}if(!visited.has(candidate)){if(visited.add(candidate),Array.isArray(candidate)){for(let item of candidate)walk(item);return}for(let child of Object.values(candidate))walk(child)}}};return walk(value),references},getExistsBranchKind=(expression,parameterName)=>{let meaningfulTerms=collectTopLevelOrTerms2(expression).filter(term=>getGuardedParameterName2(term)!==parameterName);if(meaningfulTerms.length!==1)return null;let predicate=unwrapParens(meaningfulTerms[0]),isInlineQueryValue=value=>value instanceof InlineQuery||hasSelectQuery(value);if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="exists")return isInlineQueryValue(unwrapParens(predicate.expression))?"exists":null;if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not exists")return isInlineQueryValue(unwrapParens(predicate.expression))?"not-exists":null;if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not"&&unwrapParens(predicate.expression)instanceof UnaryExpression){let nested=unwrapParens(predicate.expression);if(nested.operator.value.trim().toLowerCase()==="exists"&&isInlineQueryValue(unwrapParens(nested.expression)))return"not-exists"}return null},getExistsPredicateDetails=(expression,parameterName)=>{let meaningfulTerms=collectTopLevelOrTerms2(expression).filter(term=>getGuardedParameterName2(term)!==parameterName);if(meaningfulTerms.length!==1)return null;let predicate=unwrapParens(meaningfulTerms[0]),isInlineQueryValue=value=>value instanceof InlineQuery||hasSelectQuery(value);if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="exists"){let candidate=unwrapParens(predicate.expression);return isInlineQueryValue(candidate)?{kind:"exists",subquery:candidate.selectQuery}:null}if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not exists"){let candidate=unwrapParens(predicate.expression);return isInlineQueryValue(candidate)?{kind:"not-exists",subquery:candidate.selectQuery}:null}if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not"&&unwrapParens(predicate.expression)instanceof UnaryExpression){let nested=unwrapParens(predicate.expression),candidate=unwrapParens(nested.expression);if(nested.operator.value.trim().toLowerCase()==="exists"&&isInlineQueryValue(candidate))return{kind:"not-exists",subquery:candidate.selectQuery}}return null},getBranchInfo=branch=>{let scalar=getScalarBranchDetails(branch.expression,branch.parameterName);if(scalar)return{parameterName:branch.parameterName,kind:"scalar",operator:scalar.operator,target:scalar.target,query:branch.query,expression:branch.expression,sql:formatSqlComponent(branch.expression)};let existsKind=getExistsBranchKind(branch.expression,branch.parameterName);return existsKind?{parameterName:branch.parameterName,kind:existsKind,query:branch.query,expression:branch.expression,sql:formatSqlComponent(branch.expression)}:{parameterName:branch.parameterName,kind:"expression",query:branch.query,expression:branch.expression,sql:formatSqlComponent(branch.expression)}},isEquivalentScalarBranch=(branch,query,parameterName,operator,targetColumnText)=>branch.query===query&&branch.kind==="scalar"&&branch.parameterName===parameterName&&branch.operator===operator&&branch.target!==void 0&&normalizeIdentifier2(branch.target)===normalizeIdentifier2(targetColumnText),SSSQLFilterBuilder=class{constructor(tableColumnResolver){this.tableColumnResolver=tableColumnResolver;this.finder=new UpstreamSelectQueryFinder(this.tableColumnResolver)}list(query){let parsed=this.parseQuery(query);return collectSupportedOptionalConditionBranches(parsed).map(getBranchInfo)}planScaffold(query,filters){if(typeof query=="string"){let entries=Object.entries(filters);if(entries.length===1){let[filterName,filterValue]=entries[0];if(isExplicitEqualityScaffoldValue(filterValue))try{return this.planScalarInsert(query,{target:filterName,parameterName:makeParameterName(filterName),operator:"="})}catch{}}}return this.planRewrite(query,parsed=>this.scaffold(parsed,filters))}dryRunScaffold(query,filters){return this.planScaffold(query,filters)}planScaffoldBranch(query,spec){if(typeof query=="string"&&(spec.kind==="exists"||spec.kind==="not-exists"))try{return this.planExistsInsert(query,spec)}catch{}if(typeof query=="string"&&spec.kind!=="exists"&&spec.kind!=="not-exists")try{return this.planScalarInsert(query,spec)}catch{}return this.planRewrite(query,parsed=>this.scaffoldBranch(parsed,spec))}dryRunScaffoldBranch(query,spec){return this.planScaffoldBranch(query,spec)}planRefresh(query,filters){if(typeof query=="string")try{let parsed=SelectQueryParser.parse(query);if(!this.refreshParsed(parsed,filters).changed)return this.buildPlanFromEdits(query,[],[],[])}catch{}return this.planRewrite(query,parsed=>this.refresh(parsed,filters))}dryRunRefresh(query,filters){return this.planRefresh(query,filters)}planRemove(query,spec){if(typeof query=="string")try{return this.planBranchRemoval(query,spec)}catch{}return this.planRewrite(query,parsed=>this.remove(parsed,spec))}dryRunRemove(query,spec){return this.planRemove(query,spec)}planRemoveAll(query){return this.planRewrite(query,parsed=>this.removeAll(parsed))}dryRunRemoveAll(query){return this.planRemoveAll(query)}scaffold(query,filters){let parsed=this.parseQuery(query);for(let[filterName,filterValue]of Object.entries(filters)){if(!isExplicitEqualityScaffoldValue(filterValue))throw new Error(`SSSQL scaffold only supports equality filters in v1. Use structured scaffold or refresh for pre-authored branches: '${filterName}'.`);this.scaffoldBranch(parsed,{target:filterName,parameterName:makeParameterName(filterName),operator:"="})}return parsed}scaffoldBranch(query,spec){let parsed=this.parseQuery(query);return spec.kind==="exists"||spec.kind==="not-exists"?(this.scaffoldExistsBranch(parsed,spec),parsed):(this.scaffoldScalarBranch(parsed,spec),parsed)}refresh(query,filters){let parsed=this.parseQuery(query);return this.refreshParsed(parsed,filters),parsed}refreshParsed(parsed,filters){let changed=!1;for(let[filterName,filterValue]of Object.entries(filters)){let parameterName=filterName,target=null,matches=collectSupportedOptionalConditionBranches(parsed).filter(branch=>branch.parameterName===parameterName);if(matches.length===0&&(target=this.resolveTarget(parsed,filterName),parameterName=target.parameterName,matches=collectSupportedOptionalConditionBranches(parsed).filter(branch=>branch.parameterName===parameterName)),matches.length===0){if(target||(target=this.resolveTarget(parsed,filterName),parameterName=target.parameterName),!isExplicitEqualityScaffoldValue(filterValue))throw new Error(`No existing SSSQL branch was found for '${filterName}', and v1 scaffold only supports equality filters.`);this.scaffoldScalarBranch(parsed,{target:filterName,parameterName:target.parameterName,operator:"="}),changed=!0;continue}if(matches.length>1)throw new Error(`Multiple SSSQL branches matched parameter ':${parameterName}'. Refresh is ambiguous.`);let[match]=matches;if(!match)continue;let correlatedPlan=this.buildCorrelatedRefreshPlan(parsed,match);if(correlatedPlan){if(correlatedPlan.target.query===match.query)continue;this.rebaseMovedBranchByAlias(match.expression,correlatedPlan.sourceAlias,correlatedPlan.target.column),rebuildWhereWithoutTerm(match.query,match.expression),correlatedPlan.target.query.appendWhere(match.expression),changed=!0;continue}!target&&(target=this.tryResolveTarget(parsed,filterName),!target)||match.query!==target.query&&(this.rebaseMovedBranch(match.expression,match.query,target.column),rebuildWhereWithoutTerm(match.query,match.expression),target.query.appendWhere(match.expression),changed=!0)}return{query:parsed,changed}}remove(query,spec){let parsed=this.parseQuery(query),matches=this.findMatchingBranchInfos(parsed,spec);if(matches.length===0)return parsed;if(matches.length>1)throw new Error(`Multiple SSSQL branches matched parameter ':${spec.parameterName}'. Remove is ambiguous.`);let[match]=matches;return match&&rebuildWhereWithoutTerm(match.query,match.expression),parsed}removeAll(query){let parsed=this.parseQuery(query),matches=this.list(parsed);for(let match of matches)rebuildWhereWithoutTerm(match.query,match.expression);return parsed}parseQuery(query){return typeof query=="string"?SelectQueryParser.parse(query):query}planScalarInsert(sourceSql,spec){let parsed=SelectQueryParser.parse(sourceSql),target=this.resolveTarget(parsed,spec.target);if(target.query!==parsed)return this.planRewrite(sourceSql,query=>this.scaffoldBranch(query,spec));let parameterName=spec.parameterName?.trim()||target.parameterName,operator=normalizeScalarOperator(spec.operator),targetColumnText=findSourceColumnReferenceText(sourceSql,target.column),branchSql=`(:${parameterName} is null or ${targetColumnText} ${operator} :${parameterName})`,normalizedBranch=normalizeSql(branchSql);return this.list(parsed).find(existing=>existing.query===target.query&&normalizeSql(existing.sql)===normalizedBranch||isEquivalentScalarBranch(existing,target.query,parameterName,operator,targetColumnText))?this.buildPlanFromEdits(sourceSql,[],[],[]):this.buildMinimalInsertPlan(sourceSql,branchSql,{branchKind:"scalar",parameterName,column:targetColumnText})}planExistsInsert(sourceSql,spec){let parameterName=spec.parameterName.trim();if(!parameterName)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires parameterName.");if(spec.anchorColumns.length===0)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires at least one anchorColumn.");let parsed=SelectQueryParser.parse(sourceSql),anchorTargets=spec.anchorColumns.map(anchorColumn=>this.resolveTarget(parsed,anchorColumn)),targetQueries=[...new Set(anchorTargets.map(target=>target.query))];if(targetQueries.length!==1)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold anchor columns must resolve within one query scope.");let targetQuery=targetQueries[0];if(targetQuery!==parsed)return this.planRewrite(sourceSql,query=>this.scaffoldBranch(query,spec));let sourceColumns=anchorTargets.map(target=>findSourceColumnReferenceText(sourceSql,target.column)),substitutedSql=substituteAnchorPlaceholders(spec.query,sourceColumns).trim();enforceSubqueryConstraints(substitutedSql);let subquery=SelectQueryParser.parse(substitutedSql),parameterNames=new Set(ParameterCollector.collect(subquery).map(parameter=>parameter.name.value));if(parameterNames.size!==1||!parameterNames.has(parameterName))throw new Error(`SSSQL ${spec.kind.toUpperCase()} scaffold query must reference only parameter ':${parameterName}'.`);let branchSql=`(:${parameterName} is null or ${spec.kind==="not-exists"?"not exists":"exists"} (${substitutedSql}))`;return this.list(parsed).find(existing=>existing.query===targetQuery&&normalizeSql(existing.sql)===normalizeSql(branchSql))?this.buildPlanFromEdits(sourceSql,[],[],[]):this.buildMinimalInsertPlan(sourceSql,branchSql,{branchKind:spec.kind,parameterName,column:sourceColumns.join(", ")})}buildMinimalInsertPlan(sourceSql,branchSql,target){let insertPosition=findMinimalWhereInsertPosition(sourceSql),prefix=`${insertPosition.position===0||!/\s/.test(sourceSql[insertPosition.position-1])?" ":""}${insertPosition.hasWhere?"and":"where"} `,suffix=insertPosition.position<getStatementEndPosition(sourceSql)?" ":"",branchLabel=target.branchKind==="scalar"?"scalar":target.branchKind,edit={start:insertPosition.position,end:insertPosition.position,before:"",after:`${prefix}${branchSql}${suffix}`,kind:"insert",reason:insertPosition.hasWhere?`Append SSSQL ${branchLabel} branch to the existing WHERE clause.`:`Create a WHERE clause for the SSSQL ${branchLabel} branch.`,target},changedRegions=[{kind:"target-branch",start:edit.start+prefix.length,end:edit.start+edit.after.length-suffix.length,message:`Inserted SSSQL ${branchLabel} optional branch.`}];return insertPosition.hasWhere?changedRegions.unshift({kind:"boolean-operator",start:edit.start,end:edit.start+prefix.length,message:`Inserted AND before the SSSQL ${branchLabel} branch.`}):changedRegions.unshift({kind:"where-keyword",start:edit.start,end:edit.start+prefix.length,message:`Inserted WHERE before the SSSQL ${branchLabel} branch.`}),this.buildPlanFromEdits(sourceSql,[edit],changedRegions,[])}planBranchRemoval(sourceSql,spec){let parsed=SelectQueryParser.parse(sourceSql),matches=this.findMatchingBranchInfos(parsed,spec);if(matches.length>1)return this.buildPlanFromEdits(sourceSql,[],[],[],[{code:"REWRITE_FAILED",message:"SSSQL remove planning found multiple matching branches.",detail:`Multiple SSSQL branches matched parameter ':${spec.parameterName}'. Remove is ambiguous.`}]);if(matches.length===0)return this.buildPlanFromEdits(sourceSql,[],[],[]);let branchSpans=findOptionalBranchSpans(sourceSql,spec.parameterName);if(branchSpans.length>1)return this.planRewrite(sourceSql,query=>this.remove(query,spec));let span=branchSpans[0];if(!span)return this.planRewrite(sourceSql,query=>this.remove(query,spec));let beforeOperator=findBooleanOperatorBefore(sourceSql,span.start),afterOperator=findBooleanOperatorAfter(sourceSql,span.end),where=findWhereBefore(sourceSql,span.start),start=span.start,end=span.end,changedRegions=[{kind:"target-branch",start:span.start,end:span.end,message:"Removed SSSQL optional branch."}];if(beforeOperator)start=beforeOperator.start,changedRegions.unshift({kind:"boolean-operator",start:beforeOperator.start,end:beforeOperator.end,message:`Removed adjacent ${beforeOperator.value.toUpperCase()} before the SSSQL branch.`});else if(afterOperator)end=afterOperator.end,changedRegions.push({kind:"boolean-operator",start:afterOperator.start,end:afterOperator.end,message:`Removed adjacent ${afterOperator.value.toUpperCase()} after the SSSQL branch.`});else if(where){for(start=where.start;end<sourceSql.length&&/\s/.test(sourceSql[end]);)end++;changedRegions.unshift({kind:"where-keyword",start:where.start,end:where.end,message:"Removed WHERE because the SSSQL branch was the only condition."})}let edit={start,end,before:sourceSql.slice(start,end),after:"",kind:"delete",reason:"Remove the targeted SSSQL optional branch from the source SQL.",target:{branchKind:matches[0].kind,parameterName:matches[0].parameterName,column:matches[0].target}};return this.buildPlanFromEdits(sourceSql,[edit],changedRegions,[])}buildPlanFromEdits(sourceSql,edits,changedRegions,warnings,errors=[]){let plannedSql=errors.length===0?applyRewriteEdits(sourceSql,edits):void 0,beforeTokens=tokenizeForRewritePlan(sourceSql),beforeComments=collectCommentFragments(sourceSql),afterTokens=plannedSql!==void 0?tokenizeForRewritePlan(plannedSql):[],afterComments=plannedSql!==void 0?collectCommentFragments(plannedSql):[],commentsPreserved=plannedSql!==void 0?commentsPreservedInOrder(beforeComments,afterComments):!1,changedOnlyTargetBranches=errors.length===0&&changedRegions.every(region=>region.kind==="target-branch"||region.kind==="where-keyword"||region.kind==="boolean-operator"||region.kind==="parentheses")&&commentsPreserved,planWarnings=[...warnings];if(plannedSql!==void 0&&applyRewriteEdits(sourceSql,edits)!==plannedSql&&(errors=[...errors,{code:"APPLY_PLAN_MISMATCH",message:"Applying SSSQL rewrite plan edits did not reproduce the planned SQL."}]),plannedSql!==void 0)try{SelectQueryParser.parse(plannedSql)}catch(error){errors=[...errors,{code:"PARSE_AFTER_FAILED",message:"The SQL produced by SSSQL rewrite planning could not be parsed.",detail:error instanceof Error?error.message:error}]}return plannedSql!==void 0&&!commentsPreserved&&planWarnings.push({code:"COMMENTS_NOT_PRESERVED",message:"One or more input SQL comments are missing or reordered after the SSSQL rewrite."}),{ok:errors.length===0,requiresFullReformat:!1,edits,sql:plannedSql,safety:{tokenCountBefore:beforeTokens.length,tokenCountAfter:afterTokens.length,tokenSequencePreserved:plannedSql!==void 0?tokenSequencesEqual(beforeTokens,afterTokens):!1,commentsPreserved,changedOnlyTargetBranches,changedRegions},warnings:planWarnings,errors}}planRewrite(query,rewrite){let warnings=[],errors=[],sourceSql=typeof query=="string"?query:formatSqlComponent(query);typeof query!="string"&&warnings.push({code:"SOURCE_SQL_UNAVAILABLE",message:"SSSQL rewrite planning received an AST, so the source SQL had to be formatter-generated before analysis."});let beforeTokens=[],beforeComments=[];try{beforeTokens=tokenizeForRewritePlan(sourceSql),beforeComments=collectCommentFragments(sourceSql)}catch(error){errors.push({code:"TOKENIZE_BEFORE_FAILED",message:"Could not tokenize the input SQL before SSSQL rewrite planning.",detail:error instanceof Error?error.message:error})}let plannedSql,afterTokens=[],afterComments=[];if(errors.length===0)try{let parsed=SelectQueryParser.parse(sourceSql),rewritten=rewrite(parsed);plannedSql=formatSqlComponent(rewritten)}catch(error){errors.push({code:"REWRITE_FAILED",message:"SSSQL rewrite planning could not produce a rewritten query.",detail:error instanceof Error?error.message:error})}if(plannedSql!==void 0){try{SelectQueryParser.parse(plannedSql)}catch(error){errors.push({code:"PARSE_AFTER_FAILED",message:"The SQL produced by SSSQL rewrite planning could not be parsed.",detail:error instanceof Error?error.message:error})}try{afterTokens=tokenizeForRewritePlan(plannedSql),afterComments=collectCommentFragments(plannedSql)}catch(error){errors.push({code:"TOKENIZE_AFTER_FAILED",message:"Could not tokenize the SQL produced by SSSQL rewrite planning.",detail:error instanceof Error?error.message:error})}}let edits=plannedSql!==void 0&&plannedSql!==sourceSql?[{start:0,end:sourceSql.length,before:sourceSql,after:plannedSql,kind:"replace",reason:"Current SSSQL rewrite planning is backed by AST rewrite plus formatter output."}]:[],changedRegions=edits.length>0?[{kind:"formatter-rewrite",start:0,end:sourceSql.length,message:"The conservative SSSQL rewrite plan requires replacing formatter output for the full SQL text."}]:[],requiresFullReformat=edits.length>0,tokenSequencePreserved=plannedSql!==void 0?tokenSequencesEqual(beforeTokens,afterTokens):!1,commentsPreserved=plannedSql!==void 0?commentsPreservedInOrder(beforeComments,afterComments):!1,changedOnlyTargetBranches=edits.length===0;return requiresFullReformat&&warnings.push({code:"FULL_REFORMAT_REQUIRED",message:"The current SSSQL rewrite plan can only represent the change as a full SQL replacement."}),plannedSql!==void 0&&!tokenSequencePreserved&&warnings.push({code:"TOKEN_SEQUENCE_CHANGED",message:"The SQL token sequence changes after the SSSQL rewrite. The conservative planner cannot prove that only target branches changed.",detail:{tokenCountBefore:beforeTokens.length,tokenCountAfter:afterTokens.length}}),plannedSql!==void 0&&!commentsPreserved&&warnings.push({code:"COMMENTS_NOT_PRESERVED",message:"One or more input SQL comments are missing or reordered after the SSSQL rewrite."}),plannedSql!==void 0&&countCommandToken(afterTokens,"as")>countCommandToken(beforeTokens,"as")&&warnings.push({code:"OPTIONAL_ALIAS_AS_ADDED",message:"The rewrite output contains more AS tokens than the input, which may indicate formatter-added aliases."}),plannedSql!==void 0&&!sourceSql.includes('"')&&plannedSql.includes('"')&&warnings.push({code:"IDENTIFIER_QUOTES_ADDED",message:"The rewrite output contains double-quoted identifiers that were not present in the input SQL."}),{ok:errors.length===0,requiresFullReformat,edits,sql:plannedSql,safety:{tokenCountBefore:beforeTokens.length,tokenCountAfter:afterTokens.length,tokenSequencePreserved,commentsPreserved,changedOnlyTargetBranches,changedRegions},warnings,errors}}findMatchingBranchInfos(root,spec){let normalizedOperator=spec.operator?normalizeScalarOperator(spec.operator):void 0,normalizedTarget=spec.target?normalizeIdentifier2(spec.target):void 0;return this.list(root).filter(branch=>!(branch.parameterName!==spec.parameterName||spec.kind&&branch.kind!==spec.kind||normalizedOperator&&branch.operator!==normalizedOperator||normalizedTarget&&(!branch.target||normalizeIdentifier2(branch.target)!==normalizedTarget)))}scaffoldScalarBranch(root,spec){let target=this.resolveTarget(root,spec.target),parameterName=spec.parameterName?.trim()||target.parameterName,operator=normalizeScalarOperator(spec.operator),branch=buildOptionalScalarBranch(target.column,parameterName,operator),branchSql=normalizeSql(formatSqlComponent(branch));this.list(root).find(existing=>existing.query===target.query&&normalizeSql(existing.sql)===branchSql)||target.query.appendWhere(branch)}scaffoldExistsBranch(root,spec){let parameterName=spec.parameterName.trim();if(!parameterName)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires parameterName.");if(spec.anchorColumns.length===0)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires at least one anchorColumn.");let anchorTargets=spec.anchorColumns.map(anchorColumn=>this.resolveTarget(root,anchorColumn)),targetQueries=[...new Set(anchorTargets.map(target=>target.query))];if(targetQueries.length!==1)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold anchor columns must resolve within one query scope.");let targetQuery=targetQueries[0],formattedColumns=anchorTargets.map(target=>formatSqlComponent(target.column)),substitutedSql=substituteAnchorPlaceholders(spec.query,formattedColumns).trim();enforceSubqueryConstraints(substitutedSql);let subquery=SelectQueryParser.parse(substitutedSql),parameterNames=new Set(ParameterCollector.collect(subquery).map(parameter=>parameter.name.value));if(parameterNames.size!==1||!parameterNames.has(parameterName))throw new Error(`SSSQL ${spec.kind.toUpperCase()} scaffold query must reference only parameter ':${parameterName}'.`);let branch=buildOptionalExistsBranch(parameterName,subquery,spec.kind),branchSql=normalizeSql(formatSqlComponent(branch));this.list(root).find(existing=>existing.query===targetQuery&&normalizeSql(existing.sql)===branchSql)||targetQuery.appendWhere(branch)}resolveTarget(root,filterName){let qualified=parseQualifiedFilterName(filterName),lookupColumn=qualified?.column??filterName.trim(),matches=[...new Set(this.finder.find(root,lookupColumn))].map(query=>this.resolveTargetInQuery(query,filterName,qualified)).filter(target=>target!==null);if(matches.length===0)throw new Error(`Could not resolve SSSQL filter target '${filterName}' in the current query graph.`);if(matches.length>1)throw new Error(`SSSQL filter target '${filterName}' is ambiguous across multiple query scopes.`);return matches[0]}resolveTargetInQuery(query,filterName,qualified){return qualified?this.resolveQualifiedTarget(query,qualified):this.resolveUnqualifiedTarget(query,filterName)}resolveQualifiedTarget(query,filterName){let alias=this.findAliasForTable(query,filterName.table);if(!alias)return null;let matches=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query).filter(entry=>entry.value instanceof ColumnReference).filter(entry=>normalizeColumnReferenceKey(entry.value)===`${normalizeIdentifier2(alias)}.${normalizeIdentifier2(filterName.column)}`);if(matches.length===0)return null;if(matches.length>1)throw new Error(`SSSQL scaffold target '${filterName.table}.${filterName.column}' resolved to multiple columns.`);return{query,column:matches[0].value,parameterName:makeParameterName(`${filterName.table}.${filterName.column}`)}}resolveUnqualifiedTarget(query,filterName){let matches=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query).filter(entry=>entry.value instanceof ColumnReference).filter(entry=>normalizeIdentifier2(entry.name)===normalizeIdentifier2(filterName));if(matches.length===0)return null;if(matches.length>1)throw new Error(`SSSQL scaffold target '${filterName}' is ambiguous. Use a qualified table.column reference.`);return{query,column:matches[0].value,parameterName:makeParameterName(filterName)}}tryResolveTarget(root,filterName){try{return this.resolveTarget(root,filterName)}catch{return null}}findAliasForTable(query,tableName){let normalizedTable=normalizeIdentifier2(tableName),matchingAliases=(query.fromClause?.getSources()??[]).map(source=>this.resolveAliasForSource(source,normalizedTable)).filter(alias=>alias!==null);if(matchingAliases.length===0)return null;if(matchingAliases.length>1)throw new Error(`SSSQL scaffold target table '${tableName}' is ambiguous in the selected query scope.`);return matchingAliases[0]}resolveAliasForSource(source,normalizedTable){if(!(source.datasource instanceof TableSource))return null;let sourceName=normalizeIdentifier2(source.datasource.getSourceName()),shortName=normalizeIdentifier2(source.datasource.table.name);return sourceName!==normalizedTable&&shortName!==normalizedTable?null:source.getAliasName()??source.datasource.table.name}buildCorrelatedRefreshPlan(root,branch){let details=getExistsPredicateDetails(branch.expression,branch.parameterName);if(!details)return null;let sourceAliases=this.collectSourceAliases(branch.query),candidatesByKey=new Map;for(let reference of new ColumnReferenceCollector().collect(details.subquery)){let namespace=normalizeIdentifier2(reference.getNamespace());if(!namespace||!sourceAliases.has(namespace))continue;let column=normalizeIdentifier2(reference.column.name),key=`${namespace}.${column}`;candidatesByKey.has(key)||candidatesByKey.set(key,{namespace,column})}let candidates=[...candidatesByKey.values()];if(candidates.length===0)throw new Error(`SSSQL refresh could not infer a correlated anchor for ':${branch.parameterName}'.`);if(candidates.length>1){let listed=candidates.map(candidate=>`${candidate.namespace}.${candidate.column}`).join(", ");throw new Error(`SSSQL refresh found multiple correlated anchor candidates for ':${branch.parameterName}' (${listed}).`)}let[anchor]=candidates;if(!anchor)throw new Error(`SSSQL refresh could not infer a correlated anchor for ':${branch.parameterName}'.`);return{target:this.resolveCorrelatedAnchorTarget(root,branch.query,anchor,branch.parameterName),sourceAlias:anchor.namespace}}collectSourceAliases(query){let aliases=new Set;for(let source of query.fromClause?.getSources()??[]){let sourceAlias=this.getSourceAlias(source);sourceAlias&&aliases.add(sourceAlias)}return aliases}resolveCorrelatedAnchorTarget(root,sourceQuery,anchor,parameterName){let sourceExpression=this.findSourceExpressionByAlias(sourceQuery,anchor.namespace,parameterName),upstreamQuery=this.resolveSourceExpressionToUpstreamQuery(root,sourceExpression,parameterName);return upstreamQuery?this.resolveAnchorTargetInQuery(upstreamQuery,anchor,parameterName):{query:sourceQuery,column:new ColumnReference(anchor.namespace,anchor.column),parameterName}}findSourceExpressionByAlias(query,alias,parameterName){let matches=(query.fromClause?.getSources()??[]).filter(source=>this.getSourceAlias(source)===alias);if(matches.length===0)throw new Error(`SSSQL refresh could not resolve correlated alias '${alias}' for ':${parameterName}'.`);if(matches.length>1)throw new Error(`SSSQL refresh found multiple correlated sources for alias '${alias}' and ':${parameterName}'.`);return matches[0]}resolveSourceExpressionToUpstreamQuery(root,source,parameterName){if(source.datasource instanceof SubQuerySource){if(source.datasource.query instanceof SimpleSelectQuery)return source.datasource.query;throw new Error(`SSSQL refresh requires a simple query anchor for ':${parameterName}'.`)}if(!(source.datasource instanceof TableSource))return null;let cteName=normalizeIdentifier2(source.datasource.table.name),cteMatches=new CTECollector().collect(root).filter(cte2=>normalizeIdentifier2(cte2.getSourceAliasName())===cteName);if(cteMatches.length===0)return null;if(cteMatches.length>1)throw new Error(`SSSQL refresh found multiple CTE anchors for ':${parameterName}' (${source.datasource.table.name}).`);let[cte]=cteMatches;if(!cte)return null;let cteQuery=cte.query;if(!(cteQuery instanceof SimpleSelectQuery))throw new Error(`SSSQL refresh requires a simple CTE anchor for ':${parameterName}'.`);return cteQuery}resolveAnchorTargetInQuery(query,anchor,parameterName){let matches=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query).filter(entry=>entry.value instanceof ColumnReference).filter(entry=>normalizeIdentifier2(entry.name)===anchor.column);if(matches.length===0)throw new Error(`SSSQL refresh could not resolve correlated anchor column '${anchor.column}' for ':${parameterName}'.`);if(matches.length>1)throw new Error(`SSSQL refresh found multiple correlated anchor columns '${anchor.column}' for ':${parameterName}'.`);return{query,column:matches[0].value,parameterName}}getSourceAlias(source){let explicitAlias=source.getAliasName();return explicitAlias?normalizeIdentifier2(explicitAlias):source.datasource instanceof TableSource?normalizeIdentifier2(source.datasource.table.name):null}rebaseMovedBranch(expression,sourceQuery,targetColumn){let targetNamespace=targetColumn.qualifiedName.namespaces?targetColumn.qualifiedName.namespaces.map(namespace=>namespace.name):null,targetColumnName=normalizeIdentifier2(targetColumn.column.name),sourceAliases=new Set(collectColumnReferencesDeep(expression).filter(reference=>normalizeIdentifier2(reference.column.name)===targetColumnName).map(reference=>normalizeIdentifier2(reference.getNamespace())).filter(namespace=>namespace.length>0));if(sourceAliases.size===0)return;if(sourceAliases.size>1){let aliases=[...sourceAliases].join(", ");throw new Error(`SSSQL refresh cannot safely rebase '${targetColumn.column.name}' across multiple aliases (${aliases}).`)}let[sourceAlias]=[...sourceAliases];if(new Set((sourceQuery.fromClause?.getSources()??[]).map(source=>source.getAliasName()).filter(alias=>typeof alias=="string").map(alias=>normalizeIdentifier2(alias))).has(sourceAlias))for(let reference of collectColumnReferencesDeep(expression))normalizeIdentifier2(reference.getNamespace())===sourceAlias&&(reference.qualifiedName.namespaces=targetNamespace?.map(namespace=>new IdentifierString(namespace))??null)}rebaseMovedBranchByAlias(expression,sourceAlias,targetColumn){let normalizedSourceAlias=normalizeIdentifier2(sourceAlias);if(!normalizedSourceAlias)return;let targetNamespace=targetColumn.qualifiedName.namespaces?targetColumn.qualifiedName.namespaces.map(namespace=>namespace.name):null;for(let reference of collectColumnReferencesDeep(expression))normalizeIdentifier2(reference.getNamespace())===normalizedSourceAlias&&(reference.qualifiedName.namespaces=targetNamespace?.map(namespace=>new IdentifierString(namespace))??null)}},scaffoldSssqlQuery=(sqlContent,filters)=>({query:new SSSQLFilterBuilder().scaffold(sqlContent,filters)}),refreshSssqlQuery=(sqlContent,filters)=>({query:new SSSQLFilterBuilder().refresh(sqlContent,filters)});var BaseDataFlowNode=class{constructor(id,label,type,shape,details){this.id=id;this.label=label;this.type=type;this.shape=shape;this.details=details}},DataSourceNode=class _DataSourceNode extends BaseDataFlowNode{constructor(id,label,type){super(id,label,type,type==="subquery"?"hexagon":"cylinder");this.annotations=new Set}addAnnotation(annotation){this.annotations.add(annotation)}hasAnnotation(annotation){return this.annotations.has(annotation)}getMermaidRepresentation(){return this.shape==="hexagon"?`${this.id}{{${this.label}}}`:`${this.id}[(${this.label})]`}static createTable(tableName){return new _DataSourceNode(`table_${tableName}`,tableName,"table")}static createCTE(cteName){return new _DataSourceNode(`cte_${cteName}`,`CTE:${cteName}`,"cte")}static createSubquery(alias){return new _DataSourceNode(`subquery_${alias}`,`SubQuery:${alias}`,"subquery")}},ProcessNode=class _ProcessNode extends BaseDataFlowNode{constructor(id,operation,context=""){let nodeId=context?`${context}_${operation.toLowerCase().replace(/\s+/g,"_")}`:operation.toLowerCase().replace(/\s+/g,"_");super(nodeId,operation,"process","hexagon")}getMermaidRepresentation(){return`${this.id}{{${this.label}}}`}static createWhere(context){return new _ProcessNode(`${context}_where`,"WHERE",context)}static createGroupBy(context){return new _ProcessNode(`${context}_group_by`,"GROUP BY",context)}static createHaving(context){return new _ProcessNode(`${context}_having`,"HAVING",context)}static createSelect(context){return new _ProcessNode(`${context}_select`,"SELECT",context)}static createOrderBy(context){return new _ProcessNode(`${context}_order_by`,"ORDER BY",context)}static createLimit(context,hasOffset=!1){let label=hasOffset?"LIMIT/OFFSET":"LIMIT";return new _ProcessNode(`${context}_limit`,label,context)}},OperationNode=class _OperationNode extends BaseDataFlowNode{constructor(id,operation,shape="diamond"){super(id,operation,"operation",shape)}getMermaidRepresentation(){switch(this.shape){case"rounded":return`${this.id}(${this.label})`;case"rectangle":return`${this.id}[${this.label}]`;case"hexagon":return`${this.id}{{${this.label}}}`;case"stadium":return`${this.id}([${this.label}])`;default:return`${this.id}{${this.label}}`}}static createJoin(joinId,joinType){let label,normalizedType=joinType.trim().toLowerCase();return normalizedType==="join"?label="INNER JOIN":normalizedType.endsWith(" join")?label=normalizedType.toUpperCase():label=normalizedType.toUpperCase()+" JOIN",new _OperationNode(`join_${joinId}`,label,"rectangle")}static createUnion(unionId,unionType="UNION ALL"){return new _OperationNode(`${unionType.toLowerCase().replace(/\s+/g,"_")}_${unionId}`,unionType.toUpperCase(),"rectangle")}static createSetOperation(operationId,operation){let normalizedOp=operation.toUpperCase(),id=`${normalizedOp.toLowerCase().replace(/\s+/g,"_")}_${operationId}`;return new _OperationNode(id,normalizedOp,"rectangle")}},OutputNode=class extends BaseDataFlowNode{constructor(context="main"){let label=context==="main"?"Final Result":`${context} Result`;super(`${context}_output`,label,"output","stadium")}getMermaidRepresentation(){return`${this.id}([${this.label}])`}};var DataFlowConnection=class _DataFlowConnection{constructor(from,to,label){this.from=from;this.to=to;this.label=label}getMermaidRepresentation(){let arrow=this.label?` -->|${this.label}| `:" --> ";return`${this.from}${arrow}${this.to}`}static create(from,to,label){return new _DataFlowConnection(from,to,label)}static createWithNullability(from,to,isNullable){let label=isNullable?"NULLABLE":"NOT NULL";return new _DataFlowConnection(from,to,label)}},DataFlowEdgeCollection=class{constructor(){this.edges=[];this.connectionSet=new Set}add(edge){let key=`${edge.from}->${edge.to}`;this.connectionSet.has(key)||(this.edges.push(edge),this.connectionSet.add(key))}addConnection(from,to,label){this.add(DataFlowConnection.create(from,to,label))}addJoinConnection(from,to,isNullable){this.add(DataFlowConnection.createWithNullability(from,to,isNullable))}hasConnection(from,to){return this.connectionSet.has(`${from}->${to}`)}getAll(){return[...this.edges]}getMermaidRepresentation(){return this.edges.map(edge=>edge.getMermaidRepresentation()).join(`
50
50
  `)}};var DataFlowGraph=class{constructor(){this.nodes=new Map;this.edges=new DataFlowEdgeCollection}addNode(node){this.nodes.set(node.id,node)}addEdge(edge){this.edges.add(edge)}addConnection(from,to,label){this.edges.addConnection(from,to,label)}hasNode(nodeId){return this.nodes.has(nodeId)}hasConnection(from,to){return this.edges.hasConnection(from,to)}getNode(nodeId){return this.nodes.get(nodeId)}getAllNodes(){return Array.from(this.nodes.values())}getAllEdges(){return this.edges.getAll()}generateMermaid(direction="TD",title){let mermaid=`flowchart ${direction}
51
51
  `;title&&(mermaid+=` %% ${title}
52
52
  `);let nodeLines=Array.from(this.nodes.values()).map(node=>` ${node.getMermaidRepresentation()}`).join(`
@@ -54,5 +54,5 @@ ${query}`}addRestorationComments(sql,targetNode,warnings){let comments=[];return
54
54
  `),this.nodes.size>0&&this.edges.getAll().length>0&&(mermaid+=`
55
55
  `);let edgeRepresentation=this.edges.getMermaidRepresentation();return edgeRepresentation&&(mermaid+=` ${edgeRepresentation}
56
56
  `),mermaid}getOrCreateTable(tableName){let nodeId=`table_${tableName}`,node=this.nodes.get(nodeId);return node||(node=DataSourceNode.createTable(tableName),this.addNode(node)),node}getOrCreateCTE(cteName){let nodeId=`cte_${cteName}`,node=this.nodes.get(nodeId);return node||(node=DataSourceNode.createCTE(cteName),this.addNode(node)),node}getOrCreateSubquery(alias){let nodeId=`subquery_${alias}`,node=this.nodes.get(nodeId);return node||(node=DataSourceNode.createSubquery(alias),this.addNode(node)),node}createProcessNode(type,context){let node=new ProcessNode(context,type);return this.addNode(node),node}createJoinNode(joinId,joinType){let node=OperationNode.createJoin(joinId,joinType);return this.addNode(node),node}createSetOperationNode(operationId,operation){let node=OperationNode.createSetOperation(operationId,operation);return this.addNode(node),node}createOutputNode(context="main"){let node=new OutputNode(context);return this.addNode(node),node}};var DataSourceHandler=class{constructor(graph){this.graph=graph}processSource(sourceExpr,cteNames,queryProcessor){if(sourceExpr.datasource instanceof TableSource)return this.processTableSource(sourceExpr.datasource,cteNames);if(sourceExpr.datasource instanceof SubQuerySource)return this.processSubquerySource(sourceExpr,cteNames,queryProcessor);throw new Error("Unsupported source type")}processTableSource(tableSource,cteNames){let tableName=tableSource.getSourceName();return cteNames.has(tableName)?this.graph.getOrCreateCTE(tableName).id:this.graph.getOrCreateTable(tableName).id}processSubquerySource(sourceExpr,cteNames,queryProcessor){let alias=sourceExpr.aliasExpression?.table.name||"subquery",subqueryNode=this.graph.getOrCreateSubquery(alias),subqueryResultId=queryProcessor(sourceExpr.datasource.query,`subquery_${alias}_internal`,cteNames);return subqueryResultId&&!this.graph.hasConnection(subqueryResultId,subqueryNode.id)&&this.graph.addConnection(subqueryResultId,subqueryNode.id),subqueryNode.id}extractTableNodeIds(fromClause,cteNames){let tableNodeIds=[],sourceExpr=fromClause.source;if(sourceExpr.datasource instanceof TableSource){let tableName=sourceExpr.datasource.getSourceName();if(cteNames.has(tableName)){let cteNode=this.graph.getOrCreateCTE(tableName);tableNodeIds.push(cteNode.id)}else{let tableNode=this.graph.getOrCreateTable(tableName);tableNodeIds.push(tableNode.id)}}if(fromClause.joins&&fromClause.joins.length>0)for(let join of fromClause.joins){let joinSourceExpr=join.source;if(joinSourceExpr.datasource instanceof TableSource){let tableName=joinSourceExpr.datasource.getSourceName();if(cteNames.has(tableName)){let cteNode=this.graph.getOrCreateCTE(tableName);tableNodeIds.push(cteNode.id)}else{let tableNode=this.graph.getOrCreateTable(tableName);tableNodeIds.push(tableNode.id)}}}return tableNodeIds}};var JoinHandler=class{constructor(graph,dataSourceHandler){this.graph=graph;this.dataSourceHandler=dataSourceHandler;this.joinIdCounter=0}resetJoinCounter(){this.joinIdCounter=0}getNextJoinId(){return String(++this.joinIdCounter)}processFromClause(fromClause,cteNames,queryProcessor){let mainSourceId=this.dataSourceHandler.processSource(fromClause.source,cteNames,queryProcessor);return fromClause.joins&&fromClause.joins.length>0?this.processJoins(fromClause.joins,mainSourceId,cteNames,queryProcessor):mainSourceId}processJoins(joins,currentNodeId,cteNames,queryProcessor){let resultNodeId=currentNodeId;for(let join of joins){let joinNodeId=this.dataSourceHandler.processSource(join.source,cteNames,queryProcessor),joinOpId=this.getNextJoinId(),joinNode=this.graph.createJoinNode(joinOpId,join.joinType.value),{leftLabel,rightLabel}=this.getJoinNullabilityLabels(join.joinType.value);resultNodeId&&!this.graph.hasConnection(resultNodeId,joinNode.id)&&this.graph.addConnection(resultNodeId,joinNode.id,leftLabel),joinNodeId&&!this.graph.hasConnection(joinNodeId,joinNode.id)&&this.graph.addConnection(joinNodeId,joinNode.id,rightLabel),resultNodeId=joinNode.id}return resultNodeId}getJoinNullabilityLabels(joinType){switch(joinType.toLowerCase()){case"left join":return{leftLabel:"NOT NULL",rightLabel:"NULLABLE"};case"right join":return{leftLabel:"NULLABLE",rightLabel:"NOT NULL"};case"inner join":case"join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};case"full join":case"full outer join":return{leftLabel:"NULLABLE",rightLabel:"NULLABLE"};case"cross join":return{leftLabel:"NOT NULL",rightLabel:"NOT NULL"};default:return{leftLabel:"",rightLabel:""}}}};var ProcessHandler=class{constructor(graph,dataSourceHandler){this.graph=graph;this.dataSourceHandler=dataSourceHandler}processQueryClauses(query,context,currentNodeId,cteNames,queryProcessor){return currentNodeId}};var CTEHandler=class{constructor(graph){this.graph=graph}processCTEs(withClause,cteNames,queryProcessor){for(let i=0;i<withClause.tables.length;i++){let cteName=withClause.tables[i].getSourceAliasName(),cteNode=this.graph.getOrCreateCTE(cteName);cteNames.add(cteName),withClause.recursive&&i===0&&cteNode.addAnnotation("recursive")}for(let i=0;i<withClause.tables.length;i++){let cte=withClause.tables[i],cteName=cte.getSourceAliasName(),cteNode=this.graph.getOrCreateCTE(cteName),cteResultId=queryProcessor(cte.query,`cte_${cteName}`,cteNames);if(cteResultId&&!this.graph.hasConnection(cteResultId,cteNode.id)){let label=withClause.recursive&&i===0?"RECURSIVE":void 0;this.graph.addConnection(cteResultId,cteNode.id,label)}}}detectRecursiveReference(query,cteName){return query.toString().toLowerCase().includes(cteName.toLowerCase())}};var QueryFlowDiagramGenerator=class _QueryFlowDiagramGenerator{constructor(){this.graph=new DataFlowGraph,this.dataSourceHandler=new DataSourceHandler(this.graph),this.joinHandler=new JoinHandler(this.graph,this.dataSourceHandler),this.processHandler=new ProcessHandler(this.graph,this.dataSourceHandler),this.cteHandler=new CTEHandler(this.graph)}generateMermaidFlow(query,options){this.graph=new DataFlowGraph,this.dataSourceHandler=new DataSourceHandler(this.graph),this.joinHandler=new JoinHandler(this.graph,this.dataSourceHandler),this.processHandler=new ProcessHandler(this.graph,this.dataSourceHandler),this.cteHandler=new CTEHandler(this.graph),this.joinHandler.resetJoinCounter();let parsedQuery=typeof query=="string"?SelectQueryParser.parse(query):query,cteNames=new Set;return this.processQuery(parsedQuery,"main",cteNames),this.graph.generateMermaid(options?.direction||"TD",options?.title)}static generate(sql){return new _QueryFlowDiagramGenerator().generateMermaidFlow(sql)}processQuery(query,context,cteNames){if(query instanceof SimpleSelectQuery)return this.processSimpleQuery(query,context,cteNames);if(query instanceof BinarySelectQuery)return this.processBinaryQuery(query,context,cteNames);throw new Error("Unsupported query type")}processSimpleQuery(query,context,cteNames){query.withClause&&this.cteHandler.processCTEs(query.withClause,cteNames,this.processQuery.bind(this));let currentNodeId="";return query.fromClause&&(query.fromClause.joins&&query.fromClause.joins.length>0?currentNodeId=this.joinHandler.processFromClause(query.fromClause,cteNames,this.processQuery.bind(this)):currentNodeId=this.dataSourceHandler.processSource(query.fromClause.source,cteNames,this.processQuery.bind(this))),currentNodeId&&(currentNodeId=this.processHandler.processQueryClauses(query,context,currentNodeId,cteNames,this.processQuery.bind(this))),this.handleOutputNode(currentNodeId,context)}processBinaryQuery(query,context,cteNames){let parts=this.flattenBinaryChain(query,query.operator.value);return parts.length>2?this.processMultiPartOperation(parts,query.operator.value,context,cteNames):this.processSimpleBinaryOperation(query,context,cteNames)}processSimpleBinaryOperation(query,context,cteNames){let leftNodeId=this.processQuery(query.left,`${context}_left`,cteNames),rightNodeId=this.processQuery(query.right,`${context}_right`,cteNames),operationId=context==="main"?"main":context.replace(/^cte_/,""),operationNode=this.graph.createSetOperationNode(operationId,query.operator.value);return leftNodeId&&!this.graph.hasConnection(leftNodeId,operationNode.id)&&this.graph.addConnection(leftNodeId,operationNode.id),rightNodeId&&!this.graph.hasConnection(rightNodeId,operationNode.id)&&this.graph.addConnection(rightNodeId,operationNode.id),operationNode.id}processMultiPartOperation(parts,operator,context,cteNames){let partNodes=[],operationId=context==="main"?"main":context.replace(/^cte_/,""),operationNode=this.graph.createSetOperationNode(operationId,operator);for(let i=0;i<parts.length;i++){let partContext=`${context}_part${i+1}`,partNodeId=this.processQuery(parts[i],partContext,cteNames);partNodes.push(partNodeId)}for(let partNodeId of partNodes)partNodeId&&!this.graph.hasConnection(partNodeId,operationNode.id)&&this.graph.addConnection(partNodeId,operationNode.id);return operationNode.id}handleOutputNode(currentNodeId,context){if(context==="main"){let outputNode=this.graph.createOutputNode(context);return currentNodeId&&this.graph.addConnection(currentNodeId,outputNode.id),outputNode.id}return currentNodeId}flattenBinaryChain(query,operator){let parts=[],collectParts=q=>{q instanceof BinarySelectQuery&&q.operator.value===operator?(collectParts(q.left),collectParts(q.right)):parts.push(q)};return collectParts(query),parts}};var SqlParamInjector=class{constructor(optionsOrResolver,options){typeof optionsOrResolver=="function"?(this.tableColumnResolver=optionsOrResolver,this.options=options||{}):(this.tableColumnResolver=void 0,this.options=optionsOrResolver||{})}inject(query,state){typeof query=="string"&&(query=SelectQueryParser.parse(query));let finder=new UpstreamSelectQueryFinder(this.tableColumnResolver,this.options),collector=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}),normalize=s=>this.options.ignoreCaseAndUnderscore?s.toLowerCase().replace(/_/g,""):s,allowedOps=["min","max","like","ilike","in","any","=","<",">","!=","<>","<=",">=","or","and","column"],stateValues=Object.values(state);if(stateValues.length>0&&stateValues.every(value=>value===void 0)&&!this.options.allowAllUndefined)throw new Error("All parameters are undefined. This would result in fetching all records. Use allowAllUndefined: true option to explicitly allow this behavior.");let qualifiedParams=[],unqualifiedParams=[];for(let[name,stateValue]of Object.entries(state))stateValue!==void 0&&(this.isQualifiedColumnName(name)?qualifiedParams.push([name,stateValue]):unqualifiedParams.push([name,stateValue]));for(let[name,stateValue]of qualifiedParams)this.processStateParameter(name,stateValue,query,finder,collector,normalize,allowedOps,injectOrConditions,injectAndConditions,injectSimpleCondition,injectComplexConditions,validateOperators);let processedQualifiedColumns=new Set;for(let[qualifiedName,_]of qualifiedParams){let parsed=this.parseQualifiedColumnName(qualifiedName);parsed&&processedQualifiedColumns.add(`${parsed.table.toLowerCase()}.${parsed.column.toLowerCase()}`)}for(let[name,stateValue]of unqualifiedParams)this.processUnqualifiedParameter(name,stateValue,query,finder,collector,normalize,allowedOps,injectOrConditions,injectAndConditions,injectSimpleCondition,injectComplexConditions,validateOperators,processedQualifiedColumns);function injectAndConditions(q,baseName,andConditions,normalize2,availableColumns){for(let i=0;i<andConditions.length;i++){let andCondition=andConditions[i],columnName=andCondition.column||baseName,entry=availableColumns.find(item=>normalize2(item.name)===normalize2(columnName));if(!entry)throw new Error(`Column '${columnName}' not found in query for AND condition`);let columnRef=entry.value;if("="in andCondition&&andCondition["="]!==void 0){let paramName=`${baseName}_and_${i}_eq`,paramExpr=new ParameterExpression(paramName,andCondition["="]);q.appendWhere(new BinaryExpression(columnRef,"=",paramExpr))}if("min"in andCondition&&andCondition.min!==void 0){let paramName=`${baseName}_and_${i}_min`,paramExpr=new ParameterExpression(paramName,andCondition.min);q.appendWhere(new BinaryExpression(columnRef,">=",paramExpr))}if("max"in andCondition&&andCondition.max!==void 0){let paramName=`${baseName}_and_${i}_max`,paramExpr=new ParameterExpression(paramName,andCondition.max);q.appendWhere(new BinaryExpression(columnRef,"<=",paramExpr))}if("like"in andCondition&&andCondition.like!==void 0){let paramName=`${baseName}_and_${i}_like`,paramExpr=new ParameterExpression(paramName,andCondition.like);q.appendWhere(new BinaryExpression(columnRef,"like",paramExpr))}if("ilike"in andCondition&&andCondition.ilike!==void 0){let paramName=`${baseName}_and_${i}_ilike`,paramExpr=new ParameterExpression(paramName,andCondition.ilike);q.appendWhere(new BinaryExpression(columnRef,"ilike",paramExpr))}if("in"in andCondition&&andCondition.in!==void 0){let prms=andCondition.in.map((v,j)=>new ParameterExpression(`${baseName}_and_${i}_in_${j}`,v));q.appendWhere(new BinaryExpression(columnRef,"in",new ParenExpression(new ValueList(prms))))}if("any"in andCondition&&andCondition.any!==void 0){let paramName=`${baseName}_and_${i}_any`,paramExpr=new ParameterExpression(paramName,andCondition.any);q.appendWhere(new BinaryExpression(columnRef,"=",new FunctionCall(null,"any",paramExpr,null)))}if("<"in andCondition&&andCondition["<"]!==void 0){let paramName=`${baseName}_and_${i}_lt`,paramExpr=new ParameterExpression(paramName,andCondition["<"]);q.appendWhere(new BinaryExpression(columnRef,"<",paramExpr))}if(">"in andCondition&&andCondition[">"]!==void 0){let paramName=`${baseName}_and_${i}_gt`,paramExpr=new ParameterExpression(paramName,andCondition[">"]);q.appendWhere(new BinaryExpression(columnRef,">",paramExpr))}if("!="in andCondition&&andCondition["!="]!==void 0){let paramName=`${baseName}_and_${i}_neq`,paramExpr=new ParameterExpression(paramName,andCondition["!="]);q.appendWhere(new BinaryExpression(columnRef,"!=",paramExpr))}if("<>"in andCondition&&andCondition["<>"]!==void 0){let paramName=`${baseName}_and_${i}_ne`,paramExpr=new ParameterExpression(paramName,andCondition["<>"]);q.appendWhere(new BinaryExpression(columnRef,"<>",paramExpr))}if("<="in andCondition&&andCondition["<="]!==void 0){let paramName=`${baseName}_and_${i}_le`,paramExpr=new ParameterExpression(paramName,andCondition["<="]);q.appendWhere(new BinaryExpression(columnRef,"<=",paramExpr))}if(">="in andCondition&&andCondition[">="]!==void 0){let paramName=`${baseName}_and_${i}_ge`,paramExpr=new ParameterExpression(paramName,andCondition[">="]);q.appendWhere(new BinaryExpression(columnRef,">=",paramExpr))}}}function injectOrConditions(q,baseName,orConditions,normalize2,availableColumns){let orExpressions=[];for(let i=0;i<orConditions.length;i++){let orCondition=orConditions[i],columnName=orCondition.column||baseName,entry=availableColumns.find(item=>normalize2(item.name)===normalize2(columnName));if(!entry)throw new Error(`Column '${columnName}' not found in query for OR condition`);let columnRef=entry.value,branchConditions=[];if("="in orCondition&&orCondition["="]!==void 0){let paramName=`${baseName}_or_${i}_eq`,paramExpr=new ParameterExpression(paramName,orCondition["="]);branchConditions.push(new BinaryExpression(columnRef,"=",paramExpr))}if("min"in orCondition&&orCondition.min!==void 0){let paramName=`${baseName}_or_${i}_min`,paramExpr=new ParameterExpression(paramName,orCondition.min);branchConditions.push(new BinaryExpression(columnRef,">=",paramExpr))}if("max"in orCondition&&orCondition.max!==void 0){let paramName=`${baseName}_or_${i}_max`,paramExpr=new ParameterExpression(paramName,orCondition.max);branchConditions.push(new BinaryExpression(columnRef,"<=",paramExpr))}if("like"in orCondition&&orCondition.like!==void 0){let paramName=`${baseName}_or_${i}_like`,paramExpr=new ParameterExpression(paramName,orCondition.like);branchConditions.push(new BinaryExpression(columnRef,"like",paramExpr))}if("ilike"in orCondition&&orCondition.ilike!==void 0){let paramName=`${baseName}_or_${i}_ilike`,paramExpr=new ParameterExpression(paramName,orCondition.ilike);branchConditions.push(new BinaryExpression(columnRef,"ilike",paramExpr))}if("in"in orCondition&&orCondition.in!==void 0){let prms=orCondition.in.map((v,j)=>new ParameterExpression(`${baseName}_or_${i}_in_${j}`,v));branchConditions.push(new BinaryExpression(columnRef,"in",new ParenExpression(new ValueList(prms))))}if("any"in orCondition&&orCondition.any!==void 0){let paramName=`${baseName}_or_${i}_any`,paramExpr=new ParameterExpression(paramName,orCondition.any);branchConditions.push(new BinaryExpression(columnRef,"=",new FunctionCall(null,"any",paramExpr,null)))}if("<"in orCondition&&orCondition["<"]!==void 0){let paramName=`${baseName}_or_${i}_lt`,paramExpr=new ParameterExpression(paramName,orCondition["<"]);branchConditions.push(new BinaryExpression(columnRef,"<",paramExpr))}if(">"in orCondition&&orCondition[">"]!==void 0){let paramName=`${baseName}_or_${i}_gt`,paramExpr=new ParameterExpression(paramName,orCondition[">"]);branchConditions.push(new BinaryExpression(columnRef,">",paramExpr))}if("!="in orCondition&&orCondition["!="]!==void 0){let paramName=`${baseName}_or_${i}_neq`,paramExpr=new ParameterExpression(paramName,orCondition["!="]);branchConditions.push(new BinaryExpression(columnRef,"!=",paramExpr))}if("<>"in orCondition&&orCondition["<>"]!==void 0){let paramName=`${baseName}_or_${i}_ne`,paramExpr=new ParameterExpression(paramName,orCondition["<>"]);branchConditions.push(new BinaryExpression(columnRef,"<>",paramExpr))}if("<="in orCondition&&orCondition["<="]!==void 0){let paramName=`${baseName}_or_${i}_le`,paramExpr=new ParameterExpression(paramName,orCondition["<="]);branchConditions.push(new BinaryExpression(columnRef,"<=",paramExpr))}if(">="in orCondition&&orCondition[">="]!==void 0){let paramName=`${baseName}_or_${i}_ge`,paramExpr=new ParameterExpression(paramName,orCondition[">="]);branchConditions.push(new BinaryExpression(columnRef,">=",paramExpr))}if(branchConditions.length>0){let branchExpr=branchConditions[0];for(let j=1;j<branchConditions.length;j++)branchExpr=new BinaryExpression(branchExpr,"and",branchConditions[j]);branchConditions.length>1?orExpressions.push(new ParenExpression(branchExpr)):orExpressions.push(branchExpr)}}if(orExpressions.length>0){let finalOrExpr=orExpressions[0];for(let i=1;i<orExpressions.length;i++)finalOrExpr=new BinaryExpression(finalOrExpr,"or",orExpressions[i]);q.appendWhere(new ParenExpression(finalOrExpr))}}function validateOperators(stateValue,allowedOps2,name){Object.keys(stateValue).forEach(op=>{if(!allowedOps2.includes(op))throw new Error(`Unsupported operator '${op}' for state key '${name}'`)})}function injectSimpleCondition(q,columnRef,name,stateValue){let paramExpr=new ParameterExpression(name,stateValue);q.appendWhere(new BinaryExpression(columnRef,"=",paramExpr))}function injectComplexConditions(q,columnRef,name,stateValue){let conditions=[];if("="in stateValue){let paramEq=new ParameterExpression(name,stateValue["="]);conditions.push(new BinaryExpression(columnRef,"=",paramEq))}if("min"in stateValue){let paramMin=new ParameterExpression(name+"_min",stateValue.min);conditions.push(new BinaryExpression(columnRef,">=",paramMin))}if("max"in stateValue){let paramMax=new ParameterExpression(name+"_max",stateValue.max);conditions.push(new BinaryExpression(columnRef,"<=",paramMax))}if("like"in stateValue){let paramLike=new ParameterExpression(name+"_like",stateValue.like);conditions.push(new BinaryExpression(columnRef,"like",paramLike))}if("ilike"in stateValue){let paramIlike=new ParameterExpression(name+"_ilike",stateValue.ilike);conditions.push(new BinaryExpression(columnRef,"ilike",paramIlike))}if("in"in stateValue){let prms=stateValue.in.map((v,i)=>new ParameterExpression(`${name}_in_${i}`,v));conditions.push(new BinaryExpression(columnRef,"in",new ParenExpression(new ValueList(prms))))}if("any"in stateValue){let paramAny=new ParameterExpression(name+"_any",stateValue.any);conditions.push(new BinaryExpression(columnRef,"=",new FunctionCall(null,"any",paramAny,null)))}if("<"in stateValue){let paramLT=new ParameterExpression(name+"_lt",stateValue["<"]);conditions.push(new BinaryExpression(columnRef,"<",paramLT))}if(">"in stateValue){let paramGT=new ParameterExpression(name+"_gt",stateValue[">"]);conditions.push(new BinaryExpression(columnRef,">",paramGT))}if("!="in stateValue){let paramNEQ=new ParameterExpression(name+"_neq",stateValue["!="]);conditions.push(new BinaryExpression(columnRef,"!=",paramNEQ))}if("<>"in stateValue){let paramNE=new ParameterExpression(name+"_ne",stateValue["<>"]);conditions.push(new BinaryExpression(columnRef,"<>",paramNE))}if("<="in stateValue){let paramLE=new ParameterExpression(name+"_le",stateValue["<="]);conditions.push(new BinaryExpression(columnRef,"<=",paramLE))}if(">="in stateValue){let paramGE=new ParameterExpression(name+"_ge",stateValue[">="]);conditions.push(new BinaryExpression(columnRef,">=",paramGE))}if(conditions.length===1)q.appendWhere(conditions[0]);else if(conditions.length>1){let combinedExpr=conditions[0];for(let i=1;i<conditions.length;i++)combinedExpr=new BinaryExpression(combinedExpr,"and",conditions[i]);q.appendWhere(new ParenExpression(combinedExpr))}}return query}isOrCondition(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)&&"or"in value}isAndCondition(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)&&"and"in value}isExplicitColumnMapping(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)&&"column"in value&&!("or"in value)}isValidatableObject(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)&&Object.getPrototypeOf(value)===Object.prototype}parseQualifiedColumnName(qualifiedName){let parts=qualifiedName.split(".");return parts.length===2&&parts[0].trim()&&parts[1].trim()?{table:parts[0].trim(),column:parts[1].trim()}:null}isQualifiedColumnName(name){return name.includes(".")&&this.parseQualifiedColumnName(name)!==null}sanitizeParameterName(name){return name.replace(/\./g,"_")}hasColumnMapping(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)&&"column"in value}isSimpleValue(value){return value===null||typeof value!="object"||Array.isArray(value)||value instanceof Date}processStateParameter(name,stateValue,query,finder,collector,normalize,allowedOps,injectOrConditions,injectAndConditions,injectSimpleCondition,injectComplexConditions,validateOperators){if(this.isOrCondition(stateValue)){let orConditions=stateValue.or;if(orConditions&&orConditions.length>0){let targetQuery=this.findTargetQueryForLogicalCondition(finder,query,name,orConditions),allColumns=this.getAllAvailableColumns(targetQuery,collector);injectOrConditions(targetQuery,name,orConditions,normalize,allColumns);return}}if(this.isAndCondition(stateValue)){let andConditions=stateValue.and;if(andConditions&&andConditions.length>0){let targetQuery=this.findTargetQueryForLogicalCondition(finder,query,name,andConditions),allColumns=this.getAllAvailableColumns(targetQuery,collector);injectAndConditions(targetQuery,name,andConditions,normalize,allColumns);return}}if(this.isExplicitColumnMapping(stateValue)){let explicitColumnName=stateValue.column;if(explicitColumnName){let queries=finder.find(query,explicitColumnName);if(queries.length===0)throw new Error(`Explicit column '${explicitColumnName}' not found in query`);for(let q of queries){let entry=this.getAllAvailableColumns(q,collector).find(item=>normalize(item.name)===normalize(explicitColumnName));if(!entry)throw new Error(`Explicit column '${explicitColumnName}' not found in query`);this.isValidatableObject(stateValue)&&validateOperators(stateValue,allowedOps,name),injectComplexConditions(q,entry.value,name,stateValue)}return}}this.processRegularColumnCondition(name,stateValue,query,finder,collector,normalize,allowedOps,injectSimpleCondition,injectComplexConditions,validateOperators)}processUnqualifiedParameter(name,stateValue,query,finder,collector,normalize,allowedOps,injectOrConditions,injectAndConditions,injectSimpleCondition,injectComplexConditions,validateOperators,processedQualifiedColumns){if(this.isOrCondition(stateValue)){let orConditions=stateValue.or;if(orConditions&&orConditions.length>0){let targetQuery=this.findTargetQueryForLogicalCondition(finder,query,name,orConditions),allColumns=this.getAllAvailableColumns(targetQuery,collector);injectOrConditions(targetQuery,name,orConditions,normalize,allColumns);return}}if(this.isAndCondition(stateValue)){let andConditions=stateValue.and;if(andConditions&&andConditions.length>0){let targetQuery=this.findTargetQueryForLogicalCondition(finder,query,name,andConditions),allColumns=this.getAllAvailableColumns(targetQuery,collector);injectAndConditions(targetQuery,name,andConditions,normalize,allColumns);return}}if(this.isExplicitColumnMapping(stateValue)){let explicitColumnName=stateValue.column;if(explicitColumnName){let queries2=finder.find(query,explicitColumnName);if(queries2.length===0)throw new Error(`Explicit column '${explicitColumnName}' not found in query`);for(let q of queries2){let entry=this.getAllAvailableColumns(q,collector).find(item=>normalize(item.name)===normalize(explicitColumnName));if(!entry)throw new Error(`Explicit column '${explicitColumnName}' not found in query`);this.isValidatableObject(stateValue)&&validateOperators(stateValue,allowedOps,name),injectComplexConditions(q,entry.value,name,stateValue)}return}}let queries=finder.find(query,name);if(queries.length===0){if(this.options.ignoreNonExistentColumns)return;throw new Error(`Column '${name}' not found in query`)}for(let q of queries){let allColumns=this.getAllAvailableColumns(q,collector),tableMapping=this.buildTableMapping(q),matchingColumns=allColumns.filter(item=>normalize(item.name)===normalize(name));for(let entry of matchingColumns){let skipColumn=!1;if(entry.value&&typeof entry.value.getNamespace=="function"){let namespace=entry.value.getNamespace();if(namespace){let realTableName=tableMapping.aliasToRealTable.get(namespace.toLowerCase());if(realTableName){let qualifiedKey=`${realTableName.toLowerCase()}.${name.toLowerCase()}`;processedQualifiedColumns.has(qualifiedKey)&&(skipColumn=!0)}}}if(skipColumn)continue;let columnRef=entry.value;this.isValidatableObject(stateValue)&&validateOperators(stateValue,allowedOps,name);let targetColumn=columnRef;if(this.hasColumnMapping(stateValue)){let explicitColumnName=stateValue.column;if(explicitColumnName){let explicitEntry=allColumns.find(item=>normalize(item.name)===normalize(explicitColumnName));explicitEntry&&(targetColumn=explicitEntry.value)}}this.isSimpleValue(stateValue)?injectSimpleCondition(q,targetColumn,name,stateValue):injectComplexConditions(q,targetColumn,name,stateValue)}}}processRegularColumnCondition(name,stateValue,query,finder,collector,normalize,allowedOps,injectSimpleCondition,injectComplexConditions,validateOperators){let searchColumnName=name,targetTableName;if(this.isQualifiedColumnName(name)){let parsed=this.parseQualifiedColumnName(name);parsed&&(searchColumnName=parsed.column,targetTableName=parsed.table)}let queries=finder.find(query,searchColumnName);if(queries.length===0){if(this.options.ignoreNonExistentColumns)return;throw new Error(`Column '${searchColumnName}' not found in query`)}for(let q of queries){let allColumns=this.getAllAvailableColumns(q,collector),entry;if(targetTableName){let tableMapping=this.buildTableMapping(q);if(entry=allColumns.find(item=>{if(!(normalize(item.name)===normalize(searchColumnName)))return!1;if(item.value&&typeof item.value.getNamespace=="function"){let namespace=item.value.getNamespace();if(namespace){let normalizedNamespace=normalize(namespace),normalizedTargetTable=normalize(targetTableName),realTableName=tableMapping.aliasToRealTable.get(normalizedNamespace);if(realTableName&&normalize(realTableName)===normalizedTargetTable)return!0}}return!1}),!entry){if(this.options.ignoreNonExistentColumns)continue;let tableMapping2=this.buildTableMapping(q),hasRealTable=Array.from(tableMapping2.realTableToAlias.keys()).some(realTable=>normalize(realTable)===normalize(targetTableName)),hasAliasTable=Array.from(tableMapping2.aliasToRealTable.keys()).some(alias=>normalize(alias)===normalize(targetTableName));throw!hasRealTable&&!hasAliasTable?new Error(`Column '${name}' (qualified as ${name}) not found in query`):hasAliasTable&&!hasRealTable?new Error(`Column '${name}' not found. Only real table names are allowed in qualified column references (e.g., 'users.name'), not aliases (e.g., 'u.name').`):new Error(`Column '${name}' (qualified as ${name}) not found in query`)}}else if(entry=allColumns.find(item=>normalize(item.name)===normalize(searchColumnName)),!entry)throw new Error(`Column '${searchColumnName}' not found in query`);let columnRef=entry.value;this.isValidatableObject(stateValue)&&validateOperators(stateValue,allowedOps,name);let targetColumn=columnRef;if(this.hasColumnMapping(stateValue)){let explicitColumnName=stateValue.column;if(explicitColumnName){let explicitEntry=allColumns.find(item=>normalize(item.name)===normalize(explicitColumnName));explicitEntry&&(targetColumn=explicitEntry.value)}}let parameterName=this.sanitizeParameterName(name);this.isSimpleValue(stateValue)?injectSimpleCondition(q,targetColumn,parameterName,stateValue):injectComplexConditions(q,targetColumn,parameterName,stateValue)}}findTargetQueryForLogicalCondition(finder,query,baseName,conditions){let referencedColumns=conditions.map(cond=>cond.column||baseName).filter((col,index,arr)=>arr.indexOf(col)===index);for(let colName of referencedColumns){let queries=finder.find(query,colName);if(queries.length>0)return queries[0]}let conditionType=conditions===conditions.or?"OR":"AND";throw new Error(`None of the ${conditionType} condition columns [${referencedColumns.join(", ")}] found in query`)}getAllAvailableColumns(query,collector){let columns=collector.collect(query),cteColumns=this.collectCTEColumns(query);return[...columns,...cteColumns]}collectCTEColumns(query){let cteColumns=[];if(query.withClause)for(let cte of query.withClause.tables)try{let columns=this.collectColumnsFromCteQuery(cte.query);cteColumns.push(...columns)}catch{}return cteColumns}collectColumnsFromCteQuery(query){return this.isSelectQuery(query)?this.collectColumnsFromSelectQuery(query):this.collectColumnsFromReturning(query)}collectColumnsFromSelectQuery(query){return query instanceof SimpleSelectQuery?new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query):query instanceof BinarySelectQuery?this.collectColumnsFromSelectQuery(query.left):[]}collectColumnsFromReturning(query){if(query instanceof InsertQuery||query instanceof UpdateQuery||query instanceof DeleteQuery||query instanceof MergeQuery){if(!query.returningClause)return[];let columns=[];for(let item of query.returningClause.items){let columnName=item.identifier?.name??this.extractColumnName(item);columnName&&columns.push({name:columnName,value:item.value})}return columns}return[]}extractColumnName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}buildTableMapping(query){let aliasToRealTable=new Map,realTableToAlias=new Map;try{if(query.fromClause&&(this.processSourceForMapping(query.fromClause.source,aliasToRealTable,realTableToAlias),query.fromClause.joins))for(let join of query.fromClause.joins)this.processSourceForMapping(join.source,aliasToRealTable,realTableToAlias);if(query.withClause)for(let cte of query.withClause.tables){let cteAlias=cte.getSourceAliasName();cteAlias&&(aliasToRealTable.set(cteAlias.toLowerCase(),cteAlias),realTableToAlias.set(cteAlias.toLowerCase(),cteAlias))}}catch{}return{aliasToRealTable,realTableToAlias}}processSourceForMapping(source,aliasToRealTable,realTableToAlias){try{if(source.datasource instanceof TableSource){let realTableName=source.datasource.getSourceName(),aliasName=source.aliasExpression?.table?.name||realTableName;realTableName&&aliasName&&(aliasToRealTable.set(aliasName.toLowerCase(),realTableName),realTableToAlias.set(realTableName.toLowerCase(),aliasName),aliasName===realTableName&&aliasToRealTable.set(realTableName.toLowerCase(),realTableName))}}catch{}}};var SchemaManager=class{constructor(schemas){this.schemas=schemas,this.validateSchemas()}validateSchemas(){let tableNames=Object.keys(this.schemas),errors=[];if(Object.entries(this.schemas).forEach(([tableName,table])=>{Object.entries(table.columns).filter(([_,col])=>col.isPrimaryKey).map(([name,_])=>name).length===0&&errors.push(`Table '${tableName}' has no primary key defined`),table.relationships?.forEach(rel=>{tableNames.includes(rel.table)||errors.push(`Table '${tableName}' references unknown table '${rel.table}' in relationship`)})}),errors.length>0)throw new Error(`Schema validation failed:\\n${errors.join("\\n")}`)}getTableColumns(tableName){let table=this.schemas[tableName];return table?Object.keys(table.columns):[]}createTableColumnResolver(){return tableName=>this.getTableColumns(tableName)}getTableNames(){return Object.keys(this.schemas)}getTable(tableName){return this.schemas[tableName]}getPrimaryKey(tableName){let table=this.schemas[tableName];if(!table)return;let primaryKeyEntry=Object.entries(table.columns).find(([_,col])=>col.isPrimaryKey);return primaryKeyEntry?primaryKeyEntry[0]:void 0}getForeignKeys(tableName){let table=this.schemas[tableName];if(!table)return[];let foreignKeys=[];return Object.entries(table.columns).forEach(([columnName,column])=>{column.foreignKey&&foreignKeys.push({column:columnName,referencedTable:column.foreignKey.table,referencedColumn:column.foreignKey.column})}),foreignKeys}};function createSchemaManager(schemas){return new SchemaManager(schemas)}function createTableColumnResolver(schemas){return new SchemaManager(schemas).createTableColumnResolver()}function buildRelationGraphFromCreateTableQueries(queries){let relations=[],byChildTable=new Map,byParentTable=new Map,tableNames=new Set,seen=new Set;for(let query of queries){let childTable=normalizeRelationTableName(buildQualifiedName(query.namespaces,query.tableName.name));tableNames.add(childTable);for(let column of query.columns)for(let constraint of column.constraints){if(constraint.kind!=="references"||!constraint.reference)continue;let edge=createEdge({childTable,parentTable:normalizeRelationTableName(constraint.reference.targetTable.toString()),childColumns:[column.name.name],parentColumns:constraint.reference.columns?.map(item=>item.name)??[],constraintKind:"column-reference",constraintName:constraint.constraintName?.name??null,evidenceKind:"column-reference",confidence:"confirmed"});addEdge(relations,byChildTable,byParentTable,seen,tableNames,edge)}for(let constraint of query.tableConstraints){if(constraint.kind!=="foreign-key"||!constraint.reference)continue;let edge=createEdge({childTable,parentTable:normalizeRelationTableName(constraint.reference.targetTable.toString()),childColumns:constraint.columns?.map(item=>item.name)??[],parentColumns:constraint.reference.columns?.map(item=>item.name)??[],constraintKind:"table-foreign-key",constraintName:constraint.constraintName?.name??null,evidenceKind:"table-foreign-key",confidence:"confirmed"});addEdge(relations,byChildTable,byParentTable,seen,tableNames,edge)}}return{relations,byChildTable,byParentTable,tableNames}}function getOutgoingRelations(graph,childTable){return[...graph.byChildTable.get(normalizeRelationTableName(childTable))??[]]}function getIncomingRelations(graph,parentTable){return[...graph.byParentTable.get(normalizeRelationTableName(parentTable))??[]]}function addEdge(relations,byChildTable,byParentTable,seen,tableNames,edge){tableNames.add(edge.childTable),tableNames.add(edge.parentTable);let signature=[edge.childTable,edge.parentTable,edge.childColumns.join(","),edge.parentColumns.join(","),edge.constraintKind].join("|");seen.has(signature)||(seen.add(signature),relations.push(edge),pushIndexedEdge(byChildTable,edge.childTable,edge),pushIndexedEdge(byParentTable,edge.parentTable,edge))}function pushIndexedEdge(index,key,edge){let bucket=index.get(key)??[];bucket.push(edge),index.set(key,bucket)}function createEdge(params){return{childTable:params.childTable,parentTable:params.parentTable,childColumns:[...params.childColumns],parentColumns:[...params.parentColumns],constraintKind:params.constraintKind,constraintName:params.constraintName,evidenceKind:params.evidenceKind,confidence:params.confidence,isSelfReference:params.childTable===params.parentTable}}function buildQualifiedName(namespaces,name){return[...namespaces??[],name].join(".")}function normalizeRelationTableName(tableName){return normalizeTableName(tableName)}function getQualifiedNameText(value){return normalizeRelationTableName(value.toString())}var KeywordCache=class{static{this.joinSuggestionCache=new Map}static{this.commandSuggestionCache=new Map}static{this.initialized=!1}static initialize(){if(this.initialized)return;let joinPatterns=[["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"]],suggestionMap=new Map,completePhrases=new Set;joinPatterns.forEach(pattern=>{pattern.length>1&&completePhrases.add(pattern.slice(1).join(" ").toUpperCase())}),joinPatterns.forEach(pattern=>{for(let i=0;i<pattern.length-1;i++){let prefix=pattern[i];suggestionMap.has(prefix)||suggestionMap.set(prefix,new Set),joinPatterns.forEach(candidatePattern=>{if(candidatePattern.length>i+1&&candidatePattern[i]===prefix){let completePhrase=candidatePattern.slice(i+1).join(" ").toUpperCase();suggestionMap.get(prefix).add(completePhrase)}})}}),suggestionMap.forEach((suggestions,keyword)=>{this.joinSuggestionCache.set(keyword.toLowerCase(),Array.from(suggestions))}),this.initializeCommandKeywords(),this.initialized=!0}static getJoinSuggestions(keyword){return this.initialize(),this.joinSuggestionCache.get(keyword.toLowerCase())||[]}static isValidJoinKeyword(keyword){return joinkeywordParser.parse(keyword,0)!==null}static getPartialSuggestions(partialKeyword){this.initialize();let partial=partialKeyword.toLowerCase(),suggestions=[];return this.joinSuggestionCache.forEach((values,key)=>{key.startsWith(partial)&&(suggestions.push(key),values.forEach(value=>{suggestions.includes(value)||suggestions.push(value)}))}),suggestions}static getAllJoinKeywords(){this.initialize();let allKeywords=new Set;return this.joinSuggestionCache.forEach((values,key)=>{allKeywords.add(key),values.forEach(value=>allKeywords.add(value))}),Array.from(allKeywords)}static initializeCommandKeywords(){let commandPatterns=this.extractCommandPatternsFromTrie(),suggestionMap=new Map;commandPatterns.forEach(pattern=>{for(let i=0;i<pattern.length-1;i++){let prefix=pattern[i],nextWord=pattern[i+1];suggestionMap.has(prefix)||suggestionMap.set(prefix,new Set),suggestionMap.get(prefix).add(nextWord)}}),suggestionMap.forEach((suggestions,keyword)=>{this.commandSuggestionCache.set(keyword.toLowerCase(),Array.from(suggestions))})}static extractCommandPatternsFromTrie(){return[["group","by"],["order","by"],["distinct","on"],["not","materialized"],["row","only"],["rows","only"],["percent","with","ties"],["key","share"],["no","key","update"],["union","all"],["intersect","all"],["except","all"],["partition","by"],["within","group"],["with","ordinality"]]}static getCommandSuggestions(keyword){return this.initialize(),this.commandSuggestionCache.get(keyword.toLowerCase())||[]}static reset(){this.joinSuggestionCache.clear(),this.commandSuggestionCache.clear(),this.initialized=!1}};var CursorContextAnalyzer=class{static{this.patternCache=null}static getKeywordPatterns(){if(this.patternCache!==null)return this.patternCache;let requiresKeywords=new Map,suggestsTables=new Set,suggestsColumns=new Set;return this.extractKeywordPatterns(requiresKeywords,suggestsTables,suggestsColumns),this.patternCache={requiresKeywords,suggestsTables,suggestsColumns},this.patternCache}static extractKeywordPatterns(requiresKeywords,suggestsTables,suggestsColumns){let tableContexts=["from","join"],columnContexts=["select","where","on","having","by"];for(let keyword of tableContexts)this.isKeywordInDictionary(keyword)&&suggestsTables.add(keyword);for(let keyword of columnContexts)this.isKeywordInDictionary(keyword)&&suggestsColumns.add(keyword);this.extractRequiresKeywordPatterns(requiresKeywords)}static isKeywordInDictionary(keyword){return KeywordCache.isValidJoinKeyword(keyword)?!0:["from","join","select","where","on","having","by","group","order"].includes(keyword)}static extractRequiresKeywordPatterns(requiresKeywords){let potentialFirstWords=["inner","left","right","full","cross","natural","outer","group","order"];for(let word of potentialFirstWords){let possibleFollowups=this.findPossibleFollowups(word);possibleFollowups.length>0&&requiresKeywords.set(word,possibleFollowups)}}static findPossibleFollowups(word){let followups=new Set;return KeywordCache.getJoinSuggestions(word.toLowerCase()).forEach(s=>followups.add(s.toUpperCase())),KeywordCache.getCommandSuggestions(word.toLowerCase()).forEach(s=>followups.add(s.toUpperCase())),Array.from(followups)}static requiresSpecificKeywords(tokenValue){let requiredKeywords=this.getKeywordPatterns().requiresKeywords.get(tokenValue);return requiredKeywords?{suggestKeywords:!0,requiredKeywords}:null}static analyzeIntelliSense(sql,cursorPosition){try{let allLexemes=LexemeCursor.getAllLexemesWithPosition(sql),actualTokenIndex=-1,actualCurrentToken;for(let i=0;i<allLexemes.length;i++){let lexeme=allLexemes[i];if(lexeme.position){if(cursorPosition>=lexeme.position.startPosition&&cursorPosition<=lexeme.position.endPosition){actualCurrentToken=lexeme,actualTokenIndex=i;break}else if(lexeme.position.startPosition>cursorPosition){actualTokenIndex=Math.max(0,i-1),actualCurrentToken=actualTokenIndex>=0?allLexemes[actualTokenIndex]:void 0;break}}}actualTokenIndex===-1&&allLexemes.length>0&&(actualTokenIndex=allLexemes.length-1,actualCurrentToken=allLexemes[actualTokenIndex]);let previousToken=actualTokenIndex>0?allLexemes[actualTokenIndex-1]:void 0;if(this.isAfterDot(sql,cursorPosition,previousToken))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,tableScope:this.findPrecedingIdentifier(sql,cursorPosition,allLexemes),currentToken:actualCurrentToken,previousToken};if(actualCurrentToken){let currentValue=actualCurrentToken.value.toLowerCase(),keywordRequirement=this.requiresSpecificKeywords(currentValue);if(keywordRequirement)return{suggestTables:!1,suggestColumns:!1,...keywordRequirement,currentToken:actualCurrentToken,previousToken}}let tokenValue=actualCurrentToken?.value.toLowerCase(),prevValue=previousToken?.value.toLowerCase();if(tokenValue){let patterns=this.getKeywordPatterns();if(patterns.suggestsTables.has(tokenValue))return{suggestTables:!0,suggestColumns:!1,suggestKeywords:!1,currentToken:actualCurrentToken,previousToken};if(patterns.suggestsColumns.has(tokenValue))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,currentToken:actualCurrentToken,previousToken}}if(prevValue){let patterns=this.getKeywordPatterns(),keywordRequirement=this.requiresSpecificKeywords(prevValue);if(keywordRequirement&&tokenValue!=="join"&&tokenValue!=="outer"&&tokenValue!=="by")return{suggestTables:!1,suggestColumns:!1,...keywordRequirement,currentToken:actualCurrentToken,previousToken};if(patterns.suggestsTables.has(prevValue))return{suggestTables:!0,suggestColumns:!1,suggestKeywords:!1,currentToken:actualCurrentToken,previousToken};if(patterns.suggestsColumns.has(prevValue))return{suggestTables:!1,suggestColumns:!0,suggestKeywords:!1,currentToken:actualCurrentToken,previousToken}}return{suggestTables:!1,suggestColumns:!1,suggestKeywords:!0,currentToken:actualCurrentToken,previousToken}}catch{return{suggestTables:!1,suggestColumns:!1,suggestKeywords:!1}}}static analyzeIntelliSenseAt(sql,position){let charOffset=TextPositionUtils.lineColumnToCharOffset(sql,position);return charOffset===-1?{suggestTables:!1,suggestColumns:!1,suggestKeywords:!1}:this.analyzeIntelliSense(sql,charOffset)}static isAfterDot(sql,cursorPosition,previousToken){if(cursorPosition>0&&sql[cursorPosition-1]==="."||previousToken&&previousToken.value===".")return!0;let pos=cursorPosition-1;for(;pos>=0&&/\s/.test(sql[pos]);)pos--;return pos>=0&&sql[pos]==="."}static findPrecedingIdentifier(sql,cursorPosition,lexemes){if(this.isAfterDot(sql,cursorPosition)){let pos=cursorPosition-1;for(;pos>=0&&/\s/.test(sql[pos]);)pos--;if(pos>=0&&sql[pos]==="."){let identifierEnd=pos;for(;pos>=0&&/\s/.test(sql[pos]);)pos--;for(;pos>=0&&/[a-zA-Z0-9_]/.test(sql[pos]);)pos--;let identifierStart=pos+1;if(identifierStart<identifierEnd)return sql.substring(identifierStart,identifierEnd)}for(let i=lexemes.length-1;i>=0;i--)if(lexemes[i].value==="."&&lexemes[i].position&&lexemes[i].position.startPosition<cursorPosition){if(i>0&&this.isIdentifier(lexemes[i-1]))return lexemes[i-1].value;break}}}static isIdentifier(lexeme){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(lexeme.value)}};var ScopeResolver=class{static resolve(sql,cursorPosition){return this.createEmptyScope()}static resolveAt(sql,position){let charOffset=TextPositionUtils.lineColumnToCharOffset(sql,position);return charOffset===-1?this.createEmptyScope():this.resolve(sql,charOffset)}static getColumnsForTable(sql,cursorPosition,tableOrAlias){let scope=this.resolve(sql,cursorPosition),table=scope.availableTables.find(t=>t.name===tableOrAlias||t.alias===tableOrAlias);return table?scope.visibleColumns.filter(col=>col.tableName===table.name||table.alias&&col.tableAlias===table.alias):[]}static analyzeScopeFromQuery(query){let scope={availableTables:[],availableCTEs:[],subqueryLevel:0,visibleColumns:[],currentQuery:query,parentQueries:[]};if(query instanceof SimpleSelectQuery)scope.availableCTEs=this.collectCTEs(query),scope.availableTables=this.collectTablesFromQuery(query),scope.visibleColumns=this.collectVisibleColumns(scope.availableTables,scope.availableCTEs);else if(query instanceof BinarySelectQuery){let leftScope=this.analyzeScopeFromQuery(query.left),rightScope=this.analyzeScopeFromQuery(query.right);scope.availableTables=[...leftScope.availableTables,...rightScope.availableTables],scope.availableCTEs=[...leftScope.availableCTEs,...rightScope.availableCTEs],scope.visibleColumns=[...leftScope.visibleColumns,...rightScope.visibleColumns]}return scope}static collectCTEs(query){let ctes=[];if(query.withClause){let collectedCTEs=new CTECollector().collect(query);for(let cte of collectedCTEs)ctes.push({name:cte.getSourceAliasName(),query:cte.query,columns:this.extractCTEColumns(cte.query),materialized:cte.materialized||!1})}return ctes}static collectTablesFromQuery(query){let tables=[];if(query.fromClause){let fromTables=this.extractTablesFromFromClause(query.fromClause);tables.push(...fromTables)}return tables}static extractTablesFromFromClause(fromClause){let tables=[];if(fromClause.source.datasource instanceof TableSource){let table={name:this.extractTableName(fromClause.source.datasource.qualifiedName),alias:fromClause.source.aliasExpression?.table.name,schema:this.extractSchemaName(fromClause.source.datasource.qualifiedName),fullName:this.getQualifiedNameString(fromClause.source.datasource.qualifiedName),sourceType:"table"};tables.push(table)}else if(fromClause.source.datasource instanceof SubQuerySource){let table={name:fromClause.source.aliasExpression?.table.name||"subquery",alias:fromClause.source.aliasExpression?.table.name,fullName:fromClause.source.aliasExpression?.table.name||"subquery",sourceType:"subquery",originalQuery:fromClause.source.datasource.query};tables.push(table)}if(fromClause.joins)for(let join of fromClause.joins){let joinTables=this.extractTablesFromJoin(join);tables.push(...joinTables)}return tables}static extractTablesFromJoin(join){let tables=[];if(join.source.datasource instanceof TableSource){let table={name:this.extractTableName(join.source.datasource.qualifiedName),alias:join.source.aliasExpression?.table.name,schema:this.extractSchemaName(join.source.datasource.qualifiedName),fullName:this.getQualifiedNameString(join.source.datasource.qualifiedName),sourceType:"table"};tables.push(table)}else if(join.source.datasource instanceof SubQuerySource){let table={name:join.source.aliasExpression?.table.name||"subquery",alias:join.source.aliasExpression?.table.name,fullName:join.source.aliasExpression?.table.name||"subquery",sourceType:"subquery",originalQuery:join.source.datasource.query};tables.push(table)}return tables}static getQualifiedNameString(qualifiedName){return qualifiedName.toString()}static extractTableName(qualifiedName){let parts=this.getQualifiedNameString(qualifiedName).split(".");return parts[parts.length-1]}static extractSchemaName(qualifiedName){let parts=this.getQualifiedNameString(qualifiedName).split(".");return parts.length>1?parts[parts.length-2]:void 0}static extractCTEColumns(query){try{if(this.isSelectQuery(query))return query instanceof SimpleSelectQuery&&query.selectClause?this.extractColumnsFromItems(query.selectClause.items):void 0;if((query instanceof InsertQuery||query instanceof UpdateQuery||query instanceof DeleteQuery||query instanceof MergeQuery)&&query.returningClause)return this.extractColumnsFromItems(query.returningClause.items)}catch{}}static extractColumnsFromItems(items){let columns=[];for(let item of items){if(item.identifier){columns.push(item.identifier.name);continue}let columnName=this.extractColumnNameFromExpression(item.value);columnName&&columns.push(columnName)}return columns.length>0?columns:void 0}static extractColumnNameFromExpression(expression){if(expression instanceof ColumnReference)return expression.column.name;if(expression&&typeof expression=="object"&&"value"in expression)return expression.value}static isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}static collectVisibleColumns(tables,ctes){let columns=[];for(let cte of ctes)if(cte.columns)for(let columnName of cte.columns)columns.push({name:columnName,tableName:cte.name,fullReference:`${cte.name}.${columnName}`});for(let table of tables)table.sourceType==="table"&&columns.push({name:"*",tableName:table.name,tableAlias:table.alias,fullReference:`${table.alias||table.name}.*`});return columns}static createEmptyScope(){return{availableTables:[],availableCTEs:[],subqueryLevel:0,visibleColumns:[],parentQueries:[]}}};var PositionAwareParser=class{static parseToPosition(sql,cursorPosition,options={}){let charPosition=typeof cursorPosition=="number"?cursorPosition:TextPositionUtils.lineColumnToCharOffset(sql,cursorPosition);if(charPosition===-1)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};try{let normalResult=this.tryNormalParse(sql,charPosition,options);return normalResult.success?normalResult:options.errorRecovery?this.tryErrorRecovery(sql,charPosition,options):normalResult}catch(error){return{success:!1,error:error instanceof Error?error.message:String(error),stoppedAtCursor:!1}}}static parseCurrentQuery(sql,cursorPosition,options={}){let charPosition=typeof cursorPosition=="number"?cursorPosition:TextPositionUtils.lineColumnToCharOffset(sql,cursorPosition);if(charPosition===-1)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};let queryBoundaries=this.findQueryBoundaries(sql),currentQuery=this.findQueryAtPosition(queryBoundaries,charPosition);if(!currentQuery)return{success:!1,error:"No query found at cursor position",stoppedAtCursor:!1};let relativePosition=charPosition-currentQuery.start,querySQL=sql.substring(currentQuery.start,currentQuery.end);return this.parseToPosition(querySQL,relativePosition,options)}static tryNormalParse(sql,cursorPosition,options){if(cursorPosition<0||cursorPosition>sql.length)return{success:!1,error:"Invalid cursor position",stoppedAtCursor:!1};let trimmedSql=sql.trim(),appearsIncomplete=[".",",","SELECT","FROM","WHERE","JOIN","ON","GROUP BY","ORDER BY"].some(pattern=>trimmedSql.toLowerCase().endsWith(pattern.toLowerCase())),analysisResult=SelectQueryParser.analyze(sql);if(!analysisResult.success||appearsIncomplete)return{...analysisResult,success:!1};let allTokens=this.getAllTokens(sql),cursorToken=this.findTokenAtPosition(allTokens,cursorPosition),beforeCursor=this.findTokenBeforePosition(allTokens,cursorPosition);return{...analysisResult,parsedTokens:allTokens,tokenBeforeCursor:beforeCursor,stoppedAtCursor:cursorPosition<sql.length,recoveryAttempts:0}}static tryErrorRecovery(sql,cursorPosition,options){let maxAttempts=options.maxRecoveryAttempts||5,attempts=0,strategies=[()=>this.recoverWithTokenInsertion(sql,cursorPosition,options),()=>this.recoverWithTruncation(sql,cursorPosition,options),()=>this.recoverWithCompletion(sql,cursorPosition,options),()=>this.recoverWithMinimalSQL(sql,cursorPosition,options)];for(let strategy of strategies){if(attempts>=maxAttempts)break;attempts++;try{let result=strategy();if(result.success)return result.recoveryAttempts=attempts,result}catch{continue}}return{success:!1,error:"All error recovery attempts failed",recoveryAttempts:attempts,stoppedAtCursor:!1}}static recoverWithTokenInsertion(sql,cursorPosition,options){if(!options.insertMissingTokens)throw new Error("Token insertion disabled");let fixes=[{pattern:/SELECT\s*$/i,replacement:"SELECT 1 "},{pattern:/FROM\s*$/i,replacement:"FROM dual "},{pattern:/WHERE\s*$/i,replacement:"WHERE 1=1 "},{pattern:/JOIN\s*$/i,replacement:"JOIN dual ON 1=1 "},{pattern:/ON\s*$/i,replacement:"ON 1=1 "},{pattern:/GROUP\s+BY\s*$/i,replacement:"GROUP BY 1 "},{pattern:/ORDER\s+BY\s*$/i,replacement:"ORDER BY 1 "}],fixedSQL=sql;for(let fix of fixes)if(fix.pattern.test(sql)){fixedSQL=sql.replace(fix.pattern,fix.replacement);break}if(fixedSQL===sql)throw new Error("No applicable token insertion found");let result=SelectQueryParser.analyze(fixedSQL),tokens=this.getAllTokens(sql);return{...result,parsedTokens:tokens,tokenBeforeCursor:this.findTokenBeforePosition(tokens,cursorPosition),stoppedAtCursor:!0,recoveryAttempts:1}}static recoverWithTruncation(sql,cursorPosition,options){let truncated=sql.substring(0,cursorPosition),completions=[""," 1"," FROM dual"," WHERE 1=1"];for(let completion of completions)try{let testSQL=truncated+completion,result=SelectQueryParser.analyze(testSQL);if(result.success){let tokens=this.getAllTokens(sql);return{...result,parsedTokens:tokens.filter(t=>t.position&&t.position.startPosition<=cursorPosition),tokenBeforeCursor:this.findTokenBeforePosition(tokens,cursorPosition),stoppedAtCursor:!0,recoveryAttempts:1}}}catch{continue}throw new Error("Truncation recovery failed")}static recoverWithCompletion(sql,cursorPosition,options){let beforeCursor=sql.substring(0,cursorPosition),afterCursor=sql.substring(cursorPosition),completions=[{pattern:/\.\s*$/,completion:"id"},{pattern:/\w+\s*$/,completion:""},{pattern:/,\s*$/,completion:"1"},{pattern:/\(\s*$/,completion:"1)"}];for(let comp of completions)if(comp.pattern.test(beforeCursor)){let testSQL=beforeCursor+comp.completion+afterCursor;try{let result=SelectQueryParser.analyze(testSQL);if(result.success){let tokens=this.getAllTokens(sql);return{...result,parsedTokens:tokens,tokenBeforeCursor:this.findTokenBeforePosition(tokens,cursorPosition),stoppedAtCursor:!0,recoveryAttempts:1}}}catch{continue}}throw new Error("Completion recovery failed")}static recoverWithMinimalSQL(sql,cursorPosition,options){let minimalSQL="SELECT 1 FROM dual WHERE 1=1";try{let result=SelectQueryParser.analyze(minimalSQL),tokens=this.getAllTokens(sql);return{success:!0,query:result.query,parsedTokens:tokens.filter(t=>t.position&&t.position.startPosition<=cursorPosition),tokenBeforeCursor:this.findTokenBeforePosition(tokens,cursorPosition),stoppedAtCursor:!0,partialAST:result.query,recoveryAttempts:1}}catch{throw new Error("Minimal SQL recovery failed")}}static getAllTokens(sql){try{return LexemeCursor.getAllLexemesWithPosition(sql)}catch{return[]}}static findTokenAtPosition(tokens,position){return tokens.find(token=>token.position&&position>=token.position.startPosition&&position<token.position.endPosition)}static findTokenBeforePosition(tokens,position){let beforeToken;for(let token of tokens)if(token.position)if(token.position.endPosition<=position)beforeToken=token;else{if(token.position.startPosition<position)break;break}return beforeToken}static findQueryBoundaries(sql){let boundaries=[],currentStart=0,inString=!1,stringChar="",inComment=!1;for(let i=0;i<sql.length;i++){let char=sql[i],nextChar=i<sql.length-1?sql[i+1]:"";if(!inComment&&(char==="'"||char==='"')){inString?char===stringChar&&(inString=!1,stringChar=""):(inString=!0,stringChar=char);continue}if(!inString&&char==="-"&&nextChar==="-"){inComment=!0,i++;continue}if(inComment&&char===`
57
- `){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)}};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,AlterSequenceStatement,AlterTableAddColumn,AlterTableAddConstraint,AlterTableAlterColumnDefault,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,CheckpointStatement,CheckpointStatementParser,ClusterStatement,ClusterStatementParser,ColumnConstraintDefinition,ColumnReference,ColumnReferenceCollector,CommentEditor,CommentOnParser,CommentOnStatement,CommonTable,CreateIndexParser,CreateIndexStatement,CreateSchemaStatement,CreateSequenceStatement,CreateTableParser,CreateTableQuery,CursorContextAnalyzer,DDLDiffGenerator,DDLGeneralizer,DDLToFixtureConverter,DeleteClause,DeleteQuery,DeleteQueryParser,DeleteResultSelectConverter,Distinct,DistinctOn,DropConstraintParser,DropConstraintStatement,DropIndexParser,DropIndexStatement,DropSchemaStatement,DropTableParser,DropTableStatement,DuplicateCTEError,DuplicateDetectionMode,DynamicQueryBuilder,ExplainOption,ExplainStatement,FetchClause,FetchExpression,FetchType,FetchUnit,FilterableItem,FilterableItemCollector,FixtureCteBuilder,ForClause,Formatter,FromClause,FunctionCall,FunctionSource,GroupByClause,HavingClause,IdentifierString,IndexColumnDefinition,InlineQuery,InsertClause,InsertQuery,InsertQueryParser,InsertQuerySelectValuesConverter,InsertResultSelectConverter,InvalidCTENameError,JoinClause,JoinOnClause,JoinUsingClause,JsonPredicateExpression,LexemeCursor,LimitClause,LiteralValue,LockMode,MergeAction,MergeDeleteAction,MergeDoNothingAction,MergeInsertAction,MergeQuery,MergeQueryParser,MergeResultSelectConverter,MergeUpdateAction,MergeWhenClause,MultiQuerySplitter,MultiQueryUtils,NullsSortDirection,OffsetClause,OnConflictClause,OrderByClause,OrderByItem,OriginalFormatRestorer,ParameterExpression,ParameterHelper,ParenExpression,ParenSource,PartitionByClause,PositionAwareParser,QualifiedName,QueryBuilder,QueryFlowDiagramGenerator,RawString,ReferenceDefinition,ReindexStatement,ReindexStatementParser,ReturningAlias,ReturningClause,SSSQLFilterBuilder,SchemaCollector,SchemaManager,ScopeResolver,SelectClause,SelectItem,SelectQueryParser,SelectResultSelectConverter,SelectValueCollector,SelectableColumnCollector,SetClause,SetClauseItem,SimpleSelectQuery,SimulatedSelectConverter,SmartRenamer,SortDirection,SourceAliasExpression,SourceExpression,SqlComponent,SqlDialectConfiguration,SqlFormatter,SqlIdentifierRenamer,SqlPaginationInjector,SqlParamInjector,SqlParameterBinder,SqlParser,SqlSchemaValidator,SqlSortInjector,SqlTokenizer,StringSpecifierExpression,SubQuerySource,SwitchCaseArgument,TableColumnDefinition,TableConstraintDefinition,TableSchema,TableSource,TableSourceCollector,TokenType,TupleExpression,TypeValue,UnaryExpression,UpdateClause,UpdateQuery,UpdateQueryParser,UpdateResultSelectConverter,UpstreamSelectQueryFinder,UsingClause,VALID_PRESETS,VacuumStatement,VacuumStatementParser,ValueList,ValuesQuery,WhereClause,WindowFrameBound,WindowFrameBoundStatic,WindowFrameBoundaryValue,WindowFrameClause,WindowFrameExpression,WindowFrameSpec,WindowFrameType,WindowsClause,WithClause,WithClauseParser,buildRelationGraphFromCreateTableQueries,collectSupportedOptionalConditionBranchSpans,collectSupportedOptionalConditionBranches,createSchemaManager,createTableColumnResolver,createTableDefinitionFromCreateTableQuery,createTableDefinitionRegistryFromCreateTableQueries,createTableDefinitionRegistryFromSchema,getCompletionSuggestions,getCursorContext,getIncomingRelations,getIntelliSenseInfo,getOutgoingRelations,getQualifiedNameText,normalizeTableName,optimizeUnusedCtes,optimizeUnusedCtesToFixedPoint,optimizeUnusedLeftJoins,optimizeUnusedLeftJoinsToFixedPoint,parseToPosition,pruneOptionalConditionBranches,refreshSssqlQuery,resolveScope,scaffoldSssqlQuery,splitQueries,tableNameVariants};
57
+ `){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)}};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,AlterSequenceStatement,AlterTableAddColumn,AlterTableAddConstraint,AlterTableAlterColumnDefault,AlterTableDropColumn,AlterTableDropConstraint,AlterTableParser,AlterTableStatement,AnalyzeStatement,ArrayExpression,ArrayIndexExpression,ArrayQueryExpression,ArraySliceExpression,AstCommentAttachmentExtractor,BetweenExpression,BinaryExpression,BinarySelectQuery,CTECollector,CTEComposer,CTEDependencyAnalyzer,CTEDisabler,CTENormalizer,CTENotFoundError,CTEQueryDecomposer,CTERegionDetector,CTERenamer,CTETableReferenceCollector,CaseExpression,CaseKeyValuePair,CastExpression,CheckpointStatement,CheckpointStatementParser,ClauseScopedColumnReferenceCollector,ClusterStatement,ClusterStatementParser,ColumnConstraintDefinition,ColumnReference,ColumnReferenceCollector,CommentEditor,CommentOnParser,CommentOnStatement,CommonTable,CreateIndexParser,CreateIndexStatement,CreateSchemaStatement,CreateSequenceStatement,CreateTableParser,CreateTableQuery,CursorContextAnalyzer,DDLDiffGenerator,DDLGeneralizer,DDLToFixtureConverter,DeleteClause,DeleteQuery,DeleteQueryParser,DeleteResultSelectConverter,Distinct,DistinctOn,DropConstraintParser,DropConstraintStatement,DropIndexParser,DropIndexStatement,DropSchemaStatement,DropTableParser,DropTableStatement,DuplicateCTEError,DuplicateDetectionMode,DynamicQueryBuilder,ExplainOption,ExplainStatement,FetchClause,FetchExpression,FetchType,FetchUnit,FilterableItem,FilterableItemCollector,FixtureCteBuilder,ForClause,Formatter,FromClause,FunctionCall,FunctionSource,GroupByClause,HavingClause,IdentifierString,IndexColumnDefinition,InlineQuery,InsertClause,InsertQuery,InsertQueryParser,InsertQuerySelectValuesConverter,InsertResultSelectConverter,InvalidCTENameError,JoinClause,JoinOnClause,JoinUsingClause,JsonPredicateExpression,LexemeCursor,LimitClause,LiteralValue,LockMode,MergeAction,MergeDeleteAction,MergeDoNothingAction,MergeInsertAction,MergeQuery,MergeQueryParser,MergeResultSelectConverter,MergeUpdateAction,MergeWhenClause,MultiQuerySplitter,MultiQueryUtils,NamedQueryDefinitionExtractor,NullsSortDirection,OffsetClause,OnConflictClause,OrderByClause,OrderByItem,OriginalFormatRestorer,ParameterExpression,ParameterHelper,ParenExpression,ParenSource,PartitionByClause,PositionAwareParser,QualifiedName,QueryBuilder,QueryFlowDiagramGenerator,RawString,ReferenceDefinition,ReindexStatement,ReindexStatementParser,ReturningAlias,ReturningClause,SSSQLFilterBuilder,SchemaCollector,SchemaManager,ScopeResolver,SelectBodyExtractor,SelectClause,SelectItem,SelectOutputCollector,SelectQueryParser,SelectResultSelectConverter,SelectValueCollector,SelectableColumnCollector,SetClause,SetClauseItem,SimpleSelectQuery,SimulatedSelectConverter,SmartRenamer,SortDirection,SourceAliasExpression,SourceExpression,SqlComponent,SqlDialectConfiguration,SqlFormatter,SqlIdentifierRenamer,SqlPaginationInjector,SqlParamInjector,SqlParameterBinder,SqlParser,SqlSchemaValidator,SqlSortInjector,SqlTokenizer,StringSpecifierExpression,SubQuerySource,SwitchCaseArgument,TableColumnDefinition,TableConstraintDefinition,TableSchema,TableSource,TableSourceCollector,TokenType,TupleExpression,TypeValue,UnaryExpression,UpdateClause,UpdateQuery,UpdateQueryParser,UpdateResultSelectConverter,UpstreamSelectQueryFinder,UsingClause,VALID_PRESETS,VacuumStatement,VacuumStatementParser,ValueList,ValuesQuery,WhereClause,WildcardColumnInferenceCollector,WindowFrameBound,WindowFrameBoundStatic,WindowFrameBoundaryValue,WindowFrameClause,WindowFrameExpression,WindowFrameSpec,WindowFrameType,WindowsClause,WithClause,WithClauseParser,buildRelationGraphFromCreateTableQueries,collectSupportedOptionalConditionBranchSpans,collectSupportedOptionalConditionBranches,createSchemaManager,createTableColumnResolver,createTableDefinitionFromCreateTableQuery,createTableDefinitionRegistryFromCreateTableQueries,createTableDefinitionRegistryFromSchema,extractAstCommentAttachments,getCompletionSuggestions,getCursorContext,getIncomingRelations,getIntelliSenseInfo,getOutgoingRelations,getQualifiedNameText,normalizeTableName,optimizeUnusedCtes,optimizeUnusedCtesToFixedPoint,optimizeUnusedLeftJoins,optimizeUnusedLeftJoinsToFixedPoint,parseToPosition,pruneOptionalConditionBranches,refreshSssqlQuery,resolveScope,scaffoldSssqlQuery,splitQueries,tableNameVariants};
58
58
  //# sourceMappingURL=index.min.js.map