rawsql-ts 0.24.2 → 0.24.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.min.js +7 -7
- package/dist/esm/index.min.js.map +2 -2
- package/dist/esm/parsers/CommandExpressionParser.d.ts +2 -0
- package/dist/esm/parsers/CommandExpressionParser.js +49 -4
- package/dist/esm/parsers/CommandExpressionParser.js.map +1 -1
- package/dist/esm/parsers/HavingParser.js +6 -0
- package/dist/esm/parsers/HavingParser.js.map +1 -1
- package/dist/esm/parsers/JoinOnClauseParser.js +6 -0
- package/dist/esm/parsers/JoinOnClauseParser.js.map +1 -1
- package/dist/esm/parsers/LimitClauseParser.js +6 -0
- package/dist/esm/parsers/LimitClauseParser.js.map +1 -1
- package/dist/esm/parsers/OffsetClauseParser.js +6 -0
- package/dist/esm/parsers/OffsetClauseParser.js.map +1 -1
- package/dist/esm/parsers/OrderByClauseParser.d.ts +2 -0
- package/dist/esm/parsers/OrderByClauseParser.js +42 -29
- package/dist/esm/parsers/OrderByClauseParser.js.map +1 -1
- package/dist/esm/parsers/SqlPrintTokenParser.d.ts +3 -0
- package/dist/esm/parsers/SqlPrintTokenParser.js +70 -6
- package/dist/esm/parsers/SqlPrintTokenParser.js.map +1 -1
- package/dist/esm/parsers/ValueParser.js +5 -3
- package/dist/esm/parsers/ValueParser.js.map +1 -1
- package/dist/esm/transformers/SqlPrinter.d.ts +9 -0
- package/dist/esm/transformers/SqlPrinter.js +143 -5
- package/dist/esm/transformers/SqlPrinter.js.map +1 -1
- package/dist/index.min.js +7 -7
- package/dist/index.min.js.map +2 -2
- package/dist/parsers/CommandExpressionParser.js +49 -4
- package/dist/parsers/CommandExpressionParser.js.map +1 -1
- package/dist/parsers/HavingParser.js +6 -0
- package/dist/parsers/HavingParser.js.map +1 -1
- package/dist/parsers/JoinOnClauseParser.js +6 -0
- package/dist/parsers/JoinOnClauseParser.js.map +1 -1
- package/dist/parsers/LimitClauseParser.js +6 -0
- package/dist/parsers/LimitClauseParser.js.map +1 -1
- package/dist/parsers/OffsetClauseParser.js +6 -0
- package/dist/parsers/OffsetClauseParser.js.map +1 -1
- package/dist/parsers/OrderByClauseParser.js +42 -29
- package/dist/parsers/OrderByClauseParser.js.map +1 -1
- package/dist/parsers/SqlPrintTokenParser.js +71 -6
- package/dist/parsers/SqlPrintTokenParser.js.map +1 -1
- package/dist/parsers/ValueParser.js +5 -3
- package/dist/parsers/ValueParser.js.map +1 -1
- package/dist/src/parsers/CommandExpressionParser.d.ts +2 -0
- package/dist/src/parsers/OrderByClauseParser.d.ts +2 -0
- package/dist/src/parsers/SqlPrintTokenParser.d.ts +3 -0
- package/dist/src/transformers/SqlPrinter.d.ts +9 -0
- package/dist/transformers/SqlPrinter.js +143 -5
- package/dist/transformers/SqlPrinter.js.map +1 -1
- package/dist/tsconfig.browser.tsbuildinfo +1 -1
- package/package.json +1 -1
package/dist/index.min.js
CHANGED
|
@@ -7,34 +7,34 @@ ${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&¤t.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("${")&¶mName.endsWith("}")?paramName=paramName.slice(2,-1):paramName=paramName.slice(1);let value=new ParameterExpression(paramName);return idx++,{value,newIndex:idx}}};var StringSpecifierExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index,specifer=lexemes[idx].value;if(idx++,idx>=lexemes.length||lexemes[idx].type!==1)throw new Error(`Expected string literal after string specifier at index ${idx}`);let value=lexemes[idx].value;return idx++,{value:new StringSpecifierExpression(specifer,value),newIndex:idx}}};var CommandExpressionParser=class _CommandExpressionParser{static parseFromLexeme(lexemes,index){let idx=index,current=lexemes[idx];if(current.value==="case"){let caseKeywordComments=current.comments,caseKeywordPositionedComments=current.positionedComments;return idx++,this.parseCaseExpression(lexemes,idx,caseKeywordComments,caseKeywordPositionedComments)}else if(current.value==="case when"){let caseWhenKeywordComments=current.comments,caseWhenKeywordPositionedComments=current.positionedComments;return idx++,this.parseCaseWhenExpression(lexemes,idx,caseWhenKeywordComments,caseWhenKeywordPositionedComments)}return this.parseModifierUnaryExpression(lexemes,idx)}static parseModifierUnaryExpression(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&128){let command=lexemes[idx].value;idx++;let result=ValueParser.parseFromLexeme(lexemes,idx);return{value:new UnaryExpression(command,result.value),newIndex:result.newIndex}}throw new Error(`Invalid modifier unary expression at index ${idx}, Lexeme: ${lexemes[idx].value}`)}static parseCaseExpression(lexemes,index,caseKeywordComments,caseKeywordPositionedComments){let idx=index,condition=ValueParser.parseFromLexeme(lexemes,idx);idx=condition.newIndex;let switchCaseResult=this.parseSwitchCaseArgument(lexemes,idx,[]);idx=switchCaseResult.newIndex;let result=new CaseExpression(condition.value,switchCaseResult.value);return caseKeywordPositionedComments&&caseKeywordPositionedComments.length>0?result.positionedComments=caseKeywordPositionedComments:caseKeywordComments&&caseKeywordComments.length>0&&(result.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(caseKeywordComments,"before")]),{value:result,newIndex:idx}}static parseCaseWhenExpression(lexemes,index,caseWhenKeywordComments,caseWhenKeywordPositionedComments){let idx=index,casewhenResult=this.parseCaseConditionValuePair(lexemes,idx);idx=casewhenResult.newIndex;let caseWhenList=[casewhenResult.value],switchCaseResult=this.parseSwitchCaseArgument(lexemes,idx,caseWhenList);idx=switchCaseResult.newIndex;let result=new CaseExpression(null,switchCaseResult.value);return caseWhenKeywordPositionedComments&&caseWhenKeywordPositionedComments.length>0?result.positionedComments=caseWhenKeywordPositionedComments:caseWhenKeywordComments&&caseWhenKeywordComments.length>0&&(result.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(caseWhenKeywordComments,"before")]),{value:result,newIndex:idx}}static parseSwitchCaseArgument(lexemes,index,initialWhenThenList){let idx=index,whenThenList=[...initialWhenThenList];idx=this.parseAdditionalWhenClauses(lexemes,idx,whenThenList);let{elseValue,elseComments,newIndex:elseIndex}=this.parseElseClause(lexemes,idx);idx=elseIndex;let{endComments,newIndex:endIndex}=this.parseEndClause(lexemes,idx);if(idx=endIndex,whenThenList.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${idx})`);let switchCaseArg=new SwitchCaseArgument(whenThenList,elseValue);return this.applySwitchCaseComments(switchCaseArg,elseComments,endComments),{value:switchCaseArg,newIndex:idx}}static parseAdditionalWhenClauses(lexemes,index,whenThenList){let idx=index;for(;idx<lexemes.length&&this.isCommandWithValue(lexemes[idx],"when");){idx++;let whenResult=this.parseCaseConditionValuePair(lexemes,idx);idx=whenResult.newIndex,whenThenList.push(whenResult.value)}return idx}static parseElseClause(lexemes,index){let elseValue=null,elseComments=null,idx=index;if(idx<lexemes.length&&this.isCommandWithValue(lexemes[idx],"else")){elseComments=this.extractKeywordComments(lexemes[idx]),idx++;let elseResult=ValueParser.parseFromLexeme(lexemes,idx);elseValue=elseResult.value,idx=elseResult.newIndex}return{elseValue,elseComments,newIndex:idx}}static parseEndClause(lexemes,index){let idx=index,endComments=null;if(idx<lexemes.length&&this.isCommandWithValue(lexemes[idx],"end"))endComments=this.extractKeywordComments(lexemes[idx]),idx++;else throw new Error(`The CASE expression requires 'end' keyword at the end (index ${idx})`);return{endComments,newIndex:idx}}static extractKeywordComments(token){return{legacy:token.comments,positioned:token.positionedComments}}static applySwitchCaseComments(switchCaseArg,elseComments,endComments){let allPositionedComments=[],allLegacyComments=[];elseComments?.positioned&&elseComments.positioned.length>0&&allPositionedComments.push(...elseComments.positioned),elseComments?.legacy&&elseComments.legacy.length>0&&allLegacyComments.push(...elseComments.legacy),endComments?.positioned&&endComments.positioned.length>0&&allPositionedComments.push(...endComments.positioned),endComments?.legacy&&endComments.legacy.length>0&&allLegacyComments.push(...endComments.legacy),allPositionedComments.length>0?switchCaseArg.positionedComments=allPositionedComments:allLegacyComments.length>0&&(switchCaseArg.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(allLegacyComments,"after")])}static isCommandWithValue(lexeme,value){return(lexeme.type&128)!==0&&lexeme.value===value}static parseCaseConditionValuePair(lexemes,index){let idx=index,condition=ValueParser.parseFromLexeme(lexemes,idx);if(idx=condition.newIndex,idx>=lexemes.length||!(lexemes[idx].type&128)||lexemes[idx].value!=="then")throw new Error(`Expected 'then' after WHEN condition at index ${idx}`);let thenKeywordComments=lexemes[idx].comments,thenKeywordPositionedComments=lexemes[idx].positionedComments;idx++;let value=ValueParser.parseFromLexeme(lexemes,idx);idx=value.newIndex;let keyValuePair=new CaseKeyValuePair(condition.value,value.value);return thenKeywordPositionedComments&&thenKeywordPositionedComments.length>0?keyValuePair.positionedComments=thenKeywordPositionedComments:thenKeywordComments&&thenKeywordComments.length>0&&(keyValuePair.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(thenKeywordComments,"after")]),{value:keyValuePair,newIndex:idx}}static convertLegacyToPositioned(legacyComments,position="before"){return{position,comments:legacyComments}}};var OrderByClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The ORDER BY clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="order by")throw new Error(`Syntax error at position ${idx}: Expected 'ORDER BY' keyword but found "${lexemes[idx].value}". ORDER BY clauses must start with the ORDER BY keywords.`);idx++;let items=[],item=this.parseItem(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=this.parseItem(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No ordering expressions found. The ORDER BY clause requires at least one expression to order by.`);return{value:new OrderByClause(items),newIndex:idx}}static parseItem(lexemes,index){let idx=index,parsedValue=ValueParser.parseFromLexeme(lexemes,idx),value=parsedValue.value;if(idx=parsedValue.newIndex,idx>=lexemes.length)return{value,newIndex:idx};let sortDirectionComments=null,sortDirection=null;if(idx<lexemes.length){let token=lexemes[idx];if(token.value==="asc"?(sortDirection="asc",idx++):token.value==="desc"&&(sortDirection="desc",idx++),sortDirection!==null){if(token.positionedComments&&token.positionedComments.length>0){sortDirectionComments=[];for(let posComment of token.positionedComments)posComment.comments&&posComment.comments.length>0&&sortDirectionComments.push(...posComment.comments)}token.comments&&token.comments.length>0&&(sortDirectionComments||(sortDirectionComments=[]),sortDirectionComments.push(...token.comments))}}let nullsSortDirection=idx>=lexemes.length?null:lexemes[idx].value==="nulls first"?(idx++,"first"):lexemes[idx].value==="nulls last"?(idx++,"last"):null;return sortDirectionComments&&sortDirectionComments.length>0&&(value.comments?value.comments.push(...sortDirectionComments):value.comments=sortDirectionComments),sortDirection===null&&nullsSortDirection===null?{value,newIndex:idx}:{value:new OrderByItem(value,sortDirection,nullsSortDirection),newIndex:idx}}};var PartitionByParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The PARTITION BY clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="partition by")throw new Error(`Syntax error at position ${idx}: Expected 'PARTITION BY' keyword but found "${lexemes[idx].value}". PARTITION BY clauses must start with the PARTITION BY keywords.`);idx++;let items=[],item=ValueParser.parseFromLexeme(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=ValueParser.parseFromLexeme(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No partition expressions found. The PARTITION BY clause requires at least one expression to partition by.`);return items.length===1?{value:new PartitionByClause(items[0]),newIndex:idx}:{value:new PartitionByClause(new ValueList(items)),newIndex:idx}}};var WindowExpressionParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The window frame expression is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].type!==4)throw new Error(`Syntax error at position ${idx}: Expected opening parenthesis '(' but found "${lexemes[idx].value}".`);idx++;let partition=null,order=null,frameSpec=null;if(idx<lexemes.length&&lexemes[idx].value==="partition by"){let partitionResult=PartitionByParser.parseFromLexeme(lexemes,idx);partition=partitionResult.value,idx=partitionResult.newIndex}if(idx<lexemes.length&&lexemes[idx].value==="order by"){let orderResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);order=orderResult.value,idx=orderResult.newIndex}if(idx<lexemes.length&&this.isFrameTypeKeyword(lexemes[idx].value)){let frameSpecResult=this.parseFrameSpec(lexemes,idx);frameSpec=frameSpecResult.value,idx=frameSpecResult.newIndex}if(idx>=lexemes.length||lexemes[idx].type!==8)throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis ')' for window frame. Each opening parenthesis must have a matching closing parenthesis.`);return idx++,{value:new WindowFrameExpression(partition,order,frameSpec),newIndex:idx}}static isFrameTypeKeyword(value){let lowerValue=value;return lowerValue==="rows"||lowerValue==="range"||lowerValue==="groups"}static parseFrameSpec(lexemes,index){let idx=index,frameTypeStr=lexemes[idx].value,frameType;switch(frameTypeStr){case"rows":frameType="rows";break;case"range":frameType="range";break;case"groups":frameType="groups";break;default:throw new Error(`Syntax error at position ${idx}: Invalid frame type "${lexemes[idx].value}". Expected one of: ROWS, RANGE, GROUPS.`)}if(idx++,idx<lexemes.length&&lexemes[idx].value==="between"){idx++;let startBoundResult=this.parseFrameBoundary(lexemes,idx),startBound=startBoundResult.value;if(idx=startBoundResult.newIndex,idx>=lexemes.length||lexemes[idx].value!=="and")throw new Error(`Syntax error at position ${idx}: Expected 'AND' keyword in BETWEEN clause.`);idx++;let endBoundResult=this.parseFrameBoundary(lexemes,idx),endBound=endBoundResult.value;return idx=endBoundResult.newIndex,{value:new WindowFrameSpec(frameType,startBound,endBound),newIndex:idx}}else{let boundaryResult=this.parseFrameBoundary(lexemes,idx),startBound=boundaryResult.value;return idx=boundaryResult.newIndex,{value:new WindowFrameSpec(frameType,startBound,null),newIndex:idx}}}static parseFrameBoundary(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&128){let currentValue=lexemes[idx].value,frameBound;switch(currentValue){case"current row":frameBound="current row";break;case"unbounded preceding":frameBound="unbounded preceding";break;case"unbounded following":frameBound="unbounded following";break;default:throw new Error(`Syntax error at position ${idx}: Invalid frame type "${lexemes[idx].value}". Expected one of: ROWS, RANGE, GROUPS.`)}return{value:new WindowFrameBoundStatic(frameBound),newIndex:idx+1}}else if(idx<lexemes.length&&lexemes[idx].type&1){let valueResult=ValueParser.parseFromLexeme(lexemes,idx);if(idx=valueResult.newIndex,idx<lexemes.length&&lexemes[idx].type&128){let direction=lexemes[idx].value,isFollowing;if(direction==="preceding")isFollowing=!1;else if(direction==="following")isFollowing=!0;else throw new Error(`Syntax error at position ${idx}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`);return idx++,{value:new WindowFrameBoundaryValue(valueResult.value,isFollowing),newIndex:idx}}else throw new Error(`Syntax error at position ${idx}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`)}throw new Error(`Syntax error at position ${idx}: Expected a valid frame boundary component.`)}};var OverExpressionParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The OVER expression is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="over")throw new Error(`Syntax error at position ${idx}: Expected 'OVER' keyword but found "${lexemes[idx].value}". OVER expressions must start with the OVER keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'OVER' keyword. Expected either a window name or an opening parenthesis '('.");if(lexemes[idx].type&64){let name=lexemes[idx].value;return idx++,{value:new IdentifierString(name),newIndex:idx}}if(lexemes[idx].type&4)return WindowExpressionParser.parseFromLexeme(lexemes,idx);throw new Error(`Syntax error at position ${idx}: Expected a window name or opening parenthesis '(' after OVER keyword, but found "${lexemes[idx].value}".`)}};var ParseError=class _ParseError extends Error{constructor(message,index,context){super(message);this.index=index;this.context=context;this.name="ParseError"}static fromUnparsedLexemes(lexemes,index,messagePrefix){let start=Math.max(0,index-2),end=Math.min(lexemes.length,index+3),context=lexemes.slice(start,end).map((lexeme,idx)=>{let marker=idx+start===index?">":" ",typeName=TokenType[lexeme.type]||lexeme.type;return`${marker} ${idx+start}:${lexeme.value} [${typeName}]`}).join(`
|
|
10
|
+
${this.getDebugPositionInfo(this.position)}`);let tokenStartPos=this.position,tokenEndPos=this.position=this.readerManager.getMaxPosition(),suffixComment=this.readComment();this.position=suffixComment.position;let prefixComments=this.mergeComments(pendingLeading,prefixComment.lines);pendingLeading=null,tokenData.push({lexeme,startPos:tokenStartPos,endPos:tokenEndPos,prefixComments,suffixComments:suffixComment.lines}),previous=lexeme}let statementEnd=this.position,lexemes=this.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&¤t.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("${")&¶mName.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(`
|
|
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&¤t.type&2&¤t.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.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,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");if(arg.namespaces)for(let i=0;i<arg.namespaces.length;i++)token.innerTokens.push(arg.namespaces[i].accept(this)),token.innerTokens.push(_SqlPrintTokenParser.DOT_TOKEN);let originalNameComments=arg.name.positionedComments,originalNameLegacyComments=arg.name.comments;arg.name.positionedComments=null,arg.name.comments=null;let nameToken=arg.name.accept(this);return token.innerTokens.push(nameToken),arg.name.positionedComments=originalNameComments,arg.name.comments=originalNameLegacyComments,(this.hasPositionedComments(arg.name)||this.hasLegacyComments(arg.name))&&this.addComponentComments(token,arg.name),this.addComponentComments(token,arg),token}visitPartitionByClause(arg){let token=new SqlPrintToken(1,"partition by","PartitionByClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.value)),token}visitOrderByClause(arg){let token=new SqlPrintToken(1,"order by","OrderByClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.order.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.order[i]));return token}visitOrderByItem(arg){let token=new SqlPrintToken(0,"","OrderByItem");return token.innerTokens.push(this.visit(arg.value)),arg.sortDirection&&arg.sortDirection!=="asc"?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"desc"))):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")))),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 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&¤t.type&2&¤t.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(`
|
|
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");return token.innerTokens.push(arg.qualifiedName.accept(this)),this.addComponentComments(token,arg),token}visitFunctionCall(arg){let token=new SqlPrintToken(0,"","FunctionCall");if(token.innerTokens.push(arg.qualifiedName.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),arg.argument&&(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),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.expression)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),innerBeforeComments.length>0){let commentBlocks=this.createCommentBlocks(innerBeforeComments),insertIndex=1;for(let commentBlock of commentBlocks)token.innerTokens.splice(insertIndex,0,commentBlock),insertIndex++}if(innerAfterComments.length>0){let commentBlocks=this.createCommentBlocks(innerAfterComments),insertIndex=token.innerTokens.length;for(let commentBlock of commentBlocks)token.innerTokens.splice(insertIndex-1,0,commentBlock)}return hasOwnComments&&(this.addPositionedCommentsToParenExpression(token,arg),arg.positionedComments=null),token}visitCastExpression(arg){let token=new SqlPrintToken(0,"","CastExpression");return this.castStyle==="postgres"?(token.innerTokens.push(this.visit(arg.input)),token.innerTokens.push(new SqlPrintToken(5,"::")),token.innerTokens.push(this.visit(arg.castType)),token):(token.innerTokens.push(new SqlPrintToken(1,"cast")),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.input)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"as")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.castType)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token)}visitCaseExpression(arg){let token=new SqlPrintToken(0,"","CaseExpression");arg.positionedComments&&arg.positionedComments.length>0&&(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null);let promotedComments=[],trailingSwitchComments=this.extractSwitchAfterComments(arg.switchCase),conditionToken=null;arg.condition&&(conditionToken=this.visit(arg.condition),promotedComments.push(...this.collectCaseLeadingCommentBlocks(conditionToken)));let switchToken=this.visit(arg.switchCase);if(promotedComments.push(...this.collectCaseLeadingCommentsFromSwitch(switchToken)),promotedComments.length>0&&token.innerTokens.push(...promotedComments),token.innerTokens.push(new SqlPrintToken(1,"case")),conditionToken&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(conditionToken)),token.innerTokens.push(switchToken),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"end")),trailingSwitchComments.length>0){token.innerTokens.push(new SqlPrintToken(12,""));let trailingBlocks=this.createCommentBlocks(trailingSwitchComments);token.innerTokens.push(...trailingBlocks)}return token}extractSwitchAfterComments(arg){if(!arg.positionedComments||arg.positionedComments.length===0)return[];let trailing=[],retained=[];for(let entry of arg.positionedComments)entry.position==="after"?trailing.push(...entry.comments):retained.push(entry);return arg.positionedComments=retained.length>0?retained:null,trailing}collectCaseLeadingCommentsFromSwitch(token){if(!token.innerTokens||token.innerTokens.length===0)return[];let pairToken=token.innerTokens.find(child=>child.containerType==="CaseKeyValuePair");if(!pairToken)return[];let keyToken=this.findCaseKeyToken(pairToken);return keyToken?this.collectCaseLeadingCommentBlocks(keyToken):[]}findCaseKeyToken(pairToken){for(let child of pairToken.innerTokens)if(child.containerType!=="CommentBlock"&&child.type!==10&&child.type!==1&&child.containerType!=="CaseThenValue")return child}collectCaseLeadingCommentBlocks(token){if(!token.innerTokens||token.innerTokens.length===0)return[];let collected=[];return this.collectCaseLeadingCommentBlocksRecursive(token,collected,new Set,0),collected}collectCaseLeadingCommentBlocksRecursive(token,collected,seen,depth){if(!token.innerTokens||token.innerTokens.length===0)return;let removedAny=!1;for(;token.innerTokens.length>0;){let first=token.innerTokens[0];if(first.containerType==="CommentBlock"){token.innerTokens.shift();let signature=this.commentBlockSignature(first);depth>0&&seen.has(signature)||(collected.push(first),seen.add(signature)),removedAny=!0;continue}if(!removedAny&&first.type===10)return;break}if(!token.innerTokens||token.innerTokens.length===0)return;let firstChild=token.innerTokens[0];this.isTransparentCaseWrapper(firstChild)&&this.collectCaseLeadingCommentBlocksRecursive(firstChild,collected,seen,depth+1)}isTransparentCaseWrapper(token){return token?["ColumnReference","QualifiedName","IdentifierString","RawString","LiteralValue","ParenExpression","UnaryExpression"].includes(token.containerType):!1}commentBlockSignature(commentBlock){return!commentBlock.innerTokens||commentBlock.innerTokens.length===0?"":commentBlock.innerTokens.filter(inner=>inner.text!=="").map(inner=>inner.text).join("|")}visitArrayExpression(arg){let token=new SqlPrintToken(0,"","ArrayExpression");return token.innerTokens.push(new SqlPrintToken(1,"array")),token.innerTokens.push(new SqlPrintToken(4,"[")),token.innerTokens.push(this.visit(arg.expression)),token.innerTokens.push(new SqlPrintToken(4,"]")),token}visitArrayQueryExpression(arg){let token=new SqlPrintToken(0,"","ArrayExpression");return token.innerTokens.push(new SqlPrintToken(1,"array")),token.innerTokens.push(new SqlPrintToken(4,"(")),token.innerTokens.push(this.visit(arg.query)),token.innerTokens.push(new SqlPrintToken(4,")")),token}visitArraySliceExpression(arg){let token=new SqlPrintToken(0,"","ArrayExpression");return token.innerTokens.push(this.visit(arg.array)),token.innerTokens.push(new SqlPrintToken(4,"[")),arg.startIndex&&token.innerTokens.push(this.visit(arg.startIndex)),token.innerTokens.push(new SqlPrintToken(5,":")),arg.endIndex&&token.innerTokens.push(this.visit(arg.endIndex)),token.innerTokens.push(new SqlPrintToken(4,"]")),token}visitArrayIndexExpression(arg){let token=new SqlPrintToken(0,"","ArrayExpression");return token.innerTokens.push(this.visit(arg.array)),token.innerTokens.push(new SqlPrintToken(4,"[")),token.innerTokens.push(this.visit(arg.index)),token.innerTokens.push(new SqlPrintToken(4,"]")),token}visitBetweenExpression(arg){let token=new SqlPrintToken(0,"","BetweenExpression");return token.innerTokens.push(this.visit(arg.expression)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),arg.negated&&(token.innerTokens.push(new SqlPrintToken(1,"not")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)),token.innerTokens.push(new SqlPrintToken(1,"between")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.lower)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"and")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.upper)),token}visitStringSpecifierExpression(arg){let specifier=arg.specifier.accept(this).text,value=arg.value.accept(this).text;return new SqlPrintToken(2,specifier+value,"StringSpecifierExpression")}visitTypeValue(arg){let token=new SqlPrintToken(0,"","TypeValue");return this.addComponentComments(token,arg),token.innerTokens.push(arg.qualifiedName.accept(this)),arg.argument&&(token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(this.visit(arg.argument)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN)),token}visitTupleExpression(arg){let token=new SqlPrintToken(0,"","TupleExpression"),requiresMultiline=this.tupleRequiresMultiline(arg);token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN);for(let i=0;i<arg.values.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.argumentCommaSpaceTokens()),token.innerTokens.push(this.visit(arg.values[i]));return requiresMultiline&&token.innerTokens.push(new SqlPrintToken(12,"","TupleExpression")),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}tupleRequiresMultiline(tuple){for(let value of tuple.values)if(this.hasInlineComments(value))return!0;return!1}hasInlineComments(component){return this.hasLeadingComments(component)?!0:component instanceof TupleExpression?this.tupleRequiresMultiline(component):!1}hasLeadingComments(component){let before=(component.positionedComments??[]).find(pc=>pc.position==="before");return!!(before&&before.comments.some(comment=>comment.trim().length>0))}visitWindowFrameExpression(arg){let token=new SqlPrintToken(0,"","WindowFrameExpression"),first=!0;return arg.partition&&(token.innerTokens.push(this.visit(arg.partition)),first=!1),arg.order&&(first?first=!1:token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.order))),arg.frameSpec&&(first?first=!1:token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.frameSpec))),token}visitWindowFrameSpec(arg){let token=new SqlPrintToken(0,"","WindowFrameSpec");return token.innerTokens.push(new SqlPrintToken(1,arg.frameType)),arg.endBound===null?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.startBound.accept(this))):(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"between")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.startBound.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"and")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.endBound.accept(this))),token}visitWindowFrameBoundaryValue(arg){let token=new SqlPrintToken(0,"","WindowFrameBoundaryValue");return token.innerTokens.push(arg.value.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.isFollowing?"following":"preceding")),token}visitWindowFrameBoundStatic(arg){return new SqlPrintToken(1,arg.bound)}visitSelectItem(arg){let token=new SqlPrintToken(0,"","SelectItem"),originalSelectItemPositionedComments=arg.positionedComments,originalValuePositionedComments=arg.value.positionedComments,isParenExpression=arg.value instanceof ParenExpression;isParenExpression||(arg.value.positionedComments=null);let beforeComments=arg.getPositionedComments("before"),afterComments=arg.getPositionedComments("after");if(beforeComments.length>0)if(arg.value instanceof CaseExpression){let commentBlocks=this.createCommentBlocks(beforeComments);token.innerTokens.push(...commentBlocks),token.innerTokens.push(new SqlPrintToken(12,""))}else{let commentTokens=this.createInlineCommentSequence(beforeComments);token.innerTokens.push(...commentTokens),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}if(token.innerTokens.push(this.visit(arg.value)),afterComments.length>0&&!isParenExpression){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(afterComments);token.innerTokens.push(...commentTokens)}if(arg.positionedComments=originalSelectItemPositionedComments,arg.value.positionedComments=originalValuePositionedComments,!arg.identifier)return token;if(arg.value instanceof ColumnReference){let defaultName=arg.value.column.name;if(arg.identifier.name===defaultName)return token}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let asKeywordPositionedComments="asKeywordPositionedComments"in arg?arg.asKeywordPositionedComments:null;if(asKeywordPositionedComments){let beforeComments2=asKeywordPositionedComments.filter(pc=>pc.position==="before");if(beforeComments2.length>0)for(let posComment of beforeComments2){let commentTokens=this.createInlineCommentSequence(posComment.comments);token.innerTokens.push(...commentTokens),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}}if(token.innerTokens.push(new SqlPrintToken(1,"as")),asKeywordPositionedComments){let afterComments2=asKeywordPositionedComments.filter(pc=>pc.position==="after");if(afterComments2.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let posComment of afterComments2){let commentTokens=this.createInlineCommentSequence(posComment.comments);token.innerTokens.push(...commentTokens)}}}let asKeywordComments="asKeywordComments"in arg?arg.asKeywordComments:null;if(asKeywordComments&&asKeywordComments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(asKeywordComments);token.innerTokens.push(...commentTokens)}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let identifierToken=this.visit(arg.identifier);token.innerTokens.push(identifierToken);let aliasPositionedComments="aliasPositionedComments"in arg?arg.aliasPositionedComments:null;if(aliasPositionedComments){let afterComments2=aliasPositionedComments.filter(pc=>pc.position==="after");if(afterComments2.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let posComment of afterComments2){let commentTokens=this.createInlineCommentSequence(posComment.comments);token.innerTokens.push(...commentTokens)}}}let aliasComments=arg.aliasComments;if(aliasComments&&aliasComments.length>0){token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);let commentTokens=this.createInlineCommentSequence(aliasComments);token.innerTokens.push(...commentTokens)}return token}visitSelectClause(arg){let token=new SqlPrintToken(1,"select","SelectClause");arg.positionedComments&&arg.positionedComments.length>0&&(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null);let selectKeywordText="select";for(let hint of arg.hints)selectKeywordText+=" "+this.visit(hint).text;if(arg.distinct){let distinctToken=arg.distinct.accept(this);if(distinctToken.innerTokens&&distinctToken.innerTokens.length>0){let distinctText=distinctToken.text;for(let innerToken of distinctToken.innerTokens)distinctText+=this.flattenTokenText(innerToken);selectKeywordText+=" "+distinctText}else selectKeywordText+=" "+distinctToken.text}token.text=selectKeywordText,token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.items.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.items[i]));return token}flattenTokenText(token){let result=token.text;if(token.innerTokens)for(let innerToken of token.innerTokens)result+=this.flattenTokenText(innerToken);return result}visitHintClause(arg){return new SqlPrintToken(2,arg.getFullHint())}visitDistinct(arg){let token=new SqlPrintToken(1,"distinct");return arg.positionedComments&&arg.positionedComments.length>0&&(this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null),token}visitDistinctOn(arg){let token=new SqlPrintToken(0,"","DistinctOn");return token.innerTokens.push(new SqlPrintToken(1,"distinct on")),token.innerTokens.push(_SqlPrintTokenParser.PAREN_OPEN_TOKEN),token.innerTokens.push(arg.value.accept(this)),token.innerTokens.push(_SqlPrintTokenParser.PAREN_CLOSE_TOKEN),token}visitTableSource(arg){let fullName="";Array.isArray(arg.namespaces)&&arg.namespaces.length>0&&(fullName=arg.namespaces.map(ns=>ns.accept(this).text).join(".")+"."),fullName+=arg.table.accept(this).text;let token=new SqlPrintToken(2,fullName);return this.addComponentComments(token,arg),arg.identifier&&(arg.identifier.name,arg.table.name),token}visitSourceExpression(arg){let token=new SqlPrintToken(0,"","SourceExpression");if(token.innerTokens.push(arg.datasource.accept(this)),!arg.aliasExpression)return token;if(arg.datasource instanceof TableSource){let defaultName=arg.datasource.table.name;return arg.aliasExpression.table.name===defaultName||(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),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),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
|
|
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;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.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),leadingCommentIndentLevel=hasRenderableLeadingComment?this.getLeadingCommentIndentLevel(parentContainerType,level):null;hasRenderableLeadingComment&&!this.isOnelineMode()&&this.shouldAddNewlineBeforeLeadingComments(parentContainerType)&&this.linePrinter.getCurrentLine().text.trim().length>0&&this.linePrinter.appendNewline(leadingCommentIndentLevel??level);for(let leading of leadingCommentContexts)leading.shouldRender&&this.appendToken(leading.token,leadingCommentIndentLevel??level,token.containerType,caseContextDepth,indentParentActive,leading.context,!1);if(this.smartCommentBlockBuilder&&token.containerType!=="CommentBlock"&&token.type!==12&&this.flushSmartCommentBlockBuilder(),this.pendingLineCommentBreak!==null){this.isOnelineMode()||this.linePrinter.appendNewline(this.pendingLineCommentBreak);let shouldSkipToken=token.type===12;if(this.pendingLineCommentBreak=null,shouldSkipToken)return}let effectiveCommentContext=commentContext??{position:"inline",isTopLevelContainer:containerIsTopLevel};if(token.containerType==="CommentBlock"){if(!this.shouldRenderComment(token,effectiveCommentContext))return;let commentLevel=this.getCommentBaseIndentLevel(level,parentContainerType);this.handleCommentBlockContainer(token,commentLevel,effectiveCommentContext);return}let current=this.linePrinter.getCurrentLine(),nextCaseContextDepth=this.isCaseContext(token.containerType)?caseContextDepth+1:caseContextDepth,shouldIndentNested=this.shouldIndentNestedParentheses(token,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===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()&¤t.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++;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;this.appendToken(child,innerLevel,token.containerType,nextCaseContextDepth,childIndentParentActive,childCommentContext,previousChildWasOpenParen),inMergePredicate&&this.mergeWhenPredicateDepth--,childIsAction&&isMergeWhenClause&&(mergePredicateActive=!1)}if(this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder(),enteredJoinOnClause&&this.joinOnClauseDepth--,token.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"){this.insideWithClause=!1,this.linePrinter.appendNewline(level);return}increasedIndent&&shouldIncreaseIndent&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&!delayIndentNewline&&this.linePrinter.appendNewline(level)}shouldAlignExplainStatementChild(parentType,childType){if(parentType!=="ExplainStatement")return!1;switch(childType){case"SimpleSelectQuery":case"InsertQuery":case"UpdateQuery":case"DeleteQuery":case"MergeQuery":return!0;default:return!1}}isCaseContext(containerType){switch(containerType){case"CaseExpression":case"CaseKeyValuePair":case"CaseThenValue":case"CaseElseValue":case"SwitchCaseArgument":return!0;default:return!1}}shouldSkipToken(token){return token.type===12?!1:(!token.innerTokens||token.innerTokens.length===0)&&token.text===""}applyKeywordCase(text){return this.keywordCase==="upper"?text.toUpperCase():this.keywordCase==="lower"?text.toLowerCase():text}handleKeywordToken(token,level,parentContainerType,caseContextDepth=0){let lower=token.text.toLowerCase();if(lower==="and"&&(this.andBreak!=="none"||this.whenOneLine&&parentContainerType==="MergeWhenClause")){this.handleAndOperatorToken(token,level,parentContainerType,caseContextDepth);return}else if(lower==="or"&&(this.orBreak!=="none"||this.whenOneLine&&parentContainerType==="MergeWhenClause")){this.handleOrOperatorToken(token,level,parentContainerType,caseContextDepth);return}let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}this.ensureSpaceBeforeKeyword(),this.linePrinter.appendText(text)}ensureSpaceBeforeKeyword(){let currentLine=this.linePrinter.getCurrentLine();currentLine.text===""||currentLine.text[currentLine.text.length-1]==="("||this.ensureTrailingSpace()}ensureTrailingSpace(){let currentLine=this.linePrinter.getCurrentLine();currentLine.text!==""&&(currentLine.text.endsWith(" ")||(currentLine.text+=" "),currentLine.text=currentLine.text.replace(/\s+$/," "))}tryAppendInsertClauseTokenText(text,parentContainerType){let currentLineText=this.linePrinter.getCurrentLine().text,result=this.onelineHelper.formatInsertClauseToken(text,parentContainerType,currentLineText,()=>this.ensureTrailingSpace());return result.handled?(result.text&&this.linePrinter.appendText(result.text),!0):!1}handleCommaToken(token,level,parentContainerType){let text=token.text,isWithinWithClause=parentContainerType==="WithClause",effectiveCommaBreak=this.onelineHelper.resolveCommaBreak(parentContainerType,this.commaBreak,this.cteCommaBreak,this.valuesCommaBreak);if(parentContainerType==="SetClause"&&(effectiveCommaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline")this.linePrinter.appendText(text);else if(this.withClauseStyle==="cte-oneline"&&isWithinWithClause)this.linePrinter.appendText(text),this.linePrinter.appendNewline(level);else if(effectiveCommaBreak==="before"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="before"&&(this.linePrinter.commaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||(this.linePrinter.appendNewline(level),this.newline===" "&&this.linePrinter.trimTrailingWhitespaceFromPreviousLine(),parentContainerType==="InsertClause"&&(this.linePrinter.getCurrentLine().level=level+1)),this.linePrinter.appendText(text),previousCommaBreak!=="before"&&(this.linePrinter.commaBreak=previousCommaBreak)}else if(effectiveCommaBreak==="after"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="after"&&(this.linePrinter.commaBreak="after"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),previousCommaBreak!=="after"&&(this.linePrinter.commaBreak=previousCommaBreak)}else if(effectiveCommaBreak==="none"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="none"&&(this.linePrinter.commaBreak="none"),this.linePrinter.appendText(text),this.onelineHelper.isInsertClauseOneline(parentContainerType)&&this.ensureTrailingSpace(),previousCommaBreak!=="none"&&(this.linePrinter.commaBreak=previousCommaBreak)}else this.linePrinter.appendText(text)}handleAndOperatorToken(token,level,parentContainerType,caseContextDepth=0){let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}if(this.whenOneLine&&(parentContainerType==="MergeWhenClause"||this.mergeWhenPredicateDepth>0)){this.linePrinter.appendText(text);return}this.andBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(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),(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.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){this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder();let currentLineText=this.linePrinter.getCurrentLine().text;if(!this.onelineHelper.shouldSkipInsertClauseSpace(parentContainerType,nextToken,currentLineText)){if(this.onelineHelper.shouldSkipCommentBlockSpace(parentContainerType,this.insideWithClause)){let currentLine=this.linePrinter.getCurrentLine();currentLine.text!==""&&!currentLine.text.endsWith(" ")&&this.linePrinter.appendText(" ");return}this.shouldSkipSpaceBeforeParenthesis(parentContainerType,nextToken,previousToken,priorToken)||this.linePrinter.appendText(token.text)}}findPreviousSignificantToken(tokens,index){for(let i=index-1;i>=0;i--){let candidate=tokens[i];if(!(candidate.type===10||candidate.type===12)&&!(candidate.type===6&&!this.rendersInlineComments()))return{token:candidate,index:i}}}shouldSkipSpaceBeforeParenthesis(parentContainerType,nextToken,previousToken,priorToken){return!nextToken||nextToken.type!==4||nextToken.text!=="("||!parentContainerType||!this.isCreateTableSpacingContext(parentContainerType)||!previousToken?!1:!!(this.isCreateTableNameToken(previousToken,parentContainerType)||this.isCreateTableConstraintKeyword(previousToken,parentContainerType)||priorToken&&this.isCreateTableConstraintKeyword(priorToken,parentContainerType)&&this.isIdentifierAttachedToConstraint(previousToken,priorToken,parentContainerType))}shouldAlignCreateTableSelect(containerType,parentContainerType){return containerType==="SimpleSelectQuery"&&parentContainerType==="CreateTableQuery"}isCreateTableSpacingContext(parentContainerType){switch(parentContainerType){case"CreateTableQuery":case"CreateTableDefinition":case"TableConstraintDefinition":case"ColumnConstraintDefinition":case"ReferenceDefinition":return!0;default:return!1}}isCreateTableNameToken(previousToken,parentContainerType){return parentContainerType!=="CreateTableQuery"?!1:previousToken.containerType==="QualifiedName"}isCreateTableConstraintKeyword(token,parentContainerType){if(token.type!==1)return!1;let text=token.text.toLowerCase();return parentContainerType==="ReferenceDefinition"?CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER.has(text):!!(CREATE_TABLE_SINGLE_PAREN_KEYWORDS.has(text)||CREATE_TABLE_MULTI_PAREN_KEYWORDS.has(text))}isIdentifierAttachedToConstraint(token,keywordToken,parentContainerType){if(!token)return!1;if(parentContainerType==="ReferenceDefinition")return token.containerType==="QualifiedName"&&CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER.has(keywordToken.text.toLowerCase());if(parentContainerType==="TableConstraintDefinition"||parentContainerType==="ColumnConstraintDefinition"){let normalized=keywordToken.text.toLowerCase();if(CREATE_TABLE_SINGLE_PAREN_KEYWORDS.has(normalized)||CREATE_TABLE_MULTI_PAREN_KEYWORDS.has(normalized))return token.containerType==="IdentifierString"}return!1}printCommentToken(text,level,parentContainerType){let trimmed=text.trim();if(trimmed&&!(this.commentStyle==="smart"&&parentContainerType==="CommentBlock"&&this.handleSmartCommentBlockToken(text,trimmed,level)))if(this.commentStyle==="smart"){let normalized=this.normalizeCommentForSmart(trimmed);if(normalized.lines.length>1||normalized.forceBlock){let blockText=this.buildBlockComment(normalized.lines,level);this.linePrinter.appendText(blockText)}else{let content=normalized.lines[0],lineText=content?`-- ${content}`:"--";if(parentContainerType==="CommentBlock")this.linePrinter.appendText(lineText),this.pendingLineCommentBreak=this.resolveCommentIndentLevel(level,parentContainerType);else{this.linePrinter.appendText(lineText);let effectiveLevel=this.resolveCommentIndentLevel(level,parentContainerType);this.linePrinter.appendNewline(effectiveLevel)}}}else{if(trimmed.startsWith("/*")&&trimmed.endsWith("*/"))if(/\r?\n/.test(trimmed)){let newlineReplacement=this.isOnelineMode()?" ":typeof this.newline=="string"?this.newline:`
|
|
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 lines=this.collectCommentBlockLines(token);if(lines.length===0&&!this.smartCommentBlockBuilder){this.smartCommentBlockBuilder={lines:[""],level,mode:"line"};return}!this.smartCommentBlockBuilder||this.smartCommentBlockBuilder.mode!=="line"?this.smartCommentBlockBuilder={lines:[...lines],level,mode:"line"}:this.smartCommentBlockBuilder.lines.push(...lines)}normalizeSmartBlockLine(raw){let line=raw.replace(/\s+$/g,"");return line?(line.startsWith(" ")&&(line=line.slice(2)),line.startsWith("* ")?line.slice(2):line==="*"?"":line.startsWith("*")?line.slice(1):line):""}extractLineCommentContent(trimmed){return trimmed.startsWith("--")?trimmed.slice(2).trimStart():trimmed.startsWith("/*")&&trimmed.endsWith("*/")?trimmed.slice(2,-2).trim():null}flushSmartCommentBlockBuilder(){if(!this.smartCommentBlockBuilder)return;let{lines,level,mode}=this.smartCommentBlockBuilder;if(mode==="line"){if(lines.filter(line=>line.trim()!=="").length>1){let blockText=this.buildBlockComment(lines,level);this.linePrinter.appendText(blockText)}else{let content=lines[0]??"",lineText=content?`-- ${content}`:"--";this.linePrinter.appendText(lineText)}this.isOnelineMode()||this.linePrinter.appendNewline(level),this.pendingLineCommentBreak=null}this.smartCommentBlockBuilder=null}collectCommentBlockLines(token){let lines=[],collectingBlock=!1;for(let child of token.innerTokens??[])if(child.type===6){let trimmed=child.text.trim();if(trimmed==="/*"){collectingBlock=!0;continue}if(trimmed==="*/"){collectingBlock=!1;continue}if(collectingBlock){lines.push(this.normalizeSmartBlockLine(child.text));continue}let content=this.extractLineCommentContent(trimmed);content!==null&&lines.push(content)}return lines}extractRawCommentBlockLines(token){let lines=[],collectingBlock=!1;for(let child of token.innerTokens??[])if(child.type===6){let trimmed=child.text.trim();if(trimmed==="/*"){collectingBlock=!0;continue}if(trimmed==="*/"){collectingBlock=!1;continue}if(collectingBlock){trimmed.length>0&&lines.push(trimmed);continue}}return lines}normalizeCommentForSmart(text){let trimmed=text.trim(),source=trimmed,forceBlock=!1;if(trimmed.startsWith("--"))source=trimmed.slice(2);else if(trimmed.startsWith("/*")&&trimmed.endsWith("*/")){let inner=trimmed.slice(2,-2);inner.replace(/\r?\n/g,`
|
|
24
|
+
`,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()&¤t.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,`
|
|
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==="ExplainStatement"||parentType==="ReturningClause":!1}getLeadingCommentIndentLevel(parentType,currentLevel){return parentType==="TupleExpression"||parentType==="InsertClause"||parentType==="MergeInsertAction"||parentType==="SelectClause"||parentType==="ReturningClause"||parentType==="SetClause"?currentLevel+1:currentLevel}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===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(`
|
|
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(`
|
|
34
34
|
`).length}};var MultiQuerySplitter=class{static split(text){let queries=[];if(!text||text.trim()==="")return{queries:[],originalText:text,getActive:()=>{},getQuery:()=>{},getNonEmpty:()=>[]};let rawBoundaries=this.splitRespectingQuotesAndComments(text),boundaries=this.mergeTrailingCommentSegments(rawBoundaries,text),queryIndex=0;for(let boundary of boundaries){let rawSql=boundary.text.trim(),isEmpty=this.isEmptyQuery(rawSql),sql=rawSql,startLineCol=TextPositionUtils.charOffsetToLineColumn(text,boundary.start),endLineCol=TextPositionUtils.charOffsetToLineColumn(text,boundary.end);queries.push({sql,start:boundary.start,end:boundary.end,startLine:startLineCol?.line||1,endLine:endLineCol?.line||1,index:queryIndex++,isEmpty})}return{queries,originalText:text,getActive:cursorPosition=>{let charPos=typeof cursorPosition=="number"?cursorPosition:TextPositionUtils.lineColumnToCharOffset(text,cursorPosition);if(charPos!==-1)return queries.find(query=>charPos>=query.start&&charPos<=query.end)},getQuery:index=>queries[index],getNonEmpty:()=>queries.filter(q=>!q.isEmpty)}}static splitRespectingQuotesAndComments(text){let segments=[],currentStart=0,i=0,inSingleQuote=!1,inDoubleQuote=!1,inLineComment=!1,inBlockComment=!1,inDollarQuote=!1,dollarTag="";for(;i<text.length;){let char=text[i];if(inLineComment){char===`
|
|
35
35
|
`&&(inLineComment=!1),i++;continue}if(inBlockComment){char==="*"&&text[i+1]==="/"?(inBlockComment=!1,i+=2):i++;continue}if(inDollarQuote){let closing="$"+dollarTag+"$";text.startsWith(closing,i)?(inDollarQuote=!1,dollarTag="",i+=closing.length):i++;continue}if(inSingleQuote){char==="'"&&text[i+1]==="'"?i+=2:(char==="'"&&(inSingleQuote=!1),i++);continue}if(inDoubleQuote){char==='"'&&text[i+1]==='"'?i+=2:(char==='"'&&(inDoubleQuote=!1),i++);continue}if(char==="-"&&text[i+1]==="-"){inLineComment=!0,i+=2;continue}if(char==="/"&&text[i+1]==="*"){inBlockComment=!0,i+=2;continue}if(char==="$"){let tagEnd=text.indexOf("$",i+1);if(tagEnd!==-1){let tag=text.substring(i+1,tagEnd);if(/^([a-zA-Z_]\w*)?$/.test(tag)){inDollarQuote=!0,dollarTag=tag,i=tagEnd+1;continue}}}if(char==="'"){inSingleQuote=!0,i++;continue}if(char==='"'){inDoubleQuote=!0,i++;continue}if(char===";"){segments.push({text:text.substring(currentStart,i),start:currentStart,end:i}),currentStart=i+1,i++;continue}i++}let remaining=text.substring(currentStart);return(remaining.length>0||segments.length===0)&&segments.push({text:remaining,start:currentStart,end:text.length}),segments}static mergeTrailingCommentSegments(segments,fullText){let merged=[];for(let i=0;i<segments.length;i++){let segment=segments[i],segmentText=segment.text.trim();if(this.isEmptyQuery(segmentText)&&merged.length>0){let lastSegmentText=merged[merged.length-1].text.trim(),isTrailingLineComment=segmentText.startsWith("--"),previousHasSQL=!this.isEmptyQuery(lastSegmentText);if(isTrailingLineComment&&previousHasSQL){let lastSegment=merged[merged.length-1];merged[merged.length-1]={text:fullText.substring(lastSegment.start,segment.end),start:lastSegment.start,end:segment.end}}else merged.push(segment)}else merged.push(segment)}return merged}static cleanSqlComments(sql){if(!sql)return null;let cleaned=sql;cleaned=cleaned.split(`
|
|
36
36
|
`).map(line=>{let commentStart=line.indexOf("--");return commentStart>=0?line.substring(0,commentStart):line}).join(`
|
|
37
|
-
`),cleaned=cleaned.replace(/\/\*[\s\S]*?\*\//g,"");let result=cleaned.trim();return result.length>0?result:null}static isEmptyQuery(sql){return sql?this.cleanSqlComments(sql)===null:!0}},MultiQueryUtils=class{static getContextAt(text,cursorPosition){let activeQuery=MultiQuerySplitter.split(text).getActive(cursorPosition);if(!activeQuery)return;let charPos=typeof cursorPosition=="number"?cursorPosition:TextPositionUtils.lineColumnToCharOffset(text,cursorPosition);if(charPos===-1)return;let relativePosition=charPos-activeQuery.start;return{query:activeQuery,relativePosition}}static extractQueries(text){return MultiQuerySplitter.split(text).getNonEmpty().map(q=>q.sql)}};function createTableDefinitionRegistryFromSchema(schema){let registry={};for(let table of Object.values(schema))registry[table.name]={name:table.name,columns:Object.entries(table.columns).map(([columnName,column])=>({...column,name:columnName}))};return registry}var NOT_NULL_KINDS=new Set(["not-null","primary-key"]),IDENTITY_KINDS=new Set(["generated-always-identity","generated-by-default-identity"]);function buildTableName(query){let prefixes=query.namespaces??[];return prefixes.length===0?query.tableName.name:`${prefixes.join(".")}.${query.tableName.name}`}function getColumnTypeName(column){let dataType=column.dataType;if(dataType){if(dataType instanceof TypeValue)return dataType.getTypeName();if(dataType instanceof RawString)return dataType.value}}function adaptColumn(column){let defaultConstraint=column.constraints.find(constraint=>constraint.kind==="default"),hasDefault=!!defaultConstraint,hasIdentity=column.constraints.some(constraint=>IDENTITY_KINDS.has(constraint.kind)),hasNotNull=column.constraints.some(constraint=>NOT_NULL_KINDS.has(constraint.kind)),required=hasNotNull&&!hasDefault&&!hasIdentity;return{name:column.name.name,typeName:getColumnTypeName(column),required,defaultValue:defaultConstraint?.defaultValue??(hasIdentity?"row_number() over ()":null),isNotNull:hasNotNull}}function createTableDefinitionFromCreateTableQuery(query){let qualifiedName=buildTableName(query),columns=query.columns.map(column=>adaptColumn(column));return{name:qualifiedName,columns}}function createTableDefinitionRegistryFromCreateTableQueries(queries){let registry={};for(let query of queries){let definition=createTableDefinitionFromCreateTableQuery(query);registry[definition.name]=definition}return registry}var normalizeTableName=tableName=>{let parsed=FullNameParser.parse(tableName);return[...parsed.namespaces??[],parsed.name.name].join(".").toLowerCase()},tableNameVariants=tableName=>{let namespaces=FullNameParser.parse(tableName).namespaces??[],normalized=normalizeTableName(tableName);return namespaces.length===0?[normalized]:[normalized]};var DDLToFixtureConverter=class{static convert(ddlSql){let splitResult=MultiQuerySplitter.split(ddlSql),createTableQueries=[],insertQueries=[],alterTableStatements=[];for(let query of splitResult.queries)if(!query.isEmpty)try{let ast=SqlParser.parse(query.sql);ast instanceof CreateTableQuery?createTableQueries.push(ast):ast instanceof InsertQuery?insertQueries.push(ast):ast instanceof AlterTableStatement&&alterTableStatements.push(ast)}catch{}let registry=createTableDefinitionRegistryFromCreateTableQueries(createTableQueries);this.applyAlterTableStatements(registry,alterTableStatements);let fixtureJson={};for(let[tableName,def]of Object.entries(registry))fixtureJson[tableName]={columns:def.columns.map(col=>({name:col.name,type:col.typeName,default:this.formatDefaultValue(col.defaultValue)})),rows:[]};let sequences={};for(let insert of insertQueries){if(!(insert.selectQuery instanceof ValuesQuery))continue;let tableName=insert.insertClause.source.getAliasName();if(!tableName||!fixtureJson[tableName])continue;let tableDef=registry[tableName],targetColumns=insert.insertClause.columns,valuesQuery=insert.selectQuery,columnNames=targetColumns?targetColumns.map(c=>c.name):tableDef.columns.map(c=>c.name);for(let tuple of valuesQuery.tuples){let row={};for(let i=0;i<columnNames.length;i++){let colName=columnNames[i];if(i<tuple.values.length){let val=tuple.values[i];row[colName]=this.extractValue(val)}}for(let colDef of tableDef.columns){if(row[colDef.name]!==void 0)continue;if(colDef.required)throw new Error(`Column '${colDef.name}' in table '${tableName}' cannot be null and has no default value.`);if(colDef.defaultValue!==null&&colDef.defaultValue!==void 0){let defaultValStr=this.formatDefaultValue(colDef.defaultValue);if(defaultValStr){let trimmedDefault=defaultValStr.trim(),lowerTrimmed=trimmedDefault.toLowerCase(),stringLiteralValue=trimmedDefault.startsWith("'")&&trimmedDefault.endsWith("'")?trimmedDefault.slice(1,-1).replace(/''/g,"'"):trimmedDefault;if(stringLiteralValue.toLowerCase()==="null")row[colDef.name]=null;else if(lowerTrimmed.includes("nextval"))sequences[tableName]||(sequences[tableName]={}),sequences[tableName][colDef.name]||(sequences[tableName][colDef.name]=0),sequences[tableName][colDef.name]++,row[colDef.name]=sequences[tableName][colDef.name];else if(lowerTrimmed.includes("now")||lowerTrimmed.includes("current_timestamp"))row[colDef.name]="2023-01-01 00:00:00";else if(trimmedDefault.startsWith("'")&&trimmedDefault.endsWith("'"))row[colDef.name]=stringLiteralValue;else{let num=Number(trimmedDefault);if(!isNaN(num))row[colDef.name]=num;else{let lower=trimmedDefault.toLowerCase();lower==="true"?row[colDef.name]=!0:lower==="false"?row[colDef.name]=!1:lower==="null"?row[colDef.name]=null:row[colDef.name]=trimmedDefault}}}}else row[colDef.name]=null}fixtureJson[tableName].rows.push(row)}}return fixtureJson}static applyAlterTableStatements(registry,alterStatements){if(alterStatements.length===0)return;let normalizedToKey=new Map,ambiguous=new Set;for(let tableKey of Object.keys(registry)){let normalized=normalizeTableName(tableKey),existing=normalizedToKey.get(normalized);if(existing&&existing!==tableKey){normalizedToKey.delete(normalized),ambiguous.add(normalized);continue}ambiguous.has(normalized)||normalizedToKey.set(normalized,tableKey)}let resolveTableKey=tableName=>{if(registry[tableName])return tableName;let normalized=normalizeTableName(tableName);if(!ambiguous.has(normalized))return normalizedToKey.get(normalized)};for(let alter of alterStatements){let tableName=alter.table.toString(),registryKey=resolveTableKey(tableName);if(!registryKey)continue;let tableDef=registry[registryKey];for(let action of alter.actions){if(!(action instanceof AlterTableAlterColumnDefault))continue;let targetName=action.columnName.name,column=tableDef.columns.find(col=>col.name.toLowerCase()===targetName.toLowerCase());if(!column)continue;let hadDefault=column.defaultValue!==null&&column.defaultValue!==void 0;if(action.dropDefault){column.defaultValue=null,column.isNotNull&&hadDefault&&(column.required=!0);continue}column.defaultValue=action.setDefault??null,column.required=!1}}}static extractValue(value){if(value instanceof LiteralValue)return value.value;try{let formatter2=new SqlFormatter({keywordCase:"none"}),{formattedSql}=formatter2.format(value);return formattedSql.startsWith("'")&&formattedSql.endsWith("'")?formattedSql.slice(1,-1).replace(/''/g,"'"):formattedSql}catch{return String(value)}}static formatDefaultValue(value){if(value!=null){if(typeof value=="string")return value;try{let formatter2=new SqlFormatter({keywordCase:"none"}),{formattedSql}=formatter2.format(value);return formattedSql}catch{return String(value)}}}};var SERIAL_PSEUDO_TYPE_MAP={serial:"integer",serial4:"integer",bigserial:"bigint",serial8:"bigint",smallserial:"smallint",serial2:"smallint"};function normalizeSerialPseudoType(typeName){if(!typeName)return typeName;let trimmed=typeName.trim();if(!trimmed)return trimmed;let segments=trimmed.split("."),base=segments.pop(),normalizedBase=SERIAL_PSEUDO_TYPE_MAP[base.toLowerCase()];return normalizedBase?(segments.push(normalizedBase),segments.join(".")):trimmed}function isSerialPseudoType(typeName){if(!typeName)return!1;let trimmed=typeName.trim();if(!trimmed)return!1;let base=trimmed.split(".").pop();return base?!!SERIAL_PSEUDO_TYPE_MAP[base.toLowerCase()]:!1}var FixtureCteBuilder=class{static fromSQL(sql){let fixtureJson=DDLToFixtureConverter.convert(sql);return this.fromJSON(fixtureJson)}static fromJSON(jsonDefinitions){let fixtures=[];for(let[tableName,def]of Object.entries(jsonDefinitions))if(def&&Array.isArray(def.columns)){let columns=def.columns.map(c=>({name:c.name,typeName:c.type,defaultValue:c.default})),rows=[];Array.isArray(def.rows)&&(rows=def.rows.map(rowObj=>columns.map(col=>rowObj[col.name]!==void 0?rowObj[col.name]:null))),fixtures.push({tableName,columns,rows})}return fixtures}static buildFixtures(fixtures){return fixtures.map(fixture=>this.buildFixture(fixture))}static buildFixture(fixture){let query=this.buildSelectQuery(fixture);return new CommonTable(query,fixture.tableName,null)}static buildSelectQuery(fixture){let columnCount=fixture.columns.length,selectQueries=(fixture.rows.length>0?fixture.rows:[new Array(columnCount).fill(null)]).map(row=>this.buildSelectRow(fixture.columns,row));if(selectQueries.length===0)throw new Error("No rows to build SELECT query");let result=selectQueries[0];for(let i=1;i<selectQueries.length;i++)result instanceof SimpleSelectQuery?result=result.toUnionAll(selectQueries[i]):result=result.unionAll(selectQueries[i]);if(fixture.rows.length===0&&result instanceof SimpleSelectQuery){let falseCondition=new BinaryExpression(new LiteralValue(1),"=",new LiteralValue(0));result.whereClause=new WhereClause(falseCondition)}return result}static buildSelectRow(columns,row){let items=columns.map((column,index)=>{let value=index<row.length?row[index]:null,literalValue=this.createLiteralValue(value),expression=literalValue,castTarget=normalizeSerialPseudoType(column.typeName);if(castTarget){let typeValue=new TypeValue(null,new RawString(castTarget));expression=new CastExpression(literalValue,typeValue)}return new SelectItem(expression,column.name)}),selectClause=new SelectClause(items);return new SimpleSelectQuery({selectClause})}static createLiteralValue(value){return value==null?new LiteralValue(null):typeof value=="number"?new LiteralValue(Number.isFinite(value)?value:null):typeof value=="boolean"?new LiteralValue(value):typeof value=="bigint"?new LiteralValue(value.toString()):typeof Buffer<"u"&&value instanceof Buffer?new LiteralValue(`X'${value.toString("hex")}'`):typeof value=="string"?new LiteralValue(value,void 0,!0):new LiteralValue(String(value),void 0,!0)}};function rewriteValueComponentWithColumnResolver(value,resolver){if(value instanceof ColumnReference)return resolver(value);if(value instanceof FunctionCall){let rewrittenArgument=value.argument?rewriteValueComponentWithColumnResolver(value.argument,resolver):null,rewrittenOver=value.over?rewriteOverExpression(value.over,resolver):null,rewrittenWithinGroup=value.withinGroup?rewriteOrderByClause(value.withinGroup,resolver):null,rewrittenInternalOrderBy=value.internalOrderBy?rewriteOrderByClause(value.internalOrderBy,resolver):null,rewrittenFilterCondition=value.filterCondition?rewriteValueComponentWithColumnResolver(value.filterCondition,resolver):null;return new FunctionCall(value.qualifiedName.namespaces,value.qualifiedName.name,rewrittenArgument,rewrittenOver,rewrittenWithinGroup,value.withOrdinality,rewrittenInternalOrderBy,rewrittenFilterCondition)}if(value instanceof UnaryExpression){let rewrittenExpression=rewriteValueComponentWithColumnResolver(value.expression,resolver);return new UnaryExpression(value.operator.value,rewrittenExpression)}if(value instanceof BinaryExpression){let left=rewriteValueComponentWithColumnResolver(value.left,resolver),right=rewriteValueComponentWithColumnResolver(value.right,resolver);return new BinaryExpression(left,value.operator.value,right)}if(value instanceof JsonPredicateExpression){let expression=rewriteValueComponentWithColumnResolver(value.expression,resolver);return new JsonPredicateExpression(expression,value.negated,value.jsonType,value.uniqueKeys)}if(value instanceof CaseExpression){let condition=value.condition?rewriteValueComponentWithColumnResolver(value.condition,resolver):null,switchCase=rewriteSwitchCaseArgument(value.switchCase,resolver);return new CaseExpression(condition,switchCase)}if(value instanceof SwitchCaseArgument)return rewriteSwitchCaseArgument(value,resolver);if(value instanceof CaseKeyValuePair)return rewriteCaseKeyValuePair(value,resolver);if(value instanceof BetweenExpression){let expression=rewriteValueComponentWithColumnResolver(value.expression,resolver),lower=rewriteValueComponentWithColumnResolver(value.lower,resolver),upper=rewriteValueComponentWithColumnResolver(value.upper,resolver);return new BetweenExpression(expression,lower,upper,value.negated)}if(value instanceof CastExpression){let input=rewriteValueComponentWithColumnResolver(value.input,resolver),castType=rewriteTypeValue(value.castType,resolver);return new CastExpression(input,castType)}if(value instanceof ParenExpression){let expression=rewriteValueComponentWithColumnResolver(value.expression,resolver);return new ParenExpression(expression)}if(value instanceof TupleExpression){let rewrittenValues=value.values.map(item=>rewriteValueComponentWithColumnResolver(item,resolver));return new TupleExpression(rewrittenValues)}if(value instanceof ArrayExpression){let expression=rewriteValueComponentWithColumnResolver(value.expression,resolver);return new ArrayExpression(expression)}if(value instanceof ArraySliceExpression){let array=rewriteValueComponentWithColumnResolver(value.array,resolver),startIndex=value.startIndex?rewriteValueComponentWithColumnResolver(value.startIndex,resolver):null,endIndex=value.endIndex?rewriteValueComponentWithColumnResolver(value.endIndex,resolver):null;return new ArraySliceExpression(array,startIndex,endIndex)}if(value instanceof ArrayIndexExpression){let array=rewriteValueComponentWithColumnResolver(value.array,resolver),index=rewriteValueComponentWithColumnResolver(value.index,resolver);return new ArrayIndexExpression(array,index)}if(value instanceof ArrayQueryExpression)return value;if(value instanceof ValueList){let rewrittenList=value.values.map(item=>rewriteValueComponentWithColumnResolver(item,resolver));return new ValueList(rewrittenList)}if(value instanceof InlineQuery)return value;if(value instanceof WindowFrameExpression)return rewriteWindowFrameExpression(value,resolver);if(value instanceof WindowFrameSpec)return rewriteWindowFrameSpec(value,resolver);if(value instanceof WindowFrameBoundaryValue){let rewrittenValue=rewriteValueComponentWithColumnResolver(value.value,resolver);return new WindowFrameBoundaryValue(rewrittenValue,value.isFollowing)}return value instanceof WindowFrameBoundStatic?value:value instanceof TypeValue?rewriteTypeValue(value,resolver):(value instanceof StringSpecifierExpression||value instanceof LiteralValue||value instanceof RawString||value instanceof IdentifierString||value instanceof ParameterExpression,value)}function rewriteSwitchCaseArgument(argument,resolver){let rewrittenCases=argument.cases.map(pair=>rewriteCaseKeyValuePair(pair,resolver)),elseValue=argument.elseValue?rewriteValueComponentWithColumnResolver(argument.elseValue,resolver):null;return new SwitchCaseArgument(rewrittenCases,elseValue)}function rewriteCaseKeyValuePair(pair,resolver){let key=rewriteValueComponentWithColumnResolver(pair.key,resolver),value=rewriteValueComponentWithColumnResolver(pair.value,resolver);return new CaseKeyValuePair(key,value)}function rewriteOrderByClause(clause,resolver){let rewrittenOrder=clause.order.map(component=>rewriteOrderByComponent(component,resolver));return new OrderByClause(rewrittenOrder)}function rewriteOrderByComponent(component,resolver){if(component instanceof OrderByItem){let rewrittenValue=rewriteValueComponentWithColumnResolver(component.value,resolver);return new OrderByItem(rewrittenValue,component.sortDirection,component.nullsPosition)}return rewriteValueComponentWithColumnResolver(component,resolver)}function rewriteOverExpression(over,resolver){return over instanceof WindowFrameExpression?rewriteWindowFrameExpression(over,resolver):over}function rewriteWindowFrameExpression(expression,resolver){let partition=expression.partition?rewritePartitionByClause(expression.partition,resolver):null,order=expression.order?rewriteOrderByClause(expression.order,resolver):null,frameSpec=expression.frameSpec?rewriteWindowFrameSpec(expression.frameSpec,resolver):null;return new WindowFrameExpression(partition,order,frameSpec)}function rewritePartitionByClause(clause,resolver){let value=rewriteValueComponentWithColumnResolver(clause.value,resolver);return new PartitionByClause(value)}function rewriteWindowFrameSpec(spec,resolver){let startBound=rewriteFrameBoundaryComponent(spec.startBound,resolver),endBound=spec.endBound?rewriteFrameBoundaryComponent(spec.endBound,resolver):null;return new WindowFrameSpec(spec.frameType,startBound,endBound)}function rewriteFrameBoundaryComponent(bound,resolver){if(bound instanceof WindowFrameBoundaryValue){let value=rewriteValueComponentWithColumnResolver(bound.value,resolver);return new WindowFrameBoundaryValue(value,bound.isFollowing)}return bound}function rewriteTypeValue(value,resolver){let argument=value.argument?rewriteValueComponentWithColumnResolver(value.argument,resolver):null;return new TypeValue(value.namespaces,value.qualifiedName.name,argument)}var InsertResultSelectConverter=class{static{this.BASE_CTE_NAME="__inserted_rows"}static{this.DEFAULT_MISSING_FIXTURE_STRATEGY="error"}static toSelectQuery(insertQuery,options){let preparedInsert=this.prepareInsertQuery(insertQuery),sourceQuery=preparedInsert.selectQuery;if(!sourceQuery)throw new Error("Cannot convert INSERT query without a data source.");let sourceWithClause=SelectQueryWithClauseHelper.detachWithClause(sourceQuery),targetTableName=this.extractTargetTableName(preparedInsert.insertClause),tableDefinition=this.resolveTableDefinition(targetTableName,options),fixtureTables=options?.fixtureTables??[],fixtureMap=this.buildFixtureTableMap(fixtureTables),missingStrategy=options?.missingFixtureStrategy??this.DEFAULT_MISSING_FIXTURE_STRATEGY,referencedTables=this.collectPhysicalTableReferences(sourceQuery,sourceWithClause);this.ensureFixtureCoverage(referencedTables,fixtureMap,missingStrategy);let filteredFixtures=this.filterFixtureTablesForReferences(fixtureTables,referencedTables),insertColumnNames=this.resolveInsertColumns(preparedInsert.insertClause,sourceQuery,tableDefinition),selectColumnCount=this.getSelectColumnCount(sourceQuery);if(insertColumnNames.length!==selectColumnCount)throw new Error("Insert column count does not match SELECT output columns.");let columnMetadataMap=this.buildColumnMetadata(insertColumnNames,tableDefinition);this.assertRequiredColumns(columnMetadataMap,tableDefinition),this.applyColumnCasts(sourceQuery,insertColumnNames,columnMetadataMap);let fixtureCtes=this.buildFixtureCtes(filteredFixtures),cteName=this.generateUniqueCteName(sourceWithClause,fixtureCtes),cteAlias=new SourceAliasExpression(cteName,insertColumnNames),insertedRowsCte=new CommonTable(sourceQuery,cteAlias,null),withClause=this.buildWithClause(sourceWithClause,fixtureCtes,insertedRowsCte);if(!preparedInsert.returningClause)return this.buildCountSelect(withClause,cteName);let selectItems=this.buildReturningSelectItems(preparedInsert.returningClause,tableDefinition,insertColumnNames,columnMetadataMap,cteName),fromExpr=new SourceExpression(new TableSource(null,cteName),null),fromClause=new FromClause(fromExpr,null);return new SimpleSelectQuery({withClause,selectClause:new SelectClause(selectItems),fromClause})}static prepareInsertQuery(insertQuery){return insertQuery.selectQuery instanceof ValuesQuery?InsertQuerySelectValuesConverter.toSelectUnion(insertQuery):insertQuery}static extractTargetTableName(insertClause){let datasource=insertClause.source.datasource;if(datasource instanceof TableSource)return datasource.getSourceName();throw new Error("Insert target must be a table source for conversion.")}static resolveTableDefinition(tableName,options){if(options?.tableDefinitionResolver){let resolved=options.tableDefinitionResolver(tableName);if(resolved!==void 0)return resolved}let normalizedVariants=new Set(tableNameVariants(tableName));if(options?.tableDefinitions){let normalizedMap=this.buildTableDefinitionMap(options.tableDefinitions);for(let variant of normalizedVariants){let definition=normalizedMap.get(variant);if(definition)return definition}}if(options?.fixtureTables){let fixture=options.fixtureTables.find(f=>tableNameVariants(f.tableName).some(variant=>normalizedVariants.has(variant)));if(fixture)return this.convertFixtureToTableDefinition(fixture)}}static convertFixtureToTableDefinition(fixture){return{name:fixture.tableName,columns:fixture.columns.map(col=>({name:col.name,typeName:col.typeName,required:!1,defaultValue:col.defaultValue??null}))}}static buildTableDefinitionMap(registry){let map=new Map;if(!registry)return map;for(let definition of Object.values(registry))for(let variant of tableNameVariants(definition.name))map.set(variant,definition);return map}static resolveInsertColumns(insertClause,selectQuery,tableDefinition){if(insertClause.columns&&insertClause.columns.length>0)return insertClause.columns.map(col=>col.name);if(!tableDefinition)throw new Error("Cannot infer INSERT columns without a table definition.");let columnNames=tableDefinition.columns.map(col=>col.name),expectedCount=this.getSelectColumnCount(selectQuery);if(columnNames.length!==expectedCount)throw new Error("Table definition column count does not match the SELECT output when column list is omitted.");return columnNames}static getSelectColumnCount(selectQuery){return this.getFirstSimpleSelectQuery(selectQuery).selectClause.items.length}static getFirstSimpleSelectQuery(selectQuery){if(selectQuery instanceof SimpleSelectQuery)return selectQuery;if(selectQuery instanceof BinarySelectQuery)return this.getFirstSimpleSelectQuery(selectQuery.left);throw new Error("Unsupported select query structure in insert conversion.")}static buildColumnMetadata(insertColumns,tableDefinition){let metadataMap=new Map,columnDefinitionMap=tableDefinition?new Map(tableDefinition.columns.map(col=>[this.normalizeIdentifier(col.name),col])):null;for(let columnName of insertColumns){let normalized=this.normalizeIdentifier(columnName),definition=columnDefinitionMap?.get(normalized),normalizedTypeName=normalizeSerialPseudoType(definition?.typeName);metadataMap.set(normalized,{name:columnName,normalized,provided:!0,typeName:normalizedTypeName,required:definition?.required,defaultValue:this.resolveDefaultValueExpression(definition)})}if(columnDefinitionMap){for(let[normalized,definition]of columnDefinitionMap.entries())if(!metadataMap.has(normalized)){let normalizedTypeName=normalizeSerialPseudoType(definition.typeName);metadataMap.set(normalized,{name:definition.name,normalized,provided:!1,typeName:normalizedTypeName,required:definition.required,defaultValue:this.resolveDefaultValueExpression(definition)})}}return metadataMap}static assertRequiredColumns(metadataMap,tableDefinition){if(!tableDefinition)return;let requiredColumns=new Set(tableDefinition.columns.filter(col=>col.required).map(col=>this.normalizeIdentifier(col.name)));for(let normalized of requiredColumns){let metadata=metadataMap.get(normalized);if(metadata&&metadata.provided||metadata?.defaultValue)continue;let columnName=tableDefinition.columns.find(col=>this.normalizeIdentifier(col.name)===normalized)?.name;if(columnName)throw new Error(`Required column '${columnName}' is missing from INSERT, so conversion cannot proceed.`)}}static buildReturningSelectItems(returning,tableDefinition,insertColumns,columnMetadataMap,cteName){let selectItems=[];for(let item of returning.items){if(this.isWildcardReturningItem(item)){selectItems.push(...this.expandReturningWildcard(tableDefinition,insertColumns,columnMetadataMap,cteName));continue}selectItems.push(this.buildReturningSelectItem(item,columnMetadataMap,cteName))}return selectItems}static isWildcardReturningItem(item){return item.value instanceof ColumnReference&&item.value.column.name==="*"}static expandReturningWildcard(tableDefinition,insertColumns,columnMetadataMap,cteName){let columnNames=tableDefinition?tableDefinition.columns.map(column=>column.name):insertColumns.length>0?insertColumns:null;if(!columnNames)throw new Error("Cannot expand RETURNING * without table definition or column list.");return columnNames.map(columnName=>{let metadata=this.getColumnMetadata(columnMetadataMap,columnName),expression=this.buildColumnExpression(metadata,cteName);return new SelectItem(expression,columnName)})}static buildReturningSelectItem(item,columnMetadataMap,cteName){let expression=rewriteValueComponentWithColumnResolver(item.value,column=>this.buildInsertColumnExpression(column,columnMetadataMap,cteName)),alias=this.getReturningAlias(item);return new SelectItem(expression,alias)}static buildInsertColumnExpression(column,columnMetadataMap,cteName){let columnName=this.extractColumnName(column),metadata=this.getColumnMetadata(columnMetadataMap,columnName);return this.buildColumnExpression(metadata,cteName)}static extractColumnName(column){let nameComponent=column.qualifiedName.name;return nameComponent instanceof IdentifierString?nameComponent.name:nameComponent.value}static getReturningAlias(item){return item.identifier?.name?item.identifier.name:item.value instanceof ColumnReference?item.value.toString():null}static getColumnMetadata(metadataMap,columnName){let normalized=this.normalizeIdentifier(columnName),metadata=metadataMap.get(normalized);if(!metadata)throw new Error(`Column '${columnName}' cannot be resolved for RETURNING output.`);return metadata}static buildColumnExpression(metadata,cteName){let expression;return metadata.provided?expression=new ColumnReference(cteName,metadata.name):metadata.defaultValue?expression=metadata.defaultValue:expression=new LiteralValue(null),expression}static buildTypeValue(typeName){let normalizedTypeName=normalizeSerialPseudoType(typeName)??typeName.trim(),parts=normalizedTypeName.split("."),namePart=parts.pop()?.trim()??normalizedTypeName.trim(),namespaces=parts.length>0?parts.map(part=>part.trim()):null;return new TypeValue(namespaces,new RawString(namePart))}static collectPhysicalTableReferences(selectQuery,withClause){let referencedTables=this.collectReferencedTables(selectQuery),ignoredTables=this.collectCteNamesFromWithClause(withClause),tablesToShadow=new Set;for(let table of referencedTables)ignoredTables.has(table)||tablesToShadow.add(table);let cteReferencedTables=this.collectReferencedTablesFromWithClause(withClause);for(let table of cteReferencedTables)ignoredTables.has(table)||tablesToShadow.add(table);return tablesToShadow}static buildFixtureCtes(fixtures){return!fixtures||fixtures.length===0?[]:FixtureCteBuilder.buildFixtures(fixtures)}static filterFixtureTablesForReferences(fixtures,referencedTables){if(!fixtures.length||referencedTables.size===0)return[];let filtered=[];for(let fixture of fixtures)tableNameVariants(fixture.tableName).some(variant=>referencedTables.has(variant))&&filtered.push(fixture);return filtered}static collectReferencedTablesFromWithClause(withClause){let tables=new Set;if(!withClause?.tables)return tables;for(let cte of withClause.tables)for(let table of this.collectReferencedTables(cte.query))tables.add(table);return tables}static buildWithClause(original,fixtureCtes,insertedCte){let originalTables=original?.tables??[],combinedTables=[...fixtureCtes,...originalTables,insertedCte],withClause=new WithClause(original?.recursive??!1,combinedTables);return withClause.globalComments=original?.globalComments?[...original.globalComments]:null,withClause.trailingComments=original?.trailingComments?[...original.trailingComments]:null,withClause}static buildCountSelect(withClause,cteName){let countItem=new SelectItem(new FunctionCall(null,"count",new RawString("*"),null),"count"),selectClause=new SelectClause([countItem]),fromExpr=new SourceExpression(new TableSource(null,cteName),null),fromClause=new FromClause(fromExpr,null);return new SimpleSelectQuery({withClause,selectClause,fromClause})}static buildFixtureTableMap(fixtures){let map=new Map;if(!fixtures)return map;for(let fixture of fixtures)for(let variant of tableNameVariants(fixture.tableName))map.set(variant,fixture);return map}static ensureFixtureCoverage(referencedTables,fixtureMap,strategy){if(referencedTables.size===0)return;let missingTables=this.getMissingFixtureTables(referencedTables,fixtureMap);if(missingTables.length!==0&&strategy==="error")throw new Error(`Insert SELECT refers to tables without fixture coverage: ${missingTables.join(", ")}.`)}static collectReferencedTables(query){let sources=new TableSourceCollector(!1).collect(query),referenced=new Set;for(let source of sources)for(let variant of tableNameVariants(source.getSourceName()))referenced.add(variant);return referenced}static collectCteNamesFromWithClause(withClause){let names=new Set;if(!withClause?.tables)return names;for(let table of withClause.tables)names.add(this.normalizeIdentifier(table.getSourceAliasName()));return names}static addCteNames(usedNames,tables){if(tables)for(let table of tables)usedNames.add(this.normalizeIdentifier(table.getSourceAliasName()))}static getMissingFixtureTables(referencedTables,fixtureMap){let missing=[];for(let table of referencedTables)tableNameVariants(table).some(variant=>fixtureMap.has(variant))||missing.push(table);return missing}static generateUniqueCteName(withClause,fixtureCtes){let usedNames=new Set;this.addCteNames(usedNames,fixtureCtes);for(let name of this.collectCteNamesFromWithClause(withClause))usedNames.add(name);let candidate=this.BASE_CTE_NAME,suffix=0;for(;usedNames.has(this.normalizeIdentifier(candidate));)suffix+=1,candidate=`${this.BASE_CTE_NAME}_${suffix}`;return candidate}static normalizeIdentifier(value){return value.trim().toLowerCase()}static parseDefaultValue(def){try{return ValueParser.parse(def)}catch(error){throw new Error(`Failed to parse default expression '${def}': ${error instanceof Error?error.message:String(error)}`)}}static resolveDefaultValueExpression(definition){if(!definition)return null;let defaultValue=definition.defaultValue;if(typeof defaultValue=="string"){let parsed=this.parseDefaultValue(defaultValue);return this.referencesSequence(parsed)?this.parseDefaultValue("row_number() over ()"):parsed}return defaultValue&&this.referencesSequence(defaultValue)?this.parseDefaultValue("row_number() over ()"):this.shouldUseSerialDefault(definition)?this.parseDefaultValue("row_number() over ()"):defaultValue??null}static shouldUseSerialDefault(definition){return!definition||definition.defaultValue!=null?!1:isSerialPseudoType(definition.typeName)}static referencesSequence(component){if(component instanceof FunctionCall&&(this.isSequenceFunction(component)||component.argument&&this.referencesSequence(component.argument)))return!0;if(component instanceof ValueList)return component.values.some(value=>this.referencesSequence(value));if(component instanceof BinaryExpression)return this.referencesSequence(component.left)||this.referencesSequence(component.right);if(component instanceof UnaryExpression)return this.referencesSequence(component.expression);if(component instanceof CastExpression)return this.referencesSequence(component.input);if(component instanceof ParenExpression)return this.referencesSequence(component.expression);if(component instanceof InlineQuery)return this.referencesSelect(component.selectQuery);if(component instanceof ArrayExpression)return this.referencesSequence(component.expression);if(component instanceof ArrayQueryExpression)return this.referencesSelect(component.query);if(component instanceof BetweenExpression)return this.referencesSequence(component.expression)||this.referencesSequence(component.lower)||this.referencesSequence(component.upper);if(component instanceof ArraySliceExpression)return this.referencesSequence(component.array)||(component.startIndex?this.referencesSequence(component.startIndex):!1)||(component.endIndex?this.referencesSequence(component.endIndex):!1);if(component instanceof ArrayIndexExpression)return this.referencesSequence(component.array)||this.referencesSequence(component.index);if(component instanceof SwitchCaseArgument){for(let pair of component.cases)if(this.referencesSequence(pair.key)||this.referencesSequence(pair.value))return!0;return component.elseValue?this.referencesSequence(component.elseValue):!1}return component instanceof CaseExpression?(component.condition?this.referencesSequence(component.condition):!1)||this.referencesSequence(component.switchCase):component instanceof CaseKeyValuePair?this.referencesSequence(component.key)||this.referencesSequence(component.value):component instanceof TupleExpression?component.values.some(value=>this.referencesSequence(value)):!1}static referencesSelect(query){return!1}static isSequenceFunction(call){let name=call.qualifiedName.name;return(name instanceof RawString?name.value:name.name).toLowerCase()==="nextval"}static applyColumnCasts(selectQuery,insertColumns,metadataMap){if(selectQuery instanceof SimpleSelectQuery){this.applyColumnCastsToSimple(selectQuery,insertColumns,metadataMap);return}if(selectQuery instanceof BinarySelectQuery){this.applyColumnCasts(selectQuery.left,insertColumns,metadataMap),this.applyColumnCasts(selectQuery.right,insertColumns,metadataMap);return}throw new Error("Unsupported select query structure for applying column casts.")}static applyColumnCastsToSimple(simple,insertColumns,metadataMap){let items=simple.selectClause.items;for(let i=0;i<items.length;i++){let colName=insertColumns[i],metadata=metadataMap.get(this.normalizeIdentifier(colName));if(!metadata||!metadata.typeName)continue;let identifier=items[i].identifier?.name??null,casted=new CastExpression(items[i].value,this.buildTypeValue(metadata.typeName)),newItem=new SelectItem(casted,identifier);newItem.comments=items[i].comments,newItem.positionedComments=items[i].positionedComments,simple.selectClause.items[i]=newItem}}};var UpdateResultSelectConverter=class{static{this.DEFAULT_MISSING_FIXTURE_STRATEGY="error"}static toSelectQuery(updateQuery,options){let targetTableName=this.extractTargetTableName(updateQuery.updateClause),tableDefinition=this.resolveTableDefinition(targetTableName,options),targetAlias=updateQuery.updateClause.getSourceAliasName(),fromClause=this.buildFromClause(updateQuery.updateClause.source,updateQuery.fromClause),whereClause=updateQuery.whereClause??null,selectClause=updateQuery.returningClause?this.buildReturningSelectClause(updateQuery.returningClause,updateQuery.setClause,targetAlias,tableDefinition):this.buildCountSelectClause(),selectQuery=new SimpleSelectQuery({withClause:updateQuery.withClause??void 0,selectClause,fromClause,whereClause}),fixtureTables=options?.fixtureTables??[],fixtureMap=this.buildFixtureTableMap(fixtureTables),missingStrategy=options?.missingFixtureStrategy??this.DEFAULT_MISSING_FIXTURE_STRATEGY,originalWithClause=SelectQueryWithClauseHelper.detachWithClause(selectQuery),referencedTables=this.collectPhysicalTableReferences(selectQuery,originalWithClause),cteNames=this.collectCteNamesFromWithClause(originalWithClause),targetVariants=tableNameVariants(targetTableName);for(let variant of targetVariants)cteNames.has(variant)||referencedTables.add(variant);this.ensureFixtureCoverage(referencedTables,fixtureMap,missingStrategy);let filteredFixtures=this.filterFixtureTablesForReferences(fixtureTables,referencedTables),fixtureCtes=this.buildFixtureCtes(filteredFixtures),recombinedWithClause=this.mergeWithClause(originalWithClause,fixtureCtes);return SelectQueryWithClauseHelper.setWithClause(selectQuery,recombinedWithClause),selectQuery}static buildReturningSelectClause(returning,setClause,targetAlias,tableDefinition){let setExpressionMap=this.mapSetExpressions(setClause),selectItems=this.buildReturningSelectItems(returning,setExpressionMap,targetAlias,tableDefinition);return new SelectClause(selectItems)}static buildReturningSelectItems(returning,setExpressions,targetAlias,tableDefinition){let selectItems=[];for(let item of returning.items){if(this.isWildcardReturningItem(item)){selectItems.push(...this.expandReturningWildcard(tableDefinition,setExpressions,targetAlias));continue}selectItems.push(this.buildUpdateReturningSelectItem(item,setExpressions,targetAlias,tableDefinition))}return selectItems}static isWildcardReturningItem(item){return item.value instanceof ColumnReference&&item.value.column.name==="*"}static expandReturningWildcard(tableDefinition,setExpressions,targetAlias){if(!tableDefinition)throw new Error("Cannot expand RETURNING * without table definition.");return tableDefinition.columns.map(column=>{let expression=this.buildUpdateColumnExpression(column.name,setExpressions,targetAlias,tableDefinition);return new SelectItem(expression,column.name)})}static buildUpdateReturningSelectItem(item,setExpressions,targetAlias,tableDefinition){let expression=rewriteValueComponentWithColumnResolver(item.value,column=>this.buildUpdateColumnExpression(column,setExpressions,targetAlias,tableDefinition)),alias=this.getReturningAlias(item);return new SelectItem(expression,alias)}static buildUpdateColumnExpression(columnOrName,setExpressions,targetAlias,tableDefinition){let columnName=typeof columnOrName=="string"?columnOrName:this.getColumnReferenceName(columnOrName),normalized=this.normalizeIdentifier(columnName),overrideExpression=setExpressions.get(normalized);return overrideExpression||(this.ensureColumnExists(columnName,tableDefinition),new ColumnReference(targetAlias,columnName))}static getColumnReferenceName(column){let nameComponent=column.qualifiedName.name;return nameComponent instanceof IdentifierString?nameComponent.name:nameComponent.value}static getReturningAlias(item){return item.identifier?.name?item.identifier.name:item.value instanceof ColumnReference?item.value.toString():null}static buildCountSelectClause(){let countFunction=new FunctionCall(null,"count",new RawString("*"),null),selectItem=new SelectItem(countFunction,"count");return new SelectClause([selectItem])}static buildFromClause(targetSource,fromClause){if(!fromClause)return new FromClause(targetSource,null);let joins=[];return joins.push(new JoinClause("cross join",fromClause.source,null,!1)),fromClause.joins&&joins.push(...fromClause.joins),new FromClause(targetSource,joins)}static mapSetExpressions(setClause){let expressionMap=new Map;for(let item of setClause.items){let columnName=this.extractColumnName(item);expressionMap.set(this.normalizeIdentifier(columnName),item.value)}return expressionMap}static ensureColumnExists(columnName,tableDefinition){if(!tableDefinition)return;let normalized=this.normalizeIdentifier(columnName);if(!tableDefinition.columns.some(column=>this.normalizeIdentifier(column.name)===normalized))throw new Error(`Column '${columnName}' cannot be resolved for RETURNING output.`)}static resolveTableDefinition(tableName,options){if(options?.tableDefinitionResolver){let resolved=options.tableDefinitionResolver(tableName);if(resolved!==void 0)return resolved}let normalizedVariants=new Set(tableNameVariants(tableName));if(options?.tableDefinitions){let map=this.buildTableDefinitionMap(options.tableDefinitions);for(let variant of normalizedVariants){let definition=map.get(variant);if(definition)return definition}}if(options?.fixtureTables){let fixture=options.fixtureTables.find(f=>tableNameVariants(f.tableName).some(variant=>normalizedVariants.has(variant)));if(fixture)return this.convertFixtureToTableDefinition(fixture)}}static convertFixtureToTableDefinition(fixture){return{name:fixture.tableName,columns:fixture.columns.map(col=>({name:col.name,typeName:col.typeName,required:!1,defaultValue:col.defaultValue??null}))}}static buildTableDefinitionMap(registry){let map=new Map;for(let definition of Object.values(registry))for(let variant of tableNameVariants(definition.name))map.set(variant,definition);return map}static extractTargetTableName(updateClause){let datasource=updateClause.source.datasource;if(datasource instanceof TableSource)return datasource.getSourceName();throw new Error("Update target must be a table source for conversion.")}static extractColumnName(item){let columnComponent=item.qualifiedName.name;return columnComponent instanceof RawString?columnComponent.value:columnComponent.name}static buildFixtureCtes(fixtures){return!fixtures||fixtures.length===0?[]:FixtureCteBuilder.buildFixtures(fixtures)}static collectPhysicalTableReferences(selectQuery,withClause){let referencedTables=this.collectReferencedTables(selectQuery),ignoredTables=this.collectCteNamesFromWithClause(withClause),tablesToShadow=new Set;for(let table of referencedTables)ignoredTables.has(table)||tablesToShadow.add(table);let cteReferencedTables=this.collectReferencedTablesFromWithClause(withClause);for(let table of cteReferencedTables)ignoredTables.has(table)||tablesToShadow.add(table);return tablesToShadow}static filterFixtureTablesForReferences(fixtures,referencedTables){if(!fixtures.length||referencedTables.size===0)return[];let filtered=[];for(let fixture of fixtures)tableNameVariants(fixture.tableName).some(variant=>referencedTables.has(variant))&&filtered.push(fixture);return filtered}static collectReferencedTablesFromWithClause(withClause){let tables=new Set;if(!withClause?.tables)return tables;for(let cte of withClause.tables)for(let table of this.collectReferencedTables(cte.query))tables.add(table);return tables}static buildFixtureTableMap(fixtures){let map=new Map;for(let fixture of fixtures)for(let variant of tableNameVariants(fixture.tableName))map.set(variant,fixture);return map}static ensureFixtureCoverage(referencedTables,fixtureMap,strategy){if(referencedTables.size===0)return;let missingTables=this.getMissingFixtureTables(referencedTables,fixtureMap);if(missingTables.length!==0&&strategy==="error")throw new Error(`Update SELECT refers to tables without fixture coverage: ${missingTables.join(", ")}.`)}static collectReferencedTables(query){let sources=new TableSourceCollector(!1).collect(query),normalized=new Set;for(let source of sources)for(let variant of tableNameVariants(source.getSourceName()))normalized.add(variant);return normalized}static collectCteNamesFromWithClause(withClause){let names=new Set;if(!withClause?.tables)return names;for(let table of withClause.tables)for(let variant of tableNameVariants(table.getSourceAliasName()))names.add(variant);return names}static getMissingFixtureTables(referencedTables,fixtureMap){let missing=[];for(let table of referencedTables)tableNameVariants(table).some(variant=>fixtureMap.has(variant))||missing.push(table);return missing}static mergeWithClause(original,fixtureCtes){if(!fixtureCtes.length&&!original)return null;let combinedTables=[...fixtureCtes];if(original?.tables&&combinedTables.push(...original.tables),!combinedTables.length)return null;let merged=new WithClause(original?.recursive??!1,combinedTables);return merged.globalComments=original?.globalComments?[...original.globalComments]:null,merged.trailingComments=original?.trailingComments?[...original.trailingComments]:null,merged}static normalizeIdentifier(value){return value.trim().toLowerCase()}};var DeleteResultSelectConverter=class{static{this.DEFAULT_MISSING_FIXTURE_STRATEGY="error"}static toSelectQuery(deleteQuery,options){let targetTableName=this.extractTargetTableName(deleteQuery.deleteClause),tableDefinition=this.resolveTableDefinition(targetTableName,options),targetAlias=deleteQuery.deleteClause.getSourceAliasName(),returningContext=deleteQuery.returningClause?this.buildReturningContext(deleteQuery.deleteClause,deleteQuery.usingClause,targetAlias,tableDefinition,options):null,selectClause=deleteQuery.returningClause?this.buildReturningSelectClause(deleteQuery.returningClause,returningContext):this.buildCountSelectClause(),fromClause=this.buildFromClause(deleteQuery.deleteClause,deleteQuery.usingClause),whereClause=deleteQuery.whereClause??null,selectQuery=new SimpleSelectQuery({withClause:deleteQuery.withClause??void 0,selectClause,fromClause,whereClause}),fixtureTables=options?.fixtureTables??[],fixtureMap=this.buildFixtureTableMap(fixtureTables),missingStrategy=options?.missingFixtureStrategy??this.DEFAULT_MISSING_FIXTURE_STRATEGY,originalWithClause=SelectQueryWithClauseHelper.detachWithClause(selectQuery),referencedTables=this.collectPhysicalTableReferences(selectQuery,originalWithClause),cteNames=this.collectCteNamesFromWithClause(originalWithClause),targetVariants=tableNameVariants(targetTableName);for(let variant of targetVariants)cteNames.has(variant)||referencedTables.add(variant);this.ensureFixtureCoverage(referencedTables,fixtureMap,missingStrategy);let filteredFixtures=this.filterFixtureTablesForReferences(fixtureTables,referencedTables),fixtureCtes=this.buildFixtureCtes(filteredFixtures),mergedWithClause=this.mergeWithClause(originalWithClause,fixtureCtes);return SelectQueryWithClauseHelper.setWithClause(selectQuery,mergedWithClause),selectQuery}static buildReturningSelectClause(returning,context){let selectItems=this.buildReturningSelectItems(returning,context);return new SelectClause(selectItems)}static buildReturningSelectItems(returning,context){let selectItems=[];for(let item of returning.items){if(this.isWildcardReturningItem(item)){selectItems.push(...this.expandReturningWildcard(context));continue}selectItems.push(this.buildDeleteReturningSelectItem(item,context))}return selectItems}static isWildcardReturningItem(item){return item.value instanceof ColumnReference&&item.value.column.name==="*"}static expandReturningWildcard(context){if(!context.targetDefinition)throw new Error("Cannot expand RETURNING * without table definition.");return context.targetDefinition.columns.map(column=>{let expression=this.composeDeleteColumnReference({namespaces:null,column:column.name},context);return new SelectItem(expression,column.name)})}static buildDeleteReturningSelectItem(item,context){let expression=rewriteValueComponentWithColumnResolver(item.value,column=>this.buildDeleteColumnReference(column,context)),alias=this.getReturningAlias(item);return new SelectItem(expression,alias)}static buildDeleteColumnReference(column,context){let parsed=this.parseReturningColumnName(column.toString());return this.composeDeleteColumnReference(parsed,context)}static composeDeleteColumnReference(parsedColumn,context){let definitionToValidate=this.findTableContextForNamespaces(parsedColumn.namespaces,context)?.tableDefinition??(parsedColumn.namespaces?void 0:context.targetDefinition);definitionToValidate&&this.ensureColumnExists(parsedColumn.column,definitionToValidate);let columnNamespace=parsedColumn.namespaces&&parsedColumn.namespaces.length>0?[...parsedColumn.namespaces]:context.targetAlias?[context.targetAlias]:null;return new ColumnReference(columnNamespace,parsedColumn.column)}static getReturningAlias(item){return item.identifier?.name?item.identifier.name:item.value instanceof ColumnReference?item.value.toString():null}static buildCountSelectClause(){let countFunction=new FunctionCall(null,"count",new RawString("*"),null),selectItem=new SelectItem(countFunction,"count");return new SelectClause([selectItem])}static buildFromClause(deleteClause,usingClause){if(!usingClause?.sources?.length)return new FromClause(deleteClause.source,null);let joins=usingClause.sources.map(source=>new JoinClause("cross join",source,null,!1));return new FromClause(deleteClause.source,joins)}static buildReturningContext(deleteClause,usingClause,targetAlias,targetDefinition,options){let{aliasMap,tableNameMap}=this.buildTableContexts(deleteClause,usingClause,options);return{aliasMap,tableNameMap,targetAlias,targetDefinition}}static buildTableContexts(deleteClause,usingClause,options){let aliasMap=new Map,tableNameMap=new Map,collectSource=source=>{let alias=source.getAliasName();if(!alias||!(source.datasource instanceof TableSource))return;let normalizedAlias=this.normalizeIdentifier(alias);if(aliasMap.has(normalizedAlias))return;let tableName=source.datasource.getSourceName(),tableDefinition=this.resolveTableDefinition(tableName,options),context={alias,tableName,tableDefinition};aliasMap.set(normalizedAlias,context);for(let variant of tableNameVariants(tableName))tableNameMap.has(variant)||tableNameMap.set(variant,context)};if(collectSource(deleteClause.source),usingClause)for(let source of usingClause.sources)collectSource(source);return{aliasMap,tableNameMap}}static parseReturningColumnName(columnName){let trimmed=columnName.trim();if(!trimmed)throw new Error("Returning column name cannot be empty.");try{let parsed=FullNameParser.parse(trimmed);return{namespaces:parsed.namespaces,column:parsed.name.name}}catch{let parts=trimmed.split(".").map(segment=>segment.trim()).filter(segment=>segment.length>0);if(parts.length===0)return{namespaces:null,column:trimmed};let column=parts.pop();return{namespaces:parts.length>0?parts:null,column}}}static findTableContextForNamespaces(namespaces,context){if(namespaces?.length)for(let depth=namespaces.length;depth>0;depth--){let identifier=namespaces.slice(namespaces.length-depth).join("."),normalized=this.normalizeIdentifier(identifier),aliasContext=context.aliasMap.get(normalized);if(aliasContext)return aliasContext;let tableContext=context.tableNameMap.get(normalized);if(tableContext)return tableContext}}static ensureColumnExists(columnName,tableDefinition){if(!tableDefinition)return;let normalized=this.normalizeIdentifier(columnName);if(!tableDefinition.columns.some(column=>this.normalizeIdentifier(column.name)===normalized))throw new Error(`Column '${columnName}' cannot be resolved for RETURNING output.`)}static resolveTableDefinition(tableName,options){if(options?.tableDefinitionResolver){let resolved=options.tableDefinitionResolver(tableName);if(resolved!==void 0)return resolved}let normalizedVariants=new Set(tableNameVariants(tableName));if(options?.tableDefinitions){let map=this.buildTableDefinitionMap(options.tableDefinitions);for(let variant of normalizedVariants){let definition=map.get(variant);if(definition)return definition}}if(options?.fixtureTables){let fixture=options.fixtureTables.find(f=>tableNameVariants(f.tableName).some(variant=>normalizedVariants.has(variant)));if(fixture)return this.convertFixtureToTableDefinition(fixture)}}static convertFixtureToTableDefinition(fixture){return{name:fixture.tableName,columns:fixture.columns.map(col=>({name:col.name,typeName:col.typeName,required:!1,defaultValue:col.defaultValue??null}))}}static buildTableDefinitionMap(registry){let map=new Map;for(let definition of Object.values(registry))for(let variant of tableNameVariants(definition.name))map.set(variant,definition);return map}static extractTargetTableName(deleteClause){let datasource=deleteClause.source.datasource;if(datasource instanceof TableSource)return datasource.getSourceName();throw new Error("Delete target must be a table source for conversion.")}static buildFixtureCtes(fixtures){return!fixtures||fixtures.length===0?[]:FixtureCteBuilder.buildFixtures(fixtures)}static collectPhysicalTableReferences(selectQuery,withClause){let referencedTables=this.collectReferencedTables(selectQuery),ignoredTables=this.collectCteNamesFromWithClause(withClause),tablesToShadow=new Set;for(let table of referencedTables)ignoredTables.has(table)||tablesToShadow.add(table);let cteReferencedTables=this.collectReferencedTablesFromWithClause(withClause);for(let table of cteReferencedTables)ignoredTables.has(table)||tablesToShadow.add(table);return tablesToShadow}static buildFixtureTableMap(fixtures){let map=new Map;for(let fixture of fixtures)for(let variant of tableNameVariants(fixture.tableName))map.set(variant,fixture);return map}static filterFixtureTablesForReferences(fixtures,referencedTables){if(!fixtures.length||referencedTables.size===0)return[];let filtered=[];for(let fixture of fixtures)tableNameVariants(fixture.tableName).some(variant=>referencedTables.has(variant))&&filtered.push(fixture);return filtered}static collectReferencedTablesFromWithClause(withClause){let tables=new Set;if(!withClause?.tables)return tables;for(let cte of withClause.tables)for(let table of this.collectReferencedTables(cte.query))tables.add(table);return tables}static ensureFixtureCoverage(referencedTables,fixtureMap,strategy){if(referencedTables.size===0)return;let missingTables=this.getMissingFixtureTables(referencedTables,fixtureMap);if(missingTables.length!==0&&strategy==="error")throw new Error(`Delete SELECT refers to tables without fixture coverage: ${missingTables.join(", ")}.`)}static collectReferencedTables(query){let sources=new TableSourceCollector(!1).collect(query),normalized=new Set;for(let source of sources)for(let variant of tableNameVariants(source.getSourceName()))normalized.add(variant);return normalized}static collectCteNamesFromWithClause(withClause){let names=new Set;if(!withClause?.tables)return names;for(let table of withClause.tables)for(let variant of tableNameVariants(table.getSourceAliasName()))names.add(variant);return names}static getMissingFixtureTables(referencedTables,fixtureMap){let missing=[];for(let table of referencedTables)tableNameVariants(table).some(variant=>fixtureMap.has(variant))||missing.push(table);return missing}static mergeWithClause(original,fixtureCtes){if(!fixtureCtes.length&&!original)return null;let combinedTables=[...fixtureCtes];if(original?.tables&&combinedTables.push(...original.tables),!combinedTables.length)return null;let merged=new WithClause(original?.recursive??!1,combinedTables);return merged.globalComments=original?.globalComments?[...original.globalComments]:null,merged.trailingComments=original?.trailingComments?[...original.trailingComments]:null,merged}static normalizeIdentifier(value){return value.trim().toLowerCase()}};var MergeResultSelectConverter=class{static{this.DEFAULT_MISSING_FIXTURE_STRATEGY="error"}static toSelectQuery(mergeQuery,options){let actionSelects=this.buildActionSelects(mergeQuery);if(actionSelects.length===0)throw new Error("MERGE query must include at least one action that affects rows.");let unionSource=this.combineSelects(actionSelects),derivedSource=new SourceExpression(new SubQuerySource(unionSource),new SourceAliasExpression("__merge_action_rows",null)),finalSelect=new SimpleSelectQuery({selectClause:this.buildCountSelectClause(),fromClause:new FromClause(derivedSource,null)}),fixtureTables=options?.fixtureTables??[],fixtureMap=this.buildFixtureTableMap(fixtureTables),missingStrategy=options?.missingFixtureStrategy??this.DEFAULT_MISSING_FIXTURE_STRATEGY,nativeWithClause=mergeQuery.withClause??null,referencedTables=this.collectPhysicalTableReferences(unionSource,nativeWithClause),cteNames=this.collectCteNamesFromWithClause(nativeWithClause),targetName=this.normalizeIdentifier(this.extractTargetTableName(mergeQuery.target));cteNames.has(targetName)||referencedTables.add(targetName),this.ensureFixtureCoverage(referencedTables,fixtureMap,missingStrategy);let filteredFixtures=this.filterFixtureTablesForReferences(fixtureTables,referencedTables),fixtureCtes=this.buildFixtureCtes(filteredFixtures),combinedWithClause=this.mergeWithClause(nativeWithClause,fixtureCtes);return SelectQueryWithClauseHelper.setWithClause(finalSelect,combinedWithClause),finalSelect}static buildActionSelects(mergeQuery){let selects=[];for(let clause of mergeQuery.whenClauses){let selectQuery=this.buildSelectForClause(mergeQuery,clause);selectQuery&&selects.push(selectQuery)}return selects}static buildSelectForClause(mergeQuery,clause){switch(clause.matchType){case"matched":return this.buildMatchedSelect(mergeQuery,clause);case"not_matched":case"not_matched_by_target":return this.buildNotMatchedSelect(mergeQuery,clause);case"not_matched_by_source":return this.buildNotMatchedBySourceSelect(mergeQuery,clause);default:return null}}static buildMatchedSelect(mergeQuery,clause){let action=clause.action;if(action instanceof MergeDoNothingAction||!(action instanceof MergeUpdateAction)&&!(action instanceof MergeDeleteAction))return null;let joinClause=new JoinClause("inner join",mergeQuery.source,new JoinOnClause(mergeQuery.onCondition),!1),combinedPredicate=this.combineConditions([clause.condition,this.buildActionWhereClause(action)]),whereClause=combinedPredicate?new WhereClause(combinedPredicate):null;return new SimpleSelectQuery({selectClause:this.buildLiteralSelectClause(),fromClause:new FromClause(mergeQuery.target,[joinClause]),whereClause})}static buildNotMatchedSelect(mergeQuery,clause){if(!(clause.action instanceof MergeInsertAction))return null;let notExistsExpression=this.buildNotExistsExpression(mergeQuery.target,mergeQuery.onCondition),combinedPredicate=this.combineConditions([notExistsExpression,clause.condition]),whereClause=combinedPredicate?new WhereClause(combinedPredicate):null;return new SimpleSelectQuery({selectClause:this.buildLiteralSelectClause(),fromClause:new FromClause(mergeQuery.source,null),whereClause})}static buildNotMatchedBySourceSelect(mergeQuery,clause){let action=clause.action;if(!(action instanceof MergeDeleteAction))return null;let notExistsExpression=this.buildNotExistsExpression(mergeQuery.source,mergeQuery.onCondition),combinedPredicate=this.combineConditions([notExistsExpression,clause.condition,this.buildActionWhereClause(action)]),whereClause=combinedPredicate?new WhereClause(combinedPredicate):null;return new SimpleSelectQuery({selectClause:this.buildLiteralSelectClause(),fromClause:new FromClause(mergeQuery.target,null),whereClause})}static buildNotExistsExpression(sourceReference,predicate){let existsSelect=new SimpleSelectQuery({selectClause:this.buildLiteralSelectClause(),fromClause:new FromClause(sourceReference,null),whereClause:new WhereClause(predicate)}),existsExpression=new UnaryExpression("exists",new InlineQuery(existsSelect));return new UnaryExpression("not",existsExpression)}static buildActionWhereClause(action){return action.whereClause?.condition??null}static combineConditions(predicates){let values=predicates.filter(predicate=>!!predicate);return values.length===0?null:values.reduce((acc,value)=>acc?new BinaryExpression(acc,"and",value):value,null)}static combineSelects(selects){if(selects.length===1)return selects[0];let combined=new BinarySelectQuery(selects[0],"union all",selects[1]);for(let i=2;i<selects.length;i++)combined=combined.unionAll(selects[i]);return combined}static buildLiteralSelectClause(){return new SelectClause([new SelectItem(new LiteralValue(1))])}static buildCountSelectClause(){let countFunction=new FunctionCall(null,"count",new RawString("*"),null),selectItem=new SelectItem(countFunction,"count");return new SelectClause([selectItem])}static buildFixtureCtes(fixtures){return!fixtures||fixtures.length===0?[]:FixtureCteBuilder.buildFixtures(fixtures)}static collectPhysicalTableReferences(query,withClause){let referencedTables=this.collectReferencedTables(query),ignoredTables=this.collectCteNamesFromWithClause(withClause),tablesToShadow=new Set;for(let table of referencedTables)ignoredTables.has(table)||tablesToShadow.add(table);let cteReferencedTables=this.collectReferencedTablesFromWithClause(withClause);for(let table of cteReferencedTables)ignoredTables.has(table)||tablesToShadow.add(table);return tablesToShadow}static filterFixtureTablesForReferences(fixtures,referencedTables){if(!fixtures.length||referencedTables.size===0)return[];let filtered=[];for(let fixture of fixtures)referencedTables.has(this.normalizeIdentifier(fixture.tableName))&&filtered.push(fixture);return filtered}static collectReferencedTablesFromWithClause(withClause){let tables=new Set;if(!withClause?.tables)return tables;for(let cte of withClause.tables)for(let table of this.collectReferencedTables(cte.query))tables.add(table);return tables}static extractTargetTableName(target){let datasource=target.datasource;if(datasource instanceof TableSource)return datasource.getSourceName();throw new Error("Merge target must be a table source for conversion.")}static buildFixtureTableMap(fixtures){let map=new Map;for(let fixture of fixtures)map.set(this.normalizeIdentifier(fixture.tableName),fixture);return map}static ensureFixtureCoverage(referencedTables,fixtureMap,strategy){if(referencedTables.size===0)return;let missingTables=this.getMissingFixtureTables(referencedTables,fixtureMap);if(missingTables.length!==0&&strategy==="error")throw new Error(`Merge SELECT refers to tables without fixture coverage: ${missingTables.join(", ")}.`)}static collectReferencedTables(query){let sources=new TableSourceCollector(!1).collect(query),normalized=new Set;for(let source of sources)normalized.add(this.normalizeIdentifier(source.getSourceName()));return normalized}static collectCteNamesFromWithClause(withClause){let names=new Set;if(!withClause?.tables)return names;for(let table of withClause.tables)names.add(this.normalizeIdentifier(table.getSourceAliasName()));return names}static getMissingFixtureTables(referencedTables,fixtureMap){let missing=[];for(let table of referencedTables)fixtureMap.has(table)||missing.push(table);return missing}static mergeWithClause(original,fixtureCtes){if(!fixtureCtes.length&&!original)return null;let combinedTables=[...fixtureCtes];if(original?.tables&&combinedTables.push(...original.tables),!combinedTables.length)return null;let merged=new WithClause(original?.recursive??!1,combinedTables);return merged.globalComments=original?.globalComments?[...original.globalComments]:null,merged.trailingComments=original?.trailingComments?[...original.trailingComments]:null,merged}static normalizeIdentifier(value){return value.trim().toLowerCase()}};var QueryBuilder=class _QueryBuilder{static buildBinaryQuery(queries,operator){if(!queries||queries.length===0)throw new Error("No queries provided to combine.");if(queries.length===1)throw new Error("At least two queries are required to create a BinarySelectQuery.");let wrap=q=>q instanceof ValuesQuery?_QueryBuilder.buildSimpleQuery(q):q,result=new BinarySelectQuery(wrap(queries[0]),operator,wrap(queries[1]));CTENormalizer.normalize(result);for(let i=2;i<queries.length;i++)result.appendSelectQuery(operator,wrap(queries[i]));return result}constructor(){}static buildSimpleQuery(query){if(query instanceof SimpleSelectQuery)return query;if(query instanceof BinarySelectQuery)return _QueryBuilder.buildSimpleBinaryQuery(query);if(query instanceof ValuesQuery)return _QueryBuilder.buildSimpleValuesQuery(query);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(query){let extractedOrderBy=_QueryBuilder.extractAndRemoveOrderByFromBinaryQuery(query),subQuerySource=new SubQuerySource(query),sourceExpr=new SourceExpression(subQuerySource,new SourceAliasExpression("bq",null)),fromClause=new FromClause(sourceExpr,null),selectClause=_QueryBuilder.createSelectAllClause(),q=new SimpleSelectQuery({selectClause,fromClause,orderByClause:extractedOrderBy});return CTENormalizer.normalize(q)}static extractAndRemoveOrderByFromBinaryQuery(query){return _QueryBuilder.findAndRemoveRightmostOrderBy(query)}static findAndRemoveRightmostOrderBy(query){if(query instanceof BinarySelectQuery){let rightOrderBy=_QueryBuilder.findAndRemoveRightmostOrderBy(query.right);return rightOrderBy||_QueryBuilder.findAndRemoveRightmostOrderBy(query.left)}else if(query instanceof SimpleSelectQuery){let orderBy=query.orderByClause;if(orderBy)return query.orderByClause=null,orderBy}return null}static buildSimpleValuesQuery(query){let columnCount=query.tuples.length>0?query.tuples[0].values.length:0;if(query.tuples.length===0)throw new Error("Empty VALUES clause cannot be converted to a SimpleSelectQuery");if(!query.columnAliases)throw new Error("Column aliases are required to convert a VALUES clause to SimpleSelectQuery. Please specify column aliases.");if(query.columnAliases.length!==columnCount)throw new Error(`The number of column aliases (${query.columnAliases.length}) does not match the number of columns in the first tuple (${columnCount}).`);let subQuerySource=new SubQuerySource(query),sourceExpr=new SourceExpression(subQuerySource,new SourceAliasExpression("vq",query.columnAliases)),fromClause=new FromClause(sourceExpr,null),selectItems=query.columnAliases.map(name=>new SelectItem(new ColumnReference("vq",name),name)),selectClause=new SelectClause(selectItems,null);return new SimpleSelectQuery({selectClause,fromClause})}static createSelectAllClause(){let columnRef=new ColumnReference(null,"*"),selectItem=new SelectItem(columnRef,"*");return new SelectClause([selectItem],null)}static buildCreateTableQuery(query,tableName,isTemporary=!1,ifNotExists=!1){return new CreateTableQuery({tableName,isTemporary,ifNotExists,asSelectQuery:query})}static buildInsertQuery(selectQuery,targetOrOptions,explicitColumns){let options=_QueryBuilder.normalizeInsertOptions(targetOrOptions,explicitColumns),columnNames=_QueryBuilder.prepareInsertColumns(selectQuery,options.columns??null),sourceExpr=SourceExpressionParser.parse(options.target);return new InsertQuery({insertClause:new InsertClause(sourceExpr,columnNames),selectQuery})}static convertInsertValuesToSelect(insertQuery){return InsertQuerySelectValuesConverter.toSelectUnion(insertQuery)}static convertInsertSelectToValues(insertQuery){return InsertQuerySelectValuesConverter.toValues(insertQuery)}static convertInsertToReturningSelect(insertQuery,options){return InsertResultSelectConverter.toSelectQuery(insertQuery,options)}static convertUpdateToReturningSelect(updateQuery,options){return UpdateResultSelectConverter.toSelectQuery(updateQuery,options)}static convertDeleteToReturningSelect(deleteQuery,options){return DeleteResultSelectConverter.toSelectQuery(deleteQuery,options)}static convertMergeToReturningSelect(mergeQuery,options){return MergeResultSelectConverter.toSelectQuery(mergeQuery,options)}static buildUpdateQuery(selectQuery,selectSourceOrOptions,updateTableExprRaw,primaryKeys){let options=_QueryBuilder.normalizeUpdateOptions(selectSourceOrOptions,updateTableExprRaw,primaryKeys),updateColumns=_QueryBuilder.prepareUpdateColumns(selectQuery,options.primaryKeys,options.columns??null),updateClause=new UpdateClause(SourceExpressionParser.parse(options.target)),targetAlias=updateClause.getSourceAliasName();if(!targetAlias)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let withClause=_QueryBuilder.extractWithClause(selectQuery),setItems=updateColumns.map(column=>new SetClauseItem(column,_QueryBuilder.toColumnReference(options.sourceAlias,column)));if(setItems.length===0)throw new Error("No updatable columns found. Ensure the select list contains at least one column other than the specified primary keys.");let setClause=new SetClause(setItems),fromClause=new FromClause(selectQuery.toSource(options.sourceAlias),null),whereClause=new WhereClause(_QueryBuilder.buildEqualityPredicate(targetAlias,options.sourceAlias,options.primaryKeys));return new UpdateQuery({updateClause,setClause,fromClause,whereClause,withClause:withClause??void 0})}static buildDeleteQuery(selectQuery,options){let normalized=_QueryBuilder.normalizeDeleteOptions(options),predicateColumns=_QueryBuilder.prepareDeleteColumns(selectQuery,normalized.primaryKeys,normalized.columns??null),deleteClause=new DeleteClause(SourceExpressionParser.parse(normalized.target)),targetAlias=deleteClause.getSourceAliasName();if(!targetAlias)throw new Error("Source expression does not have an alias. Please provide an alias for the delete target.");let withClause=_QueryBuilder.extractWithClause(selectQuery),predicate=_QueryBuilder.buildEqualityPredicate(targetAlias,normalized.sourceAlias,predicateColumns),sourceExpression=selectQuery.toSource(normalized.sourceAlias),existsSelectClause=new SelectClause([new SelectItem(new LiteralValue(1))]),existsSubquery=new SimpleSelectQuery({selectClause:existsSelectClause,fromClause:new FromClause(sourceExpression,null),whereClause:new WhereClause(predicate)}),whereClause=new WhereClause(new UnaryExpression("exists",new InlineQuery(existsSubquery)));return new DeleteQuery({deleteClause,whereClause,withClause:withClause??void 0})}static buildMergeQuery(selectQuery,options){let normalized=_QueryBuilder.normalizeMergeOptions(options),mergeColumnPlan=_QueryBuilder.prepareMergeColumns(selectQuery,normalized.primaryKeys,normalized.updateColumns??null,normalized.insertColumns??null,normalized.matchedAction??"update",normalized.notMatchedAction??"insert"),targetExpression=SourceExpressionParser.parse(normalized.target),targetAlias=targetExpression.getAliasName();if(!targetAlias)throw new Error("Source expression does not have an alias. Please provide an alias for the merge target.");let withClause=_QueryBuilder.extractWithClause(selectQuery),onCondition=_QueryBuilder.buildEqualityPredicate(targetAlias,normalized.sourceAlias,normalized.primaryKeys),sourceExpression=selectQuery.toSource(normalized.sourceAlias),whenClauses=[],matchedAction=normalized.matchedAction??"update";if(matchedAction==="update"){if(mergeColumnPlan.updateColumns.length===0)throw new Error("No columns available for MERGE update action. Provide updateColumns or ensure the select list includes non-key columns.");let setItems=mergeColumnPlan.updateColumns.map(column=>new SetClauseItem(column,_QueryBuilder.toColumnReference(normalized.sourceAlias,column)));whenClauses.push(new MergeWhenClause("matched",new MergeUpdateAction(new SetClause(setItems))))}else matchedAction==="delete"?whenClauses.push(new MergeWhenClause("matched",new MergeDeleteAction)):matchedAction==="doNothing"&&whenClauses.push(new MergeWhenClause("matched",new MergeDoNothingAction));let notMatchedAction=normalized.notMatchedAction??"insert";if(notMatchedAction==="insert"){if(mergeColumnPlan.insertColumns.length===0)throw new Error("Unable to infer MERGE insert columns. Provide insertColumns explicitly.");let insertValues=new ValueList(mergeColumnPlan.insertColumns.map(column=>_QueryBuilder.toColumnReference(normalized.sourceAlias,column)));whenClauses.push(new MergeWhenClause("not_matched",new MergeInsertAction({columns:mergeColumnPlan.insertColumns,values:insertValues})))}else notMatchedAction==="doNothing"&&whenClauses.push(new MergeWhenClause("not_matched",new MergeDoNothingAction));let notMatchedBySourceAction=normalized.notMatchedBySourceAction??"doNothing";if(notMatchedBySourceAction==="delete"?whenClauses.push(new MergeWhenClause("not_matched_by_source",new MergeDeleteAction)):notMatchedBySourceAction==="doNothing"&&whenClauses.push(new MergeWhenClause("not_matched_by_source",new MergeDoNothingAction)),whenClauses.length===0)throw new Error("At least one MERGE action must be generated. Adjust the merge conversion options.");return new MergeQuery({withClause:withClause??void 0,target:targetExpression,source:sourceExpression,onCondition,whenClauses})}static normalizeInsertOptions(targetOrOptions,explicitColumns){return typeof targetOrOptions=="string"?{target:targetOrOptions,columns:explicitColumns}:explicitColumns&&explicitColumns.length>0?{...targetOrOptions,columns:explicitColumns}:{...targetOrOptions}}static normalizeUpdateOptions(selectSourceOrOptions,updateTableExprRaw,primaryKeys){if(typeof selectSourceOrOptions=="string"){if(!updateTableExprRaw)throw new Error("updateTableExprRaw is required when using the legacy buildUpdateQuery signature.");if(primaryKeys===void 0)throw new Error("primaryKeys are required when using the legacy buildUpdateQuery signature.");return{target:updateTableExprRaw,primaryKeys:_QueryBuilder.normalizeColumnArray(primaryKeys),sourceAlias:selectSourceOrOptions}}return{target:selectSourceOrOptions.target,primaryKeys:_QueryBuilder.normalizeColumnArray(selectSourceOrOptions.primaryKeys),sourceAlias:selectSourceOrOptions.sourceAlias??"src",columns:selectSourceOrOptions.columns}}static normalizeDeleteOptions(options){return{...options,primaryKeys:_QueryBuilder.normalizeColumnArray(options.primaryKeys),sourceAlias:options.sourceAlias??"src"}}static normalizeMergeOptions(options){return{...options,primaryKeys:_QueryBuilder.normalizeColumnArray(options.primaryKeys),sourceAlias:options.sourceAlias??"src"}}static normalizeColumnArray(columns){let normalized=(Array.isArray(columns)?columns:[columns]).map(col=>col.trim()).filter(col=>col.length>0);if(!normalized.length)throw new Error("At least one column must be specified.");return normalized}static collectSelectItems(selectQuery){return new SelectValueCollector().collect(selectQuery)}static collectSelectColumnNames(selectQuery){let items=_QueryBuilder.collectSelectItems(selectQuery),names=[];for(let item of items){if(!item.name||item.name==="*")throw new Error("Columns cannot be inferred from the selectQuery. Make sure you are not using wildcards or unnamed columns.");names.includes(item.name)||names.push(item.name)}if(!names.length)throw new Error("Unable to determine any column names from selectQuery.");return names}static ensurePrimaryKeys(selectColumns,primaryKeys){let available=new Set(selectColumns);for(let pk of primaryKeys)if(!available.has(pk))throw new Error(`Primary key column '${pk}' is not present in selectQuery select list.`)}static prepareInsertColumns(selectQuery,optionColumns){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);if(optionColumns&&optionColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(optionColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>!selectColumns.includes(name));if(missing.length>0)throw new Error(`Columns specified in conversion options were not found in selectQuery select list: [${missing.join(", ")}].`);return _QueryBuilder.rebuildSelectClause(selectQuery,uniqueNormalized),_QueryBuilder.ensureSelectClauseSize(selectQuery,uniqueNormalized.length),uniqueNormalized}return _QueryBuilder.ensureSelectClauseSize(selectQuery,selectColumns.length),selectColumns}static prepareUpdateColumns(selectQuery,primaryKeys,explicitColumns){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);_QueryBuilder.ensurePrimaryKeys(selectColumns,primaryKeys);let primaryKeySet=new Set(primaryKeys),updateCandidates=selectColumns.filter(name=>!primaryKeySet.has(name)),updateColumnsOrdered;if(explicitColumns&&explicitColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>primaryKeySet.has(name)||!updateCandidates.includes(name));if(missing.length>0)throw new Error(`Provided update columns were not found in selectQuery output or are primary keys: [${missing.join(", ")}].`);updateColumnsOrdered=uniqueNormalized}else updateColumnsOrdered=Array.from(new Set(updateCandidates));let desiredOrder=Array.from(new Set([...primaryKeys,...updateColumnsOrdered]));return _QueryBuilder.rebuildSelectClause(selectQuery,desiredOrder),_QueryBuilder.ensureSelectClauseSize(selectQuery,desiredOrder.length),updateColumnsOrdered}static prepareDeleteColumns(selectQuery,primaryKeys,explicitColumns){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);_QueryBuilder.ensurePrimaryKeys(selectColumns,primaryKeys);let primaryKeySet=new Set(primaryKeys),matchColumns=[];if(explicitColumns&&explicitColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitColumns),preferred=new Set(normalized);matchColumns=selectColumns.filter(name=>preferred.has(name)&&!primaryKeySet.has(name))}let requiredColumns=new Set;primaryKeys.forEach(key=>requiredColumns.add(key)),matchColumns.forEach(col=>requiredColumns.add(col));let desiredOrder=selectColumns.filter(name=>requiredColumns.has(name));return _QueryBuilder.rebuildSelectClause(selectQuery,desiredOrder),_QueryBuilder.ensureSelectClauseSize(selectQuery,desiredOrder.length),desiredOrder}static prepareMergeColumns(selectQuery,primaryKeys,explicitUpdateColumns,explicitInsertColumns,matchedAction,notMatchedAction){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);_QueryBuilder.ensurePrimaryKeys(selectColumns,primaryKeys);let primaryKeySet=new Set(primaryKeys),updateColumnsOrdered=[];if(matchedAction==="update"){let candidates=selectColumns.filter(name=>!primaryKeySet.has(name));if(explicitUpdateColumns&&explicitUpdateColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitUpdateColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>primaryKeySet.has(name)||!candidates.includes(name));if(missing.length>0)throw new Error(`Provided update columns were not found in selectQuery output or are primary keys: [${missing.join(", ")}].`);updateColumnsOrdered=uniqueNormalized}else updateColumnsOrdered=Array.from(new Set(candidates))}let insertColumnsOrdered=[];if(notMatchedAction==="insert")if(explicitInsertColumns&&explicitInsertColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitInsertColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>!selectColumns.includes(name));if(missing.length>0)throw new Error(`Provided insert columns were not found in selectQuery output: [${missing.join(", ")}].`);insertColumnsOrdered=uniqueNormalized}else insertColumnsOrdered=Array.from(new Set(selectColumns));let desiredOrder=Array.from(new Set([...primaryKeys,...updateColumnsOrdered,...insertColumnsOrdered,...selectColumns])).filter(name=>selectColumns.includes(name));return _QueryBuilder.rebuildSelectClause(selectQuery,desiredOrder),_QueryBuilder.ensureSelectClauseSize(selectQuery,desiredOrder.length),{updateColumns:matchedAction==="update"?updateColumnsOrdered:[],insertColumns:notMatchedAction==="insert"?insertColumnsOrdered:[]}}static rebuildSelectClause(selectQuery,desiredColumns){let itemMap=new Map;for(let item of selectQuery.selectClause.items){let name=_QueryBuilder.getSelectItemName(item);name&&(itemMap.has(name)||itemMap.set(name,item))}let rebuiltItems=[],seen=new Set;for(let column of desiredColumns){if(seen.has(column))continue;let item=itemMap.get(column);if(!item)throw new Error(`Column '${column}' not found in select clause.`);rebuiltItems.push(item),seen.add(column)}if(!rebuiltItems.length)throw new Error("Unable to rebuild select clause with the requested columns.");selectQuery.selectClause.items=rebuiltItems}static getSelectItemName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}static ensureSelectClauseSize(selectQuery,expected){if(selectQuery.selectClause.items.length!==expected)throw new Error(`Select clause column count (${selectQuery.selectClause.items.length}) does not match expected count (${expected}).`)}static extractWithClause(selectQuery){let collected=new CTECollector().collect(selectQuery);return collected.length===0?null:(new CTEDisabler().execute(selectQuery),new WithClause(!1,collected))}static buildEqualityPredicate(leftAlias,rightAlias,columns){let uniqueColumns=_QueryBuilder.mergeUniqueColumns(columns);if(!uniqueColumns.length)throw new Error("At least one column is required to build a comparison predicate.");let predicate=null;for(let column of uniqueColumns){let comparison=new BinaryExpression(_QueryBuilder.toColumnReference(leftAlias,column),"=",_QueryBuilder.toColumnReference(rightAlias,column));predicate=predicate?new BinaryExpression(predicate,"and",comparison):comparison}return predicate}static toColumnReference(alias,column){return new ColumnReference(alias,column)}static mergeUniqueColumns(columns){let seen=new Set,result=[];for(let column of columns)seen.has(column)||(seen.add(column),result.push(column));return result}};var SimpleSelectQuery=class extends SqlComponent{constructor(params){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.cteNameCache=new Set;this.withClause=params.withClause??null,this.selectClause=params.selectClause,this.fromClause=params.fromClause??null,this.whereClause=params.whereClause??null,this.groupByClause=params.groupByClause??null,this.havingClause=params.havingClause??null,this.orderByClause=params.orderByClause??null,this.windowClause=params.windowClause??null,this.limitClause=params.limitClause??null,this.offsetClause=params.offsetClause??null,this.fetchClause=params.fetchClause??null,this.forClause=params.forClause??null,this.initializeCTECache()}static{this.kind=Symbol("SelectQuery")}initializeCTECache(){if(this.cteNameCache.clear(),this.withClause?.tables)for(let table of this.withClause.tables)this.cteNameCache.add(table.aliasExpression.table.name)}toUnion(rightQuery){return this.toBinaryQuery("union",rightQuery)}toUnionAll(rightQuery){return this.toBinaryQuery("union all",rightQuery)}toInsertQuery(options){return QueryBuilder.buildInsertQuery(this,options)}toUpdateQuery(options){return QueryBuilder.buildUpdateQuery(this,options)}toDeleteQuery(options){return QueryBuilder.buildDeleteQuery(this,options)}toMergeQuery(options){return QueryBuilder.buildMergeQuery(this,options)}toIntersect(rightQuery){return this.toBinaryQuery("intersect",rightQuery)}toIntersectAll(rightQuery){return this.toBinaryQuery("intersect all",rightQuery)}toExcept(rightQuery){return this.toBinaryQuery("except",rightQuery)}toExceptAll(rightQuery){return this.toBinaryQuery("except all",rightQuery)}toBinaryQuery(operator,rightQuery){return QueryBuilder.buildBinaryQuery([this,rightQuery],operator)}appendWhereRaw(rawCondition){let parsedCondition=ValueParser.parse(rawCondition);this.appendWhere(parsedCondition)}appendWhere(condition){this.whereClause?this.whereClause.condition=new BinaryExpression(this.whereClause.condition,"and",condition):this.whereClause=new WhereClause(condition)}appendHavingRaw(rawCondition){let parsedCondition=ValueParser.parse(rawCondition);this.appendHaving(parsedCondition)}appendHaving(condition){this.havingClause?this.havingClause.condition=new BinaryExpression(this.havingClause.condition,"and",condition):this.havingClause=new HavingClause(condition)}innerJoinRaw(joinSourceRawText,alias,columns,resolver=null){this.joinSourceRaw("inner join",joinSourceRawText,alias,columns,resolver)}leftJoinRaw(joinSourceRawText,alias,columns,resolver=null){this.joinSourceRaw("left join",joinSourceRawText,alias,columns,resolver)}rightJoinRaw(joinSourceRawText,alias,columns,resolver=null){this.joinSourceRaw("right join",joinSourceRawText,alias,columns,resolver)}innerJoin(sourceExpr,columns,resolver=null){this.joinSource("inner join",sourceExpr,columns,resolver)}leftJoin(sourceExpr,columns,resolver=null){this.joinSource("left join",sourceExpr,columns,resolver)}rightJoin(sourceExpr,columns,resolver=null){this.joinSource("right join",sourceExpr,columns,resolver)}joinSourceRaw(joinType,joinSourceRawText,alias,columns,resolver=null){let tableSource=SourceParser.parse(joinSourceRawText),sourceExpr=new SourceExpression(tableSource,new SourceAliasExpression(alias,null));this.joinSource(joinType,sourceExpr,columns,resolver)}joinSource(joinType,sourceExpr,columns,resolver=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let columnsArr=Array.isArray(columns)?columns:[columns],valueSets=new SelectableColumnCollector(resolver).collect(this),joinCondition=null,count=0,sourceAlias=sourceExpr.getAliasName();if(!sourceAlias)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let valueSet of valueSets)if(columnsArr.some(col=>col==valueSet.name)){let expr=new BinaryExpression(valueSet.value,"=",new ColumnReference([sourceAlias],valueSet.name));joinCondition?joinCondition=new BinaryExpression(joinCondition,"and",expr):joinCondition=expr,count++}if(!joinCondition||count!==columnsArr.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${columnsArr.join(", ")}`);let joinOnClause=new JoinOnClause(joinCondition),joinClause=new JoinClause(joinType,sourceExpr,joinOnClause,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(joinClause):this.fromClause.joins=[joinClause]),CTENormalizer.normalize(this)}toSource(alias){if(!alias||alias.trim()==="")throw new Error("Alias is required for toSource(). Please specify a non-empty alias name.");return new SourceExpression(new SubQuerySource(this),new SourceAliasExpression(alias,null))}appendWith(commonTable){let tables=Array.isArray(commonTable)?commonTable:[commonTable];this.withClause?this.withClause.tables.push(...tables):this.withClause=new WithClause(!1,tables),CTENormalizer.normalize(this)}appendWithRaw(rawText,alias){let query=SelectQueryParser.parse(rawText),commonTable=new CommonTable(query,alias,null);this.appendWith(commonTable)}overrideSelectItemExpr(columnName,fn){let items=this.selectClause.items.filter(item2=>item2.identifier?.name===columnName);if(items.length===0)throw new Error(`Column ${columnName} not found in the query`);if(items.length>1)throw new Error(`Duplicate column name ${columnName} found in the query`);let item=items[0],exprSql=new Formatter().visit(item.value),newValue=fn(exprSql);item.value=ValueParser.parse(newValue)}appendWhereExpr(columnName,exprBuilder,options){if(options&&options.upstream){let queries=new UpstreamSelectQueryFinder().find(this,[columnName]),collector=new SelectableColumnCollector,formatter2=new Formatter;for(let q of queries){let exprs=collector.collect(q).filter(item=>item.name===columnName).map(item=>item.value);if(exprs.length!==1)throw new Error(`Expected exactly one expression for column '${columnName}'`);let exprStr=formatter2.format(exprs[0]);q.appendWhereRaw(exprBuilder(exprStr))}}else{let collector=new SelectableColumnCollector,formatter2=new Formatter,exprs=collector.collect(this).filter(item=>item.name===columnName).map(item=>item.value);if(exprs.length!==1)throw new Error(`Expected exactly one expression for column '${columnName}'`);let exprStr=formatter2.format(exprs[0]);this.appendWhereRaw(exprBuilder(exprStr))}}setParameter(name,value){return ParameterHelper.set(this,name,value),this}toSimpleQuery(){return this}addCTE(name,query,options){if(!name||name.trim()==="")throw new InvalidCTENameError(name,"name cannot be empty or whitespace-only");if(this.hasCTE(name))throw new DuplicateCTEError(name);let materialized=options?.materialized??null,commonTable=new CommonTable(query,name,materialized);return this.appendWith(commonTable),this.cteNameCache.add(name),this}removeCTE(name){if(!this.hasCTE(name))throw new CTENotFoundError(name);return this.withClause&&(this.withClause.tables=this.withClause.tables.filter(table=>table.aliasExpression.table.name!==name),this.withClause.tables.length===0&&(this.withClause=null)),this.cteNameCache.delete(name),this}hasCTE(name){return this.cteNameCache.has(name)}getCTENames(){return this.withClause?.tables.map(table=>table.aliasExpression.table.name)??[]}replaceCTE(name,query,options){if(!name||name.trim()==="")throw new InvalidCTENameError(name,"name cannot be empty or whitespace-only");this.hasCTE(name)&&this.removeCTE(name);let materialized=options?.materialized??null,commonTable=new CommonTable(query,name,materialized);return this.appendWith(commonTable),this.cteNameCache.add(name),this}};var SelectClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The SELECT clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,distinct=null,selectTokenComments=idx<lexemes.length?lexemes[idx].comments:null;if(lexemes[idx].value!=="select")throw new Error(`Syntax error at position ${idx}: Expected 'SELECT' keyword but found "${lexemes[idx].value}". SELECT clauses must start with the SELECT keyword.`);idx++;let hints=[];for(;idx<lexemes.length&&HintClause.isHintClause(lexemes[idx].value);){let hintContent=HintClause.extractHintContent(lexemes[idx].value);hints.push(new HintClause(hintContent)),idx++}if(idx<lexemes.length&&lexemes[idx].value==="distinct")idx++,distinct=new Distinct;else if(idx<lexemes.length&&lexemes[idx].value==="distinct on"){idx++;let argument=ValueParser.parseArgument(4,8,lexemes,idx);distinct=new DistinctOn(argument.value),idx=argument.newIndex}let items=[],item=SelectItemParser.parseItem(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=SelectItemParser.parseItem(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No select items found. The SELECT clause requires at least one expression to select.`);return{value:new SelectClause(items,distinct,hints),newIndex:idx}}},SelectItemParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseItem(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The select item is complete but there are additional tokens.`);return result.value}static parseItem(lexemes,index){let idx=index,valueTokenComments=this.extractValueTokenComments(lexemes,idx),parsedValue=ValueParser.parseFromLexeme(lexemes,idx),value=parsedValue.value;idx=parsedValue.newIndex;let{asComments,newIndex:asIndex}=this.parseAsKeyword(lexemes,idx);if(idx=asIndex,idx<lexemes.length&&lexemes[idx].type&64){let alias=lexemes[idx].value,aliasComments=lexemes[idx].comments,aliasPositionedComments=lexemes[idx].positionedComments;idx++;let selectItem2=new SelectItem(value,alias);return this.applyValueTokenComments(selectItem2,valueTokenComments),this.applyAsKeywordComments(selectItem2,asComments),this.applyAliasComments(selectItem2,aliasComments,aliasPositionedComments),{value:selectItem2,newIndex:idx}}else if(value instanceof ColumnReference&&value.column.name!=="*"){let selectItem2=new SelectItem(value,value.column.name);return this.applyValueTokenComments(selectItem2,valueTokenComments),this.applyAsKeywordComments(selectItem2,asComments),{value:selectItem2,newIndex:idx}}let selectItem=new SelectItem(value);return this.applyValueTokenComments(selectItem,valueTokenComments),this.applyAsKeywordComments(selectItem,asComments),{value:selectItem,newIndex:idx}}static clearPositionedCommentsRecursively(component){!component||typeof component!="object"||("positionedComments"in component&&(component.positionedComments=null),component.left&&this.clearPositionedCommentsRecursively(component.left),component.right&&this.clearPositionedCommentsRecursively(component.right),component.qualifiedName&&this.clearPositionedCommentsRecursively(component.qualifiedName),component.table&&this.clearPositionedCommentsRecursively(component.table),component.name&&this.clearPositionedCommentsRecursively(component.name),component.args&&Array.isArray(component.args)&&component.args.forEach(arg=>{this.clearPositionedCommentsRecursively(arg)}),component.value&&this.clearPositionedCommentsRecursively(component.value))}static extractValueTokenComments(lexemes,index){if(index>=lexemes.length)return{positioned:null,legacy:null};let token=lexemes[index];return{positioned:token.positionedComments&&token.positionedComments.length>0?token.positionedComments:null,legacy:null}}static parseAsKeyword(lexemes,index){if(index>=lexemes.length||lexemes[index].value!=="as")return{asComments:{positioned:null,legacy:null},newIndex:index};let asToken=lexemes[index];return{asComments:{positioned:asToken.positionedComments&&asToken.positionedComments.length>0?asToken.positionedComments:null,legacy:asToken.comments&&asToken.comments.length>0?asToken.comments:null},newIndex:index+1}}static applyValueTokenComments(selectItem,valueTokenComments){if(valueTokenComments.positioned){for(let posComment of valueTokenComments.positioned)selectItem.addPositionedComments(posComment.position,posComment.comments);this.clearValueTokenComments(selectItem)}}static applyAsKeywordComments(selectItem,asComments){asComments.positioned?selectItem.asKeywordPositionedComments=asComments.positioned:asComments.legacy&&(selectItem.asKeywordComments=asComments.legacy)}static applyAliasComments(selectItem,aliasComments,aliasPositionedComments){aliasPositionedComments&&aliasPositionedComments.length>0?selectItem.aliasPositionedComments=aliasPositionedComments:aliasComments&&aliasComments.length>0&&(selectItem.aliasComments=aliasComments)}static clearValueTokenComments(selectItem){if("positionedComments"in selectItem.value&&(selectItem.value.positionedComments=null),selectItem.value instanceof ColumnReference){let columnRef=selectItem.value;columnRef.qualifiedName&&columnRef.qualifiedName.name&&(columnRef.qualifiedName.name.positionedComments=null)}selectItem.value instanceof BinaryExpression&&this.clearPositionedCommentsRecursively(selectItem.value)}};var JoinOnClauseParser=class{static tryParse(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].value==="on"){idx++;let condition=ValueParser.parseFromLexeme(lexemes,idx);return idx=condition.newIndex,{value:new JoinOnClause(condition.value),newIndex:idx}}return null}};var JoinUsingClauseParser=class{static tryParse(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].value==="using"){idx++;let result=ValueParser.parseArgument(4,8,lexemes,idx),usingColumns=result.value;return idx=result.newIndex,{value:new JoinUsingClause(usingColumns),newIndex:idx}}return null}};var JoinClauseParser=class{static tryParse(lexemes,index){let idx=index,joins=[];for(;this.isJoinCommand(lexemes,idx);){let joinClause=this.parseJoinClause(lexemes,idx);joins.push(joinClause.value),idx=joinClause.newIndex}return joins.length>0?{value:joins,newIndex:idx}:null}static isJoinKeyword(value){return!!joinkeywordParser.parse(value,0)}static parseLateral(lexemes,index){let idx=index;return idx<lexemes.length&&lexemes[idx].value==="lateral"?(idx++,{value:!0,newIndex:idx}):{value:!1,newIndex:idx}}static isJoinCommand(lexemes,index){return index>=lexemes.length?!1:!!(lexemes[index].type&16||this.isJoinKeyword(lexemes[index].value)===!0)}static parseJoinClause(lexemes,index){let idx=index,{joinType,joinComments,newIndex:joinIndex}=this.parseJoinKeyword(lexemes,idx);idx=joinIndex;let lateralResult=this.parseLateral(lexemes,idx),lateral=lateralResult.value;idx=lateralResult.newIndex;let sourceResult=SourceExpressionParser.parseFromLexeme(lexemes,idx);idx=sourceResult.newIndex;let joinClause=this.parseJoinCondition(lexemes,idx,joinType,sourceResult.value,lateral,joinComments);if(joinClause)return joinClause;let naturalJoinClause=new JoinClause(joinType,sourceResult.value,null,lateral);return this.applyJoinComments(naturalJoinClause,joinComments),{value:naturalJoinClause,newIndex:idx}}static parseJoinKeyword(lexemes,index){let joinType=lexemes[index].value===","?"cross join":lexemes[index].value,joinComments=this.extractJoinKeywordComments(lexemes[index]);return{joinType,joinComments,newIndex:index+1}}static extractJoinKeywordComments(token){return{positioned:token.positionedComments&&token.positionedComments.length>0?token.positionedComments:null,legacy:token.comments&&token.comments.length>0?token.comments:null}}static parseJoinCondition(lexemes,index,joinType,sourceValue,lateral,joinComments){if(index>=lexemes.length)return null;let onResult=JoinOnClauseParser.tryParse(lexemes,index);if(onResult){let joinClause=new JoinClause(joinType,sourceValue,onResult.value,lateral);return this.applyJoinComments(joinClause,joinComments),{value:joinClause,newIndex:onResult.newIndex}}let usingResult=JoinUsingClauseParser.tryParse(lexemes,index);if(usingResult){let joinClause=new JoinClause(joinType,sourceValue,usingResult.value,lateral);return this.applyJoinComments(joinClause,joinComments),{value:joinClause,newIndex:usingResult.newIndex}}return null}static applyJoinComments(joinClause,joinComments){joinComments.positioned?joinClause.joinKeywordPositionedComments=joinComments.positioned:joinComments.legacy&&(joinClause.joinKeywordComments=joinComments.legacy)}};var CommentUtils=class{static{this.SIGNIFICANT_SQL_KEYWORDS=new Set(["select","from","where","group by","having","order by","limit","offset"])}static collectClauseComments(lexemes,currentIndex,keywordValue){let normalizedKeyword=keywordValue.toLowerCase();if(currentIndex>=lexemes.length||lexemes[currentIndex].value.toLowerCase()!==normalizedKeyword)return null;let comments=[];lexemes[currentIndex].comments&&comments.push(...lexemes[currentIndex].comments);let checkIndex=currentIndex-1;for(;checkIndex>=0;){let prevToken=lexemes[checkIndex];if(prevToken.comments&&prevToken.comments.length>0){let clauseSpecificComments=prevToken.comments.filter(comment=>{let lowerComment=comment.toLowerCase();return lowerComment.includes(normalizedKeyword)||lowerComment.includes("\u306E")||lowerComment.includes("\u30B3\u30E1\u30F3\u30C8")});clauseSpecificComments.length>0&&(comments.unshift(...clauseSpecificComments),prevToken.comments=prevToken.comments.filter(c=>!clauseSpecificComments.includes(c)),prevToken.comments.length===0&&(prevToken.comments=null));break}if(this.isSignificantSqlKeyword(prevToken.value))break;checkIndex--}return comments.length>0?comments:null}static isSignificantSqlKeyword(value){return this.SIGNIFICANT_SQL_KEYWORDS.has(value.toLowerCase())}};var FromClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The FROM clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,fromTokenComments=CommentUtils.collectClauseComments(lexemes,idx,"from");if(lexemes[idx].value!=="from")throw new Error(`Syntax error at position ${idx}: Expected 'FROM' keyword but found "${lexemes[idx].value}". FROM clauses must start with the FROM keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FROM' keyword. The FROM clause requires a table reference.");let sourceExpression=SourceExpressionParser.parseFromLexeme(lexemes,idx);idx=sourceExpression.newIndex;let join=JoinClauseParser.tryParse(lexemes,idx);if(idx=join?.newIndex||idx,join!==null){let clause=new FromClause(sourceExpression.value,join.value);return{value:clause,newIndex:idx}}else{let clause=new FromClause(sourceExpression.value,null);return{value:clause,newIndex:idx}}}};var WhereClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The WHERE clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,whereLexeme=lexemes[idx],whereTokenComments=CommentUtils.collectClauseComments(lexemes,idx,"where"),wherePositionedComments=whereLexeme.positionedComments;if(whereLexeme.value!=="where")throw new Error(`Syntax error at position ${idx}: Expected 'WHERE' keyword but found "${lexemes[idx].value}". WHERE clauses must start with the WHERE keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'WHERE' keyword. The WHERE clause requires a condition expression.");let item=ValueParser.parseFromLexeme(lexemes,idx),clause=new WhereClause(item.value);return clause.comments=whereTokenComments,wherePositionedComments&&wherePositionedComments.length>0&&(clause.positionedComments=wherePositionedComments.map(comment=>({position:comment.position,comments:[...comment.comments]}))),{value:clause,newIndex:item.newIndex}}};var GroupByClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The GROUP BY clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="group by")throw new Error(`Syntax error at position ${idx}: Expected 'GROUP BY' keyword but found "${lexemes[idx].value}". GROUP BY clauses must start with the GROUP BY keywords.`);idx++;let mode=null,modeCandidate=lexemes[idx]?.value.toLowerCase();if((modeCandidate==="all"||modeCandidate==="distinct")&&(mode=modeCandidate,idx++),idx>=lexemes.length){if(mode==="all")return{value:new GroupByClause([],mode),newIndex:idx};throw new Error("Syntax error: Unexpected end of input after 'GROUP BY' keyword. The GROUP BY clause requires at least one expression to group by.")}let items=[];if(!this.isClauseBoundary(lexemes[idx])){let 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&&mode!=="all")throw new Error(`Syntax error at position ${index}: No grouping expressions found. The GROUP BY clause requires at least one expression to group by.`);return{value:new GroupByClause(items,mode),newIndex:idx}}static isClauseBoundary(lexeme){return["having","window","order by","limit","offset","fetch","for"].includes(lexeme.value)}static parseItem(lexemes,index){let idx=index,parsedValue=ValueParser.parseFromLexeme(lexemes,idx),value=parsedValue.value;return idx=parsedValue.newIndex,{value,newIndex:idx}}};var HavingClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The HAVING clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="having")throw new Error(`Syntax error at position ${idx}: Expected 'HAVING' keyword but found "${lexemes[idx].value}". HAVING clauses must start with the HAVING keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'HAVING' keyword. The HAVING clause requires a condition expression.");let item=ValueParser.parseFromLexeme(lexemes,idx);return{value:new HavingClause(item.value),newIndex:item.newIndex}}};var WindowClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The WINDOW clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="window")throw new Error(`Syntax error at position ${idx}: Expected 'WINDOW' keyword but found "${lexemes[idx].value}". WINDOW clauses must start with the WINDOW keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'WINDOW' keyword. The WINDOW clause requires at least one window definition.");let windows=[];for(;idx<lexemes.length;){if(idx>=lexemes.length||lexemes[idx].type!==64)throw new Error("Syntax error: Expected window name after 'WINDOW' keyword.");let name=lexemes[idx].value;if(idx++,idx>=lexemes.length||lexemes[idx].value!=="as")throw new Error(`Syntax error at position ${idx}: Expected 'AS' keyword after window name.`);idx++;let expr=WindowExpressionParser.parseFromLexeme(lexemes,idx);if(idx=expr.newIndex,windows.push(new WindowFrameClause(name,expr.value)),idx<lexemes.length&&lexemes[idx].type&16)idx++;else break}if(windows.length===0)throw new Error("At least one WINDOW clause is required after WINDOW keyword.");return{value:new WindowsClause(windows),newIndex:idx}}};var LimitClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The LIMIT clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="limit")throw new Error(`Syntax error at position ${idx}: Expected 'LIMIT' keyword but found "${lexemes[idx].value}". LIMIT clauses must start with the LIMIT keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'LIMIT' keyword. The LIMIT clause requires a numeric expression.");let limitItem=ValueParser.parseFromLexeme(lexemes,idx);return idx=limitItem.newIndex,{value:new LimitClause(limitItem.value),newIndex:idx}}};var ForClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The FOR clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value.toLowerCase()!=="for")throw new Error(`Syntax error at position ${idx}: Expected 'FOR' keyword but found "${lexemes[idx].value}". FOR clauses must start with the FOR keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FOR' keyword. The FOR clause requires a lock mode specification.");let lockModeValue=lexemes[idx].value,lockMode;switch(lockModeValue){case"update":lockMode="update",idx++;break;case"share":lockMode="share",idx++;break;case"key share":lockMode="key share",idx++;break;case"no key update":lockMode="no key update",idx++;break;default:throw new Error(`Syntax error at position ${idx}: Invalid lock mode "${lockModeValue}". Valid lock modes are: UPDATE, SHARE, KEY SHARE, NO KEY UPDATE.`)}return{value:new ForClause(lockMode),newIndex:idx}}};var ValuesQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The VALUES clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(idx>=lexemes.length)throw new Error(`Syntax error at position ${idx}: Expected 'VALUES' keyword but input ended early.`);let valuesLexeme=lexemes[idx];if(valuesLexeme.value.toLowerCase()!=="values")throw new Error(`Syntax error at position ${idx}: Expected 'VALUES' keyword but found "${valuesLexeme.value}". VALUES clauses must start with the VALUES keyword.`);let valuesComments=extractLexemeComments(valuesLexeme);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'VALUES' keyword. The VALUES clause requires at least one tuple expression.");let tuples=[],firstTuple=this.parseTuple(lexemes,idx);for(tuples.push(firstTuple.value),idx=firstTuple.newIndex,valuesComments.after.length>0&&firstTuple.value.addPositionedComments("before",valuesComments.after);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let tuple=this.parseTuple(lexemes,idx);tuples.push(tuple.value),idx=tuple.newIndex}let query=new ValuesQuery(tuples);return valuesComments.before.length>0&&(query.headerComments=valuesComments.before),{value:query,newIndex:idx}}static parseTuple(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].type!==4)throw new Error(`Syntax error at position ${idx}: Expected opening parenthesis but found "${idx<lexemes.length?lexemes[idx].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);let openingComments=extractLexemeComments(lexemes[idx]);idx++;let values=[];if(idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after opening parenthesis in tuple expression.");if(lexemes[idx].type&8){let tuple2=new TupleExpression([]),closingComments2=extractLexemeComments(lexemes[idx]);return idx++,openingComments.before.length>0&&tuple2.addPositionedComments("before",openingComments.before),closingComments2.after.length>0&&tuple2.addPositionedComments("after",closingComments2.after),{value:tuple2,newIndex:idx}}let firstValue=ValueParser.parseFromLexeme(lexemes,idx);for(values.push(firstValue.value),idx=firstValue.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after comma in tuple expression.");let value=ValueParser.parseFromLexeme(lexemes,idx);values.push(value.value),idx=value.newIndex}if(idx>=lexemes.length||lexemes[idx].type!==8)throw new Error(`Syntax error at position ${idx}: Expected closing parenthesis but found "${idx<lexemes.length?lexemes[idx].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);let closingComments=extractLexemeComments(lexemes[idx]);idx++;let tuple=new TupleExpression(values);return openingComments.before.length>0&&tuple.addPositionedComments("before",openingComments.before),openingComments.after.length>0&&values.length>0&&values[0].addPositionedComments("before",openingComments.after),closingComments.before.length>0&&values.length>0&&values[values.length-1].addPositionedComments("after",closingComments.before),closingComments.after.length>0&&tuple.addPositionedComments("after",closingComments.after),{value:tuple,newIndex:idx}}};var ReturningClauseParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx]?.value!=="returning")throw new Error(`Syntax error at position ${idx}: Expected 'RETURNING' but found '${lexemes[idx]?.value}'.`);let returningLexeme=lexemes[idx],returningComments=extractLexemeComments(returningLexeme);idx++;let aliasResult=this.parseReturningAliases(lexemes,idx),aliases=aliasResult.aliases;idx=aliasResult.newIndex;let items=[],firstItemResult=SelectItemParser.parseItem(lexemes,idx);for(items.push(firstItemResult.value),idx=firstItemResult.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){let commaLexeme=lexemes[idx];idx++;let itemResult=SelectItemParser.parseItem(lexemes,idx);items.push(itemResult.value),idx=itemResult.newIndex}if(items.length===0){let position=lexemes[idx]?.position?.startPosition??idx;throw new Error(`[ReturningClauseParser] Expected a column or '*' after RETURNING at position ${position}.`)}let clause=new ReturningClause(items,aliases);return returningComments.before.length>0&&clause.addPositionedComments("before",returningComments.before),returningComments.after.length>0&&items.length>0&&items[0].addPositionedComments("before",returningComments.after),{value:clause,newIndex:idx}}static parseReturningAliases(lexemes,index){let idx=index,aliases=[];if(lexemes[idx]?.value!=="with")return{aliases,newIndex:idx};if(idx++,idx>=lexemes.length||!(lexemes[idx].type&4))throw new Error(`[ReturningClauseParser] Expected '(' after RETURNING WITH at position ${idx}.`);for(idx++;idx<lexemes.length;){let kind=lexemes[idx]?.value?.toLowerCase();if(kind!=="old"&&kind!=="new")throw new Error(`[ReturningClauseParser] Expected OLD or NEW in RETURNING WITH alias list at position ${idx}.`);if(idx++,lexemes[idx]?.value!=="as")throw new Error(`[ReturningClauseParser] Expected AS after ${kind.toUpperCase()} in RETURNING WITH alias list at position ${idx}.`);idx++;let aliasResult=FullNameParser.parseFromLexeme(lexemes,idx);if(aliasResult.namespaces&&aliasResult.namespaces.length>0)throw new Error(`[ReturningClauseParser] RETURNING WITH alias must be an unqualified identifier at position ${idx}.`);if(aliases.push(new ReturningAlias(kind,aliasResult.name)),idx=aliasResult.newIndex,idx<lexemes.length&&lexemes[idx].type&16){idx++;continue}if(idx<lexemes.length&&lexemes[idx].type&8)return idx++,{aliases,newIndex:idx};throw new Error(`[ReturningClauseParser] Expected ',' or ')' in RETURNING WITH alias list at position ${idx}.`)}throw new Error("[ReturningClauseParser] Missing closing ')' in RETURNING WITH alias list.")}};var SetClauseParser=class{static parseFromLexeme(lexemes,idx){if(lexemes[idx].value!=="set")throw new Error(`Syntax error at position ${idx}: Expected 'SET' but found '${lexemes[idx].value}'.`);let setLexeme=lexemes[idx],setKeywordComments=extractLexemeComments(setLexeme);idx++;let items=[],pendingBeforeForNext=[...setKeywordComments.after],mergeUnique=(target,source)=>{for(let comment of source)target.includes(comment)||target.push(comment)},addUniquePositionedComments=(component,position,comments)=>{if(comments.length===0)return;let existing=component.getPositionedComments(position),newOnes=comments.filter(comment=>!existing.includes(comment));newOnes.length>0&&component.addPositionedComments(position,newOnes)};for(;idx<lexemes.length;){let currentLexeme=lexemes[idx];if(!currentLexeme||currentLexeme.value==="where"||currentLexeme.value==="from"||currentLexeme.value==="returning"||!(currentLexeme.type&10816))break;let columnStartComments=extractLexemeComments(currentLexeme),columnParseResult=FullNameParser.parseFromLexeme(lexemes,idx);idx=columnParseResult.newIndex;let equalsLexeme=lexemes[idx];if(!equalsLexeme||!(equalsLexeme.type&2)||equalsLexeme.value!=="=")throw new Error(`Syntax error at position ${idx}: Expected '=' after column name in SET clause.`);let equalsComments=extractLexemeComments(equalsLexeme);idx++;let valueParseResult=ValueParser.parseFromLexeme(lexemes,idx);idx=valueParseResult.newIndex;let setItem=new SetClauseItem({namespaces:columnParseResult.namespaces,column:columnParseResult.name},valueParseResult.value),beforeComments=[];if(mergeUnique(beforeComments,pendingBeforeForNext),mergeUnique(beforeComments,columnStartComments.before),beforeComments.length>0&&addUniquePositionedComments(columnParseResult.name,"before",beforeComments),pendingBeforeForNext=[],columnStartComments.after.length>0){let afterComments=[];mergeUnique(afterComments,columnStartComments.after),addUniquePositionedComments(columnParseResult.name,"after",afterComments)}if(equalsComments.before.length>0){let equalsBefore=[];mergeUnique(equalsBefore,equalsComments.before),addUniquePositionedComments(columnParseResult.name,"after",equalsBefore)}if(equalsComments.after.length>0){let equalsAfter=[];mergeUnique(equalsAfter,equalsComments.after),addUniquePositionedComments(valueParseResult.value,"before",equalsAfter)}if(items.push(setItem),lexemes[idx]?.type===16){let commaLexeme=lexemes[idx],commaComments=extractLexemeComments(commaLexeme);if(idx++,commaComments.before.length>0){let commaBefore=[];mergeUnique(commaBefore,commaComments.before),addUniquePositionedComments(setItem,"after",commaBefore)}let nextBefore=[];mergeUnique(nextBefore,commaComments.after),pendingBeforeForNext=nextBefore;continue}break}if(pendingBeforeForNext.length>0&&items.length>0){let trailingComments=[];mergeUnique(trailingComments,pendingBeforeForNext),trailingComments.length>0&&addUniquePositionedComments(items[items.length-1],"after",trailingComments)}let setClause=new SetClause(items);return setKeywordComments.before.length>0&&setClause.addPositionedComments("before",setKeywordComments.before),{setClause,newIndex:idx}}};var InsertQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The INSERT query is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value==="with"){let result=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=result.value,idx=result.newIndex}if(!lexemes[idx]||lexemes[idx].value!=="insert into"){let found=lexemes[idx]?.value??"end of input";throw new Error(`Syntax error at position ${idx}: Expected 'INSERT INTO' but found '${found}'.`)}let insertKeywordLexeme=lexemes[idx],insertKeywordComments=extractLexemeComments(insertKeywordLexeme);idx++;let sourceResult=SourceExpressionParser.parseTableSourceFromLexemes(lexemes,idx),targetSource=sourceResult.value,targetDatasource=targetSource.datasource;idx=sourceResult.newIndex,insertKeywordComments.after.length>0&&targetDatasource.addPositionedComments("before",insertKeywordComments.after);let columnIdentifiers=null,trailingInsertComments=[];if(lexemes[idx]?.type===4){let openParenLexeme=lexemes[idx],parenComments=extractLexemeComments(openParenLexeme);idx++,parenComments.before.length>0&&targetDatasource.addPositionedComments("after",parenComments.before),columnIdentifiers=[];let pendingBeforeForNext=[...parenComments.after];for(;idx<lexemes.length&&lexemes[idx].type&64;){let columnLexeme=lexemes[idx],columnComments=extractLexemeComments(columnLexeme),column=new IdentifierString(columnLexeme.value),beforeComments=[];if(pendingBeforeForNext.length>0&&beforeComments.push(...pendingBeforeForNext),columnComments.before.length>0&&beforeComments.push(...columnComments.before),beforeComments.length>0&&column.addPositionedComments("before",beforeComments),columnComments.after.length>0&&column.addPositionedComments("after",columnComments.after),columnIdentifiers.push(column),pendingBeforeForNext=[],idx++,lexemes[idx]?.type===16){pendingBeforeForNext=[...extractLexemeComments(lexemes[idx]).after],idx++;continue}break}if(pendingBeforeForNext.length>0&&columnIdentifiers.length>0&&(columnIdentifiers[columnIdentifiers.length-1].addPositionedComments("after",pendingBeforeForNext),pendingBeforeForNext=[]),lexemes[idx]?.type!==8)throw new Error(`Syntax error at position ${idx}: Expected ')' after column list.`);let closeParenComments=extractLexemeComments(lexemes[idx]);idx++,closeParenComments.before.length>0&&columnIdentifiers.length>0&&columnIdentifiers[columnIdentifiers.length-1].addPositionedComments("after",closeParenComments.before),closeParenComments.after.length>0&&(trailingInsertComments=closeParenComments.after),columnIdentifiers.length===0&&(columnIdentifiers=[])}if(idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input while parsing INSERT statement. VALUES or SELECT clause expected.");let nextToken=lexemes[idx].value.toLowerCase(),dataQuery;if(nextToken==="values"){let valuesResult=ValuesQueryParser.parseFromLexeme(lexemes,idx);dataQuery=valuesResult.value,idx=valuesResult.newIndex}else{let selectResult=SelectQueryParser.parseFromLexeme(lexemes,idx);dataQuery=selectResult.value,idx=selectResult.newIndex}let onConflictClause=null;if(lexemes[idx]?.value==="on conflict"){let onConflictResult=this.parseOnConflictClause(lexemes,idx);onConflictClause=onConflictResult.value,idx=onConflictResult.newIndex}let returningClause=null;if(lexemes[idx]?.value==="returning"){let returningResult=ReturningClauseParser.parseFromLexeme(lexemes,idx);returningClause=returningResult.value,idx=returningResult.newIndex}if(onConflictClause?.action==="select"&&!returningClause)throw new Error("Syntax error: ON CONFLICT DO SELECT requires a RETURNING clause.");let insertClause=new InsertClause(targetSource,columnIdentifiers??null);return insertKeywordComments.before.length>0&&insertClause.addPositionedComments("before",insertKeywordComments.before),trailingInsertComments.length>0&&insertClause.addPositionedComments("after",trailingInsertComments),withClause&&SelectQueryWithClauseHelper.setWithClause(dataQuery,withClause),{value:new InsertQuery({insertClause,selectQuery:dataQuery,onConflict:onConflictClause,returning:returningClause}),newIndex:idx}}static parseOnConflictClause(lexemes,index){let idx=index;if(lexemes[idx]?.value!=="on conflict")throw new Error(`Syntax error at position ${idx}: Expected 'ON CONFLICT'.`);idx++;let target=null,targetKind=null;if(lexemes[idx]?.type===4){let targetStart=idx;idx=this.consumeBalancedParentheses(lexemes,idx),target=joinLexemeValues(lexemes,targetStart,idx),targetKind="columns"}else if(lexemes[idx]?.value==="on"&&lexemes[idx+1]?.value==="constraint"){if(idx+=2,idx>=lexemes.length||lexemes[idx].value==="do select"||lexemes[idx].value==="do update"||lexemes[idx].value==="do nothing")throw new Error(`Syntax error at position ${idx}: Expected constraint name after ON CONSTRAINT.`);let targetStart=idx;idx++,target=joinLexemeValues(lexemes,targetStart,idx),targetKind="constraint"}let actionToken=lexemes[idx]?.value;if(actionToken==="do nothing")return idx++,{value:new OnConflictClause({target,targetKind,action:"nothing"}),newIndex:idx};if(actionToken==="do update"){idx++;let setResult=SetClauseParser.parseFromLexeme(lexemes,idx);idx=setResult.newIndex;let whereClause2=null;if(lexemes[idx]?.value==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause2=whereResult.value,idx=whereResult.newIndex}return{value:new OnConflictClause({target,targetKind,action:"update",setClause:setResult.setClause,whereClause:whereClause2}),newIndex:idx}}if(actionToken!=="do select"){let found=lexemes[idx]?.value??"end of input";throw new Error(`Syntax error at position ${idx}: Expected 'DO SELECT', 'DO UPDATE', or 'DO NOTHING' after ON CONFLICT but found '${found}'.`)}idx++;let forClause=null;if(lexemes[idx]?.value==="for"){let forResult=ForClauseParser.parseFromLexeme(lexemes,idx);forClause=forResult.value,idx=forResult.newIndex}let whereClause=null;if(lexemes[idx]?.value==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}return{value:new OnConflictClause({target,targetKind,action:"select",forClause,whereClause}),newIndex:idx}}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++}throw new Error(`Syntax error at position ${index}: Expected ')' after ON CONFLICT target.`)}};var UpdateClauseParser=class{static parseFromLexeme(lexemes,index){let result=SourceExpressionParser.parseFromLexeme(lexemes,index);return{value:new UpdateClause(result.value),newIndex:result.newIndex}}};var UpdateQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The UPDATE query is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value?.toLowerCase()==="with"){let withResult=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=withResult.value,idx=withResult.newIndex}if(lexemes[idx].value!=="update")throw new Error(`Syntax error at position ${idx}: Expected 'UPDATE' but found '${lexemes[idx].value}'.`);let updateLexeme=lexemes[idx],updateKeywordComments=extractLexemeComments(updateLexeme);idx++;let updateClauseResult=UpdateClauseParser.parseFromLexeme(lexemes,idx),updateClause=updateClauseResult.value;idx=updateClauseResult.newIndex,updateKeywordComments.before.length>0&&updateClause.addPositionedComments("before",updateKeywordComments.before),updateKeywordComments.after.length>0&&updateClause.addPositionedComments("after",updateKeywordComments.after);let setClauseResult=SetClauseParser.parseFromLexeme(lexemes,idx),setClause=setClauseResult.setClause;idx=setClauseResult.newIndex;let from=null;if(lexemes[idx]?.value==="from"){let result=FromClauseParser.parseFromLexeme(lexemes,idx);from=result.value,idx=result.newIndex}let where=null;if(lexemes[idx]?.value==="where"){let result=WhereClauseParser.parseFromLexeme(lexemes,idx);where=result.value,idx=result.newIndex}let returning=null;if(lexemes[idx]?.value==="returning"){let result=ReturningClauseParser.parseFromLexeme(lexemes,idx);returning=result.value,idx=result.newIndex}return{value:new UpdateQuery({withClause,updateClause,setClause,whereClause:where,fromClause:from,returning}),newIndex:idx}}};var DeleteClauseParser=class{static parseFromLexeme(lexemes,index){if(index>=lexemes.length)throw new Error(`[DeleteClauseParser] Unexpected end of input at position ${index}: expected 'DELETE FROM'.`);let deleteToken=lexemes[index];if(deleteToken?.value?.toLowerCase()!=="delete from"){let position=lexemes[index]?.position?.startPosition??index;throw new Error(`[DeleteClauseParser] Syntax error at position ${position}: expected 'DELETE FROM' but found '${lexemes[index]?.value}'.`)}let deleteTokenComments=extractLexemeComments(deleteToken),targetResult=SourceExpressionParser.parseFromLexeme(lexemes,index+1),deleteClause=new DeleteClause(targetResult.value);return deleteTokenComments.before.length>0&&deleteClause.addPositionedComments("before",deleteTokenComments.before),deleteTokenComments.after.length>0&&deleteClause.addPositionedComments("after",deleteTokenComments.after),{value:deleteClause,newIndex:targetResult.newIndex}}};var UsingClauseParser=class{static parseFromLexeme(lexemes,index){if(lexemes[index].value!=="using")throw new Error(`Syntax error at position ${index}: Expected 'USING' but found '${lexemes[index].value}'.`);let idx=index+1,sources=[],firstSource=SourceExpressionParser.parseFromLexeme(lexemes,idx);for(sources.push(firstSource.value),idx=firstSource.newIndex;lexemes[idx]?.type===16;){idx++;let nextSource=SourceExpressionParser.parseFromLexeme(lexemes,idx);sources.push(nextSource.value),idx=nextSource.newIndex}return{value:new UsingClause(sources),newIndex:idx}}};var DeleteQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The DELETE query is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value==="with"){let withResult=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=withResult.value,idx=withResult.newIndex}let deleteClauseResult=DeleteClauseParser.parseFromLexeme(lexemes,idx),deleteClause=deleteClauseResult.value;idx=deleteClauseResult.newIndex;let usingClause=null;if(lexemes[idx]?.value==="using"){let usingResult=UsingClauseParser.parseFromLexeme(lexemes,idx);usingClause=usingResult.value,idx=usingResult.newIndex}let whereClause=null;if(lexemes[idx]?.value==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}let returningClause=null;if(lexemes[idx]?.value==="returning"){let returningResult=ReturningClauseParser.parseFromLexeme(lexemes,idx);returningClause=returningResult.value,idx=returningResult.newIndex}return{value:new DeleteQuery({withClause,deleteClause,usingClause,whereClause,returning:returningClause}),newIndex:idx}}};var MergeQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The MERGE statement is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value==="with"){let withResult=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=withResult.value,idx=withResult.newIndex}let mergeKeywordLexeme=lexemes[idx],mergeKeywordComments=extractLexemeComments(mergeKeywordLexeme);if(mergeKeywordLexeme?.value!=="merge into"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'MERGE INTO' but found '${actual}'.`)}idx++;let targetResult=SourceExpressionParser.parseFromLexeme(lexemes,idx),target=targetResult.value;if(idx=targetResult.newIndex,this.addUniquePositionedComments(target.datasource,"before",mergeKeywordComments.after),lexemes[idx]?.value!=="using"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'USING' but found '${actual}'.`)}idx++;let sourceResult=SourceExpressionParser.parseFromLexeme(lexemes,idx),source=sourceResult.value;if(idx=sourceResult.newIndex,lexemes[idx]?.value!=="on"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'ON' but found '${actual}'.`)}idx++;let onConditionResult=ValueParser.parseFromLexeme(lexemes,idx),onCondition=onConditionResult.value;idx=onConditionResult.newIndex;let whenResult=this.parseWhenClauses(lexemes,idx);if(whenResult.clauses.length===0)throw new Error("[MergeQueryParser] MERGE statement must contain at least one WHEN clause.");let returningClause=null,nextIndex=whenResult.newIndex;if(lexemes[nextIndex]?.value==="returning"){let returningResult=ReturningClauseParser.parseFromLexeme(lexemes,nextIndex);returningClause=returningResult.value,nextIndex=returningResult.newIndex}let mergeQuery=new MergeQuery({withClause,target,source,onCondition,whenClauses:whenResult.clauses,returningClause});return this.addUniquePositionedComments(mergeQuery,"before",mergeKeywordComments.before),{value:mergeQuery,newIndex:nextIndex}}static parseWhenClauses(lexemes,index){let clauses=[],idx=index;for(;this.getLowerValue(lexemes[idx])==="when";){idx++;let{matchType,newIndex:matchIndex}=this.parseMatchType(lexemes,idx);idx=matchIndex;let additionalCondition=null;if(this.getLowerValue(lexemes[idx])==="and"){idx++;let conditionResult=ValueParser.parseFromLexeme(lexemes,idx);additionalCondition=conditionResult.value,idx=conditionResult.newIndex}let thenLexeme=lexemes[idx];if(this.getLowerValue(thenLexeme)!=="then"){let actual=thenLexeme?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'THEN' but found '${actual}'.`)}let thenComments=extractLexemeComments(thenLexeme),commentsBeforeThen=[],precedingLexeme=lexemes[idx-1];if(precedingLexeme){let precedingComments=extractLexemeComments(precedingLexeme);this.mergeUnique(commentsBeforeThen,precedingComments.after)}this.mergeUnique(commentsBeforeThen,thenComments.before),idx++;let actionResult=this.parseAction(lexemes,idx,thenComments.after??[]);idx=actionResult.newIndex;let whenClause=new MergeWhenClause(matchType,actionResult.action,additionalCondition);whenClause.addThenLeadingComments(commentsBeforeThen),clauses.push(whenClause)}return{clauses,newIndex:idx}}static parseMatchType(lexemes,index){let idx=index,value=this.getLowerValue(lexemes[idx]);if(value==="matched")return idx++,{matchType:"matched",newIndex:idx};if(value==="not matched")return idx++,{matchType:"not_matched",newIndex:idx};if(value==="not matched by source")return idx++,{matchType:"not_matched_by_source",newIndex:idx};if(value==="not matched by target")return idx++,{matchType:"not_matched_by_target",newIndex:idx};let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'MATCHED' or 'NOT MATCHED' but found '${actual}'.`)}static parseAction(lexemes,index,leadingComments=[]){let idx=index,token=lexemes[idx];if(!token)throw new Error("[MergeQueryParser] Unexpected end of input while parsing WHEN clause action.");let tokenValue=token.value.toLowerCase(),tokenComments=extractLexemeComments(token),actionLeadingComments=[];if(this.mergeUnique(actionLeadingComments,leadingComments),this.mergeUnique(actionLeadingComments,tokenComments.before),tokenValue==="update"||tokenValue==="update set"){let expectSetKeyword=tokenValue==="update";idx++;let pendingSetClauseComments=tokenComments.after,setResult=this.parseSetClause(lexemes,idx,expectSetKeyword,pendingSetClauseComments);idx=setResult.newIndex;let whereClause=null;if(lexemes[idx]?.value==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}let action=new MergeUpdateAction(setResult.setClause,whereClause);return this.addUniquePositionedComments(action,"before",actionLeadingComments),{action,newIndex:idx}}if(tokenValue==="delete"){idx++;let whereClause=null;if(this.getLowerValue(lexemes[idx])==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}let action=new MergeDeleteAction(whereClause);return this.addUniquePositionedComments(action,"before",actionLeadingComments),this.addUniquePositionedComments(action,"after",tokenComments.after),{action,newIndex:idx}}if(tokenValue==="do nothing"){idx++;let action=new MergeDoNothingAction;return this.addUniquePositionedComments(action,"before",actionLeadingComments),this.addUniquePositionedComments(action,"after",tokenComments.after),{action,newIndex:idx}}if(tokenValue==="insert default values"){idx++;let columnResult=this.parseInsertColumnProjection(lexemes,idx,tokenComments.after);idx=columnResult.newIndex;let action=new MergeInsertAction({columns:columnResult.columns,defaultValues:!0});return this.addUniquePositionedComments(action,"before",actionLeadingComments),this.addUniquePositionedComments(action,"after",columnResult.trailingComments),{action,newIndex:idx}}if(tokenValue==="insert"){idx++;let insertResult=this.parseInsertAction(lexemes,idx,{pendingCommentsAfterInsert:tokenComments.after});return this.addUniquePositionedComments(insertResult.action,"before",actionLeadingComments),insertResult}let actual=token.value;throw new Error(`[MergeQueryParser] Unsupported action '${actual}'. Only UPDATE, DELETE, INSERT, and DO NOTHING are supported within MERGE WHEN clauses.`)}static parseSetClause(lexemes,index,expectSetKeyword,pendingCommentsAfterUpdate=[]){let idx=index,setKeywordComments=extractLexemeComments(lexemes[idx]);if(expectSetKeyword){if(this.getLowerValue(lexemes[idx])!=="set"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'SET' but found '${actual}'.`)}idx++}else this.getLowerValue(lexemes[idx])==="set"?(setKeywordComments=extractLexemeComments(lexemes[idx]),idx++):setKeywordComments={before:[],after:[]};let items=[],pendingBeforeForNext=[];for(this.mergeUnique(pendingBeforeForNext,pendingCommentsAfterUpdate),this.mergeUnique(pendingBeforeForNext,setKeywordComments.after);idx<lexemes.length;){let currentLexeme=lexemes[idx];if(!currentLexeme||this.isSetClauseTerminator(currentLexeme)||!(currentLexeme.type&10816))break;let columnComments=extractLexemeComments(currentLexeme),{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,lexemes[idx]?.type!==2||lexemes[idx].value!=="="){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected '=' in SET clause but found '${actual}'.`)}let equalsLexeme=lexemes[idx],equalsComments=extractLexemeComments(equalsLexeme);idx++;let valueResult=ValueParser.parseFromLexeme(lexemes,idx);idx=valueResult.newIndex;let setItem=new SetClauseItem({namespaces,column:name},valueResult.value),beforeComments=[];if(this.mergeUnique(beforeComments,pendingBeforeForNext),this.mergeUnique(beforeComments,columnComments.before),this.addUniquePositionedComments(name,"before",beforeComments),pendingBeforeForNext=[],this.addUniquePositionedComments(name,"after",columnComments.after),this.addUniquePositionedComments(setItem,"after",equalsComments.before),this.addUniquePositionedComments(valueResult.value,"before",equalsComments.after),items.push(setItem),lexemes[idx]?.type===16){let commaLexeme=lexemes[idx],commaComments=extractLexemeComments(commaLexeme);idx++,this.addUniquePositionedComments(setItem,"after",commaComments.before),pendingBeforeForNext=[],this.mergeUnique(pendingBeforeForNext,commaComments.after);continue}break}if(pendingBeforeForNext.length>0&&items.length>0&&this.addUniquePositionedComments(items[items.length-1],"after",pendingBeforeForNext),items.length===0)throw new Error("[MergeQueryParser] SET clause must contain at least one column assignment.");let setClause=new SetClause(items);return this.addUniquePositionedComments(setClause,"before",setKeywordComments.before),{setClause,newIndex:idx}}static parseInsertAction(lexemes,index,options){let idx=index,pendingAfterInsert=options?.pendingCommentsAfterInsert??[],columnResult=this.parseInsertColumnProjection(lexemes,idx,pendingAfterInsert),columns=columnResult.columns;idx=columnResult.newIndex;let pendingBeforeValues=columnResult.trailingComments;if(this.getLowerValue(lexemes[idx])==="values"){let valuesLexeme=lexemes[idx],valuesComments=extractLexemeComments(valuesLexeme);idx++;let beforeValuesComments=[];this.mergeUnique(beforeValuesComments,pendingBeforeValues),this.mergeUnique(beforeValuesComments,valuesComments.before);let valuesResult=ValueParser.parseArgument(4,8,lexemes,idx);if(idx=valuesResult.newIndex,!(valuesResult.value instanceof ValueList))throw new Error("[MergeQueryParser] Unexpected VALUES payload. Expected a parenthesized value list.");let valueList=valuesResult.value,closingParenComments=extractLexemeComments(lexemes[idx-1]);this.addUniquePositionedComments(valueList,"after",closingParenComments.after),this.addUniquePositionedComments(valueList,"after",valuesComments.after);let action=new MergeInsertAction({columns,values:valueList});return action.addValuesLeadingComments(beforeValuesComments),{action,newIndex:idx}}let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Unsupported INSERT payload '${actual}'. Use VALUES (...) or DEFAULT VALUES.`)}static parseInsertColumnProjection(lexemes,index,pendingBeforeFirstColumn){let idx=index;if(lexemes[idx]?.type!==4)return{columns:null,newIndex:idx,trailingComments:[...pendingBeforeFirstColumn]};let openParenLexeme=lexemes[idx],parenComments=extractLexemeComments(openParenLexeme);idx++;let columns=[],pendingBeforeForNext=[];for(this.mergeUnique(pendingBeforeForNext,pendingBeforeFirstColumn),this.mergeUnique(pendingBeforeForNext,parenComments.before),this.mergeUnique(pendingBeforeForNext,parenComments.after);idx<lexemes.length&&lexemes[idx].type&64;){let columnLexeme=lexemes[idx],columnComments=extractLexemeComments(columnLexeme),column=new IdentifierString(columnLexeme.value),beforeComments=[];if(this.mergeUnique(beforeComments,pendingBeforeForNext),this.mergeUnique(beforeComments,columnComments.before),this.addUniquePositionedComments(column,"before",beforeComments),pendingBeforeForNext=[],this.addUniquePositionedComments(column,"after",columnComments.after),columns.push(column),idx++,lexemes[idx]?.type===16){let commaLexeme=lexemes[idx],commaComments=extractLexemeComments(commaLexeme);idx++,this.addUniquePositionedComments(column,"after",commaComments.before),pendingBeforeForNext=[],this.mergeUnique(pendingBeforeForNext,commaComments.after);continue}break}if(pendingBeforeForNext.length>0&&columns.length>0&&(this.addUniquePositionedComments(columns[columns.length-1],"after",pendingBeforeForNext),pendingBeforeForNext=[]),lexemes[idx]?.type!==8){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected ')' after column list but found '${actual}'.`)}let closeParenLexeme=lexemes[idx],closeParenComments=extractLexemeComments(closeParenLexeme);idx++,closeParenComments.before.length>0&&columns.length>0&&this.addUniquePositionedComments(columns[columns.length-1],"after",closeParenComments.before);let trailingComments=[];return this.mergeUnique(trailingComments,closeParenComments.after),this.mergeUnique(trailingComments,pendingBeforeForNext),{columns:columns.length>0?columns:[],newIndex:idx,trailingComments}}static isSetClauseTerminator(lexeme){if(!lexeme)return!1;let value=this.getLowerValue(lexeme);return value?value==="where"||value==="from"||value==="returning"||value==="when":!1}static mergeUnique(target,source){if(!(!source||source.length===0))for(let comment of source)target.includes(comment)||target.push(comment)}static addUniquePositionedComments(component,position,comments){if(!component||!comments||comments.length===0)return;let existing=component.getPositionedComments(position),newOnes=comments.filter(comment=>!existing.includes(comment));newOnes.length>0&&component.addPositionedComments(position,newOnes)}static getLowerValue(lexeme){return lexeme&&typeof lexeme.value=="string"?lexeme.value.toLowerCase():null}};var CommonTableParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The CommonTable definition is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,aliasResult=SourceAliasExpressionParser.parseFromLexeme(lexemes,idx);idx=aliasResult.newIndex,this.collectPrecedingComments(lexemes,index,aliasResult),idx=this.parseAsKeyword(lexemes,idx);let{materialized,newIndex:materializedIndex}=this.parseMaterializedFlag(lexemes,idx);idx=materializedIndex;let{query,trailingComments,newIndex:queryIndex}=this.parseInnerQuery(lexemes,idx);return idx=queryIndex,{value:new CommonTable(query,aliasResult.value,materialized),newIndex:idx,trailingComments}}static collectPrecedingComments(lexemes,index,aliasResult){if(!aliasResult.value?.table)return;let cteTable=aliasResult.value.table;for(let i=index-1;i>=0;i--){let token=lexemes[i];if(token.value.toLowerCase()==="with"){this.collectWithTokenComments(token,cteTable);break}if(token.type&16||token.value.toLowerCase()==="recursive")break;this.collectTokenComments(token,cteTable)}}static collectWithTokenComments(token,cteTable){let hasPositionedComments=!1;if(token.positionedComments&&token.positionedComments.length>0)for(let posComment of token.positionedComments)posComment.position==="after"&&posComment.comments&&(this.addPositionedComment(cteTable,"before",posComment.comments),hasPositionedComments=!0);!hasPositionedComments&&token.comments&&token.comments.length>0&&this.addPositionedComment(cteTable,"before",token.comments)}static collectTokenComments(token,cteTable){token.comments&&token.comments.length>0&&this.addPositionedComment(cteTable,"before",token.comments),token.positionedComments&&token.positionedComments.length>0&&(cteTable.positionedComments||(cteTable.positionedComments=[]),cteTable.positionedComments.unshift(...token.positionedComments))}static addPositionedComment(cteTable,position,comments){cteTable.positionedComments||(cteTable.positionedComments=[]),cteTable.positionedComments.unshift({position,comments:[...comments]})}static parseAsKeyword(lexemes,index){if(index<lexemes.length&&lexemes[index].value!=="as")throw new Error(`Syntax error at position ${index}: Expected 'AS' keyword after CTE name but found "${lexemes[index].value}".`);return index+1}static parseMaterializedFlag(lexemes,index){if(index>=lexemes.length)return{materialized:null,newIndex:index};let currentValue=lexemes[index].value;return currentValue==="materialized"?{materialized:!0,newIndex:index+1}:currentValue==="not materialized"?{materialized:!1,newIndex:index+1}:{materialized:null,newIndex:index}}static parseInnerQuery(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type!==4)throw new Error(`Syntax error at position ${idx}: Expected '(' after CTE name but found "${lexemes[idx].value}".`);let cteQueryHeaderComments=this.extractComments(lexemes[idx]);idx++;let queryResult=this.parseCteQuery(lexemes,idx);if(idx=queryResult.newIndex,this.applyCteHeaderComments(queryResult.value,cteQueryHeaderComments),idx<lexemes.length&&lexemes[idx].type!==8)throw new Error(`Syntax error at position ${idx}: Expected ')' after CTE query but found "${lexemes[idx].value}".`);let closingParenComments=this.extractComments(lexemes[idx]);return idx++,{query:queryResult.value,trailingComments:closingParenComments.length>0?closingParenComments:null,newIndex:idx}}static parseCteQuery(lexemes,index){if(index>=lexemes.length)throw new Error(`Syntax error at position ${index}: Expected CTE query but found end of input.`);switch(lexemes[index].value.toLowerCase()){case"select":case"values":return SelectQueryParser.parseFromLexeme(lexemes,index);case"insert into":return InsertQueryParser.parseFromLexeme(lexemes,index);case"update":return UpdateQueryParser.parseFromLexeme(lexemes,index);case"delete from":return DeleteQueryParser.parseFromLexeme(lexemes,index);case"merge into":return MergeQueryParser.parseFromLexeme(lexemes,index);case"with":switch(this.getCommandAfterWith(lexemes,index)){case"insert into":return InsertQueryParser.parseFromLexeme(lexemes,index);case"update":return UpdateQueryParser.parseFromLexeme(lexemes,index);case"delete from":return DeleteQueryParser.parseFromLexeme(lexemes,index);case"merge into":return MergeQueryParser.parseFromLexeme(lexemes,index);default:return SelectQueryParser.parseFromLexeme(lexemes,index)}default:throw new Error(`Syntax error at position ${index}: Expected SELECT, INSERT, UPDATE, DELETE, MERGE, or WITH in CTE query but found "${lexemes[index].value}".`)}}static applyCteHeaderComments(query,headerComments){if(headerComments.length!==0){if(this.isSelectQuery(query)){query.headerComments?query.headerComments=[...headerComments,...query.headerComments]:query.headerComments=headerComments;return}if(query instanceof InsertQuery){(SelectQueryWithClauseHelper.getWithClause(query.selectQuery)??query.insertClause).addPositionedComments("before",headerComments);return}if(query instanceof UpdateQuery){(query.withClause??query.updateClause).addPositionedComments("before",headerComments);return}if(query instanceof DeleteQuery){(query.withClause??query.deleteClause).addPositionedComments("before",headerComments);return}query instanceof MergeQuery&&(query.withClause??query).addPositionedComments("before",headerComments)}}static isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}static getCommandAfterWith(lexemes,index){try{let withResult=WithClauseParser.parseFromLexeme(lexemes,index);return lexemes[withResult.newIndex]?.value.toLowerCase()??null}catch{return null}}static extractComments(lexeme){let comments=[];if(lexeme.positionedComments)for(let posComment of lexeme.positionedComments)posComment.comments&&comments.push(...posComment.comments);return lexeme.comments&&lexeme.comments.length>0&&comments.push(...lexeme.comments),comments}};var WithClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The WITH clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,headerComments=this.extractWithTokenHeaderComments(lexemes,idx);idx=this.parseWithKeyword(lexemes,idx);let{recursive,newIndex:recursiveIndex}=this.parseRecursiveFlag(lexemes,idx);idx=recursiveIndex;let{tables,trailingComments,newIndex:ctesIndex}=this.parseAllCommonTables(lexemes,idx);idx=ctesIndex;let withClause=new WithClause(recursive,tables);return trailingComments.length>0&&(withClause.trailingComments=trailingComments),{value:withClause,newIndex:idx,headerComments}}static extractWithTokenHeaderComments(lexemes,index){if(index>=lexemes.length)return null;let withToken=lexemes[index],headerComments=null;if(withToken.positionedComments&&withToken.positionedComments.length>0)for(let posComment of withToken.positionedComments)posComment.position==="before"&&posComment.comments&&(headerComments||(headerComments=[]),headerComments.push(...posComment.comments));return!headerComments&&withToken.comments&&withToken.comments.length>0&&(headerComments=[...withToken.comments]),headerComments}static parseWithKeyword(lexemes,index){if(index<lexemes.length&&lexemes[index].value.toLowerCase()==="with")return index+1;throw new Error(`Syntax error at position ${index}: Expected WITH keyword.`)}static parseRecursiveFlag(lexemes,index){let recursive=index<lexemes.length&&lexemes[index].value.toLowerCase()==="recursive";return{recursive,newIndex:recursive?index+1:index}}static parseAllCommonTables(lexemes,index){let idx=index,tables=[],allTrailingComments=[],firstCte=CommonTableParser.parseFromLexeme(lexemes,idx);for(tables.push(firstCte.value),idx=firstCte.newIndex,firstCte.trailingComments&&allTrailingComments.push(...firstCte.trailingComments);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let cteResult=CommonTableParser.parseFromLexeme(lexemes,idx);tables.push(cteResult.value),idx=cteResult.newIndex,cteResult.trailingComments&&allTrailingComments.push(...cteResult.trailingComments)}return{tables,trailingComments:allTrailingComments,newIndex:idx}}};var FetchClauseParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="fetch")throw new Error(`Syntax error at position ${idx}: Expected 'FETCH' keyword but found "${lexemes[idx].value}".`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH' keyword.");let fetchExprResult=FetchExpressionParser.parseFromLexeme(lexemes,idx),fetchExpr=fetchExprResult.value;return idx=fetchExprResult.newIndex,{value:new FetchClause(fetchExpr),newIndex:idx}}},FetchExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index,type,typeToken=lexemes[idx].value;if(typeToken==="first")type="first";else if(typeToken==="next")type="next";else throw new Error(`Syntax error at position ${idx}: Expected 'FIRST' or 'NEXT' after 'FETCH' but found "${lexemes[idx].value}".`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT'.");let count=null,unit=null;if(lexemes[idx].value==="row only"||lexemes[idx].value==="rows only")return count=new LiteralValue(1),unit="rows only",idx++,{value:new FetchExpression(type,count,unit),newIndex:idx};let countResult=ValueParser.parseFromLexeme(lexemes,idx);if(count=countResult.value,idx=countResult.newIndex,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT <count>'.");if(lexemes[idx].value==="rows only"?(unit="rows only",idx++):lexemes[idx].value==="percent"?(unit="percent",idx++):lexemes[idx].value==="percent with ties"&&(unit="percent with ties",idx++),!unit)throw new Error("Syntax error: Expected 'ROWS ONLY', 'PERCENT', or 'PERCENT WITH TIES' after 'FETCH FIRST|NEXT <count>'.");return{value:new FetchExpression(type,count,unit),newIndex:idx}}};var OffsetClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The OFFSET clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="offset")throw new Error(`Syntax error at position ${idx}: Expected 'OFFSET' keyword but found "${lexemes[idx].value}". OFFSET clauses must start with the OFFSET keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'OFFSET' keyword. The OFFSET clause requires a numeric expression.");let offsetItem=ValueParser.parseFromLexeme(lexemes,idx);return idx=offsetItem.newIndex,idx<lexemes.length&&(lexemes[idx].value==="row"||lexemes[idx].value==="rows")&&idx++,{value:new OffsetClause(offsetItem.value),newIndex:idx}}};var LexemeCursor=class{static{this.SQL_COMMANDS=new Set(["select","from","where","and","or","order","by","group","having","limit","offset","as","on","inner","left","right","join","union","insert","update","delete","into","values","set"])}static findLexemeAtLineColumn(sql,position){let charOffset=this.lineColumnToCharOffset(sql,position);return charOffset===-1?null:this.findLexemeAtPosition(sql,charOffset)}static findLexemeAtPosition(sql,cursorPosition){if(cursorPosition<0||cursorPosition>=sql.length)return null;let lexemes=this.getAllLexemesWithPosition(sql);for(let lexeme of lexemes)if(lexeme.position&&cursorPosition>=lexeme.position.startPosition&&cursorPosition<lexeme.position.endPosition)return lexeme;return null}static getAllLexemesWithPosition(sql){if(!sql?.trim())return[];try{let lexemes=[],position=0;for(;position<sql.length&&(position=this.skipWhitespaceAndComments(sql,position),!(position>=sql.length));){let lexeme=this.parseNextToken(sql,position);lexeme?(lexemes.push(lexeme),position=lexeme.position.endPosition):position++}return lexemes}catch{return[]}}static skipWhitespaceAndComments(sql,position){return StringUtils.readWhiteSpaceAndComment(sql,position).position}static parseNextToken(sql,startPos){let char=sql[startPos];return char==="'"||char==='"'?this.parseStringLiteral(sql,startPos):/[=<>!+\-*/%().*]/.test(char)?this.parseOperator(sql,startPos):char===","?this.createLexeme(16,",",startPos,startPos+1):/[a-zA-Z0-9_]/.test(char)?this.parseWordToken(sql,startPos):null}static parseStringLiteral(sql,startPos){let quote=sql[startPos],position=startPos+1,token=quote;for(;position<sql.length&&sql[position]!==quote;)token+=sql[position++];return position<sql.length&&(token+=sql[position++]),this.createLexeme(1,token,startPos,position)}static parseOperator(sql,startPos){let token=sql[startPos],position=startPos+1;position<sql.length&&/[=<>!]/.test(sql[position])&&/[=<>!]/.test(token)&&(token+=sql[position++]);let tokenType=this.getOperatorTokenType(token);return this.createLexeme(tokenType,token,startPos,position)}static parseWordToken(sql,startPos){let position=startPos,token="";for(;position<sql.length&&/[a-zA-Z0-9_]/.test(sql[position]);)token+=sql[position++];let tokenType=this.getWordTokenType(token,sql,position),value=this.shouldLowercase(tokenType)?token.toLowerCase():token;return this.createLexeme(tokenType,value,startPos,position)}static getOperatorTokenType(token){switch(token){case"(":return 4;case")":return 8;case"*":return 64;default:return 2}}static getWordTokenType(token,sql,position){let lowerToken=token.toLowerCase();if(this.SQL_COMMANDS.has(lowerToken))return 128;let nextNonWhitespacePos=this.skipWhitespaceAndComments(sql,position);return nextNonWhitespacePos<sql.length&&sql[nextNonWhitespacePos]==="("?2048:64}static shouldLowercase(tokenType){return!!(tokenType&128)||!!(tokenType&2)||!!(tokenType&2048)}static createLexeme(type,value,startPos,endPos){return{type,value,comments:null,position:{startPosition:startPos,endPosition:endPos}}}static lineColumnToCharOffset(sql,position){if(position.line<1||position.column<1)return-1;let lines=sql.split(`
|
|
37
|
+
`),cleaned=cleaned.replace(/\/\*[\s\S]*?\*\//g,"");let result=cleaned.trim();return result.length>0?result:null}static isEmptyQuery(sql){return sql?this.cleanSqlComments(sql)===null:!0}},MultiQueryUtils=class{static getContextAt(text,cursorPosition){let activeQuery=MultiQuerySplitter.split(text).getActive(cursorPosition);if(!activeQuery)return;let charPos=typeof cursorPosition=="number"?cursorPosition:TextPositionUtils.lineColumnToCharOffset(text,cursorPosition);if(charPos===-1)return;let relativePosition=charPos-activeQuery.start;return{query:activeQuery,relativePosition}}static extractQueries(text){return MultiQuerySplitter.split(text).getNonEmpty().map(q=>q.sql)}};function createTableDefinitionRegistryFromSchema(schema){let registry={};for(let table of Object.values(schema))registry[table.name]={name:table.name,columns:Object.entries(table.columns).map(([columnName,column])=>({...column,name:columnName}))};return registry}var NOT_NULL_KINDS=new Set(["not-null","primary-key"]),IDENTITY_KINDS=new Set(["generated-always-identity","generated-by-default-identity"]);function buildTableName(query){let prefixes=query.namespaces??[];return prefixes.length===0?query.tableName.name:`${prefixes.join(".")}.${query.tableName.name}`}function getColumnTypeName(column){let dataType=column.dataType;if(dataType){if(dataType instanceof TypeValue)return dataType.getTypeName();if(dataType instanceof RawString)return dataType.value}}function adaptColumn(column){let defaultConstraint=column.constraints.find(constraint=>constraint.kind==="default"),hasDefault=!!defaultConstraint,hasIdentity=column.constraints.some(constraint=>IDENTITY_KINDS.has(constraint.kind)),hasNotNull=column.constraints.some(constraint=>NOT_NULL_KINDS.has(constraint.kind)),required=hasNotNull&&!hasDefault&&!hasIdentity;return{name:column.name.name,typeName:getColumnTypeName(column),required,defaultValue:defaultConstraint?.defaultValue??(hasIdentity?"row_number() over ()":null),isNotNull:hasNotNull}}function createTableDefinitionFromCreateTableQuery(query){let qualifiedName=buildTableName(query),columns=query.columns.map(column=>adaptColumn(column));return{name:qualifiedName,columns}}function createTableDefinitionRegistryFromCreateTableQueries(queries){let registry={};for(let query of queries){let definition=createTableDefinitionFromCreateTableQuery(query);registry[definition.name]=definition}return registry}var normalizeTableName=tableName=>{let parsed=FullNameParser.parse(tableName);return[...parsed.namespaces??[],parsed.name.name].join(".").toLowerCase()},tableNameVariants=tableName=>{let namespaces=FullNameParser.parse(tableName).namespaces??[],normalized=normalizeTableName(tableName);return namespaces.length===0?[normalized]:[normalized]};var DDLToFixtureConverter=class{static convert(ddlSql){let splitResult=MultiQuerySplitter.split(ddlSql),createTableQueries=[],insertQueries=[],alterTableStatements=[];for(let query of splitResult.queries)if(!query.isEmpty)try{let ast=SqlParser.parse(query.sql);ast instanceof CreateTableQuery?createTableQueries.push(ast):ast instanceof InsertQuery?insertQueries.push(ast):ast instanceof AlterTableStatement&&alterTableStatements.push(ast)}catch{}let registry=createTableDefinitionRegistryFromCreateTableQueries(createTableQueries);this.applyAlterTableStatements(registry,alterTableStatements);let fixtureJson={};for(let[tableName,def]of Object.entries(registry))fixtureJson[tableName]={columns:def.columns.map(col=>({name:col.name,type:col.typeName,default:this.formatDefaultValue(col.defaultValue)})),rows:[]};let sequences={};for(let insert of insertQueries){if(!(insert.selectQuery instanceof ValuesQuery))continue;let tableName=insert.insertClause.source.getAliasName();if(!tableName||!fixtureJson[tableName])continue;let tableDef=registry[tableName],targetColumns=insert.insertClause.columns,valuesQuery=insert.selectQuery,columnNames=targetColumns?targetColumns.map(c=>c.name):tableDef.columns.map(c=>c.name);for(let tuple of valuesQuery.tuples){let row={};for(let i=0;i<columnNames.length;i++){let colName=columnNames[i];if(i<tuple.values.length){let val=tuple.values[i];row[colName]=this.extractValue(val)}}for(let colDef of tableDef.columns){if(row[colDef.name]!==void 0)continue;if(colDef.required)throw new Error(`Column '${colDef.name}' in table '${tableName}' cannot be null and has no default value.`);if(colDef.defaultValue!==null&&colDef.defaultValue!==void 0){let defaultValStr=this.formatDefaultValue(colDef.defaultValue);if(defaultValStr){let trimmedDefault=defaultValStr.trim(),lowerTrimmed=trimmedDefault.toLowerCase(),stringLiteralValue=trimmedDefault.startsWith("'")&&trimmedDefault.endsWith("'")?trimmedDefault.slice(1,-1).replace(/''/g,"'"):trimmedDefault;if(stringLiteralValue.toLowerCase()==="null")row[colDef.name]=null;else if(lowerTrimmed.includes("nextval"))sequences[tableName]||(sequences[tableName]={}),sequences[tableName][colDef.name]||(sequences[tableName][colDef.name]=0),sequences[tableName][colDef.name]++,row[colDef.name]=sequences[tableName][colDef.name];else if(lowerTrimmed.includes("now")||lowerTrimmed.includes("current_timestamp"))row[colDef.name]="2023-01-01 00:00:00";else if(trimmedDefault.startsWith("'")&&trimmedDefault.endsWith("'"))row[colDef.name]=stringLiteralValue;else{let num=Number(trimmedDefault);if(!isNaN(num))row[colDef.name]=num;else{let lower=trimmedDefault.toLowerCase();lower==="true"?row[colDef.name]=!0:lower==="false"?row[colDef.name]=!1:lower==="null"?row[colDef.name]=null:row[colDef.name]=trimmedDefault}}}}else row[colDef.name]=null}fixtureJson[tableName].rows.push(row)}}return fixtureJson}static applyAlterTableStatements(registry,alterStatements){if(alterStatements.length===0)return;let normalizedToKey=new Map,ambiguous=new Set;for(let tableKey of Object.keys(registry)){let normalized=normalizeTableName(tableKey),existing=normalizedToKey.get(normalized);if(existing&&existing!==tableKey){normalizedToKey.delete(normalized),ambiguous.add(normalized);continue}ambiguous.has(normalized)||normalizedToKey.set(normalized,tableKey)}let resolveTableKey=tableName=>{if(registry[tableName])return tableName;let normalized=normalizeTableName(tableName);if(!ambiguous.has(normalized))return normalizedToKey.get(normalized)};for(let alter of alterStatements){let tableName=alter.table.toString(),registryKey=resolveTableKey(tableName);if(!registryKey)continue;let tableDef=registry[registryKey];for(let action of alter.actions){if(!(action instanceof AlterTableAlterColumnDefault))continue;let targetName=action.columnName.name,column=tableDef.columns.find(col=>col.name.toLowerCase()===targetName.toLowerCase());if(!column)continue;let hadDefault=column.defaultValue!==null&&column.defaultValue!==void 0;if(action.dropDefault){column.defaultValue=null,column.isNotNull&&hadDefault&&(column.required=!0);continue}column.defaultValue=action.setDefault??null,column.required=!1}}}static extractValue(value){if(value instanceof LiteralValue)return value.value;try{let formatter2=new SqlFormatter({keywordCase:"none"}),{formattedSql}=formatter2.format(value);return formattedSql.startsWith("'")&&formattedSql.endsWith("'")?formattedSql.slice(1,-1).replace(/''/g,"'"):formattedSql}catch{return String(value)}}static formatDefaultValue(value){if(value!=null){if(typeof value=="string")return value;try{let formatter2=new SqlFormatter({keywordCase:"none"}),{formattedSql}=formatter2.format(value);return formattedSql}catch{return String(value)}}}};var SERIAL_PSEUDO_TYPE_MAP={serial:"integer",serial4:"integer",bigserial:"bigint",serial8:"bigint",smallserial:"smallint",serial2:"smallint"};function normalizeSerialPseudoType(typeName){if(!typeName)return typeName;let trimmed=typeName.trim();if(!trimmed)return trimmed;let segments=trimmed.split("."),base=segments.pop(),normalizedBase=SERIAL_PSEUDO_TYPE_MAP[base.toLowerCase()];return normalizedBase?(segments.push(normalizedBase),segments.join(".")):trimmed}function isSerialPseudoType(typeName){if(!typeName)return!1;let trimmed=typeName.trim();if(!trimmed)return!1;let base=trimmed.split(".").pop();return base?!!SERIAL_PSEUDO_TYPE_MAP[base.toLowerCase()]:!1}var FixtureCteBuilder=class{static fromSQL(sql){let fixtureJson=DDLToFixtureConverter.convert(sql);return this.fromJSON(fixtureJson)}static fromJSON(jsonDefinitions){let fixtures=[];for(let[tableName,def]of Object.entries(jsonDefinitions))if(def&&Array.isArray(def.columns)){let columns=def.columns.map(c=>({name:c.name,typeName:c.type,defaultValue:c.default})),rows=[];Array.isArray(def.rows)&&(rows=def.rows.map(rowObj=>columns.map(col=>rowObj[col.name]!==void 0?rowObj[col.name]:null))),fixtures.push({tableName,columns,rows})}return fixtures}static buildFixtures(fixtures){return fixtures.map(fixture=>this.buildFixture(fixture))}static buildFixture(fixture){let query=this.buildSelectQuery(fixture);return new CommonTable(query,fixture.tableName,null)}static buildSelectQuery(fixture){let columnCount=fixture.columns.length,selectQueries=(fixture.rows.length>0?fixture.rows:[new Array(columnCount).fill(null)]).map(row=>this.buildSelectRow(fixture.columns,row));if(selectQueries.length===0)throw new Error("No rows to build SELECT query");let result=selectQueries[0];for(let i=1;i<selectQueries.length;i++)result instanceof SimpleSelectQuery?result=result.toUnionAll(selectQueries[i]):result=result.unionAll(selectQueries[i]);if(fixture.rows.length===0&&result instanceof SimpleSelectQuery){let falseCondition=new BinaryExpression(new LiteralValue(1),"=",new LiteralValue(0));result.whereClause=new WhereClause(falseCondition)}return result}static buildSelectRow(columns,row){let items=columns.map((column,index)=>{let value=index<row.length?row[index]:null,literalValue=this.createLiteralValue(value),expression=literalValue,castTarget=normalizeSerialPseudoType(column.typeName);if(castTarget){let typeValue=new TypeValue(null,new RawString(castTarget));expression=new CastExpression(literalValue,typeValue)}return new SelectItem(expression,column.name)}),selectClause=new SelectClause(items);return new SimpleSelectQuery({selectClause})}static createLiteralValue(value){return value==null?new LiteralValue(null):typeof value=="number"?new LiteralValue(Number.isFinite(value)?value:null):typeof value=="boolean"?new LiteralValue(value):typeof value=="bigint"?new LiteralValue(value.toString()):typeof Buffer<"u"&&value instanceof Buffer?new LiteralValue(`X'${value.toString("hex")}'`):typeof value=="string"?new LiteralValue(value,void 0,!0):new LiteralValue(String(value),void 0,!0)}};function rewriteValueComponentWithColumnResolver(value,resolver){if(value instanceof ColumnReference)return resolver(value);if(value instanceof FunctionCall){let rewrittenArgument=value.argument?rewriteValueComponentWithColumnResolver(value.argument,resolver):null,rewrittenOver=value.over?rewriteOverExpression(value.over,resolver):null,rewrittenWithinGroup=value.withinGroup?rewriteOrderByClause(value.withinGroup,resolver):null,rewrittenInternalOrderBy=value.internalOrderBy?rewriteOrderByClause(value.internalOrderBy,resolver):null,rewrittenFilterCondition=value.filterCondition?rewriteValueComponentWithColumnResolver(value.filterCondition,resolver):null;return new FunctionCall(value.qualifiedName.namespaces,value.qualifiedName.name,rewrittenArgument,rewrittenOver,rewrittenWithinGroup,value.withOrdinality,rewrittenInternalOrderBy,rewrittenFilterCondition)}if(value instanceof UnaryExpression){let rewrittenExpression=rewriteValueComponentWithColumnResolver(value.expression,resolver);return new UnaryExpression(value.operator.value,rewrittenExpression)}if(value instanceof BinaryExpression){let left=rewriteValueComponentWithColumnResolver(value.left,resolver),right=rewriteValueComponentWithColumnResolver(value.right,resolver);return new BinaryExpression(left,value.operator.value,right)}if(value instanceof JsonPredicateExpression){let expression=rewriteValueComponentWithColumnResolver(value.expression,resolver);return new JsonPredicateExpression(expression,value.negated,value.jsonType,value.uniqueKeys)}if(value instanceof CaseExpression){let condition=value.condition?rewriteValueComponentWithColumnResolver(value.condition,resolver):null,switchCase=rewriteSwitchCaseArgument(value.switchCase,resolver);return new CaseExpression(condition,switchCase)}if(value instanceof SwitchCaseArgument)return rewriteSwitchCaseArgument(value,resolver);if(value instanceof CaseKeyValuePair)return rewriteCaseKeyValuePair(value,resolver);if(value instanceof BetweenExpression){let expression=rewriteValueComponentWithColumnResolver(value.expression,resolver),lower=rewriteValueComponentWithColumnResolver(value.lower,resolver),upper=rewriteValueComponentWithColumnResolver(value.upper,resolver);return new BetweenExpression(expression,lower,upper,value.negated)}if(value instanceof CastExpression){let input=rewriteValueComponentWithColumnResolver(value.input,resolver),castType=rewriteTypeValue(value.castType,resolver);return new CastExpression(input,castType)}if(value instanceof ParenExpression){let expression=rewriteValueComponentWithColumnResolver(value.expression,resolver);return new ParenExpression(expression)}if(value instanceof TupleExpression){let rewrittenValues=value.values.map(item=>rewriteValueComponentWithColumnResolver(item,resolver));return new TupleExpression(rewrittenValues)}if(value instanceof ArrayExpression){let expression=rewriteValueComponentWithColumnResolver(value.expression,resolver);return new ArrayExpression(expression)}if(value instanceof ArraySliceExpression){let array=rewriteValueComponentWithColumnResolver(value.array,resolver),startIndex=value.startIndex?rewriteValueComponentWithColumnResolver(value.startIndex,resolver):null,endIndex=value.endIndex?rewriteValueComponentWithColumnResolver(value.endIndex,resolver):null;return new ArraySliceExpression(array,startIndex,endIndex)}if(value instanceof ArrayIndexExpression){let array=rewriteValueComponentWithColumnResolver(value.array,resolver),index=rewriteValueComponentWithColumnResolver(value.index,resolver);return new ArrayIndexExpression(array,index)}if(value instanceof ArrayQueryExpression)return value;if(value instanceof ValueList){let rewrittenList=value.values.map(item=>rewriteValueComponentWithColumnResolver(item,resolver));return new ValueList(rewrittenList)}if(value instanceof InlineQuery)return value;if(value instanceof WindowFrameExpression)return rewriteWindowFrameExpression(value,resolver);if(value instanceof WindowFrameSpec)return rewriteWindowFrameSpec(value,resolver);if(value instanceof WindowFrameBoundaryValue){let rewrittenValue=rewriteValueComponentWithColumnResolver(value.value,resolver);return new WindowFrameBoundaryValue(rewrittenValue,value.isFollowing)}return value instanceof WindowFrameBoundStatic?value:value instanceof TypeValue?rewriteTypeValue(value,resolver):(value instanceof StringSpecifierExpression||value instanceof LiteralValue||value instanceof RawString||value instanceof IdentifierString||value instanceof ParameterExpression,value)}function rewriteSwitchCaseArgument(argument,resolver){let rewrittenCases=argument.cases.map(pair=>rewriteCaseKeyValuePair(pair,resolver)),elseValue=argument.elseValue?rewriteValueComponentWithColumnResolver(argument.elseValue,resolver):null;return new SwitchCaseArgument(rewrittenCases,elseValue)}function rewriteCaseKeyValuePair(pair,resolver){let key=rewriteValueComponentWithColumnResolver(pair.key,resolver),value=rewriteValueComponentWithColumnResolver(pair.value,resolver);return new CaseKeyValuePair(key,value)}function rewriteOrderByClause(clause,resolver){let rewrittenOrder=clause.order.map(component=>rewriteOrderByComponent(component,resolver));return new OrderByClause(rewrittenOrder)}function rewriteOrderByComponent(component,resolver){if(component instanceof OrderByItem){let rewrittenValue=rewriteValueComponentWithColumnResolver(component.value,resolver);return new OrderByItem(rewrittenValue,component.sortDirection,component.nullsPosition)}return rewriteValueComponentWithColumnResolver(component,resolver)}function rewriteOverExpression(over,resolver){return over instanceof WindowFrameExpression?rewriteWindowFrameExpression(over,resolver):over}function rewriteWindowFrameExpression(expression,resolver){let partition=expression.partition?rewritePartitionByClause(expression.partition,resolver):null,order=expression.order?rewriteOrderByClause(expression.order,resolver):null,frameSpec=expression.frameSpec?rewriteWindowFrameSpec(expression.frameSpec,resolver):null;return new WindowFrameExpression(partition,order,frameSpec)}function rewritePartitionByClause(clause,resolver){let value=rewriteValueComponentWithColumnResolver(clause.value,resolver);return new PartitionByClause(value)}function rewriteWindowFrameSpec(spec,resolver){let startBound=rewriteFrameBoundaryComponent(spec.startBound,resolver),endBound=spec.endBound?rewriteFrameBoundaryComponent(spec.endBound,resolver):null;return new WindowFrameSpec(spec.frameType,startBound,endBound)}function rewriteFrameBoundaryComponent(bound,resolver){if(bound instanceof WindowFrameBoundaryValue){let value=rewriteValueComponentWithColumnResolver(bound.value,resolver);return new WindowFrameBoundaryValue(value,bound.isFollowing)}return bound}function rewriteTypeValue(value,resolver){let argument=value.argument?rewriteValueComponentWithColumnResolver(value.argument,resolver):null;return new TypeValue(value.namespaces,value.qualifiedName.name,argument)}var InsertResultSelectConverter=class{static{this.BASE_CTE_NAME="__inserted_rows"}static{this.DEFAULT_MISSING_FIXTURE_STRATEGY="error"}static toSelectQuery(insertQuery,options){let preparedInsert=this.prepareInsertQuery(insertQuery),sourceQuery=preparedInsert.selectQuery;if(!sourceQuery)throw new Error("Cannot convert INSERT query without a data source.");let sourceWithClause=SelectQueryWithClauseHelper.detachWithClause(sourceQuery),targetTableName=this.extractTargetTableName(preparedInsert.insertClause),tableDefinition=this.resolveTableDefinition(targetTableName,options),fixtureTables=options?.fixtureTables??[],fixtureMap=this.buildFixtureTableMap(fixtureTables),missingStrategy=options?.missingFixtureStrategy??this.DEFAULT_MISSING_FIXTURE_STRATEGY,referencedTables=this.collectPhysicalTableReferences(sourceQuery,sourceWithClause);this.ensureFixtureCoverage(referencedTables,fixtureMap,missingStrategy);let filteredFixtures=this.filterFixtureTablesForReferences(fixtureTables,referencedTables),insertColumnNames=this.resolveInsertColumns(preparedInsert.insertClause,sourceQuery,tableDefinition),selectColumnCount=this.getSelectColumnCount(sourceQuery);if(insertColumnNames.length!==selectColumnCount)throw new Error("Insert column count does not match SELECT output columns.");let columnMetadataMap=this.buildColumnMetadata(insertColumnNames,tableDefinition);this.assertRequiredColumns(columnMetadataMap,tableDefinition),this.applyColumnCasts(sourceQuery,insertColumnNames,columnMetadataMap);let fixtureCtes=this.buildFixtureCtes(filteredFixtures),cteName=this.generateUniqueCteName(sourceWithClause,fixtureCtes),cteAlias=new SourceAliasExpression(cteName,insertColumnNames),insertedRowsCte=new CommonTable(sourceQuery,cteAlias,null),withClause=this.buildWithClause(sourceWithClause,fixtureCtes,insertedRowsCte);if(!preparedInsert.returningClause)return this.buildCountSelect(withClause,cteName);let selectItems=this.buildReturningSelectItems(preparedInsert.returningClause,tableDefinition,insertColumnNames,columnMetadataMap,cteName),fromExpr=new SourceExpression(new TableSource(null,cteName),null),fromClause=new FromClause(fromExpr,null);return new SimpleSelectQuery({withClause,selectClause:new SelectClause(selectItems),fromClause})}static prepareInsertQuery(insertQuery){return insertQuery.selectQuery instanceof ValuesQuery?InsertQuerySelectValuesConverter.toSelectUnion(insertQuery):insertQuery}static extractTargetTableName(insertClause){let datasource=insertClause.source.datasource;if(datasource instanceof TableSource)return datasource.getSourceName();throw new Error("Insert target must be a table source for conversion.")}static resolveTableDefinition(tableName,options){if(options?.tableDefinitionResolver){let resolved=options.tableDefinitionResolver(tableName);if(resolved!==void 0)return resolved}let normalizedVariants=new Set(tableNameVariants(tableName));if(options?.tableDefinitions){let normalizedMap=this.buildTableDefinitionMap(options.tableDefinitions);for(let variant of normalizedVariants){let definition=normalizedMap.get(variant);if(definition)return definition}}if(options?.fixtureTables){let fixture=options.fixtureTables.find(f=>tableNameVariants(f.tableName).some(variant=>normalizedVariants.has(variant)));if(fixture)return this.convertFixtureToTableDefinition(fixture)}}static convertFixtureToTableDefinition(fixture){return{name:fixture.tableName,columns:fixture.columns.map(col=>({name:col.name,typeName:col.typeName,required:!1,defaultValue:col.defaultValue??null}))}}static buildTableDefinitionMap(registry){let map=new Map;if(!registry)return map;for(let definition of Object.values(registry))for(let variant of tableNameVariants(definition.name))map.set(variant,definition);return map}static resolveInsertColumns(insertClause,selectQuery,tableDefinition){if(insertClause.columns&&insertClause.columns.length>0)return insertClause.columns.map(col=>col.name);if(!tableDefinition)throw new Error("Cannot infer INSERT columns without a table definition.");let columnNames=tableDefinition.columns.map(col=>col.name),expectedCount=this.getSelectColumnCount(selectQuery);if(columnNames.length!==expectedCount)throw new Error("Table definition column count does not match the SELECT output when column list is omitted.");return columnNames}static getSelectColumnCount(selectQuery){return this.getFirstSimpleSelectQuery(selectQuery).selectClause.items.length}static getFirstSimpleSelectQuery(selectQuery){if(selectQuery instanceof SimpleSelectQuery)return selectQuery;if(selectQuery instanceof BinarySelectQuery)return this.getFirstSimpleSelectQuery(selectQuery.left);throw new Error("Unsupported select query structure in insert conversion.")}static buildColumnMetadata(insertColumns,tableDefinition){let metadataMap=new Map,columnDefinitionMap=tableDefinition?new Map(tableDefinition.columns.map(col=>[this.normalizeIdentifier(col.name),col])):null;for(let columnName of insertColumns){let normalized=this.normalizeIdentifier(columnName),definition=columnDefinitionMap?.get(normalized),normalizedTypeName=normalizeSerialPseudoType(definition?.typeName);metadataMap.set(normalized,{name:columnName,normalized,provided:!0,typeName:normalizedTypeName,required:definition?.required,defaultValue:this.resolveDefaultValueExpression(definition)})}if(columnDefinitionMap){for(let[normalized,definition]of columnDefinitionMap.entries())if(!metadataMap.has(normalized)){let normalizedTypeName=normalizeSerialPseudoType(definition.typeName);metadataMap.set(normalized,{name:definition.name,normalized,provided:!1,typeName:normalizedTypeName,required:definition.required,defaultValue:this.resolveDefaultValueExpression(definition)})}}return metadataMap}static assertRequiredColumns(metadataMap,tableDefinition){if(!tableDefinition)return;let requiredColumns=new Set(tableDefinition.columns.filter(col=>col.required).map(col=>this.normalizeIdentifier(col.name)));for(let normalized of requiredColumns){let metadata=metadataMap.get(normalized);if(metadata&&metadata.provided||metadata?.defaultValue)continue;let columnName=tableDefinition.columns.find(col=>this.normalizeIdentifier(col.name)===normalized)?.name;if(columnName)throw new Error(`Required column '${columnName}' is missing from INSERT, so conversion cannot proceed.`)}}static buildReturningSelectItems(returning,tableDefinition,insertColumns,columnMetadataMap,cteName){let selectItems=[];for(let item of returning.items){if(this.isWildcardReturningItem(item)){selectItems.push(...this.expandReturningWildcard(tableDefinition,insertColumns,columnMetadataMap,cteName));continue}selectItems.push(this.buildReturningSelectItem(item,columnMetadataMap,cteName))}return selectItems}static isWildcardReturningItem(item){return item.value instanceof ColumnReference&&item.value.column.name==="*"}static expandReturningWildcard(tableDefinition,insertColumns,columnMetadataMap,cteName){let columnNames=tableDefinition?tableDefinition.columns.map(column=>column.name):insertColumns.length>0?insertColumns:null;if(!columnNames)throw new Error("Cannot expand RETURNING * without table definition or column list.");return columnNames.map(columnName=>{let metadata=this.getColumnMetadata(columnMetadataMap,columnName),expression=this.buildColumnExpression(metadata,cteName);return new SelectItem(expression,columnName)})}static buildReturningSelectItem(item,columnMetadataMap,cteName){let expression=rewriteValueComponentWithColumnResolver(item.value,column=>this.buildInsertColumnExpression(column,columnMetadataMap,cteName)),alias=this.getReturningAlias(item);return new SelectItem(expression,alias)}static buildInsertColumnExpression(column,columnMetadataMap,cteName){let columnName=this.extractColumnName(column),metadata=this.getColumnMetadata(columnMetadataMap,columnName);return this.buildColumnExpression(metadata,cteName)}static extractColumnName(column){let nameComponent=column.qualifiedName.name;return nameComponent instanceof IdentifierString?nameComponent.name:nameComponent.value}static getReturningAlias(item){return item.identifier?.name?item.identifier.name:item.value instanceof ColumnReference?item.value.toString():null}static getColumnMetadata(metadataMap,columnName){let normalized=this.normalizeIdentifier(columnName),metadata=metadataMap.get(normalized);if(!metadata)throw new Error(`Column '${columnName}' cannot be resolved for RETURNING output.`);return metadata}static buildColumnExpression(metadata,cteName){let expression;return metadata.provided?expression=new ColumnReference(cteName,metadata.name):metadata.defaultValue?expression=metadata.defaultValue:expression=new LiteralValue(null),expression}static buildTypeValue(typeName){let normalizedTypeName=normalizeSerialPseudoType(typeName)??typeName.trim(),parts=normalizedTypeName.split("."),namePart=parts.pop()?.trim()??normalizedTypeName.trim(),namespaces=parts.length>0?parts.map(part=>part.trim()):null;return new TypeValue(namespaces,new RawString(namePart))}static collectPhysicalTableReferences(selectQuery,withClause){let referencedTables=this.collectReferencedTables(selectQuery),ignoredTables=this.collectCteNamesFromWithClause(withClause),tablesToShadow=new Set;for(let table of referencedTables)ignoredTables.has(table)||tablesToShadow.add(table);let cteReferencedTables=this.collectReferencedTablesFromWithClause(withClause);for(let table of cteReferencedTables)ignoredTables.has(table)||tablesToShadow.add(table);return tablesToShadow}static buildFixtureCtes(fixtures){return!fixtures||fixtures.length===0?[]:FixtureCteBuilder.buildFixtures(fixtures)}static filterFixtureTablesForReferences(fixtures,referencedTables){if(!fixtures.length||referencedTables.size===0)return[];let filtered=[];for(let fixture of fixtures)tableNameVariants(fixture.tableName).some(variant=>referencedTables.has(variant))&&filtered.push(fixture);return filtered}static collectReferencedTablesFromWithClause(withClause){let tables=new Set;if(!withClause?.tables)return tables;for(let cte of withClause.tables)for(let table of this.collectReferencedTables(cte.query))tables.add(table);return tables}static buildWithClause(original,fixtureCtes,insertedCte){let originalTables=original?.tables??[],combinedTables=[...fixtureCtes,...originalTables,insertedCte],withClause=new WithClause(original?.recursive??!1,combinedTables);return withClause.globalComments=original?.globalComments?[...original.globalComments]:null,withClause.trailingComments=original?.trailingComments?[...original.trailingComments]:null,withClause}static buildCountSelect(withClause,cteName){let countItem=new SelectItem(new FunctionCall(null,"count",new RawString("*"),null),"count"),selectClause=new SelectClause([countItem]),fromExpr=new SourceExpression(new TableSource(null,cteName),null),fromClause=new FromClause(fromExpr,null);return new SimpleSelectQuery({withClause,selectClause,fromClause})}static buildFixtureTableMap(fixtures){let map=new Map;if(!fixtures)return map;for(let fixture of fixtures)for(let variant of tableNameVariants(fixture.tableName))map.set(variant,fixture);return map}static ensureFixtureCoverage(referencedTables,fixtureMap,strategy){if(referencedTables.size===0)return;let missingTables=this.getMissingFixtureTables(referencedTables,fixtureMap);if(missingTables.length!==0&&strategy==="error")throw new Error(`Insert SELECT refers to tables without fixture coverage: ${missingTables.join(", ")}.`)}static collectReferencedTables(query){let sources=new TableSourceCollector(!1).collect(query),referenced=new Set;for(let source of sources)for(let variant of tableNameVariants(source.getSourceName()))referenced.add(variant);return referenced}static collectCteNamesFromWithClause(withClause){let names=new Set;if(!withClause?.tables)return names;for(let table of withClause.tables)names.add(this.normalizeIdentifier(table.getSourceAliasName()));return names}static addCteNames(usedNames,tables){if(tables)for(let table of tables)usedNames.add(this.normalizeIdentifier(table.getSourceAliasName()))}static getMissingFixtureTables(referencedTables,fixtureMap){let missing=[];for(let table of referencedTables)tableNameVariants(table).some(variant=>fixtureMap.has(variant))||missing.push(table);return missing}static generateUniqueCteName(withClause,fixtureCtes){let usedNames=new Set;this.addCteNames(usedNames,fixtureCtes);for(let name of this.collectCteNamesFromWithClause(withClause))usedNames.add(name);let candidate=this.BASE_CTE_NAME,suffix=0;for(;usedNames.has(this.normalizeIdentifier(candidate));)suffix+=1,candidate=`${this.BASE_CTE_NAME}_${suffix}`;return candidate}static normalizeIdentifier(value){return value.trim().toLowerCase()}static parseDefaultValue(def){try{return ValueParser.parse(def)}catch(error){throw new Error(`Failed to parse default expression '${def}': ${error instanceof Error?error.message:String(error)}`)}}static resolveDefaultValueExpression(definition){if(!definition)return null;let defaultValue=definition.defaultValue;if(typeof defaultValue=="string"){let parsed=this.parseDefaultValue(defaultValue);return this.referencesSequence(parsed)?this.parseDefaultValue("row_number() over ()"):parsed}return defaultValue&&this.referencesSequence(defaultValue)?this.parseDefaultValue("row_number() over ()"):this.shouldUseSerialDefault(definition)?this.parseDefaultValue("row_number() over ()"):defaultValue??null}static shouldUseSerialDefault(definition){return!definition||definition.defaultValue!=null?!1:isSerialPseudoType(definition.typeName)}static referencesSequence(component){if(component instanceof FunctionCall&&(this.isSequenceFunction(component)||component.argument&&this.referencesSequence(component.argument)))return!0;if(component instanceof ValueList)return component.values.some(value=>this.referencesSequence(value));if(component instanceof BinaryExpression)return this.referencesSequence(component.left)||this.referencesSequence(component.right);if(component instanceof UnaryExpression)return this.referencesSequence(component.expression);if(component instanceof CastExpression)return this.referencesSequence(component.input);if(component instanceof ParenExpression)return this.referencesSequence(component.expression);if(component instanceof InlineQuery)return this.referencesSelect(component.selectQuery);if(component instanceof ArrayExpression)return this.referencesSequence(component.expression);if(component instanceof ArrayQueryExpression)return this.referencesSelect(component.query);if(component instanceof BetweenExpression)return this.referencesSequence(component.expression)||this.referencesSequence(component.lower)||this.referencesSequence(component.upper);if(component instanceof ArraySliceExpression)return this.referencesSequence(component.array)||(component.startIndex?this.referencesSequence(component.startIndex):!1)||(component.endIndex?this.referencesSequence(component.endIndex):!1);if(component instanceof ArrayIndexExpression)return this.referencesSequence(component.array)||this.referencesSequence(component.index);if(component instanceof SwitchCaseArgument){for(let pair of component.cases)if(this.referencesSequence(pair.key)||this.referencesSequence(pair.value))return!0;return component.elseValue?this.referencesSequence(component.elseValue):!1}return component instanceof CaseExpression?(component.condition?this.referencesSequence(component.condition):!1)||this.referencesSequence(component.switchCase):component instanceof CaseKeyValuePair?this.referencesSequence(component.key)||this.referencesSequence(component.value):component instanceof TupleExpression?component.values.some(value=>this.referencesSequence(value)):!1}static referencesSelect(query){return!1}static isSequenceFunction(call){let name=call.qualifiedName.name;return(name instanceof RawString?name.value:name.name).toLowerCase()==="nextval"}static applyColumnCasts(selectQuery,insertColumns,metadataMap){if(selectQuery instanceof SimpleSelectQuery){this.applyColumnCastsToSimple(selectQuery,insertColumns,metadataMap);return}if(selectQuery instanceof BinarySelectQuery){this.applyColumnCasts(selectQuery.left,insertColumns,metadataMap),this.applyColumnCasts(selectQuery.right,insertColumns,metadataMap);return}throw new Error("Unsupported select query structure for applying column casts.")}static applyColumnCastsToSimple(simple,insertColumns,metadataMap){let items=simple.selectClause.items;for(let i=0;i<items.length;i++){let colName=insertColumns[i],metadata=metadataMap.get(this.normalizeIdentifier(colName));if(!metadata||!metadata.typeName)continue;let identifier=items[i].identifier?.name??null,casted=new CastExpression(items[i].value,this.buildTypeValue(metadata.typeName)),newItem=new SelectItem(casted,identifier);newItem.comments=items[i].comments,newItem.positionedComments=items[i].positionedComments,simple.selectClause.items[i]=newItem}}};var UpdateResultSelectConverter=class{static{this.DEFAULT_MISSING_FIXTURE_STRATEGY="error"}static toSelectQuery(updateQuery,options){let targetTableName=this.extractTargetTableName(updateQuery.updateClause),tableDefinition=this.resolveTableDefinition(targetTableName,options),targetAlias=updateQuery.updateClause.getSourceAliasName(),fromClause=this.buildFromClause(updateQuery.updateClause.source,updateQuery.fromClause),whereClause=updateQuery.whereClause??null,selectClause=updateQuery.returningClause?this.buildReturningSelectClause(updateQuery.returningClause,updateQuery.setClause,targetAlias,tableDefinition):this.buildCountSelectClause(),selectQuery=new SimpleSelectQuery({withClause:updateQuery.withClause??void 0,selectClause,fromClause,whereClause}),fixtureTables=options?.fixtureTables??[],fixtureMap=this.buildFixtureTableMap(fixtureTables),missingStrategy=options?.missingFixtureStrategy??this.DEFAULT_MISSING_FIXTURE_STRATEGY,originalWithClause=SelectQueryWithClauseHelper.detachWithClause(selectQuery),referencedTables=this.collectPhysicalTableReferences(selectQuery,originalWithClause),cteNames=this.collectCteNamesFromWithClause(originalWithClause),targetVariants=tableNameVariants(targetTableName);for(let variant of targetVariants)cteNames.has(variant)||referencedTables.add(variant);this.ensureFixtureCoverage(referencedTables,fixtureMap,missingStrategy);let filteredFixtures=this.filterFixtureTablesForReferences(fixtureTables,referencedTables),fixtureCtes=this.buildFixtureCtes(filteredFixtures),recombinedWithClause=this.mergeWithClause(originalWithClause,fixtureCtes);return SelectQueryWithClauseHelper.setWithClause(selectQuery,recombinedWithClause),selectQuery}static buildReturningSelectClause(returning,setClause,targetAlias,tableDefinition){let setExpressionMap=this.mapSetExpressions(setClause),selectItems=this.buildReturningSelectItems(returning,setExpressionMap,targetAlias,tableDefinition);return new SelectClause(selectItems)}static buildReturningSelectItems(returning,setExpressions,targetAlias,tableDefinition){let selectItems=[];for(let item of returning.items){if(this.isWildcardReturningItem(item)){selectItems.push(...this.expandReturningWildcard(tableDefinition,setExpressions,targetAlias));continue}selectItems.push(this.buildUpdateReturningSelectItem(item,setExpressions,targetAlias,tableDefinition))}return selectItems}static isWildcardReturningItem(item){return item.value instanceof ColumnReference&&item.value.column.name==="*"}static expandReturningWildcard(tableDefinition,setExpressions,targetAlias){if(!tableDefinition)throw new Error("Cannot expand RETURNING * without table definition.");return tableDefinition.columns.map(column=>{let expression=this.buildUpdateColumnExpression(column.name,setExpressions,targetAlias,tableDefinition);return new SelectItem(expression,column.name)})}static buildUpdateReturningSelectItem(item,setExpressions,targetAlias,tableDefinition){let expression=rewriteValueComponentWithColumnResolver(item.value,column=>this.buildUpdateColumnExpression(column,setExpressions,targetAlias,tableDefinition)),alias=this.getReturningAlias(item);return new SelectItem(expression,alias)}static buildUpdateColumnExpression(columnOrName,setExpressions,targetAlias,tableDefinition){let columnName=typeof columnOrName=="string"?columnOrName:this.getColumnReferenceName(columnOrName),normalized=this.normalizeIdentifier(columnName),overrideExpression=setExpressions.get(normalized);return overrideExpression||(this.ensureColumnExists(columnName,tableDefinition),new ColumnReference(targetAlias,columnName))}static getColumnReferenceName(column){let nameComponent=column.qualifiedName.name;return nameComponent instanceof IdentifierString?nameComponent.name:nameComponent.value}static getReturningAlias(item){return item.identifier?.name?item.identifier.name:item.value instanceof ColumnReference?item.value.toString():null}static buildCountSelectClause(){let countFunction=new FunctionCall(null,"count",new RawString("*"),null),selectItem=new SelectItem(countFunction,"count");return new SelectClause([selectItem])}static buildFromClause(targetSource,fromClause){if(!fromClause)return new FromClause(targetSource,null);let joins=[];return joins.push(new JoinClause("cross join",fromClause.source,null,!1)),fromClause.joins&&joins.push(...fromClause.joins),new FromClause(targetSource,joins)}static mapSetExpressions(setClause){let expressionMap=new Map;for(let item of setClause.items){let columnName=this.extractColumnName(item);expressionMap.set(this.normalizeIdentifier(columnName),item.value)}return expressionMap}static ensureColumnExists(columnName,tableDefinition){if(!tableDefinition)return;let normalized=this.normalizeIdentifier(columnName);if(!tableDefinition.columns.some(column=>this.normalizeIdentifier(column.name)===normalized))throw new Error(`Column '${columnName}' cannot be resolved for RETURNING output.`)}static resolveTableDefinition(tableName,options){if(options?.tableDefinitionResolver){let resolved=options.tableDefinitionResolver(tableName);if(resolved!==void 0)return resolved}let normalizedVariants=new Set(tableNameVariants(tableName));if(options?.tableDefinitions){let map=this.buildTableDefinitionMap(options.tableDefinitions);for(let variant of normalizedVariants){let definition=map.get(variant);if(definition)return definition}}if(options?.fixtureTables){let fixture=options.fixtureTables.find(f=>tableNameVariants(f.tableName).some(variant=>normalizedVariants.has(variant)));if(fixture)return this.convertFixtureToTableDefinition(fixture)}}static convertFixtureToTableDefinition(fixture){return{name:fixture.tableName,columns:fixture.columns.map(col=>({name:col.name,typeName:col.typeName,required:!1,defaultValue:col.defaultValue??null}))}}static buildTableDefinitionMap(registry){let map=new Map;for(let definition of Object.values(registry))for(let variant of tableNameVariants(definition.name))map.set(variant,definition);return map}static extractTargetTableName(updateClause){let datasource=updateClause.source.datasource;if(datasource instanceof TableSource)return datasource.getSourceName();throw new Error("Update target must be a table source for conversion.")}static extractColumnName(item){let columnComponent=item.qualifiedName.name;return columnComponent instanceof RawString?columnComponent.value:columnComponent.name}static buildFixtureCtes(fixtures){return!fixtures||fixtures.length===0?[]:FixtureCteBuilder.buildFixtures(fixtures)}static collectPhysicalTableReferences(selectQuery,withClause){let referencedTables=this.collectReferencedTables(selectQuery),ignoredTables=this.collectCteNamesFromWithClause(withClause),tablesToShadow=new Set;for(let table of referencedTables)ignoredTables.has(table)||tablesToShadow.add(table);let cteReferencedTables=this.collectReferencedTablesFromWithClause(withClause);for(let table of cteReferencedTables)ignoredTables.has(table)||tablesToShadow.add(table);return tablesToShadow}static filterFixtureTablesForReferences(fixtures,referencedTables){if(!fixtures.length||referencedTables.size===0)return[];let filtered=[];for(let fixture of fixtures)tableNameVariants(fixture.tableName).some(variant=>referencedTables.has(variant))&&filtered.push(fixture);return filtered}static collectReferencedTablesFromWithClause(withClause){let tables=new Set;if(!withClause?.tables)return tables;for(let cte of withClause.tables)for(let table of this.collectReferencedTables(cte.query))tables.add(table);return tables}static buildFixtureTableMap(fixtures){let map=new Map;for(let fixture of fixtures)for(let variant of tableNameVariants(fixture.tableName))map.set(variant,fixture);return map}static ensureFixtureCoverage(referencedTables,fixtureMap,strategy){if(referencedTables.size===0)return;let missingTables=this.getMissingFixtureTables(referencedTables,fixtureMap);if(missingTables.length!==0&&strategy==="error")throw new Error(`Update SELECT refers to tables without fixture coverage: ${missingTables.join(", ")}.`)}static collectReferencedTables(query){let sources=new TableSourceCollector(!1).collect(query),normalized=new Set;for(let source of sources)for(let variant of tableNameVariants(source.getSourceName()))normalized.add(variant);return normalized}static collectCteNamesFromWithClause(withClause){let names=new Set;if(!withClause?.tables)return names;for(let table of withClause.tables)for(let variant of tableNameVariants(table.getSourceAliasName()))names.add(variant);return names}static getMissingFixtureTables(referencedTables,fixtureMap){let missing=[];for(let table of referencedTables)tableNameVariants(table).some(variant=>fixtureMap.has(variant))||missing.push(table);return missing}static mergeWithClause(original,fixtureCtes){if(!fixtureCtes.length&&!original)return null;let combinedTables=[...fixtureCtes];if(original?.tables&&combinedTables.push(...original.tables),!combinedTables.length)return null;let merged=new WithClause(original?.recursive??!1,combinedTables);return merged.globalComments=original?.globalComments?[...original.globalComments]:null,merged.trailingComments=original?.trailingComments?[...original.trailingComments]:null,merged}static normalizeIdentifier(value){return value.trim().toLowerCase()}};var DeleteResultSelectConverter=class{static{this.DEFAULT_MISSING_FIXTURE_STRATEGY="error"}static toSelectQuery(deleteQuery,options){let targetTableName=this.extractTargetTableName(deleteQuery.deleteClause),tableDefinition=this.resolveTableDefinition(targetTableName,options),targetAlias=deleteQuery.deleteClause.getSourceAliasName(),returningContext=deleteQuery.returningClause?this.buildReturningContext(deleteQuery.deleteClause,deleteQuery.usingClause,targetAlias,tableDefinition,options):null,selectClause=deleteQuery.returningClause?this.buildReturningSelectClause(deleteQuery.returningClause,returningContext):this.buildCountSelectClause(),fromClause=this.buildFromClause(deleteQuery.deleteClause,deleteQuery.usingClause),whereClause=deleteQuery.whereClause??null,selectQuery=new SimpleSelectQuery({withClause:deleteQuery.withClause??void 0,selectClause,fromClause,whereClause}),fixtureTables=options?.fixtureTables??[],fixtureMap=this.buildFixtureTableMap(fixtureTables),missingStrategy=options?.missingFixtureStrategy??this.DEFAULT_MISSING_FIXTURE_STRATEGY,originalWithClause=SelectQueryWithClauseHelper.detachWithClause(selectQuery),referencedTables=this.collectPhysicalTableReferences(selectQuery,originalWithClause),cteNames=this.collectCteNamesFromWithClause(originalWithClause),targetVariants=tableNameVariants(targetTableName);for(let variant of targetVariants)cteNames.has(variant)||referencedTables.add(variant);this.ensureFixtureCoverage(referencedTables,fixtureMap,missingStrategy);let filteredFixtures=this.filterFixtureTablesForReferences(fixtureTables,referencedTables),fixtureCtes=this.buildFixtureCtes(filteredFixtures),mergedWithClause=this.mergeWithClause(originalWithClause,fixtureCtes);return SelectQueryWithClauseHelper.setWithClause(selectQuery,mergedWithClause),selectQuery}static buildReturningSelectClause(returning,context){let selectItems=this.buildReturningSelectItems(returning,context);return new SelectClause(selectItems)}static buildReturningSelectItems(returning,context){let selectItems=[];for(let item of returning.items){if(this.isWildcardReturningItem(item)){selectItems.push(...this.expandReturningWildcard(context));continue}selectItems.push(this.buildDeleteReturningSelectItem(item,context))}return selectItems}static isWildcardReturningItem(item){return item.value instanceof ColumnReference&&item.value.column.name==="*"}static expandReturningWildcard(context){if(!context.targetDefinition)throw new Error("Cannot expand RETURNING * without table definition.");return context.targetDefinition.columns.map(column=>{let expression=this.composeDeleteColumnReference({namespaces:null,column:column.name},context);return new SelectItem(expression,column.name)})}static buildDeleteReturningSelectItem(item,context){let expression=rewriteValueComponentWithColumnResolver(item.value,column=>this.buildDeleteColumnReference(column,context)),alias=this.getReturningAlias(item);return new SelectItem(expression,alias)}static buildDeleteColumnReference(column,context){let parsed=this.parseReturningColumnName(column.toString());return this.composeDeleteColumnReference(parsed,context)}static composeDeleteColumnReference(parsedColumn,context){let definitionToValidate=this.findTableContextForNamespaces(parsedColumn.namespaces,context)?.tableDefinition??(parsedColumn.namespaces?void 0:context.targetDefinition);definitionToValidate&&this.ensureColumnExists(parsedColumn.column,definitionToValidate);let columnNamespace=parsedColumn.namespaces&&parsedColumn.namespaces.length>0?[...parsedColumn.namespaces]:context.targetAlias?[context.targetAlias]:null;return new ColumnReference(columnNamespace,parsedColumn.column)}static getReturningAlias(item){return item.identifier?.name?item.identifier.name:item.value instanceof ColumnReference?item.value.toString():null}static buildCountSelectClause(){let countFunction=new FunctionCall(null,"count",new RawString("*"),null),selectItem=new SelectItem(countFunction,"count");return new SelectClause([selectItem])}static buildFromClause(deleteClause,usingClause){if(!usingClause?.sources?.length)return new FromClause(deleteClause.source,null);let joins=usingClause.sources.map(source=>new JoinClause("cross join",source,null,!1));return new FromClause(deleteClause.source,joins)}static buildReturningContext(deleteClause,usingClause,targetAlias,targetDefinition,options){let{aliasMap,tableNameMap}=this.buildTableContexts(deleteClause,usingClause,options);return{aliasMap,tableNameMap,targetAlias,targetDefinition}}static buildTableContexts(deleteClause,usingClause,options){let aliasMap=new Map,tableNameMap=new Map,collectSource=source=>{let alias=source.getAliasName();if(!alias||!(source.datasource instanceof TableSource))return;let normalizedAlias=this.normalizeIdentifier(alias);if(aliasMap.has(normalizedAlias))return;let tableName=source.datasource.getSourceName(),tableDefinition=this.resolveTableDefinition(tableName,options),context={alias,tableName,tableDefinition};aliasMap.set(normalizedAlias,context);for(let variant of tableNameVariants(tableName))tableNameMap.has(variant)||tableNameMap.set(variant,context)};if(collectSource(deleteClause.source),usingClause)for(let source of usingClause.sources)collectSource(source);return{aliasMap,tableNameMap}}static parseReturningColumnName(columnName){let trimmed=columnName.trim();if(!trimmed)throw new Error("Returning column name cannot be empty.");try{let parsed=FullNameParser.parse(trimmed);return{namespaces:parsed.namespaces,column:parsed.name.name}}catch{let parts=trimmed.split(".").map(segment=>segment.trim()).filter(segment=>segment.length>0);if(parts.length===0)return{namespaces:null,column:trimmed};let column=parts.pop();return{namespaces:parts.length>0?parts:null,column}}}static findTableContextForNamespaces(namespaces,context){if(namespaces?.length)for(let depth=namespaces.length;depth>0;depth--){let identifier=namespaces.slice(namespaces.length-depth).join("."),normalized=this.normalizeIdentifier(identifier),aliasContext=context.aliasMap.get(normalized);if(aliasContext)return aliasContext;let tableContext=context.tableNameMap.get(normalized);if(tableContext)return tableContext}}static ensureColumnExists(columnName,tableDefinition){if(!tableDefinition)return;let normalized=this.normalizeIdentifier(columnName);if(!tableDefinition.columns.some(column=>this.normalizeIdentifier(column.name)===normalized))throw new Error(`Column '${columnName}' cannot be resolved for RETURNING output.`)}static resolveTableDefinition(tableName,options){if(options?.tableDefinitionResolver){let resolved=options.tableDefinitionResolver(tableName);if(resolved!==void 0)return resolved}let normalizedVariants=new Set(tableNameVariants(tableName));if(options?.tableDefinitions){let map=this.buildTableDefinitionMap(options.tableDefinitions);for(let variant of normalizedVariants){let definition=map.get(variant);if(definition)return definition}}if(options?.fixtureTables){let fixture=options.fixtureTables.find(f=>tableNameVariants(f.tableName).some(variant=>normalizedVariants.has(variant)));if(fixture)return this.convertFixtureToTableDefinition(fixture)}}static convertFixtureToTableDefinition(fixture){return{name:fixture.tableName,columns:fixture.columns.map(col=>({name:col.name,typeName:col.typeName,required:!1,defaultValue:col.defaultValue??null}))}}static buildTableDefinitionMap(registry){let map=new Map;for(let definition of Object.values(registry))for(let variant of tableNameVariants(definition.name))map.set(variant,definition);return map}static extractTargetTableName(deleteClause){let datasource=deleteClause.source.datasource;if(datasource instanceof TableSource)return datasource.getSourceName();throw new Error("Delete target must be a table source for conversion.")}static buildFixtureCtes(fixtures){return!fixtures||fixtures.length===0?[]:FixtureCteBuilder.buildFixtures(fixtures)}static collectPhysicalTableReferences(selectQuery,withClause){let referencedTables=this.collectReferencedTables(selectQuery),ignoredTables=this.collectCteNamesFromWithClause(withClause),tablesToShadow=new Set;for(let table of referencedTables)ignoredTables.has(table)||tablesToShadow.add(table);let cteReferencedTables=this.collectReferencedTablesFromWithClause(withClause);for(let table of cteReferencedTables)ignoredTables.has(table)||tablesToShadow.add(table);return tablesToShadow}static buildFixtureTableMap(fixtures){let map=new Map;for(let fixture of fixtures)for(let variant of tableNameVariants(fixture.tableName))map.set(variant,fixture);return map}static filterFixtureTablesForReferences(fixtures,referencedTables){if(!fixtures.length||referencedTables.size===0)return[];let filtered=[];for(let fixture of fixtures)tableNameVariants(fixture.tableName).some(variant=>referencedTables.has(variant))&&filtered.push(fixture);return filtered}static collectReferencedTablesFromWithClause(withClause){let tables=new Set;if(!withClause?.tables)return tables;for(let cte of withClause.tables)for(let table of this.collectReferencedTables(cte.query))tables.add(table);return tables}static ensureFixtureCoverage(referencedTables,fixtureMap,strategy){if(referencedTables.size===0)return;let missingTables=this.getMissingFixtureTables(referencedTables,fixtureMap);if(missingTables.length!==0&&strategy==="error")throw new Error(`Delete SELECT refers to tables without fixture coverage: ${missingTables.join(", ")}.`)}static collectReferencedTables(query){let sources=new TableSourceCollector(!1).collect(query),normalized=new Set;for(let source of sources)for(let variant of tableNameVariants(source.getSourceName()))normalized.add(variant);return normalized}static collectCteNamesFromWithClause(withClause){let names=new Set;if(!withClause?.tables)return names;for(let table of withClause.tables)for(let variant of tableNameVariants(table.getSourceAliasName()))names.add(variant);return names}static getMissingFixtureTables(referencedTables,fixtureMap){let missing=[];for(let table of referencedTables)tableNameVariants(table).some(variant=>fixtureMap.has(variant))||missing.push(table);return missing}static mergeWithClause(original,fixtureCtes){if(!fixtureCtes.length&&!original)return null;let combinedTables=[...fixtureCtes];if(original?.tables&&combinedTables.push(...original.tables),!combinedTables.length)return null;let merged=new WithClause(original?.recursive??!1,combinedTables);return merged.globalComments=original?.globalComments?[...original.globalComments]:null,merged.trailingComments=original?.trailingComments?[...original.trailingComments]:null,merged}static normalizeIdentifier(value){return value.trim().toLowerCase()}};var MergeResultSelectConverter=class{static{this.DEFAULT_MISSING_FIXTURE_STRATEGY="error"}static toSelectQuery(mergeQuery,options){let actionSelects=this.buildActionSelects(mergeQuery);if(actionSelects.length===0)throw new Error("MERGE query must include at least one action that affects rows.");let unionSource=this.combineSelects(actionSelects),derivedSource=new SourceExpression(new SubQuerySource(unionSource),new SourceAliasExpression("__merge_action_rows",null)),finalSelect=new SimpleSelectQuery({selectClause:this.buildCountSelectClause(),fromClause:new FromClause(derivedSource,null)}),fixtureTables=options?.fixtureTables??[],fixtureMap=this.buildFixtureTableMap(fixtureTables),missingStrategy=options?.missingFixtureStrategy??this.DEFAULT_MISSING_FIXTURE_STRATEGY,nativeWithClause=mergeQuery.withClause??null,referencedTables=this.collectPhysicalTableReferences(unionSource,nativeWithClause),cteNames=this.collectCteNamesFromWithClause(nativeWithClause),targetName=this.normalizeIdentifier(this.extractTargetTableName(mergeQuery.target));cteNames.has(targetName)||referencedTables.add(targetName),this.ensureFixtureCoverage(referencedTables,fixtureMap,missingStrategy);let filteredFixtures=this.filterFixtureTablesForReferences(fixtureTables,referencedTables),fixtureCtes=this.buildFixtureCtes(filteredFixtures),combinedWithClause=this.mergeWithClause(nativeWithClause,fixtureCtes);return SelectQueryWithClauseHelper.setWithClause(finalSelect,combinedWithClause),finalSelect}static buildActionSelects(mergeQuery){let selects=[];for(let clause of mergeQuery.whenClauses){let selectQuery=this.buildSelectForClause(mergeQuery,clause);selectQuery&&selects.push(selectQuery)}return selects}static buildSelectForClause(mergeQuery,clause){switch(clause.matchType){case"matched":return this.buildMatchedSelect(mergeQuery,clause);case"not_matched":case"not_matched_by_target":return this.buildNotMatchedSelect(mergeQuery,clause);case"not_matched_by_source":return this.buildNotMatchedBySourceSelect(mergeQuery,clause);default:return null}}static buildMatchedSelect(mergeQuery,clause){let action=clause.action;if(action instanceof MergeDoNothingAction||!(action instanceof MergeUpdateAction)&&!(action instanceof MergeDeleteAction))return null;let joinClause=new JoinClause("inner join",mergeQuery.source,new JoinOnClause(mergeQuery.onCondition),!1),combinedPredicate=this.combineConditions([clause.condition,this.buildActionWhereClause(action)]),whereClause=combinedPredicate?new WhereClause(combinedPredicate):null;return new SimpleSelectQuery({selectClause:this.buildLiteralSelectClause(),fromClause:new FromClause(mergeQuery.target,[joinClause]),whereClause})}static buildNotMatchedSelect(mergeQuery,clause){if(!(clause.action instanceof MergeInsertAction))return null;let notExistsExpression=this.buildNotExistsExpression(mergeQuery.target,mergeQuery.onCondition),combinedPredicate=this.combineConditions([notExistsExpression,clause.condition]),whereClause=combinedPredicate?new WhereClause(combinedPredicate):null;return new SimpleSelectQuery({selectClause:this.buildLiteralSelectClause(),fromClause:new FromClause(mergeQuery.source,null),whereClause})}static buildNotMatchedBySourceSelect(mergeQuery,clause){let action=clause.action;if(!(action instanceof MergeDeleteAction))return null;let notExistsExpression=this.buildNotExistsExpression(mergeQuery.source,mergeQuery.onCondition),combinedPredicate=this.combineConditions([notExistsExpression,clause.condition,this.buildActionWhereClause(action)]),whereClause=combinedPredicate?new WhereClause(combinedPredicate):null;return new SimpleSelectQuery({selectClause:this.buildLiteralSelectClause(),fromClause:new FromClause(mergeQuery.target,null),whereClause})}static buildNotExistsExpression(sourceReference,predicate){let existsSelect=new SimpleSelectQuery({selectClause:this.buildLiteralSelectClause(),fromClause:new FromClause(sourceReference,null),whereClause:new WhereClause(predicate)}),existsExpression=new UnaryExpression("exists",new InlineQuery(existsSelect));return new UnaryExpression("not",existsExpression)}static buildActionWhereClause(action){return action.whereClause?.condition??null}static combineConditions(predicates){let values=predicates.filter(predicate=>!!predicate);return values.length===0?null:values.reduce((acc,value)=>acc?new BinaryExpression(acc,"and",value):value,null)}static combineSelects(selects){if(selects.length===1)return selects[0];let combined=new BinarySelectQuery(selects[0],"union all",selects[1]);for(let i=2;i<selects.length;i++)combined=combined.unionAll(selects[i]);return combined}static buildLiteralSelectClause(){return new SelectClause([new SelectItem(new LiteralValue(1))])}static buildCountSelectClause(){let countFunction=new FunctionCall(null,"count",new RawString("*"),null),selectItem=new SelectItem(countFunction,"count");return new SelectClause([selectItem])}static buildFixtureCtes(fixtures){return!fixtures||fixtures.length===0?[]:FixtureCteBuilder.buildFixtures(fixtures)}static collectPhysicalTableReferences(query,withClause){let referencedTables=this.collectReferencedTables(query),ignoredTables=this.collectCteNamesFromWithClause(withClause),tablesToShadow=new Set;for(let table of referencedTables)ignoredTables.has(table)||tablesToShadow.add(table);let cteReferencedTables=this.collectReferencedTablesFromWithClause(withClause);for(let table of cteReferencedTables)ignoredTables.has(table)||tablesToShadow.add(table);return tablesToShadow}static filterFixtureTablesForReferences(fixtures,referencedTables){if(!fixtures.length||referencedTables.size===0)return[];let filtered=[];for(let fixture of fixtures)referencedTables.has(this.normalizeIdentifier(fixture.tableName))&&filtered.push(fixture);return filtered}static collectReferencedTablesFromWithClause(withClause){let tables=new Set;if(!withClause?.tables)return tables;for(let cte of withClause.tables)for(let table of this.collectReferencedTables(cte.query))tables.add(table);return tables}static extractTargetTableName(target){let datasource=target.datasource;if(datasource instanceof TableSource)return datasource.getSourceName();throw new Error("Merge target must be a table source for conversion.")}static buildFixtureTableMap(fixtures){let map=new Map;for(let fixture of fixtures)map.set(this.normalizeIdentifier(fixture.tableName),fixture);return map}static ensureFixtureCoverage(referencedTables,fixtureMap,strategy){if(referencedTables.size===0)return;let missingTables=this.getMissingFixtureTables(referencedTables,fixtureMap);if(missingTables.length!==0&&strategy==="error")throw new Error(`Merge SELECT refers to tables without fixture coverage: ${missingTables.join(", ")}.`)}static collectReferencedTables(query){let sources=new TableSourceCollector(!1).collect(query),normalized=new Set;for(let source of sources)normalized.add(this.normalizeIdentifier(source.getSourceName()));return normalized}static collectCteNamesFromWithClause(withClause){let names=new Set;if(!withClause?.tables)return names;for(let table of withClause.tables)names.add(this.normalizeIdentifier(table.getSourceAliasName()));return names}static getMissingFixtureTables(referencedTables,fixtureMap){let missing=[];for(let table of referencedTables)fixtureMap.has(table)||missing.push(table);return missing}static mergeWithClause(original,fixtureCtes){if(!fixtureCtes.length&&!original)return null;let combinedTables=[...fixtureCtes];if(original?.tables&&combinedTables.push(...original.tables),!combinedTables.length)return null;let merged=new WithClause(original?.recursive??!1,combinedTables);return merged.globalComments=original?.globalComments?[...original.globalComments]:null,merged.trailingComments=original?.trailingComments?[...original.trailingComments]:null,merged}static normalizeIdentifier(value){return value.trim().toLowerCase()}};var QueryBuilder=class _QueryBuilder{static buildBinaryQuery(queries,operator){if(!queries||queries.length===0)throw new Error("No queries provided to combine.");if(queries.length===1)throw new Error("At least two queries are required to create a BinarySelectQuery.");let wrap=q=>q instanceof ValuesQuery?_QueryBuilder.buildSimpleQuery(q):q,result=new BinarySelectQuery(wrap(queries[0]),operator,wrap(queries[1]));CTENormalizer.normalize(result);for(let i=2;i<queries.length;i++)result.appendSelectQuery(operator,wrap(queries[i]));return result}constructor(){}static buildSimpleQuery(query){if(query instanceof SimpleSelectQuery)return query;if(query instanceof BinarySelectQuery)return _QueryBuilder.buildSimpleBinaryQuery(query);if(query instanceof ValuesQuery)return _QueryBuilder.buildSimpleValuesQuery(query);throw new Error("Unsupported query type for buildSimpleQuery")}static buildSimpleBinaryQuery(query){let extractedOrderBy=_QueryBuilder.extractAndRemoveOrderByFromBinaryQuery(query),subQuerySource=new SubQuerySource(query),sourceExpr=new SourceExpression(subQuerySource,new SourceAliasExpression("bq",null)),fromClause=new FromClause(sourceExpr,null),selectClause=_QueryBuilder.createSelectAllClause(),q=new SimpleSelectQuery({selectClause,fromClause,orderByClause:extractedOrderBy});return CTENormalizer.normalize(q)}static extractAndRemoveOrderByFromBinaryQuery(query){return _QueryBuilder.findAndRemoveRightmostOrderBy(query)}static findAndRemoveRightmostOrderBy(query){if(query instanceof BinarySelectQuery){let rightOrderBy=_QueryBuilder.findAndRemoveRightmostOrderBy(query.right);return rightOrderBy||_QueryBuilder.findAndRemoveRightmostOrderBy(query.left)}else if(query instanceof SimpleSelectQuery){let orderBy=query.orderByClause;if(orderBy)return query.orderByClause=null,orderBy}return null}static buildSimpleValuesQuery(query){let columnCount=query.tuples.length>0?query.tuples[0].values.length:0;if(query.tuples.length===0)throw new Error("Empty VALUES clause cannot be converted to a SimpleSelectQuery");if(!query.columnAliases)throw new Error("Column aliases are required to convert a VALUES clause to SimpleSelectQuery. Please specify column aliases.");if(query.columnAliases.length!==columnCount)throw new Error(`The number of column aliases (${query.columnAliases.length}) does not match the number of columns in the first tuple (${columnCount}).`);let subQuerySource=new SubQuerySource(query),sourceExpr=new SourceExpression(subQuerySource,new SourceAliasExpression("vq",query.columnAliases)),fromClause=new FromClause(sourceExpr,null),selectItems=query.columnAliases.map(name=>new SelectItem(new ColumnReference("vq",name),name)),selectClause=new SelectClause(selectItems,null);return new SimpleSelectQuery({selectClause,fromClause})}static createSelectAllClause(){let columnRef=new ColumnReference(null,"*"),selectItem=new SelectItem(columnRef,"*");return new SelectClause([selectItem],null)}static buildCreateTableQuery(query,tableName,isTemporary=!1,ifNotExists=!1){return new CreateTableQuery({tableName,isTemporary,ifNotExists,asSelectQuery:query})}static buildInsertQuery(selectQuery,targetOrOptions,explicitColumns){let options=_QueryBuilder.normalizeInsertOptions(targetOrOptions,explicitColumns),columnNames=_QueryBuilder.prepareInsertColumns(selectQuery,options.columns??null),sourceExpr=SourceExpressionParser.parse(options.target);return new InsertQuery({insertClause:new InsertClause(sourceExpr,columnNames),selectQuery})}static convertInsertValuesToSelect(insertQuery){return InsertQuerySelectValuesConverter.toSelectUnion(insertQuery)}static convertInsertSelectToValues(insertQuery){return InsertQuerySelectValuesConverter.toValues(insertQuery)}static convertInsertToReturningSelect(insertQuery,options){return InsertResultSelectConverter.toSelectQuery(insertQuery,options)}static convertUpdateToReturningSelect(updateQuery,options){return UpdateResultSelectConverter.toSelectQuery(updateQuery,options)}static convertDeleteToReturningSelect(deleteQuery,options){return DeleteResultSelectConverter.toSelectQuery(deleteQuery,options)}static convertMergeToReturningSelect(mergeQuery,options){return MergeResultSelectConverter.toSelectQuery(mergeQuery,options)}static buildUpdateQuery(selectQuery,selectSourceOrOptions,updateTableExprRaw,primaryKeys){let options=_QueryBuilder.normalizeUpdateOptions(selectSourceOrOptions,updateTableExprRaw,primaryKeys),updateColumns=_QueryBuilder.prepareUpdateColumns(selectQuery,options.primaryKeys,options.columns??null),updateClause=new UpdateClause(SourceExpressionParser.parse(options.target)),targetAlias=updateClause.getSourceAliasName();if(!targetAlias)throw new Error("Source expression does not have an alias. Please provide an alias for the source expression.");let withClause=_QueryBuilder.extractWithClause(selectQuery),setItems=updateColumns.map(column=>new SetClauseItem(column,_QueryBuilder.toColumnReference(options.sourceAlias,column)));if(setItems.length===0)throw new Error("No updatable columns found. Ensure the select list contains at least one column other than the specified primary keys.");let setClause=new SetClause(setItems),fromClause=new FromClause(selectQuery.toSource(options.sourceAlias),null),whereClause=new WhereClause(_QueryBuilder.buildEqualityPredicate(targetAlias,options.sourceAlias,options.primaryKeys));return new UpdateQuery({updateClause,setClause,fromClause,whereClause,withClause:withClause??void 0})}static buildDeleteQuery(selectQuery,options){let normalized=_QueryBuilder.normalizeDeleteOptions(options),predicateColumns=_QueryBuilder.prepareDeleteColumns(selectQuery,normalized.primaryKeys,normalized.columns??null),deleteClause=new DeleteClause(SourceExpressionParser.parse(normalized.target)),targetAlias=deleteClause.getSourceAliasName();if(!targetAlias)throw new Error("Source expression does not have an alias. Please provide an alias for the delete target.");let withClause=_QueryBuilder.extractWithClause(selectQuery),predicate=_QueryBuilder.buildEqualityPredicate(targetAlias,normalized.sourceAlias,predicateColumns),sourceExpression=selectQuery.toSource(normalized.sourceAlias),existsSelectClause=new SelectClause([new SelectItem(new LiteralValue(1))]),existsSubquery=new SimpleSelectQuery({selectClause:existsSelectClause,fromClause:new FromClause(sourceExpression,null),whereClause:new WhereClause(predicate)}),whereClause=new WhereClause(new UnaryExpression("exists",new InlineQuery(existsSubquery)));return new DeleteQuery({deleteClause,whereClause,withClause:withClause??void 0})}static buildMergeQuery(selectQuery,options){let normalized=_QueryBuilder.normalizeMergeOptions(options),mergeColumnPlan=_QueryBuilder.prepareMergeColumns(selectQuery,normalized.primaryKeys,normalized.updateColumns??null,normalized.insertColumns??null,normalized.matchedAction??"update",normalized.notMatchedAction??"insert"),targetExpression=SourceExpressionParser.parse(normalized.target),targetAlias=targetExpression.getAliasName();if(!targetAlias)throw new Error("Source expression does not have an alias. Please provide an alias for the merge target.");let withClause=_QueryBuilder.extractWithClause(selectQuery),onCondition=_QueryBuilder.buildEqualityPredicate(targetAlias,normalized.sourceAlias,normalized.primaryKeys),sourceExpression=selectQuery.toSource(normalized.sourceAlias),whenClauses=[],matchedAction=normalized.matchedAction??"update";if(matchedAction==="update"){if(mergeColumnPlan.updateColumns.length===0)throw new Error("No columns available for MERGE update action. Provide updateColumns or ensure the select list includes non-key columns.");let setItems=mergeColumnPlan.updateColumns.map(column=>new SetClauseItem(column,_QueryBuilder.toColumnReference(normalized.sourceAlias,column)));whenClauses.push(new MergeWhenClause("matched",new MergeUpdateAction(new SetClause(setItems))))}else matchedAction==="delete"?whenClauses.push(new MergeWhenClause("matched",new MergeDeleteAction)):matchedAction==="doNothing"&&whenClauses.push(new MergeWhenClause("matched",new MergeDoNothingAction));let notMatchedAction=normalized.notMatchedAction??"insert";if(notMatchedAction==="insert"){if(mergeColumnPlan.insertColumns.length===0)throw new Error("Unable to infer MERGE insert columns. Provide insertColumns explicitly.");let insertValues=new ValueList(mergeColumnPlan.insertColumns.map(column=>_QueryBuilder.toColumnReference(normalized.sourceAlias,column)));whenClauses.push(new MergeWhenClause("not_matched",new MergeInsertAction({columns:mergeColumnPlan.insertColumns,values:insertValues})))}else notMatchedAction==="doNothing"&&whenClauses.push(new MergeWhenClause("not_matched",new MergeDoNothingAction));let notMatchedBySourceAction=normalized.notMatchedBySourceAction??"doNothing";if(notMatchedBySourceAction==="delete"?whenClauses.push(new MergeWhenClause("not_matched_by_source",new MergeDeleteAction)):notMatchedBySourceAction==="doNothing"&&whenClauses.push(new MergeWhenClause("not_matched_by_source",new MergeDoNothingAction)),whenClauses.length===0)throw new Error("At least one MERGE action must be generated. Adjust the merge conversion options.");return new MergeQuery({withClause:withClause??void 0,target:targetExpression,source:sourceExpression,onCondition,whenClauses})}static normalizeInsertOptions(targetOrOptions,explicitColumns){return typeof targetOrOptions=="string"?{target:targetOrOptions,columns:explicitColumns}:explicitColumns&&explicitColumns.length>0?{...targetOrOptions,columns:explicitColumns}:{...targetOrOptions}}static normalizeUpdateOptions(selectSourceOrOptions,updateTableExprRaw,primaryKeys){if(typeof selectSourceOrOptions=="string"){if(!updateTableExprRaw)throw new Error("updateTableExprRaw is required when using the legacy buildUpdateQuery signature.");if(primaryKeys===void 0)throw new Error("primaryKeys are required when using the legacy buildUpdateQuery signature.");return{target:updateTableExprRaw,primaryKeys:_QueryBuilder.normalizeColumnArray(primaryKeys),sourceAlias:selectSourceOrOptions}}return{target:selectSourceOrOptions.target,primaryKeys:_QueryBuilder.normalizeColumnArray(selectSourceOrOptions.primaryKeys),sourceAlias:selectSourceOrOptions.sourceAlias??"src",columns:selectSourceOrOptions.columns}}static normalizeDeleteOptions(options){return{...options,primaryKeys:_QueryBuilder.normalizeColumnArray(options.primaryKeys),sourceAlias:options.sourceAlias??"src"}}static normalizeMergeOptions(options){return{...options,primaryKeys:_QueryBuilder.normalizeColumnArray(options.primaryKeys),sourceAlias:options.sourceAlias??"src"}}static normalizeColumnArray(columns){let normalized=(Array.isArray(columns)?columns:[columns]).map(col=>col.trim()).filter(col=>col.length>0);if(!normalized.length)throw new Error("At least one column must be specified.");return normalized}static collectSelectItems(selectQuery){return new SelectValueCollector().collect(selectQuery)}static collectSelectColumnNames(selectQuery){let items=_QueryBuilder.collectSelectItems(selectQuery),names=[];for(let item of items){if(!item.name||item.name==="*")throw new Error("Columns cannot be inferred from the selectQuery. Make sure you are not using wildcards or unnamed columns.");names.includes(item.name)||names.push(item.name)}if(!names.length)throw new Error("Unable to determine any column names from selectQuery.");return names}static ensurePrimaryKeys(selectColumns,primaryKeys){let available=new Set(selectColumns);for(let pk of primaryKeys)if(!available.has(pk))throw new Error(`Primary key column '${pk}' is not present in selectQuery select list.`)}static prepareInsertColumns(selectQuery,optionColumns){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);if(optionColumns&&optionColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(optionColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>!selectColumns.includes(name));if(missing.length>0)throw new Error(`Columns specified in conversion options were not found in selectQuery select list: [${missing.join(", ")}].`);return _QueryBuilder.rebuildSelectClause(selectQuery,uniqueNormalized),_QueryBuilder.ensureSelectClauseSize(selectQuery,uniqueNormalized.length),uniqueNormalized}return _QueryBuilder.ensureSelectClauseSize(selectQuery,selectColumns.length),selectColumns}static prepareUpdateColumns(selectQuery,primaryKeys,explicitColumns){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);_QueryBuilder.ensurePrimaryKeys(selectColumns,primaryKeys);let primaryKeySet=new Set(primaryKeys),updateCandidates=selectColumns.filter(name=>!primaryKeySet.has(name)),updateColumnsOrdered;if(explicitColumns&&explicitColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>primaryKeySet.has(name)||!updateCandidates.includes(name));if(missing.length>0)throw new Error(`Provided update columns were not found in selectQuery output or are primary keys: [${missing.join(", ")}].`);updateColumnsOrdered=uniqueNormalized}else updateColumnsOrdered=Array.from(new Set(updateCandidates));let desiredOrder=Array.from(new Set([...primaryKeys,...updateColumnsOrdered]));return _QueryBuilder.rebuildSelectClause(selectQuery,desiredOrder),_QueryBuilder.ensureSelectClauseSize(selectQuery,desiredOrder.length),updateColumnsOrdered}static prepareDeleteColumns(selectQuery,primaryKeys,explicitColumns){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);_QueryBuilder.ensurePrimaryKeys(selectColumns,primaryKeys);let primaryKeySet=new Set(primaryKeys),matchColumns=[];if(explicitColumns&&explicitColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitColumns),preferred=new Set(normalized);matchColumns=selectColumns.filter(name=>preferred.has(name)&&!primaryKeySet.has(name))}let requiredColumns=new Set;primaryKeys.forEach(key=>requiredColumns.add(key)),matchColumns.forEach(col=>requiredColumns.add(col));let desiredOrder=selectColumns.filter(name=>requiredColumns.has(name));return _QueryBuilder.rebuildSelectClause(selectQuery,desiredOrder),_QueryBuilder.ensureSelectClauseSize(selectQuery,desiredOrder.length),desiredOrder}static prepareMergeColumns(selectQuery,primaryKeys,explicitUpdateColumns,explicitInsertColumns,matchedAction,notMatchedAction){let selectColumns=_QueryBuilder.collectSelectColumnNames(selectQuery);_QueryBuilder.ensurePrimaryKeys(selectColumns,primaryKeys);let primaryKeySet=new Set(primaryKeys),updateColumnsOrdered=[];if(matchedAction==="update"){let candidates=selectColumns.filter(name=>!primaryKeySet.has(name));if(explicitUpdateColumns&&explicitUpdateColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitUpdateColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>primaryKeySet.has(name)||!candidates.includes(name));if(missing.length>0)throw new Error(`Provided update columns were not found in selectQuery output or are primary keys: [${missing.join(", ")}].`);updateColumnsOrdered=uniqueNormalized}else updateColumnsOrdered=Array.from(new Set(candidates))}let insertColumnsOrdered=[];if(notMatchedAction==="insert")if(explicitInsertColumns&&explicitInsertColumns.length>0){let normalized=_QueryBuilder.normalizeColumnArray(explicitInsertColumns),uniqueNormalized=normalized.filter((name,idx)=>normalized.indexOf(name)===idx),missing=uniqueNormalized.filter(name=>!selectColumns.includes(name));if(missing.length>0)throw new Error(`Provided insert columns were not found in selectQuery output: [${missing.join(", ")}].`);insertColumnsOrdered=uniqueNormalized}else insertColumnsOrdered=Array.from(new Set(selectColumns));let desiredOrder=Array.from(new Set([...primaryKeys,...updateColumnsOrdered,...insertColumnsOrdered,...selectColumns])).filter(name=>selectColumns.includes(name));return _QueryBuilder.rebuildSelectClause(selectQuery,desiredOrder),_QueryBuilder.ensureSelectClauseSize(selectQuery,desiredOrder.length),{updateColumns:matchedAction==="update"?updateColumnsOrdered:[],insertColumns:notMatchedAction==="insert"?insertColumnsOrdered:[]}}static rebuildSelectClause(selectQuery,desiredColumns){let itemMap=new Map;for(let item of selectQuery.selectClause.items){let name=_QueryBuilder.getSelectItemName(item);name&&(itemMap.has(name)||itemMap.set(name,item))}let rebuiltItems=[],seen=new Set;for(let column of desiredColumns){if(seen.has(column))continue;let item=itemMap.get(column);if(!item)throw new Error(`Column '${column}' not found in select clause.`);rebuiltItems.push(item),seen.add(column)}if(!rebuiltItems.length)throw new Error("Unable to rebuild select clause with the requested columns.");selectQuery.selectClause.items=rebuiltItems}static getSelectItemName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}static ensureSelectClauseSize(selectQuery,expected){if(selectQuery.selectClause.items.length!==expected)throw new Error(`Select clause column count (${selectQuery.selectClause.items.length}) does not match expected count (${expected}).`)}static extractWithClause(selectQuery){let collected=new CTECollector().collect(selectQuery);return collected.length===0?null:(new CTEDisabler().execute(selectQuery),new WithClause(!1,collected))}static buildEqualityPredicate(leftAlias,rightAlias,columns){let uniqueColumns=_QueryBuilder.mergeUniqueColumns(columns);if(!uniqueColumns.length)throw new Error("At least one column is required to build a comparison predicate.");let predicate=null;for(let column of uniqueColumns){let comparison=new BinaryExpression(_QueryBuilder.toColumnReference(leftAlias,column),"=",_QueryBuilder.toColumnReference(rightAlias,column));predicate=predicate?new BinaryExpression(predicate,"and",comparison):comparison}return predicate}static toColumnReference(alias,column){return new ColumnReference(alias,column)}static mergeUniqueColumns(columns){let seen=new Set,result=[];for(let column of columns)seen.has(column)||(seen.add(column),result.push(column));return result}};var SimpleSelectQuery=class extends SqlComponent{constructor(params){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.cteNameCache=new Set;this.withClause=params.withClause??null,this.selectClause=params.selectClause,this.fromClause=params.fromClause??null,this.whereClause=params.whereClause??null,this.groupByClause=params.groupByClause??null,this.havingClause=params.havingClause??null,this.orderByClause=params.orderByClause??null,this.windowClause=params.windowClause??null,this.limitClause=params.limitClause??null,this.offsetClause=params.offsetClause??null,this.fetchClause=params.fetchClause??null,this.forClause=params.forClause??null,this.initializeCTECache()}static{this.kind=Symbol("SelectQuery")}initializeCTECache(){if(this.cteNameCache.clear(),this.withClause?.tables)for(let table of this.withClause.tables)this.cteNameCache.add(table.aliasExpression.table.name)}toUnion(rightQuery){return this.toBinaryQuery("union",rightQuery)}toUnionAll(rightQuery){return this.toBinaryQuery("union all",rightQuery)}toInsertQuery(options){return QueryBuilder.buildInsertQuery(this,options)}toUpdateQuery(options){return QueryBuilder.buildUpdateQuery(this,options)}toDeleteQuery(options){return QueryBuilder.buildDeleteQuery(this,options)}toMergeQuery(options){return QueryBuilder.buildMergeQuery(this,options)}toIntersect(rightQuery){return this.toBinaryQuery("intersect",rightQuery)}toIntersectAll(rightQuery){return this.toBinaryQuery("intersect all",rightQuery)}toExcept(rightQuery){return this.toBinaryQuery("except",rightQuery)}toExceptAll(rightQuery){return this.toBinaryQuery("except all",rightQuery)}toBinaryQuery(operator,rightQuery){return QueryBuilder.buildBinaryQuery([this,rightQuery],operator)}appendWhereRaw(rawCondition){let parsedCondition=ValueParser.parse(rawCondition);this.appendWhere(parsedCondition)}appendWhere(condition){this.whereClause?this.whereClause.condition=new BinaryExpression(this.whereClause.condition,"and",condition):this.whereClause=new WhereClause(condition)}appendHavingRaw(rawCondition){let parsedCondition=ValueParser.parse(rawCondition);this.appendHaving(parsedCondition)}appendHaving(condition){this.havingClause?this.havingClause.condition=new BinaryExpression(this.havingClause.condition,"and",condition):this.havingClause=new HavingClause(condition)}innerJoinRaw(joinSourceRawText,alias,columns,resolver=null){this.joinSourceRaw("inner join",joinSourceRawText,alias,columns,resolver)}leftJoinRaw(joinSourceRawText,alias,columns,resolver=null){this.joinSourceRaw("left join",joinSourceRawText,alias,columns,resolver)}rightJoinRaw(joinSourceRawText,alias,columns,resolver=null){this.joinSourceRaw("right join",joinSourceRawText,alias,columns,resolver)}innerJoin(sourceExpr,columns,resolver=null){this.joinSource("inner join",sourceExpr,columns,resolver)}leftJoin(sourceExpr,columns,resolver=null){this.joinSource("left join",sourceExpr,columns,resolver)}rightJoin(sourceExpr,columns,resolver=null){this.joinSource("right join",sourceExpr,columns,resolver)}joinSourceRaw(joinType,joinSourceRawText,alias,columns,resolver=null){let tableSource=SourceParser.parse(joinSourceRawText),sourceExpr=new SourceExpression(tableSource,new SourceAliasExpression(alias,null));this.joinSource(joinType,sourceExpr,columns,resolver)}joinSource(joinType,sourceExpr,columns,resolver=null){if(!this.fromClause)throw new Error("A FROM clause is required to add a JOIN condition.");let columnsArr=Array.isArray(columns)?columns:[columns],valueSets=new SelectableColumnCollector(resolver).collect(this),joinCondition=null,count=0,sourceAlias=sourceExpr.getAliasName();if(!sourceAlias)throw new Error("An alias is required for the source expression to add a JOIN condition.");for(let valueSet of valueSets)if(columnsArr.some(col=>col==valueSet.name)){let expr=new BinaryExpression(valueSet.value,"=",new ColumnReference([sourceAlias],valueSet.name));joinCondition?joinCondition=new BinaryExpression(joinCondition,"and",expr):joinCondition=expr,count++}if(!joinCondition||count!==columnsArr.length)throw new Error(`Invalid JOIN condition. The specified columns were not found: ${columnsArr.join(", ")}`);let joinOnClause=new JoinOnClause(joinCondition),joinClause=new JoinClause(joinType,sourceExpr,joinOnClause,!1);this.fromClause&&(this.fromClause.joins?this.fromClause.joins.push(joinClause):this.fromClause.joins=[joinClause]),CTENormalizer.normalize(this)}toSource(alias){if(!alias||alias.trim()==="")throw new Error("Alias is required for toSource(). Please specify a non-empty alias name.");return new SourceExpression(new SubQuerySource(this),new SourceAliasExpression(alias,null))}appendWith(commonTable){let tables=Array.isArray(commonTable)?commonTable:[commonTable];this.withClause?this.withClause.tables.push(...tables):this.withClause=new WithClause(!1,tables),CTENormalizer.normalize(this)}appendWithRaw(rawText,alias){let query=SelectQueryParser.parse(rawText),commonTable=new CommonTable(query,alias,null);this.appendWith(commonTable)}overrideSelectItemExpr(columnName,fn){let items=this.selectClause.items.filter(item2=>item2.identifier?.name===columnName);if(items.length===0)throw new Error(`Column ${columnName} not found in the query`);if(items.length>1)throw new Error(`Duplicate column name ${columnName} found in the query`);let item=items[0],exprSql=new Formatter().visit(item.value),newValue=fn(exprSql);item.value=ValueParser.parse(newValue)}appendWhereExpr(columnName,exprBuilder,options){if(options&&options.upstream){let queries=new UpstreamSelectQueryFinder().find(this,[columnName]),collector=new SelectableColumnCollector,formatter2=new Formatter;for(let q of queries){let exprs=collector.collect(q).filter(item=>item.name===columnName).map(item=>item.value);if(exprs.length!==1)throw new Error(`Expected exactly one expression for column '${columnName}'`);let exprStr=formatter2.format(exprs[0]);q.appendWhereRaw(exprBuilder(exprStr))}}else{let collector=new SelectableColumnCollector,formatter2=new Formatter,exprs=collector.collect(this).filter(item=>item.name===columnName).map(item=>item.value);if(exprs.length!==1)throw new Error(`Expected exactly one expression for column '${columnName}'`);let exprStr=formatter2.format(exprs[0]);this.appendWhereRaw(exprBuilder(exprStr))}}setParameter(name,value){return ParameterHelper.set(this,name,value),this}toSimpleQuery(){return this}addCTE(name,query,options){if(!name||name.trim()==="")throw new InvalidCTENameError(name,"name cannot be empty or whitespace-only");if(this.hasCTE(name))throw new DuplicateCTEError(name);let materialized=options?.materialized??null,commonTable=new CommonTable(query,name,materialized);return this.appendWith(commonTable),this.cteNameCache.add(name),this}removeCTE(name){if(!this.hasCTE(name))throw new CTENotFoundError(name);return this.withClause&&(this.withClause.tables=this.withClause.tables.filter(table=>table.aliasExpression.table.name!==name),this.withClause.tables.length===0&&(this.withClause=null)),this.cteNameCache.delete(name),this}hasCTE(name){return this.cteNameCache.has(name)}getCTENames(){return this.withClause?.tables.map(table=>table.aliasExpression.table.name)??[]}replaceCTE(name,query,options){if(!name||name.trim()==="")throw new InvalidCTENameError(name,"name cannot be empty or whitespace-only");this.hasCTE(name)&&this.removeCTE(name);let materialized=options?.materialized??null,commonTable=new CommonTable(query,name,materialized);return this.appendWith(commonTable),this.cteNameCache.add(name),this}};var SelectClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The SELECT clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,distinct=null,selectTokenComments=idx<lexemes.length?lexemes[idx].comments:null;if(lexemes[idx].value!=="select")throw new Error(`Syntax error at position ${idx}: Expected 'SELECT' keyword but found "${lexemes[idx].value}". SELECT clauses must start with the SELECT keyword.`);idx++;let hints=[];for(;idx<lexemes.length&&HintClause.isHintClause(lexemes[idx].value);){let hintContent=HintClause.extractHintContent(lexemes[idx].value);hints.push(new HintClause(hintContent)),idx++}if(idx<lexemes.length&&lexemes[idx].value==="distinct")idx++,distinct=new Distinct;else if(idx<lexemes.length&&lexemes[idx].value==="distinct on"){idx++;let argument=ValueParser.parseArgument(4,8,lexemes,idx);distinct=new DistinctOn(argument.value),idx=argument.newIndex}let items=[],item=SelectItemParser.parseItem(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=SelectItemParser.parseItem(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No select items found. The SELECT clause requires at least one expression to select.`);return{value:new SelectClause(items,distinct,hints),newIndex:idx}}},SelectItemParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseItem(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The select item is complete but there are additional tokens.`);return result.value}static parseItem(lexemes,index){let idx=index,valueTokenComments=this.extractValueTokenComments(lexemes,idx),parsedValue=ValueParser.parseFromLexeme(lexemes,idx),value=parsedValue.value;idx=parsedValue.newIndex;let{asComments,newIndex:asIndex}=this.parseAsKeyword(lexemes,idx);if(idx=asIndex,idx<lexemes.length&&lexemes[idx].type&64){let alias=lexemes[idx].value,aliasComments=lexemes[idx].comments,aliasPositionedComments=lexemes[idx].positionedComments;idx++;let selectItem2=new SelectItem(value,alias);return this.applyValueTokenComments(selectItem2,valueTokenComments),this.applyAsKeywordComments(selectItem2,asComments),this.applyAliasComments(selectItem2,aliasComments,aliasPositionedComments),{value:selectItem2,newIndex:idx}}else if(value instanceof ColumnReference&&value.column.name!=="*"){let selectItem2=new SelectItem(value,value.column.name);return this.applyValueTokenComments(selectItem2,valueTokenComments),this.applyAsKeywordComments(selectItem2,asComments),{value:selectItem2,newIndex:idx}}let selectItem=new SelectItem(value);return this.applyValueTokenComments(selectItem,valueTokenComments),this.applyAsKeywordComments(selectItem,asComments),{value:selectItem,newIndex:idx}}static clearPositionedCommentsRecursively(component){!component||typeof component!="object"||("positionedComments"in component&&(component.positionedComments=null),component.left&&this.clearPositionedCommentsRecursively(component.left),component.right&&this.clearPositionedCommentsRecursively(component.right),component.qualifiedName&&this.clearPositionedCommentsRecursively(component.qualifiedName),component.table&&this.clearPositionedCommentsRecursively(component.table),component.name&&this.clearPositionedCommentsRecursively(component.name),component.args&&Array.isArray(component.args)&&component.args.forEach(arg=>{this.clearPositionedCommentsRecursively(arg)}),component.value&&this.clearPositionedCommentsRecursively(component.value))}static extractValueTokenComments(lexemes,index){if(index>=lexemes.length)return{positioned:null,legacy:null};let token=lexemes[index];return{positioned:token.positionedComments&&token.positionedComments.length>0?token.positionedComments:null,legacy:null}}static parseAsKeyword(lexemes,index){if(index>=lexemes.length||lexemes[index].value!=="as")return{asComments:{positioned:null,legacy:null},newIndex:index};let asToken=lexemes[index];return{asComments:{positioned:asToken.positionedComments&&asToken.positionedComments.length>0?asToken.positionedComments:null,legacy:asToken.comments&&asToken.comments.length>0?asToken.comments:null},newIndex:index+1}}static applyValueTokenComments(selectItem,valueTokenComments){if(valueTokenComments.positioned){for(let posComment of valueTokenComments.positioned)selectItem.addPositionedComments(posComment.position,posComment.comments);this.clearValueTokenComments(selectItem)}}static applyAsKeywordComments(selectItem,asComments){asComments.positioned?selectItem.asKeywordPositionedComments=asComments.positioned:asComments.legacy&&(selectItem.asKeywordComments=asComments.legacy)}static applyAliasComments(selectItem,aliasComments,aliasPositionedComments){aliasPositionedComments&&aliasPositionedComments.length>0?selectItem.aliasPositionedComments=aliasPositionedComments:aliasComments&&aliasComments.length>0&&(selectItem.aliasComments=aliasComments)}static clearValueTokenComments(selectItem){if("positionedComments"in selectItem.value&&(selectItem.value.positionedComments=null),selectItem.value instanceof ColumnReference){let columnRef=selectItem.value;columnRef.qualifiedName&&columnRef.qualifiedName.name&&(columnRef.qualifiedName.name.positionedComments=null)}selectItem.value instanceof BinaryExpression&&this.clearPositionedCommentsRecursively(selectItem.value)}};var JoinOnClauseParser=class{static tryParse(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].value==="on"){let onKeywordComments=lexemes[idx].positionedComments;idx++;let condition=ValueParser.parseFromLexeme(lexemes,idx),afterKeywordComments=onKeywordComments?.filter(comment=>comment.position==="after").flatMap(comment=>comment.comments)??[];return afterKeywordComments.length>0&&condition.value.addPositionedComments("before",afterKeywordComments),idx=condition.newIndex,{value:new JoinOnClause(condition.value),newIndex:idx}}return null}};var JoinUsingClauseParser=class{static tryParse(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].value==="using"){idx++;let result=ValueParser.parseArgument(4,8,lexemes,idx),usingColumns=result.value;return idx=result.newIndex,{value:new JoinUsingClause(usingColumns),newIndex:idx}}return null}};var JoinClauseParser=class{static tryParse(lexemes,index){let idx=index,joins=[];for(;this.isJoinCommand(lexemes,idx);){let joinClause=this.parseJoinClause(lexemes,idx);joins.push(joinClause.value),idx=joinClause.newIndex}return joins.length>0?{value:joins,newIndex:idx}:null}static isJoinKeyword(value){return!!joinkeywordParser.parse(value,0)}static parseLateral(lexemes,index){let idx=index;return idx<lexemes.length&&lexemes[idx].value==="lateral"?(idx++,{value:!0,newIndex:idx}):{value:!1,newIndex:idx}}static isJoinCommand(lexemes,index){return index>=lexemes.length?!1:!!(lexemes[index].type&16||this.isJoinKeyword(lexemes[index].value)===!0)}static parseJoinClause(lexemes,index){let idx=index,{joinType,joinComments,newIndex:joinIndex}=this.parseJoinKeyword(lexemes,idx);idx=joinIndex;let lateralResult=this.parseLateral(lexemes,idx),lateral=lateralResult.value;idx=lateralResult.newIndex;let sourceResult=SourceExpressionParser.parseFromLexeme(lexemes,idx);idx=sourceResult.newIndex;let joinClause=this.parseJoinCondition(lexemes,idx,joinType,sourceResult.value,lateral,joinComments);if(joinClause)return joinClause;let naturalJoinClause=new JoinClause(joinType,sourceResult.value,null,lateral);return this.applyJoinComments(naturalJoinClause,joinComments),{value:naturalJoinClause,newIndex:idx}}static parseJoinKeyword(lexemes,index){let joinType=lexemes[index].value===","?"cross join":lexemes[index].value,joinComments=this.extractJoinKeywordComments(lexemes[index]);return{joinType,joinComments,newIndex:index+1}}static extractJoinKeywordComments(token){return{positioned:token.positionedComments&&token.positionedComments.length>0?token.positionedComments:null,legacy:token.comments&&token.comments.length>0?token.comments:null}}static parseJoinCondition(lexemes,index,joinType,sourceValue,lateral,joinComments){if(index>=lexemes.length)return null;let onResult=JoinOnClauseParser.tryParse(lexemes,index);if(onResult){let joinClause=new JoinClause(joinType,sourceValue,onResult.value,lateral);return this.applyJoinComments(joinClause,joinComments),{value:joinClause,newIndex:onResult.newIndex}}let usingResult=JoinUsingClauseParser.tryParse(lexemes,index);if(usingResult){let joinClause=new JoinClause(joinType,sourceValue,usingResult.value,lateral);return this.applyJoinComments(joinClause,joinComments),{value:joinClause,newIndex:usingResult.newIndex}}return null}static applyJoinComments(joinClause,joinComments){joinComments.positioned?joinClause.joinKeywordPositionedComments=joinComments.positioned:joinComments.legacy&&(joinClause.joinKeywordComments=joinComments.legacy)}};var CommentUtils=class{static{this.SIGNIFICANT_SQL_KEYWORDS=new Set(["select","from","where","group by","having","order by","limit","offset"])}static collectClauseComments(lexemes,currentIndex,keywordValue){let normalizedKeyword=keywordValue.toLowerCase();if(currentIndex>=lexemes.length||lexemes[currentIndex].value.toLowerCase()!==normalizedKeyword)return null;let comments=[];lexemes[currentIndex].comments&&comments.push(...lexemes[currentIndex].comments);let checkIndex=currentIndex-1;for(;checkIndex>=0;){let prevToken=lexemes[checkIndex];if(prevToken.comments&&prevToken.comments.length>0){let clauseSpecificComments=prevToken.comments.filter(comment=>{let lowerComment=comment.toLowerCase();return lowerComment.includes(normalizedKeyword)||lowerComment.includes("\u306E")||lowerComment.includes("\u30B3\u30E1\u30F3\u30C8")});clauseSpecificComments.length>0&&(comments.unshift(...clauseSpecificComments),prevToken.comments=prevToken.comments.filter(c=>!clauseSpecificComments.includes(c)),prevToken.comments.length===0&&(prevToken.comments=null));break}if(this.isSignificantSqlKeyword(prevToken.value))break;checkIndex--}return comments.length>0?comments:null}static isSignificantSqlKeyword(value){return this.SIGNIFICANT_SQL_KEYWORDS.has(value.toLowerCase())}};var FromClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The FROM clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,fromTokenComments=CommentUtils.collectClauseComments(lexemes,idx,"from");if(lexemes[idx].value!=="from")throw new Error(`Syntax error at position ${idx}: Expected 'FROM' keyword but found "${lexemes[idx].value}". FROM clauses must start with the FROM keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FROM' keyword. The FROM clause requires a table reference.");let sourceExpression=SourceExpressionParser.parseFromLexeme(lexemes,idx);idx=sourceExpression.newIndex;let join=JoinClauseParser.tryParse(lexemes,idx);if(idx=join?.newIndex||idx,join!==null){let clause=new FromClause(sourceExpression.value,join.value);return{value:clause,newIndex:idx}}else{let clause=new FromClause(sourceExpression.value,null);return{value:clause,newIndex:idx}}}};var WhereClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The WHERE clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,whereLexeme=lexemes[idx],whereTokenComments=CommentUtils.collectClauseComments(lexemes,idx,"where"),wherePositionedComments=whereLexeme.positionedComments;if(whereLexeme.value!=="where")throw new Error(`Syntax error at position ${idx}: Expected 'WHERE' keyword but found "${lexemes[idx].value}". WHERE clauses must start with the WHERE keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'WHERE' keyword. The WHERE clause requires a condition expression.");let item=ValueParser.parseFromLexeme(lexemes,idx),clause=new WhereClause(item.value);return clause.comments=whereTokenComments,wherePositionedComments&&wherePositionedComments.length>0&&(clause.positionedComments=wherePositionedComments.map(comment=>({position:comment.position,comments:[...comment.comments]}))),{value:clause,newIndex:item.newIndex}}};var GroupByClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The GROUP BY clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="group by")throw new Error(`Syntax error at position ${idx}: Expected 'GROUP BY' keyword but found "${lexemes[idx].value}". GROUP BY clauses must start with the GROUP BY keywords.`);idx++;let mode=null,modeCandidate=lexemes[idx]?.value.toLowerCase();if((modeCandidate==="all"||modeCandidate==="distinct")&&(mode=modeCandidate,idx++),idx>=lexemes.length){if(mode==="all")return{value:new GroupByClause([],mode),newIndex:idx};throw new Error("Syntax error: Unexpected end of input after 'GROUP BY' keyword. The GROUP BY clause requires at least one expression to group by.")}let items=[];if(!this.isClauseBoundary(lexemes[idx])){let 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&&mode!=="all")throw new Error(`Syntax error at position ${index}: No grouping expressions found. The GROUP BY clause requires at least one expression to group by.`);return{value:new GroupByClause(items,mode),newIndex:idx}}static isClauseBoundary(lexeme){return["having","window","order by","limit","offset","fetch","for"].includes(lexeme.value)}static parseItem(lexemes,index){let idx=index,parsedValue=ValueParser.parseFromLexeme(lexemes,idx),value=parsedValue.value;return idx=parsedValue.newIndex,{value,newIndex:idx}}};var HavingClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The HAVING clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="having")throw new Error(`Syntax error at position ${idx}: Expected 'HAVING' keyword but found "${lexemes[idx].value}". HAVING clauses must start with the HAVING keyword.`);let havingKeywordComments=lexemes[idx].positionedComments;if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'HAVING' keyword. The HAVING clause requires a condition expression.");let item=ValueParser.parseFromLexeme(lexemes,idx),afterKeywordComments=havingKeywordComments?.filter(comment=>comment.position==="after").flatMap(comment=>comment.comments)??[];return afterKeywordComments.length>0&&item.value.addPositionedComments("before",afterKeywordComments),{value:new HavingClause(item.value),newIndex:item.newIndex}}};var WindowClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The WINDOW clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="window")throw new Error(`Syntax error at position ${idx}: Expected 'WINDOW' keyword but found "${lexemes[idx].value}". WINDOW clauses must start with the WINDOW keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'WINDOW' keyword. The WINDOW clause requires at least one window definition.");let windows=[];for(;idx<lexemes.length;){if(idx>=lexemes.length||lexemes[idx].type!==64)throw new Error("Syntax error: Expected window name after 'WINDOW' keyword.");let name=lexemes[idx].value;if(idx++,idx>=lexemes.length||lexemes[idx].value!=="as")throw new Error(`Syntax error at position ${idx}: Expected 'AS' keyword after window name.`);idx++;let expr=WindowExpressionParser.parseFromLexeme(lexemes,idx);if(idx=expr.newIndex,windows.push(new WindowFrameClause(name,expr.value)),idx<lexemes.length&&lexemes[idx].type&16)idx++;else break}if(windows.length===0)throw new Error("At least one WINDOW clause is required after WINDOW keyword.");return{value:new WindowsClause(windows),newIndex:idx}}};var LimitClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The LIMIT clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="limit")throw new Error(`Syntax error at position ${idx}: Expected 'LIMIT' keyword but found "${lexemes[idx].value}". LIMIT clauses must start with the LIMIT keyword.`);let limitKeywordComments=lexemes[idx].positionedComments;if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'LIMIT' keyword. The LIMIT clause requires a numeric expression.");let limitItem=ValueParser.parseFromLexeme(lexemes,idx),afterKeywordComments=limitKeywordComments?.filter(comment=>comment.position==="after").flatMap(comment=>comment.comments)??[];return afterKeywordComments.length>0&&limitItem.value.addPositionedComments("before",afterKeywordComments),idx=limitItem.newIndex,{value:new LimitClause(limitItem.value),newIndex:idx}}};var ForClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The FOR clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value.toLowerCase()!=="for")throw new Error(`Syntax error at position ${idx}: Expected 'FOR' keyword but found "${lexemes[idx].value}". FOR clauses must start with the FOR keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FOR' keyword. The FOR clause requires a lock mode specification.");let lockModeValue=lexemes[idx].value,lockMode;switch(lockModeValue){case"update":lockMode="update",idx++;break;case"share":lockMode="share",idx++;break;case"key share":lockMode="key share",idx++;break;case"no key update":lockMode="no key update",idx++;break;default:throw new Error(`Syntax error at position ${idx}: Invalid lock mode "${lockModeValue}". Valid lock modes are: UPDATE, SHARE, KEY SHARE, NO KEY UPDATE.`)}return{value:new ForClause(lockMode),newIndex:idx}}};var ValuesQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The VALUES clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(idx>=lexemes.length)throw new Error(`Syntax error at position ${idx}: Expected 'VALUES' keyword but input ended early.`);let valuesLexeme=lexemes[idx];if(valuesLexeme.value.toLowerCase()!=="values")throw new Error(`Syntax error at position ${idx}: Expected 'VALUES' keyword but found "${valuesLexeme.value}". VALUES clauses must start with the VALUES keyword.`);let valuesComments=extractLexemeComments(valuesLexeme);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'VALUES' keyword. The VALUES clause requires at least one tuple expression.");let tuples=[],firstTuple=this.parseTuple(lexemes,idx);for(tuples.push(firstTuple.value),idx=firstTuple.newIndex,valuesComments.after.length>0&&firstTuple.value.addPositionedComments("before",valuesComments.after);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let tuple=this.parseTuple(lexemes,idx);tuples.push(tuple.value),idx=tuple.newIndex}let query=new ValuesQuery(tuples);return valuesComments.before.length>0&&(query.headerComments=valuesComments.before),{value:query,newIndex:idx}}static parseTuple(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].type!==4)throw new Error(`Syntax error at position ${idx}: Expected opening parenthesis but found "${idx<lexemes.length?lexemes[idx].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);let openingComments=extractLexemeComments(lexemes[idx]);idx++;let values=[];if(idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after opening parenthesis in tuple expression.");if(lexemes[idx].type&8){let tuple2=new TupleExpression([]),closingComments2=extractLexemeComments(lexemes[idx]);return idx++,openingComments.before.length>0&&tuple2.addPositionedComments("before",openingComments.before),closingComments2.after.length>0&&tuple2.addPositionedComments("after",closingComments2.after),{value:tuple2,newIndex:idx}}let firstValue=ValueParser.parseFromLexeme(lexemes,idx);for(values.push(firstValue.value),idx=firstValue.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after comma in tuple expression.");let value=ValueParser.parseFromLexeme(lexemes,idx);values.push(value.value),idx=value.newIndex}if(idx>=lexemes.length||lexemes[idx].type!==8)throw new Error(`Syntax error at position ${idx}: Expected closing parenthesis but found "${idx<lexemes.length?lexemes[idx].value:"end of input"}". Tuple expressions in VALUES clause must be enclosed in parentheses.`);let closingComments=extractLexemeComments(lexemes[idx]);idx++;let tuple=new TupleExpression(values);return openingComments.before.length>0&&tuple.addPositionedComments("before",openingComments.before),openingComments.after.length>0&&values.length>0&&values[0].addPositionedComments("before",openingComments.after),closingComments.before.length>0&&values.length>0&&values[values.length-1].addPositionedComments("after",closingComments.before),closingComments.after.length>0&&tuple.addPositionedComments("after",closingComments.after),{value:tuple,newIndex:idx}}};var ReturningClauseParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx]?.value!=="returning")throw new Error(`Syntax error at position ${idx}: Expected 'RETURNING' but found '${lexemes[idx]?.value}'.`);let returningLexeme=lexemes[idx],returningComments=extractLexemeComments(returningLexeme);idx++;let aliasResult=this.parseReturningAliases(lexemes,idx),aliases=aliasResult.aliases;idx=aliasResult.newIndex;let items=[],firstItemResult=SelectItemParser.parseItem(lexemes,idx);for(items.push(firstItemResult.value),idx=firstItemResult.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){let commaLexeme=lexemes[idx];idx++;let itemResult=SelectItemParser.parseItem(lexemes,idx);items.push(itemResult.value),idx=itemResult.newIndex}if(items.length===0){let position=lexemes[idx]?.position?.startPosition??idx;throw new Error(`[ReturningClauseParser] Expected a column or '*' after RETURNING at position ${position}.`)}let clause=new ReturningClause(items,aliases);return returningComments.before.length>0&&clause.addPositionedComments("before",returningComments.before),returningComments.after.length>0&&items.length>0&&items[0].addPositionedComments("before",returningComments.after),{value:clause,newIndex:idx}}static parseReturningAliases(lexemes,index){let idx=index,aliases=[];if(lexemes[idx]?.value!=="with")return{aliases,newIndex:idx};if(idx++,idx>=lexemes.length||!(lexemes[idx].type&4))throw new Error(`[ReturningClauseParser] Expected '(' after RETURNING WITH at position ${idx}.`);for(idx++;idx<lexemes.length;){let kind=lexemes[idx]?.value?.toLowerCase();if(kind!=="old"&&kind!=="new")throw new Error(`[ReturningClauseParser] Expected OLD or NEW in RETURNING WITH alias list at position ${idx}.`);if(idx++,lexemes[idx]?.value!=="as")throw new Error(`[ReturningClauseParser] Expected AS after ${kind.toUpperCase()} in RETURNING WITH alias list at position ${idx}.`);idx++;let aliasResult=FullNameParser.parseFromLexeme(lexemes,idx);if(aliasResult.namespaces&&aliasResult.namespaces.length>0)throw new Error(`[ReturningClauseParser] RETURNING WITH alias must be an unqualified identifier at position ${idx}.`);if(aliases.push(new ReturningAlias(kind,aliasResult.name)),idx=aliasResult.newIndex,idx<lexemes.length&&lexemes[idx].type&16){idx++;continue}if(idx<lexemes.length&&lexemes[idx].type&8)return idx++,{aliases,newIndex:idx};throw new Error(`[ReturningClauseParser] Expected ',' or ')' in RETURNING WITH alias list at position ${idx}.`)}throw new Error("[ReturningClauseParser] Missing closing ')' in RETURNING WITH alias list.")}};var SetClauseParser=class{static parseFromLexeme(lexemes,idx){if(lexemes[idx].value!=="set")throw new Error(`Syntax error at position ${idx}: Expected 'SET' but found '${lexemes[idx].value}'.`);let setLexeme=lexemes[idx],setKeywordComments=extractLexemeComments(setLexeme);idx++;let items=[],pendingBeforeForNext=[...setKeywordComments.after],mergeUnique=(target,source)=>{for(let comment of source)target.includes(comment)||target.push(comment)},addUniquePositionedComments=(component,position,comments)=>{if(comments.length===0)return;let existing=component.getPositionedComments(position),newOnes=comments.filter(comment=>!existing.includes(comment));newOnes.length>0&&component.addPositionedComments(position,newOnes)};for(;idx<lexemes.length;){let currentLexeme=lexemes[idx];if(!currentLexeme||currentLexeme.value==="where"||currentLexeme.value==="from"||currentLexeme.value==="returning"||!(currentLexeme.type&10816))break;let columnStartComments=extractLexemeComments(currentLexeme),columnParseResult=FullNameParser.parseFromLexeme(lexemes,idx);idx=columnParseResult.newIndex;let equalsLexeme=lexemes[idx];if(!equalsLexeme||!(equalsLexeme.type&2)||equalsLexeme.value!=="=")throw new Error(`Syntax error at position ${idx}: Expected '=' after column name in SET clause.`);let equalsComments=extractLexemeComments(equalsLexeme);idx++;let valueParseResult=ValueParser.parseFromLexeme(lexemes,idx);idx=valueParseResult.newIndex;let setItem=new SetClauseItem({namespaces:columnParseResult.namespaces,column:columnParseResult.name},valueParseResult.value),beforeComments=[];if(mergeUnique(beforeComments,pendingBeforeForNext),mergeUnique(beforeComments,columnStartComments.before),beforeComments.length>0&&addUniquePositionedComments(columnParseResult.name,"before",beforeComments),pendingBeforeForNext=[],columnStartComments.after.length>0){let afterComments=[];mergeUnique(afterComments,columnStartComments.after),addUniquePositionedComments(columnParseResult.name,"after",afterComments)}if(equalsComments.before.length>0){let equalsBefore=[];mergeUnique(equalsBefore,equalsComments.before),addUniquePositionedComments(columnParseResult.name,"after",equalsBefore)}if(equalsComments.after.length>0){let equalsAfter=[];mergeUnique(equalsAfter,equalsComments.after),addUniquePositionedComments(valueParseResult.value,"before",equalsAfter)}if(items.push(setItem),lexemes[idx]?.type===16){let commaLexeme=lexemes[idx],commaComments=extractLexemeComments(commaLexeme);if(idx++,commaComments.before.length>0){let commaBefore=[];mergeUnique(commaBefore,commaComments.before),addUniquePositionedComments(setItem,"after",commaBefore)}let nextBefore=[];mergeUnique(nextBefore,commaComments.after),pendingBeforeForNext=nextBefore;continue}break}if(pendingBeforeForNext.length>0&&items.length>0){let trailingComments=[];mergeUnique(trailingComments,pendingBeforeForNext),trailingComments.length>0&&addUniquePositionedComments(items[items.length-1],"after",trailingComments)}let setClause=new SetClause(items);return setKeywordComments.before.length>0&&setClause.addPositionedComments("before",setKeywordComments.before),{setClause,newIndex:idx}}};var InsertQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The INSERT query is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value==="with"){let result=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=result.value,idx=result.newIndex}if(!lexemes[idx]||lexemes[idx].value!=="insert into"){let found=lexemes[idx]?.value??"end of input";throw new Error(`Syntax error at position ${idx}: Expected 'INSERT INTO' but found '${found}'.`)}let insertKeywordLexeme=lexemes[idx],insertKeywordComments=extractLexemeComments(insertKeywordLexeme);idx++;let sourceResult=SourceExpressionParser.parseTableSourceFromLexemes(lexemes,idx),targetSource=sourceResult.value,targetDatasource=targetSource.datasource;idx=sourceResult.newIndex,insertKeywordComments.after.length>0&&targetDatasource.addPositionedComments("before",insertKeywordComments.after);let columnIdentifiers=null,trailingInsertComments=[];if(lexemes[idx]?.type===4){let openParenLexeme=lexemes[idx],parenComments=extractLexemeComments(openParenLexeme);idx++,parenComments.before.length>0&&targetDatasource.addPositionedComments("after",parenComments.before),columnIdentifiers=[];let pendingBeforeForNext=[...parenComments.after];for(;idx<lexemes.length&&lexemes[idx].type&64;){let columnLexeme=lexemes[idx],columnComments=extractLexemeComments(columnLexeme),column=new IdentifierString(columnLexeme.value),beforeComments=[];if(pendingBeforeForNext.length>0&&beforeComments.push(...pendingBeforeForNext),columnComments.before.length>0&&beforeComments.push(...columnComments.before),beforeComments.length>0&&column.addPositionedComments("before",beforeComments),columnComments.after.length>0&&column.addPositionedComments("after",columnComments.after),columnIdentifiers.push(column),pendingBeforeForNext=[],idx++,lexemes[idx]?.type===16){pendingBeforeForNext=[...extractLexemeComments(lexemes[idx]).after],idx++;continue}break}if(pendingBeforeForNext.length>0&&columnIdentifiers.length>0&&(columnIdentifiers[columnIdentifiers.length-1].addPositionedComments("after",pendingBeforeForNext),pendingBeforeForNext=[]),lexemes[idx]?.type!==8)throw new Error(`Syntax error at position ${idx}: Expected ')' after column list.`);let closeParenComments=extractLexemeComments(lexemes[idx]);idx++,closeParenComments.before.length>0&&columnIdentifiers.length>0&&columnIdentifiers[columnIdentifiers.length-1].addPositionedComments("after",closeParenComments.before),closeParenComments.after.length>0&&(trailingInsertComments=closeParenComments.after),columnIdentifiers.length===0&&(columnIdentifiers=[])}if(idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input while parsing INSERT statement. VALUES or SELECT clause expected.");let nextToken=lexemes[idx].value.toLowerCase(),dataQuery;if(nextToken==="values"){let valuesResult=ValuesQueryParser.parseFromLexeme(lexemes,idx);dataQuery=valuesResult.value,idx=valuesResult.newIndex}else{let selectResult=SelectQueryParser.parseFromLexeme(lexemes,idx);dataQuery=selectResult.value,idx=selectResult.newIndex}let onConflictClause=null;if(lexemes[idx]?.value==="on conflict"){let onConflictResult=this.parseOnConflictClause(lexemes,idx);onConflictClause=onConflictResult.value,idx=onConflictResult.newIndex}let returningClause=null;if(lexemes[idx]?.value==="returning"){let returningResult=ReturningClauseParser.parseFromLexeme(lexemes,idx);returningClause=returningResult.value,idx=returningResult.newIndex}if(onConflictClause?.action==="select"&&!returningClause)throw new Error("Syntax error: ON CONFLICT DO SELECT requires a RETURNING clause.");let insertClause=new InsertClause(targetSource,columnIdentifiers??null);return insertKeywordComments.before.length>0&&insertClause.addPositionedComments("before",insertKeywordComments.before),trailingInsertComments.length>0&&insertClause.addPositionedComments("after",trailingInsertComments),withClause&&SelectQueryWithClauseHelper.setWithClause(dataQuery,withClause),{value:new InsertQuery({insertClause,selectQuery:dataQuery,onConflict:onConflictClause,returning:returningClause}),newIndex:idx}}static parseOnConflictClause(lexemes,index){let idx=index;if(lexemes[idx]?.value!=="on conflict")throw new Error(`Syntax error at position ${idx}: Expected 'ON CONFLICT'.`);idx++;let target=null,targetKind=null;if(lexemes[idx]?.type===4){let targetStart=idx;idx=this.consumeBalancedParentheses(lexemes,idx),target=joinLexemeValues(lexemes,targetStart,idx),targetKind="columns"}else if(lexemes[idx]?.value==="on"&&lexemes[idx+1]?.value==="constraint"){if(idx+=2,idx>=lexemes.length||lexemes[idx].value==="do select"||lexemes[idx].value==="do update"||lexemes[idx].value==="do nothing")throw new Error(`Syntax error at position ${idx}: Expected constraint name after ON CONSTRAINT.`);let targetStart=idx;idx++,target=joinLexemeValues(lexemes,targetStart,idx),targetKind="constraint"}let actionToken=lexemes[idx]?.value;if(actionToken==="do nothing")return idx++,{value:new OnConflictClause({target,targetKind,action:"nothing"}),newIndex:idx};if(actionToken==="do update"){idx++;let setResult=SetClauseParser.parseFromLexeme(lexemes,idx);idx=setResult.newIndex;let whereClause2=null;if(lexemes[idx]?.value==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause2=whereResult.value,idx=whereResult.newIndex}return{value:new OnConflictClause({target,targetKind,action:"update",setClause:setResult.setClause,whereClause:whereClause2}),newIndex:idx}}if(actionToken!=="do select"){let found=lexemes[idx]?.value??"end of input";throw new Error(`Syntax error at position ${idx}: Expected 'DO SELECT', 'DO UPDATE', or 'DO NOTHING' after ON CONFLICT but found '${found}'.`)}idx++;let forClause=null;if(lexemes[idx]?.value==="for"){let forResult=ForClauseParser.parseFromLexeme(lexemes,idx);forClause=forResult.value,idx=forResult.newIndex}let whereClause=null;if(lexemes[idx]?.value==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}return{value:new OnConflictClause({target,targetKind,action:"select",forClause,whereClause}),newIndex:idx}}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++}throw new Error(`Syntax error at position ${index}: Expected ')' after ON CONFLICT target.`)}};var UpdateClauseParser=class{static parseFromLexeme(lexemes,index){let result=SourceExpressionParser.parseFromLexeme(lexemes,index);return{value:new UpdateClause(result.value),newIndex:result.newIndex}}};var UpdateQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The UPDATE query is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value?.toLowerCase()==="with"){let withResult=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=withResult.value,idx=withResult.newIndex}if(lexemes[idx].value!=="update")throw new Error(`Syntax error at position ${idx}: Expected 'UPDATE' but found '${lexemes[idx].value}'.`);let updateLexeme=lexemes[idx],updateKeywordComments=extractLexemeComments(updateLexeme);idx++;let updateClauseResult=UpdateClauseParser.parseFromLexeme(lexemes,idx),updateClause=updateClauseResult.value;idx=updateClauseResult.newIndex,updateKeywordComments.before.length>0&&updateClause.addPositionedComments("before",updateKeywordComments.before),updateKeywordComments.after.length>0&&updateClause.addPositionedComments("after",updateKeywordComments.after);let setClauseResult=SetClauseParser.parseFromLexeme(lexemes,idx),setClause=setClauseResult.setClause;idx=setClauseResult.newIndex;let from=null;if(lexemes[idx]?.value==="from"){let result=FromClauseParser.parseFromLexeme(lexemes,idx);from=result.value,idx=result.newIndex}let where=null;if(lexemes[idx]?.value==="where"){let result=WhereClauseParser.parseFromLexeme(lexemes,idx);where=result.value,idx=result.newIndex}let returning=null;if(lexemes[idx]?.value==="returning"){let result=ReturningClauseParser.parseFromLexeme(lexemes,idx);returning=result.value,idx=result.newIndex}return{value:new UpdateQuery({withClause,updateClause,setClause,whereClause:where,fromClause:from,returning}),newIndex:idx}}};var DeleteClauseParser=class{static parseFromLexeme(lexemes,index){if(index>=lexemes.length)throw new Error(`[DeleteClauseParser] Unexpected end of input at position ${index}: expected 'DELETE FROM'.`);let deleteToken=lexemes[index];if(deleteToken?.value?.toLowerCase()!=="delete from"){let position=lexemes[index]?.position?.startPosition??index;throw new Error(`[DeleteClauseParser] Syntax error at position ${position}: expected 'DELETE FROM' but found '${lexemes[index]?.value}'.`)}let deleteTokenComments=extractLexemeComments(deleteToken),targetResult=SourceExpressionParser.parseFromLexeme(lexemes,index+1),deleteClause=new DeleteClause(targetResult.value);return deleteTokenComments.before.length>0&&deleteClause.addPositionedComments("before",deleteTokenComments.before),deleteTokenComments.after.length>0&&deleteClause.addPositionedComments("after",deleteTokenComments.after),{value:deleteClause,newIndex:targetResult.newIndex}}};var UsingClauseParser=class{static parseFromLexeme(lexemes,index){if(lexemes[index].value!=="using")throw new Error(`Syntax error at position ${index}: Expected 'USING' but found '${lexemes[index].value}'.`);let idx=index+1,sources=[],firstSource=SourceExpressionParser.parseFromLexeme(lexemes,idx);for(sources.push(firstSource.value),idx=firstSource.newIndex;lexemes[idx]?.type===16;){idx++;let nextSource=SourceExpressionParser.parseFromLexeme(lexemes,idx);sources.push(nextSource.value),idx=nextSource.newIndex}return{value:new UsingClause(sources),newIndex:idx}}};var DeleteQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The DELETE query is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value==="with"){let withResult=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=withResult.value,idx=withResult.newIndex}let deleteClauseResult=DeleteClauseParser.parseFromLexeme(lexemes,idx),deleteClause=deleteClauseResult.value;idx=deleteClauseResult.newIndex;let usingClause=null;if(lexemes[idx]?.value==="using"){let usingResult=UsingClauseParser.parseFromLexeme(lexemes,idx);usingClause=usingResult.value,idx=usingResult.newIndex}let whereClause=null;if(lexemes[idx]?.value==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}let returningClause=null;if(lexemes[idx]?.value==="returning"){let returningResult=ReturningClauseParser.parseFromLexeme(lexemes,idx);returningClause=returningResult.value,idx=returningResult.newIndex}return{value:new DeleteQuery({withClause,deleteClause,usingClause,whereClause,returning:returningClause}),newIndex:idx}}};var MergeQueryParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexemes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The MERGE statement is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,withClause=null;if(lexemes[idx]?.value==="with"){let withResult=WithClauseParser.parseFromLexeme(lexemes,idx);withClause=withResult.value,idx=withResult.newIndex}let mergeKeywordLexeme=lexemes[idx],mergeKeywordComments=extractLexemeComments(mergeKeywordLexeme);if(mergeKeywordLexeme?.value!=="merge into"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'MERGE INTO' but found '${actual}'.`)}idx++;let targetResult=SourceExpressionParser.parseFromLexeme(lexemes,idx),target=targetResult.value;if(idx=targetResult.newIndex,this.addUniquePositionedComments(target.datasource,"before",mergeKeywordComments.after),lexemes[idx]?.value!=="using"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'USING' but found '${actual}'.`)}idx++;let sourceResult=SourceExpressionParser.parseFromLexeme(lexemes,idx),source=sourceResult.value;if(idx=sourceResult.newIndex,lexemes[idx]?.value!=="on"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'ON' but found '${actual}'.`)}idx++;let onConditionResult=ValueParser.parseFromLexeme(lexemes,idx),onCondition=onConditionResult.value;idx=onConditionResult.newIndex;let whenResult=this.parseWhenClauses(lexemes,idx);if(whenResult.clauses.length===0)throw new Error("[MergeQueryParser] MERGE statement must contain at least one WHEN clause.");let returningClause=null,nextIndex=whenResult.newIndex;if(lexemes[nextIndex]?.value==="returning"){let returningResult=ReturningClauseParser.parseFromLexeme(lexemes,nextIndex);returningClause=returningResult.value,nextIndex=returningResult.newIndex}let mergeQuery=new MergeQuery({withClause,target,source,onCondition,whenClauses:whenResult.clauses,returningClause});return this.addUniquePositionedComments(mergeQuery,"before",mergeKeywordComments.before),{value:mergeQuery,newIndex:nextIndex}}static parseWhenClauses(lexemes,index){let clauses=[],idx=index;for(;this.getLowerValue(lexemes[idx])==="when";){idx++;let{matchType,newIndex:matchIndex}=this.parseMatchType(lexemes,idx);idx=matchIndex;let additionalCondition=null;if(this.getLowerValue(lexemes[idx])==="and"){idx++;let conditionResult=ValueParser.parseFromLexeme(lexemes,idx);additionalCondition=conditionResult.value,idx=conditionResult.newIndex}let thenLexeme=lexemes[idx];if(this.getLowerValue(thenLexeme)!=="then"){let actual=thenLexeme?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'THEN' but found '${actual}'.`)}let thenComments=extractLexemeComments(thenLexeme),commentsBeforeThen=[],precedingLexeme=lexemes[idx-1];if(precedingLexeme){let precedingComments=extractLexemeComments(precedingLexeme);this.mergeUnique(commentsBeforeThen,precedingComments.after)}this.mergeUnique(commentsBeforeThen,thenComments.before),idx++;let actionResult=this.parseAction(lexemes,idx,thenComments.after??[]);idx=actionResult.newIndex;let whenClause=new MergeWhenClause(matchType,actionResult.action,additionalCondition);whenClause.addThenLeadingComments(commentsBeforeThen),clauses.push(whenClause)}return{clauses,newIndex:idx}}static parseMatchType(lexemes,index){let idx=index,value=this.getLowerValue(lexemes[idx]);if(value==="matched")return idx++,{matchType:"matched",newIndex:idx};if(value==="not matched")return idx++,{matchType:"not_matched",newIndex:idx};if(value==="not matched by source")return idx++,{matchType:"not_matched_by_source",newIndex:idx};if(value==="not matched by target")return idx++,{matchType:"not_matched_by_target",newIndex:idx};let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'MATCHED' or 'NOT MATCHED' but found '${actual}'.`)}static parseAction(lexemes,index,leadingComments=[]){let idx=index,token=lexemes[idx];if(!token)throw new Error("[MergeQueryParser] Unexpected end of input while parsing WHEN clause action.");let tokenValue=token.value.toLowerCase(),tokenComments=extractLexemeComments(token),actionLeadingComments=[];if(this.mergeUnique(actionLeadingComments,leadingComments),this.mergeUnique(actionLeadingComments,tokenComments.before),tokenValue==="update"||tokenValue==="update set"){let expectSetKeyword=tokenValue==="update";idx++;let pendingSetClauseComments=tokenComments.after,setResult=this.parseSetClause(lexemes,idx,expectSetKeyword,pendingSetClauseComments);idx=setResult.newIndex;let whereClause=null;if(lexemes[idx]?.value==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}let action=new MergeUpdateAction(setResult.setClause,whereClause);return this.addUniquePositionedComments(action,"before",actionLeadingComments),{action,newIndex:idx}}if(tokenValue==="delete"){idx++;let whereClause=null;if(this.getLowerValue(lexemes[idx])==="where"){let whereResult=WhereClauseParser.parseFromLexeme(lexemes,idx);whereClause=whereResult.value,idx=whereResult.newIndex}let action=new MergeDeleteAction(whereClause);return this.addUniquePositionedComments(action,"before",actionLeadingComments),this.addUniquePositionedComments(action,"after",tokenComments.after),{action,newIndex:idx}}if(tokenValue==="do nothing"){idx++;let action=new MergeDoNothingAction;return this.addUniquePositionedComments(action,"before",actionLeadingComments),this.addUniquePositionedComments(action,"after",tokenComments.after),{action,newIndex:idx}}if(tokenValue==="insert default values"){idx++;let columnResult=this.parseInsertColumnProjection(lexemes,idx,tokenComments.after);idx=columnResult.newIndex;let action=new MergeInsertAction({columns:columnResult.columns,defaultValues:!0});return this.addUniquePositionedComments(action,"before",actionLeadingComments),this.addUniquePositionedComments(action,"after",columnResult.trailingComments),{action,newIndex:idx}}if(tokenValue==="insert"){idx++;let insertResult=this.parseInsertAction(lexemes,idx,{pendingCommentsAfterInsert:tokenComments.after});return this.addUniquePositionedComments(insertResult.action,"before",actionLeadingComments),insertResult}let actual=token.value;throw new Error(`[MergeQueryParser] Unsupported action '${actual}'. Only UPDATE, DELETE, INSERT, and DO NOTHING are supported within MERGE WHEN clauses.`)}static parseSetClause(lexemes,index,expectSetKeyword,pendingCommentsAfterUpdate=[]){let idx=index,setKeywordComments=extractLexemeComments(lexemes[idx]);if(expectSetKeyword){if(this.getLowerValue(lexemes[idx])!=="set"){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected 'SET' but found '${actual}'.`)}idx++}else this.getLowerValue(lexemes[idx])==="set"?(setKeywordComments=extractLexemeComments(lexemes[idx]),idx++):setKeywordComments={before:[],after:[]};let items=[],pendingBeforeForNext=[];for(this.mergeUnique(pendingBeforeForNext,pendingCommentsAfterUpdate),this.mergeUnique(pendingBeforeForNext,setKeywordComments.after);idx<lexemes.length;){let currentLexeme=lexemes[idx];if(!currentLexeme||this.isSetClauseTerminator(currentLexeme)||!(currentLexeme.type&10816))break;let columnComments=extractLexemeComments(currentLexeme),{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,lexemes[idx]?.type!==2||lexemes[idx].value!=="="){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected '=' in SET clause but found '${actual}'.`)}let equalsLexeme=lexemes[idx],equalsComments=extractLexemeComments(equalsLexeme);idx++;let valueResult=ValueParser.parseFromLexeme(lexemes,idx);idx=valueResult.newIndex;let setItem=new SetClauseItem({namespaces,column:name},valueResult.value),beforeComments=[];if(this.mergeUnique(beforeComments,pendingBeforeForNext),this.mergeUnique(beforeComments,columnComments.before),this.addUniquePositionedComments(name,"before",beforeComments),pendingBeforeForNext=[],this.addUniquePositionedComments(name,"after",columnComments.after),this.addUniquePositionedComments(setItem,"after",equalsComments.before),this.addUniquePositionedComments(valueResult.value,"before",equalsComments.after),items.push(setItem),lexemes[idx]?.type===16){let commaLexeme=lexemes[idx],commaComments=extractLexemeComments(commaLexeme);idx++,this.addUniquePositionedComments(setItem,"after",commaComments.before),pendingBeforeForNext=[],this.mergeUnique(pendingBeforeForNext,commaComments.after);continue}break}if(pendingBeforeForNext.length>0&&items.length>0&&this.addUniquePositionedComments(items[items.length-1],"after",pendingBeforeForNext),items.length===0)throw new Error("[MergeQueryParser] SET clause must contain at least one column assignment.");let setClause=new SetClause(items);return this.addUniquePositionedComments(setClause,"before",setKeywordComments.before),{setClause,newIndex:idx}}static parseInsertAction(lexemes,index,options){let idx=index,pendingAfterInsert=options?.pendingCommentsAfterInsert??[],columnResult=this.parseInsertColumnProjection(lexemes,idx,pendingAfterInsert),columns=columnResult.columns;idx=columnResult.newIndex;let pendingBeforeValues=columnResult.trailingComments;if(this.getLowerValue(lexemes[idx])==="values"){let valuesLexeme=lexemes[idx],valuesComments=extractLexemeComments(valuesLexeme);idx++;let beforeValuesComments=[];this.mergeUnique(beforeValuesComments,pendingBeforeValues),this.mergeUnique(beforeValuesComments,valuesComments.before);let valuesResult=ValueParser.parseArgument(4,8,lexemes,idx);if(idx=valuesResult.newIndex,!(valuesResult.value instanceof ValueList))throw new Error("[MergeQueryParser] Unexpected VALUES payload. Expected a parenthesized value list.");let valueList=valuesResult.value,closingParenComments=extractLexemeComments(lexemes[idx-1]);this.addUniquePositionedComments(valueList,"after",closingParenComments.after),this.addUniquePositionedComments(valueList,"after",valuesComments.after);let action=new MergeInsertAction({columns,values:valueList});return action.addValuesLeadingComments(beforeValuesComments),{action,newIndex:idx}}let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Unsupported INSERT payload '${actual}'. Use VALUES (...) or DEFAULT VALUES.`)}static parseInsertColumnProjection(lexemes,index,pendingBeforeFirstColumn){let idx=index;if(lexemes[idx]?.type!==4)return{columns:null,newIndex:idx,trailingComments:[...pendingBeforeFirstColumn]};let openParenLexeme=lexemes[idx],parenComments=extractLexemeComments(openParenLexeme);idx++;let columns=[],pendingBeforeForNext=[];for(this.mergeUnique(pendingBeforeForNext,pendingBeforeFirstColumn),this.mergeUnique(pendingBeforeForNext,parenComments.before),this.mergeUnique(pendingBeforeForNext,parenComments.after);idx<lexemes.length&&lexemes[idx].type&64;){let columnLexeme=lexemes[idx],columnComments=extractLexemeComments(columnLexeme),column=new IdentifierString(columnLexeme.value),beforeComments=[];if(this.mergeUnique(beforeComments,pendingBeforeForNext),this.mergeUnique(beforeComments,columnComments.before),this.addUniquePositionedComments(column,"before",beforeComments),pendingBeforeForNext=[],this.addUniquePositionedComments(column,"after",columnComments.after),columns.push(column),idx++,lexemes[idx]?.type===16){let commaLexeme=lexemes[idx],commaComments=extractLexemeComments(commaLexeme);idx++,this.addUniquePositionedComments(column,"after",commaComments.before),pendingBeforeForNext=[],this.mergeUnique(pendingBeforeForNext,commaComments.after);continue}break}if(pendingBeforeForNext.length>0&&columns.length>0&&(this.addUniquePositionedComments(columns[columns.length-1],"after",pendingBeforeForNext),pendingBeforeForNext=[]),lexemes[idx]?.type!==8){let actual=lexemes[idx]?.value??"end of input";throw new Error(`[MergeQueryParser] Syntax error at position ${idx}: expected ')' after column list but found '${actual}'.`)}let closeParenLexeme=lexemes[idx],closeParenComments=extractLexemeComments(closeParenLexeme);idx++,closeParenComments.before.length>0&&columns.length>0&&this.addUniquePositionedComments(columns[columns.length-1],"after",closeParenComments.before);let trailingComments=[];return this.mergeUnique(trailingComments,closeParenComments.after),this.mergeUnique(trailingComments,pendingBeforeForNext),{columns:columns.length>0?columns:[],newIndex:idx,trailingComments}}static isSetClauseTerminator(lexeme){if(!lexeme)return!1;let value=this.getLowerValue(lexeme);return value?value==="where"||value==="from"||value==="returning"||value==="when":!1}static mergeUnique(target,source){if(!(!source||source.length===0))for(let comment of source)target.includes(comment)||target.push(comment)}static addUniquePositionedComments(component,position,comments){if(!component||!comments||comments.length===0)return;let existing=component.getPositionedComments(position),newOnes=comments.filter(comment=>!existing.includes(comment));newOnes.length>0&&component.addPositionedComments(position,newOnes)}static getLowerValue(lexeme){return lexeme&&typeof lexeme.value=="string"?lexeme.value.toLowerCase():null}};var CommonTableParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The CommonTable definition is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,aliasResult=SourceAliasExpressionParser.parseFromLexeme(lexemes,idx);idx=aliasResult.newIndex,this.collectPrecedingComments(lexemes,index,aliasResult),idx=this.parseAsKeyword(lexemes,idx);let{materialized,newIndex:materializedIndex}=this.parseMaterializedFlag(lexemes,idx);idx=materializedIndex;let{query,trailingComments,newIndex:queryIndex}=this.parseInnerQuery(lexemes,idx);return idx=queryIndex,{value:new CommonTable(query,aliasResult.value,materialized),newIndex:idx,trailingComments}}static collectPrecedingComments(lexemes,index,aliasResult){if(!aliasResult.value?.table)return;let cteTable=aliasResult.value.table;for(let i=index-1;i>=0;i--){let token=lexemes[i];if(token.value.toLowerCase()==="with"){this.collectWithTokenComments(token,cteTable);break}if(token.type&16||token.value.toLowerCase()==="recursive")break;this.collectTokenComments(token,cteTable)}}static collectWithTokenComments(token,cteTable){let hasPositionedComments=!1;if(token.positionedComments&&token.positionedComments.length>0)for(let posComment of token.positionedComments)posComment.position==="after"&&posComment.comments&&(this.addPositionedComment(cteTable,"before",posComment.comments),hasPositionedComments=!0);!hasPositionedComments&&token.comments&&token.comments.length>0&&this.addPositionedComment(cteTable,"before",token.comments)}static collectTokenComments(token,cteTable){token.comments&&token.comments.length>0&&this.addPositionedComment(cteTable,"before",token.comments),token.positionedComments&&token.positionedComments.length>0&&(cteTable.positionedComments||(cteTable.positionedComments=[]),cteTable.positionedComments.unshift(...token.positionedComments))}static addPositionedComment(cteTable,position,comments){cteTable.positionedComments||(cteTable.positionedComments=[]),cteTable.positionedComments.unshift({position,comments:[...comments]})}static parseAsKeyword(lexemes,index){if(index<lexemes.length&&lexemes[index].value!=="as")throw new Error(`Syntax error at position ${index}: Expected 'AS' keyword after CTE name but found "${lexemes[index].value}".`);return index+1}static parseMaterializedFlag(lexemes,index){if(index>=lexemes.length)return{materialized:null,newIndex:index};let currentValue=lexemes[index].value;return currentValue==="materialized"?{materialized:!0,newIndex:index+1}:currentValue==="not materialized"?{materialized:!1,newIndex:index+1}:{materialized:null,newIndex:index}}static parseInnerQuery(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type!==4)throw new Error(`Syntax error at position ${idx}: Expected '(' after CTE name but found "${lexemes[idx].value}".`);let cteQueryHeaderComments=this.extractComments(lexemes[idx]);idx++;let queryResult=this.parseCteQuery(lexemes,idx);if(idx=queryResult.newIndex,this.applyCteHeaderComments(queryResult.value,cteQueryHeaderComments),idx<lexemes.length&&lexemes[idx].type!==8)throw new Error(`Syntax error at position ${idx}: Expected ')' after CTE query but found "${lexemes[idx].value}".`);let closingParenComments=this.extractComments(lexemes[idx]);return idx++,{query:queryResult.value,trailingComments:closingParenComments.length>0?closingParenComments:null,newIndex:idx}}static parseCteQuery(lexemes,index){if(index>=lexemes.length)throw new Error(`Syntax error at position ${index}: Expected CTE query but found end of input.`);switch(lexemes[index].value.toLowerCase()){case"select":case"values":return SelectQueryParser.parseFromLexeme(lexemes,index);case"insert into":return InsertQueryParser.parseFromLexeme(lexemes,index);case"update":return UpdateQueryParser.parseFromLexeme(lexemes,index);case"delete from":return DeleteQueryParser.parseFromLexeme(lexemes,index);case"merge into":return MergeQueryParser.parseFromLexeme(lexemes,index);case"with":switch(this.getCommandAfterWith(lexemes,index)){case"insert into":return InsertQueryParser.parseFromLexeme(lexemes,index);case"update":return UpdateQueryParser.parseFromLexeme(lexemes,index);case"delete from":return DeleteQueryParser.parseFromLexeme(lexemes,index);case"merge into":return MergeQueryParser.parseFromLexeme(lexemes,index);default:return SelectQueryParser.parseFromLexeme(lexemes,index)}default:throw new Error(`Syntax error at position ${index}: Expected SELECT, INSERT, UPDATE, DELETE, MERGE, or WITH in CTE query but found "${lexemes[index].value}".`)}}static applyCteHeaderComments(query,headerComments){if(headerComments.length!==0){if(this.isSelectQuery(query)){query.headerComments?query.headerComments=[...headerComments,...query.headerComments]:query.headerComments=headerComments;return}if(query instanceof InsertQuery){(SelectQueryWithClauseHelper.getWithClause(query.selectQuery)??query.insertClause).addPositionedComments("before",headerComments);return}if(query instanceof UpdateQuery){(query.withClause??query.updateClause).addPositionedComments("before",headerComments);return}if(query instanceof DeleteQuery){(query.withClause??query.deleteClause).addPositionedComments("before",headerComments);return}query instanceof MergeQuery&&(query.withClause??query).addPositionedComments("before",headerComments)}}static isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}static getCommandAfterWith(lexemes,index){try{let withResult=WithClauseParser.parseFromLexeme(lexemes,index);return lexemes[withResult.newIndex]?.value.toLowerCase()??null}catch{return null}}static extractComments(lexeme){let comments=[];if(lexeme.positionedComments)for(let posComment of lexeme.positionedComments)posComment.comments&&comments.push(...posComment.comments);return lexeme.comments&&lexeme.comments.length>0&&comments.push(...lexeme.comments),comments}};var WithClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The WITH clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index,headerComments=this.extractWithTokenHeaderComments(lexemes,idx);idx=this.parseWithKeyword(lexemes,idx);let{recursive,newIndex:recursiveIndex}=this.parseRecursiveFlag(lexemes,idx);idx=recursiveIndex;let{tables,trailingComments,newIndex:ctesIndex}=this.parseAllCommonTables(lexemes,idx);idx=ctesIndex;let withClause=new WithClause(recursive,tables);return trailingComments.length>0&&(withClause.trailingComments=trailingComments),{value:withClause,newIndex:idx,headerComments}}static extractWithTokenHeaderComments(lexemes,index){if(index>=lexemes.length)return null;let withToken=lexemes[index],headerComments=null;if(withToken.positionedComments&&withToken.positionedComments.length>0)for(let posComment of withToken.positionedComments)posComment.position==="before"&&posComment.comments&&(headerComments||(headerComments=[]),headerComments.push(...posComment.comments));return!headerComments&&withToken.comments&&withToken.comments.length>0&&(headerComments=[...withToken.comments]),headerComments}static parseWithKeyword(lexemes,index){if(index<lexemes.length&&lexemes[index].value.toLowerCase()==="with")return index+1;throw new Error(`Syntax error at position ${index}: Expected WITH keyword.`)}static parseRecursiveFlag(lexemes,index){let recursive=index<lexemes.length&&lexemes[index].value.toLowerCase()==="recursive";return{recursive,newIndex:recursive?index+1:index}}static parseAllCommonTables(lexemes,index){let idx=index,tables=[],allTrailingComments=[],firstCte=CommonTableParser.parseFromLexeme(lexemes,idx);for(tables.push(firstCte.value),idx=firstCte.newIndex,firstCte.trailingComments&&allTrailingComments.push(...firstCte.trailingComments);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let cteResult=CommonTableParser.parseFromLexeme(lexemes,idx);tables.push(cteResult.value),idx=cteResult.newIndex,cteResult.trailingComments&&allTrailingComments.push(...cteResult.trailingComments)}return{tables,trailingComments:allTrailingComments,newIndex:idx}}};var FetchClauseParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="fetch")throw new Error(`Syntax error at position ${idx}: Expected 'FETCH' keyword but found "${lexemes[idx].value}".`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH' keyword.");let fetchExprResult=FetchExpressionParser.parseFromLexeme(lexemes,idx),fetchExpr=fetchExprResult.value;return idx=fetchExprResult.newIndex,{value:new FetchClause(fetchExpr),newIndex:idx}}},FetchExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index,type,typeToken=lexemes[idx].value;if(typeToken==="first")type="first";else if(typeToken==="next")type="next";else throw new Error(`Syntax error at position ${idx}: Expected 'FIRST' or 'NEXT' after 'FETCH' but found "${lexemes[idx].value}".`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT'.");let count=null,unit=null;if(lexemes[idx].value==="row only"||lexemes[idx].value==="rows only")return count=new LiteralValue(1),unit="rows only",idx++,{value:new FetchExpression(type,count,unit),newIndex:idx};let countResult=ValueParser.parseFromLexeme(lexemes,idx);if(count=countResult.value,idx=countResult.newIndex,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'FETCH FIRST|NEXT <count>'.");if(lexemes[idx].value==="rows only"?(unit="rows only",idx++):lexemes[idx].value==="percent"?(unit="percent",idx++):lexemes[idx].value==="percent with ties"&&(unit="percent with ties",idx++),!unit)throw new Error("Syntax error: Expected 'ROWS ONLY', 'PERCENT', or 'PERCENT WITH TIES' after 'FETCH FIRST|NEXT <count>'.");return{value:new FetchExpression(type,count,unit),newIndex:idx}}};var OffsetClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The OFFSET clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="offset")throw new Error(`Syntax error at position ${idx}: Expected 'OFFSET' keyword but found "${lexemes[idx].value}". OFFSET clauses must start with the OFFSET keyword.`);let offsetKeywordComments=lexemes[idx].positionedComments;if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'OFFSET' keyword. The OFFSET clause requires a numeric expression.");let offsetItem=ValueParser.parseFromLexeme(lexemes,idx),afterKeywordComments=offsetKeywordComments?.filter(comment=>comment.position==="after").flatMap(comment=>comment.comments)??[];return afterKeywordComments.length>0&&offsetItem.value.addPositionedComments("before",afterKeywordComments),idx=offsetItem.newIndex,idx<lexemes.length&&(lexemes[idx].value==="row"||lexemes[idx].value==="rows")&&idx++,{value:new OffsetClause(offsetItem.value),newIndex:idx}}};var LexemeCursor=class{static{this.SQL_COMMANDS=new Set(["select","from","where","and","or","order","by","group","having","limit","offset","as","on","inner","left","right","join","union","insert","update","delete","into","values","set"])}static findLexemeAtLineColumn(sql,position){let charOffset=this.lineColumnToCharOffset(sql,position);return charOffset===-1?null:this.findLexemeAtPosition(sql,charOffset)}static findLexemeAtPosition(sql,cursorPosition){if(cursorPosition<0||cursorPosition>=sql.length)return null;let lexemes=this.getAllLexemesWithPosition(sql);for(let lexeme of lexemes)if(lexeme.position&&cursorPosition>=lexeme.position.startPosition&&cursorPosition<lexeme.position.endPosition)return lexeme;return null}static getAllLexemesWithPosition(sql){if(!sql?.trim())return[];try{let lexemes=[],position=0;for(;position<sql.length&&(position=this.skipWhitespaceAndComments(sql,position),!(position>=sql.length));){let lexeme=this.parseNextToken(sql,position);lexeme?(lexemes.push(lexeme),position=lexeme.position.endPosition):position++}return lexemes}catch{return[]}}static skipWhitespaceAndComments(sql,position){return StringUtils.readWhiteSpaceAndComment(sql,position).position}static parseNextToken(sql,startPos){let char=sql[startPos];return char==="'"||char==='"'?this.parseStringLiteral(sql,startPos):/[=<>!+\-*/%().*]/.test(char)?this.parseOperator(sql,startPos):char===","?this.createLexeme(16,",",startPos,startPos+1):/[a-zA-Z0-9_]/.test(char)?this.parseWordToken(sql,startPos):null}static parseStringLiteral(sql,startPos){let quote=sql[startPos],position=startPos+1,token=quote;for(;position<sql.length&&sql[position]!==quote;)token+=sql[position++];return position<sql.length&&(token+=sql[position++]),this.createLexeme(1,token,startPos,position)}static parseOperator(sql,startPos){let token=sql[startPos],position=startPos+1;position<sql.length&&/[=<>!]/.test(sql[position])&&/[=<>!]/.test(token)&&(token+=sql[position++]);let tokenType=this.getOperatorTokenType(token);return this.createLexeme(tokenType,token,startPos,position)}static parseWordToken(sql,startPos){let position=startPos,token="";for(;position<sql.length&&/[a-zA-Z0-9_]/.test(sql[position]);)token+=sql[position++];let tokenType=this.getWordTokenType(token,sql,position),value=this.shouldLowercase(tokenType)?token.toLowerCase():token;return this.createLexeme(tokenType,value,startPos,position)}static getOperatorTokenType(token){switch(token){case"(":return 4;case")":return 8;case"*":return 64;default:return 2}}static getWordTokenType(token,sql,position){let lowerToken=token.toLowerCase();if(this.SQL_COMMANDS.has(lowerToken))return 128;let nextNonWhitespacePos=this.skipWhitespaceAndComments(sql,position);return nextNonWhitespacePos<sql.length&&sql[nextNonWhitespacePos]==="("?2048:64}static shouldLowercase(tokenType){return!!(tokenType&128)||!!(tokenType&2)||!!(tokenType&2048)}static createLexeme(type,value,startPos,endPos){return{type,value,comments:null,position:{startPosition:startPos,endPosition:endPos}}}static lineColumnToCharOffset(sql,position){if(position.line<1||position.column<1)return-1;let lines=sql.split(`
|
|
38
38
|
`);if(position.line>lines.length)return-1;let targetLine=lines[position.line-1];if(position.column>targetLine.length+1)return-1;let offset=0;for(let i=0;i<position.line-1;i++)offset+=lines[i].length+1;return offset+=position.column-1,offset}static charOffsetToLineColumn(sql,charOffset){if(charOffset<0||charOffset>sql.length)return null;let lines=sql.split(`
|
|
39
39
|
`),currentOffset=0;for(let lineIndex=0;lineIndex<lines.length;lineIndex++){let lineLength=lines[lineIndex].length;if(charOffset<currentOffset+lineLength)return{line:lineIndex+1,column:charOffset-currentOffset+1};if(charOffset===currentOffset+lineLength&&lineIndex<lines.length-1)return{line:lineIndex+2,column:1};currentOffset+=lineLength+1}if(charOffset===sql.length){let lastLine=lines[lines.length-1];return{line:lines.length,column:lastLine.length+1}}return null}};var CTERegionDetector=class{static analyzeCursorPosition(sql,cursorPosition){let cteRegions=this.extractCTERegions(sql),currentCTE=this.calculateExtendedCTEBoundaries(sql,cteRegions).find(region=>cursorPosition>=region.startPosition&&cursorPosition<region.extendedEndPosition);return currentCTE?{isInCTE:!0,cteRegion:{name:currentCTE.name,startPosition:currentCTE.startPosition,endPosition:currentCTE.endPosition,sqlContent:currentCTE.sqlContent},executableSQL:currentCTE.sqlContent}:{isInCTE:!1,cteRegion:null,executableSQL:this.extractMainQuery(sql,cteRegions)}}static getCursorCte(sql,cursorPosition){try{let analysis=this.analyzeCursorPosition(sql,cursorPosition);return analysis.isInCTE&&analysis.cteRegion?.name||null}catch{return null}}static getCursorCteAt(sql,line,column){try{let position=this.lineColumnToPosition(sql,line,column);return position===-1?null:this.getCursorCte(sql,position)}catch{return null}}static lineColumnToPosition(text,line,column){if(line<1||column<1)return-1;let lines=text.split(`
|
|
40
40
|
`);if(line>lines.length)return-1;let targetLine=lines[line-1];if(column>targetLine.length+1)return-1;let position=0;for(let i=0;i<line-1;i++)position+=lines[i].length+1;return position+=column-1,position}static positionToLineColumn(text,position){if(position<0||position>text.length)return null;let lines=text.substring(0,position).split(`
|