rawsql-ts 0.22.0 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.min.js +5 -5
- package/dist/esm/index.min.js.map +3 -3
- package/dist/esm/parsers/FullNameParser.js +5 -0
- package/dist/esm/parsers/FullNameParser.js.map +1 -1
- package/dist/esm/parsers/IdentifierDecorator.d.ts +5 -0
- package/dist/esm/parsers/IdentifierDecorator.js +80 -4
- package/dist/esm/parsers/IdentifierDecorator.js.map +1 -1
- package/dist/esm/parsers/SqlPrintTokenParser.d.ts +2 -0
- package/dist/esm/parsers/SqlPrintTokenParser.js +6 -5
- package/dist/esm/parsers/SqlPrintTokenParser.js.map +1 -1
- package/dist/esm/parsers/ValueParser.d.ts +1 -0
- package/dist/esm/parsers/ValueParser.js +12 -0
- package/dist/esm/parsers/ValueParser.js.map +1 -1
- package/dist/esm/tokenReaders/LiteralTokenReader.js +2 -5
- package/dist/esm/tokenReaders/LiteralTokenReader.js.map +1 -1
- package/dist/esm/transformers/FormatOptionResolver.d.ts +9 -5
- package/dist/esm/transformers/FormatOptionResolver.js +7 -3
- package/dist/esm/transformers/FormatOptionResolver.js.map +1 -1
- package/dist/esm/transformers/SqlFormatter.d.ts +3 -1
- package/dist/esm/transformers/SqlFormatter.js +4 -4
- package/dist/esm/transformers/SqlFormatter.js.map +1 -1
- package/dist/esm/utils/SqlSpecialValueKeywords.d.ts +2 -0
- package/dist/esm/utils/SqlSpecialValueKeywords.js +15 -0
- package/dist/esm/utils/SqlSpecialValueKeywords.js.map +1 -0
- package/dist/index.min.js +5 -5
- package/dist/index.min.js.map +3 -3
- package/dist/parsers/FullNameParser.js +5 -0
- package/dist/parsers/FullNameParser.js.map +1 -1
- package/dist/parsers/IdentifierDecorator.js +80 -4
- package/dist/parsers/IdentifierDecorator.js.map +1 -1
- package/dist/parsers/SqlPrintTokenParser.js +6 -5
- package/dist/parsers/SqlPrintTokenParser.js.map +1 -1
- package/dist/parsers/ValueParser.js +12 -0
- package/dist/parsers/ValueParser.js.map +1 -1
- package/dist/src/parsers/IdentifierDecorator.d.ts +5 -0
- package/dist/src/parsers/SqlPrintTokenParser.d.ts +2 -0
- package/dist/src/parsers/ValueParser.d.ts +1 -0
- package/dist/src/transformers/FormatOptionResolver.d.ts +9 -5
- package/dist/src/transformers/SqlFormatter.d.ts +3 -1
- package/dist/src/utils/SqlSpecialValueKeywords.d.ts +2 -0
- package/dist/tokenReaders/LiteralTokenReader.js +2 -5
- package/dist/tokenReaders/LiteralTokenReader.js.map +1 -1
- package/dist/transformers/FormatOptionResolver.js +7 -3
- package/dist/transformers/FormatOptionResolver.js.map +1 -1
- package/dist/transformers/SqlFormatter.js +6 -6
- package/dist/transformers/SqlFormatter.js.map +1 -1
- package/dist/tsconfig.browser.tsbuildinfo +1 -1
- package/dist/utils/SqlSpecialValueKeywords.js +18 -0
- package/dist/utils/SqlSpecialValueKeywords.js.map +1 -0
- package/package.json +1 -1
package/dist/index.min.js
CHANGED
|
@@ -3,14 +3,14 @@ ${caret}`}static skipWhiteSpace(input,position){let length=input.length;for(;pos
|
|
|
3
3
|
`),processedLines=[];for(let rawLine of rawLines){let trimmedLine=rawLine.trim(),isSeparatorLine=/^\s*[-=_+*#]+\s*$/.test(rawLine);trimmedLine!==""||isSeparatorLine?processedLines.push(isSeparatorLine?rawLine.trim():trimmedLine):processedLines.push("")}for(;processedLines.length>0&&processedLines[0]==="";)processedLines.shift();for(;processedLines.length>0&&processedLines[processedLines.length-1]==="";)processedLines.pop();return processedLines}static readWhiteSpaceAndComment(input,position){let lines=null,length=input.length;for(;position<length;){let oldPosition=position;if(position=_StringUtils.skipWhiteSpace(input,position),position!==oldPosition)continue;let charCode=input.charCodeAt(position);if(charCode===45&&position+1<length&&input.charCodeAt(position+1)===45){let commentStart=position+2;for(position=commentStart;position<length&&input.charCodeAt(position)!==10;)position++;let comment=input.slice(commentStart,position).trim();comment&&(lines===null&&(lines=[]),lines.push(comment));continue}if(charCode===47&&position+1<length&&input.charCodeAt(position+1)===42){if(position+2<length&&input.charCodeAt(position+2)===43)break;let contentStart=position+2;position=contentStart;let closed=!1;for(;position+1<length;){if(input.charCodeAt(position)===42&&input.charCodeAt(position+1)===47){let processedLines=this.processBlockCommentContent(input.slice(contentStart,position));position+=2,processedLines.length>0&&(lines===null&&(lines=[]),lines.push(...processedLines)),closed=!0;break}position++}if(!closed){let processedLines=this.processBlockCommentContent(input.slice(contentStart));processedLines.length>0&&(lines===null&&(lines=[]),lines.push(...processedLines)),position=length}continue}break}return{position,lines}}static readRegularIdentifier(input,position){let result=this.tryReadRegularIdentifier(input,position);if(!result)throw new Error(`Unexpected character. position: ${position}
|
|
4
4
|
${_StringUtils.getDebugPositionInfo(input,position)}`);return result}static tryReadRegularIdentifier(input,position){let start=position,length=input.length;for(;position<length&&!CharLookupTable.isDelimiterCode(input.charCodeAt(position));)position++;if(start===position)return null;for(;position+1<input.length&&input[position]==="["&&input[position+1]==="]";){let beforeIdentifier=input.slice(0,start).trim();if(beforeIdentifier===""||/[)]$/.test(beforeIdentifier)||/\b(select|from|where|and|or|set|values|insert|update|delete)\s*$/i.test(beforeIdentifier))break;position+=2}return{identifier:input.slice(start,position),newPosition:position}}};var BaseTokenReader=class{constructor(input,position=0){this.input=input,this.position=position}getPosition(){return this.position}setPosition(position){this.position=position}isEndOfInput(shift=0){return this.position+shift>=this.input.length}canRead(shift=0){return!this.isEndOfInput(shift)}read(expectChar){if(this.isEndOfInput())throw new Error(`Unexpected character. expect: ${expectChar}, actual: EndOfInput, position: ${this.position}`);let char=this.input[this.position];if(char!==expectChar)throw new Error(`Unexpected character. expect: ${expectChar}, actual: ${char}, position: ${this.position}`);return this.position++,char}createLexeme(type,value,comments=null,startPosition,endPosition){let lexeme={type,value:type===128||type===2||type===2048?value.toLowerCase():value,comments};return startPosition!==void 0&&endPosition!==void 0&&(lexeme.position={startPosition,endPosition}),lexeme}createLexemeWithPosition(type,value,startPos,comments=null){return this.createLexeme(type,value,comments,startPos,startPos+value.length)}getDebugPositionInfo(errPosition){return StringUtils.getDebugPositionInfo(this.input,errPosition)}};var KeywordParser=class{constructor(trie5){this.trie=trie5}isEndOfInput(input,position,shift=0){return position+shift>=input.length}canParse(input,position,shift=0){return!this.isEndOfInput(input,position,shift)}parse(input,position){if(this.isEndOfInput(input,position))return null;this.trie.reset();let result=StringUtils.tryReadRegularIdentifier(input,position);if(result===null)return null;let matchResult=this.trie.pushLexeme(result.identifier.toLowerCase());if(matchResult===0)return null;if(matchResult===3)return{keyword:result.identifier,newPosition:result.newPosition};let lexeme=result.identifier,commentResult=StringUtils.readWhiteSpaceAndComment(input,result.newPosition);position=commentResult.position;let collectedComments=commentResult.lines?[...commentResult.lines]:[];if(this.isEndOfInput(input,position))return matchResult===2?{keyword:lexeme,newPosition:position,comments:collectedComments.length>0?collectedComments:void 0}:null;for(;this.canParse(input,position);){let previousMatchResult=matchResult,result2=StringUtils.tryReadRegularIdentifier(input,position);if(result2!==null){if(matchResult=this.trie.pushLexeme(result2.identifier.toLowerCase()),matchResult===0){if(previousMatchResult===2)break;return null}lexeme+=" "+result2.identifier;let nextCommentResult=StringUtils.readWhiteSpaceAndComment(input,result2.newPosition);if(position=nextCommentResult.position,nextCommentResult.lines&&nextCommentResult.lines.length>0&&collectedComments.push(...nextCommentResult.lines),matchResult===3)break}else{if(previousMatchResult===2)break;return null}}return{keyword:lexeme,newPosition:position,comments:collectedComments.length>0?collectedComments:void 0}}};var KeywordTrie=class{constructor(keywords2){this.root=this.createNode();for(let i=0;i<keywords2.length;i++)this.addKeyword(keywords2[i]);this.currentNode=this.root}createNode(){return{children:new Map,isFinal:!1}}addKeyword(keyword){let node=this.root;for(let i=0;i<keyword.length;i++){let word=keyword[i],nextNode=node.children.get(word);nextNode||(nextNode=this.createNode(),node.children.set(word,nextNode)),node=nextNode}node.isFinal=!0}reset(){this.currentNode=this.root}pushLexeme(lexeme){let nextNode=this.currentNode.children.get(lexeme);return nextNode?(this.currentNode=nextNode,nextNode.isFinal?nextNode.children.size===0?3:2:1):0}};var joinTrie=new KeywordTrie([["join"],["inner","join"],["cross","join"],["left","join"],["left","outer","join"],["right","join"],["right","outer","join"],["full","join"],["full","outer","join"],["natural","join"],["natural","inner","join"],["natural","left","join"],["natural","left","outer","join"],["natural","right","join"],["natural","right","outer","join"],["natural","full","join"],["natural","full","outer","join"],["lateral","join"],["lateral","inner","join"],["lateral","left","join"],["lateral","left","outer","join"]]),keywordTrie=new KeywordTrie([["with"],["recursive"],["materialized"],["not","materialized"],["select"],["from"],["distinct"],["distinct","on"],["where"],["group","by"],["having"],["order","by"],["limit"],["offset"],["fetch"],["first"],["next"],["row"],["row","only"],["rows","only"],["percent"],["percent","with","ties"],["for"],["update"],["share"],["key","share"],["no","key","update"],["union"],["union","all"],["intersect"],["intersect","all"],["except"],["except","all"],["window"],["over"],["partition","by"],["range"],["rows"],["groups"],["within","group"],["with","ordinality"],["current","row"],["unbounded","preceding"],["unbounded","following"],["preceding"],["following"],["on"],["using"],["lateral"],["case"],["case","when"],["when"],["then"],["else"],["end"],["insert","into"],["update"],["delete","from"],["merge","into"],["matched"],["not","matched"],["not","matched","by","source"],["not","matched","by","target"],["update","set"],["if","not","exists"],["if","exists"],["do","nothing"],["insert","default","values"],["values"],["set"],["returning"],["analyze"],["create","table"],["create","temporary","table"],["create","temp","table"],["create","unlogged","table"],["create","schema"],["create","sequence"],["create","temporary","sequence"],["create","temp","sequence"],["alter","table"],["alter","sequence"],["drop","table"],["drop","schema"],["drop","index"],["drop","sequence"],["drop","constraint"],["comment","on","table"],["comment","on","column"],["create","index"],["create","unique","index"],["add"],["add","constraint"],["constraint"],["primary","key"],["unique"],["unique","key"],["foreign","key"],["references"],["check"],["default"],["not","null"],["null"],["generated","always"],["generated","always","as","identity"],["generated","by","default"],["generated","by","default","as","identity"],["identity"],["collate"],["deferrable"],["not","deferrable"],["initially","immediate"],["initially","deferred"],["match"],["match","full"],["match","partial"],["match","simple"],["not","valid"],["on","delete"],["on","update"],["cascade"],["restrict"],["no","action"],["set","null"],["set","default"],["include"],["only"],["concurrently"],["tablespace"],["tablesample"],["as"],["asc"],["desc"],["nulls","first"],["nulls","last"]]),keywordParser=new KeywordParser(keywordTrie),joinkeywordParser=new KeywordParser(joinTrie);function canStartJoinKeyword(input,position){let code=input.charCodeAt(position)|32;return code===106||code===105||code===99||code===108||code===114||code===102||code===110}var CommandTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;if(canStartJoinKeyword(this.input,this.position)){let keywordJoin=joinkeywordParser.parse(this.input,this.position);if(keywordJoin!==null)return this.position=keywordJoin.newPosition,this.createLexeme(128,keywordJoin.keyword)}let keyword=keywordParser.parse(this.input,this.position);if(keyword!==null){this.position=keyword.newPosition;let lexeme=this.createLexeme(128,keyword.keyword,keyword.comments);return keyword.comments&&keyword.comments.length>0&&(lexeme.positionedComments=[{position:"after",comments:keyword.comments}]),lexeme}if(this.canRead(2)&&this.input[this.position]==="/"&&this.input[this.position+1]==="*"&&this.input[this.position+2]==="+"){this.position+=3;let start=this.position;for(;this.position+1<this.input.length;){if(this.input[this.position]==="*"&&this.input[this.position+1]==="/")return this.position+=2,this.createLexeme(128,"/*+ "+this.input.slice(start,this.position-2).trim()+" */");this.position++}throw new Error(`Block comment is not closed. position: ${this.position}`)}return null}};var EscapedIdentifierTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(char==="`"){let identifier=this.readEscapedIdentifier("`");return this.createLexeme(64,identifier)}if(char==='"'){let identifier=this.readEscapedIdentifier('"');return this.createLexeme(64,identifier)}if(char==="["&&this.isSqlServerBracketIdentifier(previous)){let identifier=this.readEscapedIdentifier("]");return this.createLexeme(64,identifier)}return null}isSqlServerBracketIdentifier(previous){if(previous?.value==="array")return!1;let start=this.position+1,pos=start;for(;pos<this.input.length&&this.input[pos]!=="]";){let char=this.input[pos];if(char===":"||char===","||char==="+"||char==="-"||char==="*"||char==="/"||char==="("||char===")")return!1;pos++}if(pos>=this.input.length)return!1;let content=this.input.slice(start,pos).trim();return content===""?!1:/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$/.test(content)}readEscapedIdentifier(delimiter){let start=this.position;this.position++;let foundClosing=!1;for(;this.canRead();){if(this.input[this.position]===delimiter){foundClosing=!0;break}this.position++}if(!foundClosing)throw new Error(`Closing delimiter is not found. position: ${start}, delimiter: ${delimiter}
|
|
5
5
|
${this.getDebugPositionInfo(start)}`);if(start===this.position)throw new Error(`Closing delimiter is not found. position: ${start}, delimiter: ${delimiter}
|
|
6
|
-
${this.getDebugPositionInfo(start)}`);return this.position++,this.input.slice(start+1,this.position-1)}};var trie=new KeywordTrie([["grouping","sets"],["array"]]),keywordParser2=new KeywordParser(trie),FunctionTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let keyword=keywordParser2.parse(this.input,this.position);if(keyword!==null)return this.position=keyword.newPosition,this.createLexeme(2048,keyword.keyword);let result=StringUtils.tryReadRegularIdentifier(this.input,this.position);if(!result)return null;this.position=result.newPosition;var shift=StringUtils.readWhiteSpaceAndComment(this.input,this.position).position-this.position;return this.canRead(shift)&&this.input[this.position+shift]==="("?this.createLexeme(2048,result.identifier):null}};var IdentifierTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(char==="*")return this.position++,this.createLexeme(64,char);let result=StringUtils.readRegularIdentifier(this.input,this.position);return this.position=result.newPosition,this.createLexeme(64,result.identifier)}};function looksLikeSqlServerMoneyLiteral(input,position){let length=input.length;if(position<0||position+1>=length||input[position]!=="$"||!CharLookupTable.isDigit(input[position+1]))return!1;let pos=position+1;for(;pos<length&&CharLookupTable.isDigit(input[pos]);)pos++;if(pos<length&&input[pos]==="."&&pos+1<length&&CharLookupTable.isDigit(input[pos+1]))return!0;let sawThousandsGroup=!1;for(;pos<length&&input[pos]===",";){let groupStart=pos+1;if(groupStart>=length||!CharLookupTable.isDigit(input[groupStart]))break;let groupEnd=groupStart+3;for(let index=groupStart;index<groupEnd;index++)if(index>=length||!CharLookupTable.isDigit(input[index]))return!1;sawThousandsGroup=!0,pos=groupEnd}if(!sawThousandsGroup)return!1;if(pos<length&&input[pos]==="."){let decimalStart=pos+1;if(decimalStart>=length||!CharLookupTable.isDigit(input[decimalStart]))return!1;let decimalPos=decimalStart;for(;decimalPos<length&&CharLookupTable.isDigit(input[decimalPos]);)decimalPos++}return!0}var
|
|
6
|
+
${this.getDebugPositionInfo(start)}`);return this.position++,this.input.slice(start+1,this.position-1)}};var trie=new KeywordTrie([["grouping","sets"],["array"]]),keywordParser2=new KeywordParser(trie),FunctionTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let keyword=keywordParser2.parse(this.input,this.position);if(keyword!==null)return this.position=keyword.newPosition,this.createLexeme(2048,keyword.keyword);let result=StringUtils.tryReadRegularIdentifier(this.input,this.position);if(!result)return null;this.position=result.newPosition;var shift=StringUtils.readWhiteSpaceAndComment(this.input,this.position).position-this.position;return this.canRead(shift)&&this.input[this.position+shift]==="("?this.createLexeme(2048,result.identifier):null}};var IdentifierTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(char==="*")return this.position++,this.createLexeme(64,char);let result=StringUtils.readRegularIdentifier(this.input,this.position);return this.position=result.newPosition,this.createLexeme(64,result.identifier)}};function looksLikeSqlServerMoneyLiteral(input,position){let length=input.length;if(position<0||position+1>=length||input[position]!=="$"||!CharLookupTable.isDigit(input[position+1]))return!1;let pos=position+1;for(;pos<length&&CharLookupTable.isDigit(input[pos]);)pos++;if(pos<length&&input[pos]==="."&&pos+1<length&&CharLookupTable.isDigit(input[pos+1]))return!0;let sawThousandsGroup=!1;for(;pos<length&&input[pos]===",";){let groupStart=pos+1;if(groupStart>=length||!CharLookupTable.isDigit(input[groupStart]))break;let groupEnd=groupStart+3;for(let index=groupStart;index<groupEnd;index++)if(index>=length||!CharLookupTable.isDigit(input[index]))return!1;sawThousandsGroup=!0,pos=groupEnd}if(!sawThousandsGroup)return!1;if(pos<length&&input[pos]==="."){let decimalStart=pos+1;if(decimalStart>=length||!CharLookupTable.isDigit(input[decimalStart]))return!1;let decimalPos=decimalStart;for(;decimalPos<length&&CharLookupTable.isDigit(input[decimalPos]);)decimalPos++}return!0}var SQL_SPECIAL_VALUE_KEYWORDS=["current_catalog","current_date","current_role","current_schema","current_time","current_timestamp","current_user","localtime","localtimestamp","session_user","user"],SQL_SPECIAL_VALUE_KEYWORD_SET=new Set(SQL_SPECIAL_VALUE_KEYWORDS);var keywords=[["null"],["true"],["false"],...SQL_SPECIAL_VALUE_KEYWORDS.map(keyword=>[keyword]),["unbounded"],["normalized"],["nfc","normalized"],["nfd","normalized"],["nfkc","normalized"],["nfkd","normalized"],["nfc"],["nfd"],["nfkc"],["nfkd"]],trie2=new KeywordTrie(keywords),literalKeywordParser=new KeywordParser(trie2),LiteralTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(char==="'"){let value=this.readSingleQuotedString();return this.createLexeme(1,value)}let keyword=this.tryReadKeyword();if(keyword)return keyword;if(char==="."&&this.canRead(1)&&CharLookupTable.isDigit(this.input[this.position+1]))return this.createLexeme(1,this.readDigit());if(CharLookupTable.isDigit(char))return this.createLexeme(1,this.readDigit());if(char==="$"&&this.isDollarQuotedString())return this.createLexeme(1,this.readDollarQuotedString());if(char==="$"&&looksLikeSqlServerMoneyLiteral(this.input,this.position)){this.position++;let numberPart=this.readMoneyDigit();return this.createLexeme(1,"$"+numberPart)}if((char==="+"||char==="-")&&this.determineSignOrOperator(previous)==="sign"){let sign=char;this.position++;let pos=this.position;for(;this.canRead()&&CharLookupTable.isWhitespace(this.input[this.position]);)this.position++;if(this.canRead()&&(CharLookupTable.isDigit(this.input[this.position])||this.input[this.position]==="."&&this.canRead(1)&&CharLookupTable.isDigit(this.input[this.position+1])))return this.createLexeme(1,sign==="-"?sign+this.readDigit():this.readDigit());this.position=pos-1}return null}tryReadKeyword(){let result=literalKeywordParser.parse(this.input,this.position);return result?(this.position=result.newPosition,this.createLexeme(1,result.keyword)):null}determineSignOrOperator(previous){if(previous===null)return"sign";let operatorContextFlags=9545;return(previous.type&operatorContextFlags)!==0?"operator":"sign"}readDigit(){let start=this.position,hasDot=!1,hasExponent=!1;if(this.canRead(1)&&this.input[this.position]==="0"&&"xbo".includes(this.input[this.position+1].toLowerCase())){let prefixType=this.input[this.position+1].toLowerCase();this.position+=2;let isHex=prefixType==="x";for(;this.canRead();){let c=this.input[this.position];if(CharLookupTable.isDigit(c)||isHex&&CharLookupTable.isHexChar(c))this.position++;else break}return this.input.slice(start,this.position)}for(this.input[start]==="."&&(hasDot=!0,this.position++);this.canRead();){let char=this.input[this.position];if(char==="."&&!hasDot)hasDot=!0;else if((char==="e"||char==="E")&&!hasExponent)hasExponent=!0,this.canRead(1)&&(this.input[this.position+1]==="+"||this.input[this.position+1]==="-")&&this.position++;else if(!CharLookupTable.isDigit(char))break;this.position++}if(start===this.position)throw new Error(`Unexpected character. position: ${start}
|
|
7
7
|
${this.getDebugPositionInfo(start)}`);return this.input[start]==="."?"0"+this.input.slice(start,this.position):this.input.slice(start,this.position)}readMoneyDigit(){let start=this.position,hasDot=!1;for(;this.canRead();){let char=this.input[this.position];if(char==="."&&!hasDot)hasDot=!0;else if(!(char===","&&!hasDot)){if(!CharLookupTable.isDigit(char))break}this.position++}if(start===this.position)throw new Error(`Unexpected character. position: ${start}
|
|
8
8
|
${this.getDebugPositionInfo(start)}`);return this.input.slice(start,this.position)}readSingleQuotedString(){let start=this.position,closed=!1;for(this.read("'");this.canRead();){let char=this.input[this.position];if(this.position++,char==="\\"&&this.canRead(1)){this.position++;continue}else if(char==="'"){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 trie3=new KeywordTrie([["and"],["or"],["is"],["is","not"],["is","distinct","from"],["is","not","distinct","from"],["like"],["ilike"],["in"],["exists"],["between"],["not","like"],["not","ilike"],["not","in"],["not","exists"],["not","between"],["escape"],["uescape"],["similar","to"],["not","similar","to"],["similar"],["placing"],["rlike"],["regexp"],["mod"],["xor"],["not"],["both"],["leading"],["trailing"],["both","from"],["leading","from"],["trailing","from"],["year","from"],["month","from"],["day","from"],["hour","from"],["minute","from"],["second","from"],["dow","from"],["doy","from"],["isodow","from"],["quarter","from"],["week","from"],["epoch","from"],["at","time","zone"]]),operatorOrTypeTrie=new KeywordTrie([["date"],["time"],["timestamp"],["timestamptz"],["timetz"],["interval"],["boolean"],["integer"],["bigint"],["smallint"],["numeric"],["decimal"],["real"],["double","precision"],["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),keywordParser3=new KeywordParser(trie3),operatorOrTypeParser=new KeywordParser(operatorOrTypeTrie);var OperatorTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(CharLookupTable.isOperatorSymbol(char)){let start=this.position;for(;this.canRead()&&CharLookupTable.isOperatorSymbol(this.input[this.position])&&(this.position++,!!this.canRead());){let previous2=this.input[this.position-1],next=this.input[this.position];if(previous2==="-"&&next==="-"||previous2==="/"&&next==="*")break}this.position===start&&this.position++;let resut=this.input.slice(start,this.position);return this.createLexeme(2,resut)}let result=operatorOrTypeParser.parse(this.input,this.position);if(result!==null){this.position=result.newPosition;let lexeme=this.createLexeme(8258,result.keyword);return result.comments&&result.comments.length>0&&(lexeme.positionedComments=[...lexeme.positionedComments??[],{position:"after",comments:[...result.comments]}]),lexeme}return result=keywordParser3.parse(this.input,this.position),result!==null?(this.position=result.newPosition,this.createLexeme(2,result.keyword)):null}};var ParameterTokenReader=class extends BaseTokenReader{constructor(input){super(input)}tryRead(previous){if(this.isEndOfInput())return null;if(this.canRead(1)&&this.input[this.position]==="$"&&this.input[this.position+1]==="{"){this.position+=2;let start=this.position;for(;this.canRead()&&this.input[this.position]!=="}";)this.position++;if(this.isEndOfInput())throw new Error(`Unexpected end of input. Expected closing '}' for parameter at position ${start}`);let identifier=this.input.slice(start,this.position);if(identifier.length===0)throw new Error("Empty parameter name is not allowed: found ${} at position "+(start-2));return this.position++,this.createLexeme(256,"${"+identifier+"}")}let char=this.input[this.position];if(CharLookupTable.isNamedParameterPrefix(char)){if(this.canRead(1)&&CharLookupTable.isOperatorSymbol(this.input[this.position+1])||char===":"&&this.isInArraySliceContext()||char==="$"&&this.isDollarQuotedString()||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 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 FunctionTokenReader(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.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){super(),this.qualifiedName=new QualifiedName(namespaces,name),this.argument=argument,this.over=over,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}},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){super(),this.grouping=expression}},HavingClause=class extends SqlComponent{static{this.kind=Symbol("HavingClause")}constructor(condition){super(),this.condition=condition}},TableSource=class extends SqlComponent{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof IdentifierString?this.qualifiedName.name:new IdentifierString(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(namespaces,table){super();let tbl=typeof table=="string"?new IdentifierString(table):table;this.qualifiedName=new QualifiedName(namespaces,tbl)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(namespace=>namespace.name).join(".")+"."+(this.qualifiedName.name instanceof RawString?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof RawString?this.qualifiedName.name.value:this.qualifiedName.name.name}},FunctionSource=class extends SqlComponent{static{this.kind=Symbol("FunctionSource")}constructor(name,argument,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}},ReturningClause=class extends SqlComponent{static{this.kind=Symbol("ReturningClause")}constructor(items){super(),this.items=items}get columns(){return this.items.map(item=>item.value instanceof ColumnReference?item.value.column:new IdentifierString(item.identifier?.name??""))}},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&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.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){super(),this.qualifiedName=new QualifiedName(namespaces,name),this.argument=argument,this.over=over,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}},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){super(),this.grouping=expression}},HavingClause=class extends SqlComponent{static{this.kind=Symbol("HavingClause")}constructor(condition){super(),this.condition=condition}},TableSource=class extends SqlComponent{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof IdentifierString?this.qualifiedName.name:new IdentifierString(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(namespaces,table){super();let tbl=typeof table=="string"?new IdentifierString(table):table;this.qualifiedName=new QualifiedName(namespaces,tbl)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(namespace=>namespace.name).join(".")+"."+(this.qualifiedName.name instanceof RawString?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof RawString?this.qualifiedName.name.value:this.qualifiedName.name.name}},FunctionSource=class extends SqlComponent{static{this.kind=Symbol("FunctionSource")}constructor(name,argument,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}},ReturningClause=class extends SqlComponent{static{this.kind=Symbol("ReturningClause")}constructor(items){super(),this.items=items}get columns(){return this.items.map(item=>item.value instanceof ColumnReference?item.value.column:new IdentifierString(item.identifier?.name??""))}},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(`
|
|
11
11
|
`),message=`${messagePrefix} Unparsed lexeme remains at index ${index}: ${lexemes[index].value}
|
|
12
12
|
Context:
|
|
13
|
-
${context}`;return new _ParseError(message,index,context)}};function extractLexemeComments(lexeme){let before=[],after=[];if(!lexeme)return{before,after};if(lexeme.positionedComments&&lexeme.positionedComments.length>0)for(let positioned of lexeme.positionedComments)!positioned.comments||positioned.comments.length===0||(positioned.position==="before"?before.push(...positioned.comments):positioned.position==="after"&&after.push(...positioned.comments));else lexeme.comments&&lexeme.comments.length>0&&before.push(...lexeme.comments);return{before,after}}var FunctionExpressionParser=class{static{this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY=new Set(["string_agg","array_agg","json_agg","jsonb_agg","json_object_agg","jsonb_object_agg","xmlagg"])}static parseArrayExpression(lexemes,index){let idx=index;if(idx+1<lexemes.length&&lexemes[idx+1].type&512){idx++;let arg=ValueParser.parseArgument(512,1024,lexemes,idx);return idx=arg.newIndex,{value:new ArrayExpression(arg.value),newIndex:idx}}else if(idx+1<lexemes.length&&lexemes[idx+1].type&4){idx++,idx++;let arg=SelectQueryParser.parseFromLexeme(lexemes,idx);return idx=arg.newIndex,idx++,{value:new ArrayQueryExpression(arg.value),newIndex:idx}}throw new Error(`Invalid ARRAY syntax at index ${idx}, expected ARRAY[... or ARRAY(...)`)}static parseFromLexeme(lexemes,index){let idx=index,current=lexemes[idx];return current.value==="array"?this.parseArrayExpression(lexemes,idx):current.value==="substring"||current.value==="overlay"?this.parseKeywordFunction(lexemes,idx,[{key:"from",required:!1},{key:"for",required:!1}]):current.value==="cast"?this.parseKeywordFunction(lexemes,idx,[{key:"as",required:!0}]):current.value==="trim"?this.parseKeywordFunction(lexemes,idx,[{key:"from",required:!1}]):this.parseFunctionCall(lexemes,idx)}static tryParseBinaryExpression(lexemes,index,left,allowAndOperator=!0,allowOrOperator=!0){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&2){let operator=lexemes[idx].value.toLowerCase();if(!allowAndOperator&&operator==="and"||!allowOrOperator&&operator==="or")return null;if(idx++,operator==="between")return this.parseBetweenExpression(lexemes,idx,left,!1);if(operator==="not between")return this.parseBetweenExpression(lexemes,idx,left,!0);if(operator==="::"){let typeValue=this.parseTypeValue(lexemes,idx);return idx=typeValue.newIndex,{value:new CastExpression(left,typeValue.value),newIndex:idx}}let rightResult=ValueParser.parseFromLexeme(lexemes,idx);return idx=rightResult.newIndex,{value:new BinaryExpression(left,operator,rightResult.value),newIndex:idx}}return null}static parseBetweenExpression(lexemes,index,value,negated){let idx=index,lower=ValueParser.parseFromLexeme(lexemes,idx,!1);if(idx=lower.newIndex,idx<lexemes.length&&lexemes[idx].type&2&&lexemes[idx].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${idx}`);idx++;let upper=this.parseBetweenUpperBound(lexemes,idx);return idx=upper.newIndex,{value:new BetweenExpression(value,lower.value,upper.value,negated),newIndex:idx}}static parseBetweenUpperBound(lexemes,index){return ValueParser.parseFromLexeme(lexemes,index,!1,!1)}static parseFunctionCall(lexemes,index){let idx=index,fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx),namespaces=fullNameResult.namespaces,name=fullNameResult.name;if(idx=fullNameResult.newIndex,idx<lexemes.length&&lexemes[idx].type&4){let functionName=name.name.toLowerCase(),arg,closingComments=null,internalOrderBy=null;if(this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY.has(functionName)){let result=this.parseAggregateArguments(lexemes,idx);arg={value:result.arguments,newIndex:result.newIndex},internalOrderBy=result.orderByClause,closingComments=result.closingComments}else{let argWithComments=this.parseArgumentWithComments(lexemes,idx);arg={value:argWithComments.value,newIndex:argWithComments.newIndex},closingComments=argWithComments.closingComments}idx=arg.newIndex;let withinGroup=null;if(idx<lexemes.length&&lexemes[idx].value==="within group"){let withinGroupResult=this.parseWithinGroupClause(lexemes,idx);withinGroup=withinGroupResult.value,idx=withinGroupResult.newIndex}let 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;if(idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++),idx<lexemes.length&&lexemes[idx].value==="over"){let over=OverExpressionParser.parseFromLexeme(lexemes,idx);idx=over.newIndex;let value=new FunctionCall(namespaces,name.name,arg.value,over.value,withinGroup,withOrdinality,internalOrderBy,filterCondition);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);return closingComments&&closingComments.length>0&&value.addPositionedComments("after",closingComments),{value,newIndex:idx}}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Expected opening parenthesis after function name '${name.name}'.`)}static parseKeywordFunction(lexemes,index,keywords2){let idx=index,fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx),namespaces=fullNameResult.namespaces,name=fullNameResult.name;if(idx=fullNameResult.newIndex,idx<lexemes.length&&lexemes[idx].type&4){idx++;let input=ValueParser.parseFromLexeme(lexemes,idx),arg=input.value;if(idx=input.newIndex,idx<lexemes.length&&lexemes[idx].type&16)return this.parseFunctionCall(lexemes,index);for(let{key,required}of keywords2)if(idx<lexemes.length&&lexemes[idx].type&128&&lexemes[idx].value===key)if(idx++,idx<lexemes.length&&lexemes[idx].type&8192){let typeValue=this.parseTypeValue(lexemes,idx);arg=new BinaryExpression(arg,key,typeValue.value),idx=typeValue.newIndex}else{let right=ValueParser.parseFromLexeme(lexemes,idx);arg=new BinaryExpression(arg,key,right.value),idx=right.newIndex}else if(required)throw ParseError.fromUnparsedLexemes(lexemes,idx,`Keyword '${key}' is required for ${name.name} function.`);if(idx<lexemes.length&&lexemes[idx].type&8){idx++;let withinGroup=null;if(idx<lexemes.length&&lexemes[idx].value==="within group"){let withinGroupResult=this.parseWithinGroupClause(lexemes,idx);withinGroup=withinGroupResult.value,idx=withinGroupResult.newIndex}let withOrdinality=!1;if(idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++),idx<lexemes.length&&lexemes[idx].value==="over"){idx++;let over=OverExpressionParser.parseFromLexeme(lexemes,idx);return idx=over.newIndex,{value:new FunctionCall(namespaces,name.name,arg,over.value,withinGroup,withOrdinality,null),newIndex:idx}}else return{value:new FunctionCall(namespaces,name.name,arg,null,withinGroup,withOrdinality,null),newIndex:idx}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Missing closing parenthesis for function '${name.name}'.`)}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Missing opening parenthesis for function '${name.name}'.`)}static parseTypeValue(lexemes,index){let idx=index,{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,idx<lexemes.length&&lexemes[idx].type&4){let arg=ValueParser.parseArgument(4,8,lexemes,idx);idx=arg.newIndex;let value=new TypeValue(namespaces,new RawString(name.name),arg.value);return arg.value.positionedComments&&(value.positionedComments=arg.value.positionedComments),arg.value.comments,{value,newIndex:idx}}else return{value:new TypeValue(namespaces,new RawString(name.name)),newIndex:idx}}static parseWithinGroupClause(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].value!=="within group")throw new Error(`Expected 'WITHIN GROUP' at index ${idx}`);if(idx++,idx>=lexemes.length||!(lexemes[idx].type&4))throw new Error(`Expected '(' after 'WITHIN GROUP' at index ${idx}`);idx++;let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);if(idx=orderByResult.newIndex,idx>=lexemes.length||!(lexemes[idx].type&8))throw new Error(`Expected ')' after WITHIN GROUP ORDER BY clause at index ${idx}`);return idx++,{value:orderByResult.value,newIndex:idx}}static 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,"*":30,"/":30,"%":30,"^":40,"::":50,"unary+":100,"unary-":100,not:100}}static getPrecedence(operator){let precedence=this.precedenceMap[operator.toLowerCase()];return precedence!==void 0?precedence:0}static hasHigherOrEqualPrecedence(operator1,operator2){return this.getPrecedence(operator1)>=this.getPrecedence(operator2)}static isLogicalOperator(operator){let op=operator.toLowerCase();return op==="and"||op==="or"}static isBetweenOperator(operator){let op=operator.toLowerCase();return op==="between"||op==="not between"}static isComparisonOperator(operator){let lowerOp=operator.toLowerCase();return["=","!=","<>","<",">","<=",">=","like","ilike","similar to","in","not in","->","->>","#>","#>>","@>","<@","?","?|","?&","~","~*","!~","!~*","rlike","regexp"].includes(lowerOp)}};var ValueParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw ParseError.fromUnparsedLexemes(lexemes,result.newIndex,"[ValueParser]");return result.value}static parseFromLexeme(lexemes,index,allowAndOperator=!0,allowOrOperator=!0){return this.parseExpressionWithPrecedence(lexemes,index,0,allowAndOperator,allowOrOperator)}static parseExpressionWithPrecedence(lexemes,index,minPrecedence,allowAndOperator=!0,allowOrOperator=!0){let idx=index,comment=lexemes[idx].comments,positionedComments=lexemes[idx].positionedComments,left=this.parseItem(lexemes,idx);positionedComments&&positionedComments.length>0&&!left.value.positionedComments?left.value.positionedComments=positionedComments:left.value.comments===null&&comment&&comment.length>0&&(left.value.comments=comment),idx=left.newIndex;let result=left.value,arrayAccessResult=this.parseArrayAccess(lexemes,idx,result);for(result=arrayAccessResult.value,idx=arrayAccessResult.newIndex;idx<lexemes.length&&lexemes[idx].type&2;){let operatorToken=lexemes[idx],operator=operatorToken.value;if(!allowAndOperator&&operator.toLowerCase()==="and"||!allowOrOperator&&operator.toLowerCase()==="or")break;let precedence=OperatorPrecedence.getPrecedence(operator);if(precedence<minPrecedence)break;if(idx++,OperatorPrecedence.isBetweenOperator(operator)){let betweenResult=FunctionExpressionParser.parseBetweenExpression(lexemes,idx,result,operator.toLowerCase().includes("not"));result=betweenResult.value,idx=betweenResult.newIndex;continue}if(operator==="::"){let typeValue=FunctionExpressionParser.parseTypeValue(lexemes,idx);result=new CastExpression(result,typeValue.value),idx=typeValue.newIndex;continue}let nextMinPrecedence=precedence+1,rightResult=this.parseExpressionWithPrecedence(lexemes,idx,nextMinPrecedence,allowAndOperator,allowOrOperator);idx=rightResult.newIndex;let binaryExpr=new BinaryExpression(result,operator,rightResult.value);operatorToken.comments&&operatorToken.comments.length>0&&(binaryExpr.operator.comments=operatorToken.comments),operatorToken.positionedComments&&operatorToken.positionedComments.length>0&&(binaryExpr.operator.positionedComments=operatorToken.positionedComments),result=binaryExpr}return{value:result,newIndex:idx}}static transferPositionedComments(lexeme,value){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){let result=LiteralParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&4){let result=ParenExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&2048){let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&2){let result=UnaryExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&256){let result=ParameterExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&4096){let result=StringSpecifierExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&128){let result=CommandExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&512){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx),value=new ColumnReference(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}else if(current.type&8192){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(newIndex<lexemes.length&&lexemes[newIndex].type&4)if(this.isTypeConstructor(lexemes,newIndex,name.name)){let result=FunctionExpressionParser.parseTypeValue(lexemes,idx);return this.transferPositionedComments(current,result.value),{value:result.value,newIndex:result.newIndex}}else{let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else{let value=new TypeValue(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}}throw ParseError.fromUnparsedLexemes(lexemes,idx,"[ValueParser] Invalid lexeme.")}static parseArgument(openToken,closeToken,lexemes,index){let idx=index,args=[];if(idx<lexemes.length&&lexemes[idx].type===openToken){let openParenToken=lexemes[idx];if(idx++,idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,{value:new ValueList([]),newIndex:idx};if(idx<lexemes.length&&lexemes[idx].value==="*"){let wildcard=new ColumnReference(null,"*");if(openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let beforeComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");beforeComments.length>0&&(wildcard.positionedComments=beforeComments.map(pc=>({position:"before",comments:pc.comments})))}else openParenToken.comments&&openParenToken.comments.length>0&&(wildcard.comments=openParenToken.comments);if(idx++,idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,{value:wildcard,newIndex:idx};throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis after wildcard '*'.")}let result=this.parseFromLexeme(lexemes,idx);if(idx=result.newIndex,openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let afterComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){let beforeComments=afterComments.map(pc=>({position:"before",comments:pc.comments}));result.value.positionedComments?result.value.positionedComments=[...beforeComments,...result.value.positionedComments]:result.value.positionedComments=beforeComments}}else openParenToken.comments&&openParenToken.comments.length>0&&(result.value.comments?result.value.comments=openParenToken.comments.concat(result.value.comments):result.value.comments=openParenToken.comments);for(args.push(result.value);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let argResult=this.parseFromLexeme(lexemes,idx);idx=argResult.newIndex,args.push(argResult.value)}if(idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,args.length===1?{value:args[0],newIndex:idx}:{value:new ValueList(args),newIndex:idx};throw ParseError.fromUnparsedLexemes(lexemes,idx,"Missing closing parenthesis.")}throw ParseError.fromUnparsedLexemes(lexemes,index,"Expected opening parenthesis.")}static parseArrayAccess(lexemes,index,baseExpression){let idx=index,result=baseExpression;for(;idx<lexemes.length&&lexemes[idx].type&512&&!this.isSqlServerBracketIdentifier(lexemes,idx);){if(idx++,idx>=lexemes.length)throw new Error(`Expected array index or slice after '[' at index ${idx-1}`);if(lexemes[idx].type&1024)throw new Error(`Empty array access brackets not supported at index ${idx}`);let startExpr=null,isSlice=!1;if(lexemes[idx].type&2&&lexemes[idx].value===":")isSlice=!0,idx++;else{let colonPrecedence=OperatorPrecedence.getPrecedence(":"),firstResult=this.parseExpressionWithPrecedence(lexemes,idx,colonPrecedence+1);startExpr=firstResult.value,idx=firstResult.newIndex,idx<lexemes.length&&lexemes[idx].type&2&&lexemes[idx].value===":"&&(isSlice=!0,idx++)}if(isSlice){let endExpr=null;if(idx<lexemes.length&&!(lexemes[idx].type&1024)){let colonPrecedence=OperatorPrecedence.getPrecedence(":"),endResult=this.parseExpressionWithPrecedence(lexemes,idx,colonPrecedence+1);endExpr=endResult.value,idx=endResult.newIndex}if(idx>=lexemes.length||!(lexemes[idx].type&1024))throw new Error(`Expected ']' after array slice at index ${idx}`);idx++,result=new ArraySliceExpression(result,startExpr,endExpr)}else{if(!startExpr){let indexResult=this.parseFromLexeme(lexemes,idx);startExpr=indexResult.value,idx=indexResult.newIndex}if(idx>=lexemes.length||!(lexemes[idx].type&1024))throw new Error(`Expected ']' after array index at index ${idx}`);idx++,result=new ArrayIndexExpression(result,startExpr)}}return{value:result,newIndex:idx}}static isSqlServerBracketIdentifier(lexemes,bracketIndex){let idx=bracketIndex+1;if(idx>=lexemes.length)return!1;for(;idx<lexemes.length&&!(lexemes[idx].type&1024);){let token=lexemes[idx];if(token.type&64||token.type&2&&token.value==="."){idx++;continue}return!1}if(idx>=lexemes.length)return!1;let closingBracketIndex=idx;if(closingBracketIndex+1<lexemes.length){let nextToken=lexemes[closingBracketIndex+1];if(nextToken.type&2&&nextToken.value===".")return!0}idx=bracketIndex+1;let hasOnlyIdentifiersAndDots=!0;for(;idx<closingBracketIndex;){let token=lexemes[idx];if(!(token.type&64||token.type&2&&token.value===".")){hasOnlyIdentifiersAndDots=!1;break}idx++}return hasOnlyIdentifiersAndDots}static isTypeConstructor(lexemes,openParenIndex,typeName){let alwaysTypeConstructors=["NUMERIC","DECIMAL","VARCHAR","CHAR","CHARACTER","TIMESTAMP","TIME","INTERVAL"],upperTypeName=typeName.toUpperCase();if(alwaysTypeConstructors.includes(upperTypeName))return!0;if(upperTypeName==="DATE"){let firstArgIndex=openParenIndex+1;if(firstArgIndex<lexemes.length){let firstArg=lexemes[firstArgIndex];return!(firstArg.type&1&&typeof firstArg.value=="string"&&isNaN(Number(firstArg.value)))}}return!1}};var 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(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)}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(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)}visitHavingClause(clause){let newCondition=this.visit(clause.condition);return new HavingClause(newCondition)}visitOrderByClause(clause){let newOrder=clause.order.map(item=>this.visit(item));return new OrderByClause(newOrder)}visitWindowFrameClause(clause){let newExpression=this.visit(clause.expression);return new WindowFrameClause(clause.name.name,newExpression)}visitLimitClause(clause){let newLimit=this.visit(clause.value);return new LimitClause(newLimit)}visitForClause(clause){return new ForClause(clause.lockMode)}visitParenExpression(expr){let newExpression=this.visit(expr.expression);return new ParenExpression(newExpression)}visitBinaryExpression(expr){let newLeft=this.visit(expr.left),newRight=this.visit(expr.right);return new BinaryExpression(newLeft,expr.operator.value,newRight)}visitUnaryExpression(expr){let newExpression=this.visit(expr.expression);return new UnaryExpression(expr.operator.value,newExpression)}visitCaseExpression(expr){let newCondition=expr.condition?this.visit(expr.condition):null,newSwitchCase=this.visit(expr.switchCase);return new CaseExpression(newCondition,newSwitchCase)}visitSwitchCaseArgument(switchCase){let newCases=switchCase.cases.map(caseItem=>this.visit(caseItem)),newElseValue=switchCase.elseValue?this.visit(switchCase.elseValue):null;return new SwitchCaseArgument(newCases,newElseValue)}visitCaseKeyValuePair(pair){let newKey=this.visit(pair.key),newValue=this.visit(pair.value);return new CaseKeyValuePair(newKey,newValue)}visitBetweenExpression(expr){let newExpression=this.visit(expr.expression),newLower=this.visit(expr.lower),newUpper=this.visit(expr.upper);return new BetweenExpression(newExpression,newLower,newUpper,expr.negated)}visitFunctionCall(func){let newArgument=func.argument?this.visit(func.argument):null,newOver=func.over?this.visit(func.over):null;return new FunctionCall(func.namespaces,func.name,newArgument,newOver)}visitArrayExpression(expr){let newExpression=this.visit(expr.expression);return new ArrayExpression(newExpression)}visitArrayQueryExpression(expr){let newQuery=this.visit(expr.query);return new ArrayQueryExpression(newQuery)}visitTupleExpression(expr){let newValues=expr.values.map(value=>this.visit(value));return new TupleExpression(newValues)}visitCastExpression(expr){let newInput=this.visit(expr.input),newCastType=this.visit(expr.castType);return new CastExpression(newInput,newCastType)}visitTypeValue(typeValue){let newArgument=typeValue.argument?this.visit(typeValue.argument):null;return new TypeValue(typeValue.namespaces,typeValue.name,newArgument)}visitSelectItem(item){let newValue=this.visit(item.value);return new SelectItem(newValue,item.identifier?.name)}visitIdentifierString(ident){return ident}visitRawString(raw){return raw}visitColumnReference(column){return column}visitSourceExpression(source){let newSource=this.visit(source.datasource),newAlias=source.aliasExpression;return new SourceExpression(newSource,newAlias)}visitTableSource(source){return source}visitParenSource(source){let newSource=this.visit(source.source);return new ParenSource(newSource)}visitParameterExpression(param){return param}visitWindowFrameExpression(expr){let newPartition=expr.partition?this.visit(expr.partition):null,newOrder=expr.order?this.visit(expr.order):null,newFrameSpec=expr.frameSpec?this.visit(expr.frameSpec):null;return new WindowFrameExpression(newPartition,newOrder,newFrameSpec)}visitWindowFrameSpec(spec){return spec}visitLiteralValue(value){return value}visitOrderByItem(item){let newValue=this.visit(item.value);return new OrderByItem(newValue,item.sortDirection,item.nullsPosition)}visitValueList(valueList){let newValues=valueList.values.map(value=>this.visit(value));return new ValueList(newValues)}visitArraySliceExpression(expr){return expr}visitArrayIndexExpression(expr){return expr}visitStringSpecifierExpression(expr){return expr}visitPartitionByClause(clause){let newValue=this.visit(clause.value);return new PartitionByClause(newValue)}};var TableSourceCollector=class{constructor(selectableOnly=!0,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(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)}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??'"'}decorate(text){return text=this.start+text+this.end,text}};var ParameterDecorator=class{constructor(options){this.prefix=options?.prefix??":",this.suffix=options?.suffix??"",this.style=options?.style??"named"}decorate(text,index){let paramText="";return this.style==="anonymous"?paramText=this.prefix:this.style==="indexed"?paramText=this.prefix+index:this.style==="named"&&(paramText=this.prefix+text+this.suffix),text=paramText,text}};var 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??'"'}),this.castStyle=options?.castStyle??"standard",this.constraintStyle=options?.constraintStyle??"postgres",this.normalizeJoinConditionOrder=options?.joinConditionOrderByDeclaration??!1,this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(QualifiedName.kind,expr=>this.visitQualifiedName(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(WindowFrameBoundStatic.kind,expr=>this.visitWindowFrameBoundStatic(expr)),this.handlers.set(WindowFrameBoundaryValue.kind,expr=>this.visitWindowFrameBoundaryValue(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(Distinct.kind,expr=>this.visitDistinct(expr)),this.handlers.set(DistinctOn.kind,expr=>this.visitDistinctOn(expr)),this.handlers.set(HintClause.kind,expr=>this.visitHintClause(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(SourceAliasExpression.kind,expr=>this.visitSourceAliasExpression(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(WindowsClause.kind,expr=>this.visitWindowClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.visitOffsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(FetchExpression.kind,expr=>this.visitFetchExpression(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleQuery(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(InsertClause.kind,expr=>this.visitInsertClause(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(UpdateClause.kind,expr=>this.visitUpdateClause(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(DeleteClause.kind,expr=>this.visitDeleteClause(expr)),this.handlers.set(UsingClause.kind,expr=>this.visitUsingClause(expr)),this.handlers.set(SetClause.kind,expr=>this.visitSetClause(expr)),this.handlers.set(SetClauseItem.kind,expr=>this.visitSetClauseItem(expr)),this.handlers.set(ReturningClause.kind,expr=>this.visitReturningClause(expr)),this.handlers.set(CreateTableQuery.kind,expr=>this.visitCreateTableQuery(expr)),this.handlers.set(TableColumnDefinition.kind,expr=>this.visitTableColumnDefinition(expr)),this.handlers.set(ColumnConstraintDefinition.kind,expr=>this.visitColumnConstraintDefinition(expr)),this.handlers.set(TableConstraintDefinition.kind,expr=>this.visitTableConstraintDefinition(expr)),this.handlers.set(ReferenceDefinition.kind,expr=>this.visitReferenceDefinition(expr)),this.handlers.set(CreateIndexStatement.kind,expr=>this.visitCreateIndexStatement(expr)),this.handlers.set(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"))),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 FunctionExpressionParser=class{static{this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY=new Set(["string_agg","array_agg","json_agg","jsonb_agg","json_object_agg","jsonb_object_agg","xmlagg"])}static parseArrayExpression(lexemes,index){let idx=index;if(idx+1<lexemes.length&&lexemes[idx+1].type&512){idx++;let arg=ValueParser.parseArgument(512,1024,lexemes,idx);return idx=arg.newIndex,{value:new ArrayExpression(arg.value),newIndex:idx}}else if(idx+1<lexemes.length&&lexemes[idx+1].type&4){idx++,idx++;let arg=SelectQueryParser.parseFromLexeme(lexemes,idx);return idx=arg.newIndex,idx++,{value:new ArrayQueryExpression(arg.value),newIndex:idx}}throw new Error(`Invalid ARRAY syntax at index ${idx}, expected ARRAY[... or ARRAY(...)`)}static parseFromLexeme(lexemes,index){let idx=index,current=lexemes[idx];return current.value==="array"?this.parseArrayExpression(lexemes,idx):current.value==="substring"||current.value==="overlay"?this.parseKeywordFunction(lexemes,idx,[{key:"from",required:!1},{key:"for",required:!1}]):current.value==="cast"?this.parseKeywordFunction(lexemes,idx,[{key:"as",required:!0}]):current.value==="trim"?this.parseKeywordFunction(lexemes,idx,[{key:"from",required:!1}]):this.parseFunctionCall(lexemes,idx)}static tryParseBinaryExpression(lexemes,index,left,allowAndOperator=!0,allowOrOperator=!0){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&2){let operator=lexemes[idx].value.toLowerCase();if(!allowAndOperator&&operator==="and"||!allowOrOperator&&operator==="or")return null;if(idx++,operator==="between")return this.parseBetweenExpression(lexemes,idx,left,!1);if(operator==="not between")return this.parseBetweenExpression(lexemes,idx,left,!0);if(operator==="::"){let typeValue=this.parseTypeValue(lexemes,idx);return idx=typeValue.newIndex,{value:new CastExpression(left,typeValue.value),newIndex:idx}}let rightResult=ValueParser.parseFromLexeme(lexemes,idx);return idx=rightResult.newIndex,{value:new BinaryExpression(left,operator,rightResult.value),newIndex:idx}}return null}static parseBetweenExpression(lexemes,index,value,negated){let idx=index,lower=ValueParser.parseFromLexeme(lexemes,idx,!1);if(idx=lower.newIndex,idx<lexemes.length&&lexemes[idx].type&2&&lexemes[idx].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${idx}`);idx++;let upper=this.parseBetweenUpperBound(lexemes,idx);return idx=upper.newIndex,{value:new BetweenExpression(value,lower.value,upper.value,negated),newIndex:idx}}static parseBetweenUpperBound(lexemes,index){return ValueParser.parseFromLexeme(lexemes,index,!1,!1)}static parseFunctionCall(lexemes,index){let idx=index,fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx),namespaces=fullNameResult.namespaces,name=fullNameResult.name;if(idx=fullNameResult.newIndex,idx<lexemes.length&&lexemes[idx].type&4){let functionName=name.name.toLowerCase(),arg,closingComments=null,internalOrderBy=null;if(this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY.has(functionName)){let result=this.parseAggregateArguments(lexemes,idx);arg={value:result.arguments,newIndex:result.newIndex},internalOrderBy=result.orderByClause,closingComments=result.closingComments}else{let argWithComments=this.parseArgumentWithComments(lexemes,idx);arg={value:argWithComments.value,newIndex:argWithComments.newIndex},closingComments=argWithComments.closingComments}idx=arg.newIndex;let withinGroup=null;if(idx<lexemes.length&&lexemes[idx].value==="within group"){let withinGroupResult=this.parseWithinGroupClause(lexemes,idx);withinGroup=withinGroupResult.value,idx=withinGroupResult.newIndex}let 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;if(idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++),idx<lexemes.length&&lexemes[idx].value==="over"){let over=OverExpressionParser.parseFromLexeme(lexemes,idx);idx=over.newIndex;let value=new FunctionCall(namespaces,name.name,arg.value,over.value,withinGroup,withOrdinality,internalOrderBy,filterCondition);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);return closingComments&&closingComments.length>0&&value.addPositionedComments("after",closingComments),{value,newIndex:idx}}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Expected opening parenthesis after function name '${name.name}'.`)}static parseKeywordFunction(lexemes,index,keywords2){let idx=index,fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx),namespaces=fullNameResult.namespaces,name=fullNameResult.name;if(idx=fullNameResult.newIndex,idx<lexemes.length&&lexemes[idx].type&4){idx++;let input=ValueParser.parseFromLexeme(lexemes,idx),arg=input.value;if(idx=input.newIndex,idx<lexemes.length&&lexemes[idx].type&16)return this.parseFunctionCall(lexemes,index);for(let{key,required}of keywords2)if(idx<lexemes.length&&lexemes[idx].type&128&&lexemes[idx].value===key)if(idx++,idx<lexemes.length&&lexemes[idx].type&8192){let typeValue=this.parseTypeValue(lexemes,idx);arg=new BinaryExpression(arg,key,typeValue.value),idx=typeValue.newIndex}else{let right=ValueParser.parseFromLexeme(lexemes,idx);arg=new BinaryExpression(arg,key,right.value),idx=right.newIndex}else if(required)throw ParseError.fromUnparsedLexemes(lexemes,idx,`Keyword '${key}' is required for ${name.name} function.`);if(idx<lexemes.length&&lexemes[idx].type&8){idx++;let withinGroup=null;if(idx<lexemes.length&&lexemes[idx].value==="within group"){let withinGroupResult=this.parseWithinGroupClause(lexemes,idx);withinGroup=withinGroupResult.value,idx=withinGroupResult.newIndex}let withOrdinality=!1;if(idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++),idx<lexemes.length&&lexemes[idx].value==="over"){idx++;let over=OverExpressionParser.parseFromLexeme(lexemes,idx);return idx=over.newIndex,{value:new FunctionCall(namespaces,name.name,arg,over.value,withinGroup,withOrdinality,null),newIndex:idx}}else return{value:new FunctionCall(namespaces,name.name,arg,null,withinGroup,withOrdinality,null),newIndex:idx}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Missing closing parenthesis for function '${name.name}'.`)}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Missing opening parenthesis for function '${name.name}'.`)}static parseTypeValue(lexemes,index){let idx=index,{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,idx<lexemes.length&&lexemes[idx].type&4){let arg=ValueParser.parseArgument(4,8,lexemes,idx);idx=arg.newIndex;let value=new TypeValue(namespaces,new RawString(name.name),arg.value);return arg.value.positionedComments&&(value.positionedComments=arg.value.positionedComments),arg.value.comments,{value,newIndex:idx}}else return{value:new TypeValue(namespaces,new RawString(name.name)),newIndex:idx}}static parseWithinGroupClause(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].value!=="within group")throw new Error(`Expected 'WITHIN GROUP' at index ${idx}`);if(idx++,idx>=lexemes.length||!(lexemes[idx].type&4))throw new Error(`Expected '(' after 'WITHIN GROUP' at index ${idx}`);idx++;let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);if(idx=orderByResult.newIndex,idx>=lexemes.length||!(lexemes[idx].type&8))throw new Error(`Expected ')' after WITHIN GROUP ORDER BY clause at index ${idx}`);return idx++,{value:orderByResult.value,newIndex:idx}}static 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,"*":30,"/":30,"%":30,"^":40,"::":50,"unary+":100,"unary-":100,not:100}}static getPrecedence(operator){let precedence=this.precedenceMap[operator.toLowerCase()];return precedence!==void 0?precedence:0}static hasHigherOrEqualPrecedence(operator1,operator2){return this.getPrecedence(operator1)>=this.getPrecedence(operator2)}static isLogicalOperator(operator){let op=operator.toLowerCase();return op==="and"||op==="or"}static isBetweenOperator(operator){let op=operator.toLowerCase();return op==="between"||op==="not between"}static isComparisonOperator(operator){let lowerOp=operator.toLowerCase();return["=","!=","<>","<",">","<=",">=","like","ilike","similar to","in","not in","->","->>","#>","#>>","@>","<@","?","?|","?&","~","~*","!~","!~*","rlike","regexp"].includes(lowerOp)}};var ValueParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw ParseError.fromUnparsedLexemes(lexemes,result.newIndex,"[ValueParser]");return result.value}static parseFromLexeme(lexemes,index,allowAndOperator=!0,allowOrOperator=!0){return this.parseExpressionWithPrecedence(lexemes,index,0,allowAndOperator,allowOrOperator)}static parseExpressionWithPrecedence(lexemes,index,minPrecedence,allowAndOperator=!0,allowOrOperator=!0){let idx=index,comment=lexemes[idx].comments,positionedComments=lexemes[idx].positionedComments,left=this.parseItem(lexemes,idx);positionedComments&&positionedComments.length>0&&!left.value.positionedComments?left.value.positionedComments=positionedComments:left.value.comments===null&&comment&&comment.length>0&&(left.value.comments=comment),idx=left.newIndex;let result=left.value,arrayAccessResult=this.parseArrayAccess(lexemes,idx,result);for(result=arrayAccessResult.value,idx=arrayAccessResult.newIndex;idx<lexemes.length&&lexemes[idx].type&2;){let operatorToken=lexemes[idx],operator=operatorToken.value;if(!allowAndOperator&&operator.toLowerCase()==="and"||!allowOrOperator&&operator.toLowerCase()==="or")break;let precedence=OperatorPrecedence.getPrecedence(operator);if(precedence<minPrecedence)break;if(idx++,OperatorPrecedence.isBetweenOperator(operator)){let betweenResult=FunctionExpressionParser.parseBetweenExpression(lexemes,idx,result,operator.toLowerCase().includes("not"));result=betweenResult.value,idx=betweenResult.newIndex;continue}if(operator==="::"){let typeValue=FunctionExpressionParser.parseTypeValue(lexemes,idx);result=new CastExpression(result,typeValue.value),idx=typeValue.newIndex;continue}let nextMinPrecedence=precedence+1,rightResult=this.parseExpressionWithPrecedence(lexemes,idx,nextMinPrecedence,allowAndOperator,allowOrOperator);idx=rightResult.newIndex;let binaryExpr=new BinaryExpression(result,operator,rightResult.value);operatorToken.comments&&operatorToken.comments.length>0&&(binaryExpr.operator.comments=operatorToken.comments),operatorToken.positionedComments&&operatorToken.positionedComments.length>0&&(binaryExpr.operator.positionedComments=operatorToken.positionedComments),result=binaryExpr}return{value:result,newIndex:idx}}static transferPositionedComments(lexeme,value){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(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)}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(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)}visitHavingClause(clause){let newCondition=this.visit(clause.condition);return new HavingClause(newCondition)}visitOrderByClause(clause){let newOrder=clause.order.map(item=>this.visit(item));return new OrderByClause(newOrder)}visitWindowFrameClause(clause){let newExpression=this.visit(clause.expression);return new WindowFrameClause(clause.name.name,newExpression)}visitLimitClause(clause){let newLimit=this.visit(clause.value);return new LimitClause(newLimit)}visitForClause(clause){return new ForClause(clause.lockMode)}visitParenExpression(expr){let newExpression=this.visit(expr.expression);return new ParenExpression(newExpression)}visitBinaryExpression(expr){let newLeft=this.visit(expr.left),newRight=this.visit(expr.right);return new BinaryExpression(newLeft,expr.operator.value,newRight)}visitUnaryExpression(expr){let newExpression=this.visit(expr.expression);return new UnaryExpression(expr.operator.value,newExpression)}visitCaseExpression(expr){let newCondition=expr.condition?this.visit(expr.condition):null,newSwitchCase=this.visit(expr.switchCase);return new CaseExpression(newCondition,newSwitchCase)}visitSwitchCaseArgument(switchCase){let newCases=switchCase.cases.map(caseItem=>this.visit(caseItem)),newElseValue=switchCase.elseValue?this.visit(switchCase.elseValue):null;return new SwitchCaseArgument(newCases,newElseValue)}visitCaseKeyValuePair(pair){let newKey=this.visit(pair.key),newValue=this.visit(pair.value);return new CaseKeyValuePair(newKey,newValue)}visitBetweenExpression(expr){let newExpression=this.visit(expr.expression),newLower=this.visit(expr.lower),newUpper=this.visit(expr.upper);return new BetweenExpression(newExpression,newLower,newUpper,expr.negated)}visitFunctionCall(func){let newArgument=func.argument?this.visit(func.argument):null,newOver=func.over?this.visit(func.over):null;return new FunctionCall(func.namespaces,func.name,newArgument,newOver)}visitArrayExpression(expr){let newExpression=this.visit(expr.expression);return new ArrayExpression(newExpression)}visitArrayQueryExpression(expr){let newQuery=this.visit(expr.query);return new ArrayQueryExpression(newQuery)}visitTupleExpression(expr){let newValues=expr.values.map(value=>this.visit(value));return new TupleExpression(newValues)}visitCastExpression(expr){let newInput=this.visit(expr.input),newCastType=this.visit(expr.castType);return new CastExpression(newInput,newCastType)}visitTypeValue(typeValue){let newArgument=typeValue.argument?this.visit(typeValue.argument):null;return new TypeValue(typeValue.namespaces,typeValue.name,newArgument)}visitSelectItem(item){let newValue=this.visit(item.value);return new SelectItem(newValue,item.identifier?.name)}visitIdentifierString(ident){return ident}visitRawString(raw){return raw}visitColumnReference(column){return column}visitSourceExpression(source){let newSource=this.visit(source.datasource),newAlias=source.aliasExpression;return new SourceExpression(newSource,newAlias)}visitTableSource(source){return source}visitParenSource(source){let newSource=this.visit(source.source);return new ParenSource(newSource)}visitParameterExpression(param){return param}visitWindowFrameExpression(expr){let newPartition=expr.partition?this.visit(expr.partition):null,newOrder=expr.order?this.visit(expr.order):null,newFrameSpec=expr.frameSpec?this.visit(expr.frameSpec):null;return new WindowFrameExpression(newPartition,newOrder,newFrameSpec)}visitWindowFrameSpec(spec){return spec}visitLiteralValue(value){return value}visitOrderByItem(item){let newValue=this.visit(item.value);return new OrderByItem(newValue,item.sortDirection,item.nullsPosition)}visitValueList(valueList){let newValues=valueList.values.map(value=>this.visit(value));return new ValueList(newValues)}visitArraySliceExpression(expr){return expr}visitArrayIndexExpression(expr){return expr}visitStringSpecifierExpression(expr){return expr}visitPartitionByClause(clause){let newValue=this.visit(clause.value);return new PartitionByClause(newValue)}};var TableSourceCollector=class{constructor(selectableOnly=!0,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(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)}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.normalizeJoinConditionOrder=options?.joinConditionOrderByDeclaration??!1,this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(QualifiedName.kind,expr=>this.visitQualifiedName(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(WindowFrameBoundStatic.kind,expr=>this.visitWindowFrameBoundStatic(expr)),this.handlers.set(WindowFrameBoundaryValue.kind,expr=>this.visitWindowFrameBoundaryValue(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(Distinct.kind,expr=>this.visitDistinct(expr)),this.handlers.set(DistinctOn.kind,expr=>this.visitDistinctOn(expr)),this.handlers.set(HintClause.kind,expr=>this.visitHintClause(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(SourceAliasExpression.kind,expr=>this.visitSourceAliasExpression(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(WindowsClause.kind,expr=>this.visitWindowClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.visitOffsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(FetchExpression.kind,expr=>this.visitFetchExpression(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleQuery(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(InsertClause.kind,expr=>this.visitInsertClause(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(UpdateClause.kind,expr=>this.visitUpdateClause(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(DeleteClause.kind,expr=>this.visitDeleteClause(expr)),this.handlers.set(UsingClause.kind,expr=>this.visitUsingClause(expr)),this.handlers.set(SetClause.kind,expr=>this.visitSetClause(expr)),this.handlers.set(SetClauseItem.kind,expr=>this.visitSetClauseItem(expr)),this.handlers.set(ReturningClause.kind,expr=>this.visitReturningClause(expr)),this.handlers.set(CreateTableQuery.kind,expr=>this.visitCreateTableQuery(expr)),this.handlers.set(TableColumnDefinition.kind,expr=>this.visitTableColumnDefinition(expr)),this.handlers.set(ColumnConstraintDefinition.kind,expr=>this.visitColumnConstraintDefinition(expr)),this.handlers.set(TableConstraintDefinition.kind,expr=>this.visitTableConstraintDefinition(expr)),this.handlers.set(ReferenceDefinition.kind,expr=>this.visitReferenceDefinition(expr)),this.handlers.set(CreateIndexStatement.kind,expr=>this.visitCreateIndexStatement(expr)),this.handlers.set(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"))),arg.nullsPosition&&(arg.nullsPosition==="first"?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"nulls first"))):arg.nullsPosition==="last"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"nulls last")))),token}parse(arg){this.index=1;let token=this.visit(arg),paramsRaw=ParameterCollector.collect(arg).sort((a,b)=>(a.index??0)-(b.index??0)),style=this.parameterDecorator.style;if(style==="named"){let paramsObj={};for(let p of paramsRaw){let key=p.name.value;if(paramsObj.hasOwnProperty(key)){if(paramsObj[key]!==p.value)throw new Error(`Duplicate parameter name '${key}' with different values detected during query composition.`);continue}paramsObj[key]=p.value}return{token,params:paramsObj}}else if(style==="indexed"){let paramsArr=paramsRaw.map(p=>p.value);return{token,params:paramsArr}}else if(style==="anonymous"){let paramsArr=paramsRaw.map(p=>p.value);return{token,params:paramsArr}}return{token,params:[]}}componentHandlesOwnComments(component){return"handlesOwnComments"in component&&typeof component.handlesOwnComments=="function"?component.handlesOwnComments():_SqlPrintTokenParser.getSelfHandlingComponentTypes().has(component.getKind())}visit(arg){let handler=this.handlers.get(arg.getKind());if(handler){let token=handler(arg);return this.componentHandlesOwnComments(arg)||this.addComponentComments(token,arg),token}throw new Error(`[SqlPrintTokenParser] No handler for kind: ${arg.getKind().toString()}`)}hasPositionedComments(component){return(component.positionedComments?.length??0)>0}hasLegacyComments(component){return(component.comments?.length??0)>0}addComponentComments(token,component){this.hasPositionedComments(component)?this.addPositionedCommentsToToken(token,component):this.hasLegacyComments(component)&&this.addCommentsToToken(token,component.comments)}addPositionedCommentsToToken(token,component){if(!this.hasPositionedComments(component))return;let beforeComments=component.getPositionedComments("before");if(beforeComments.length>0){let commentBlocks=this.createCommentBlocks(beforeComments);for(let i=commentBlocks.length-1;i>=0;i--)token.innerTokens.unshift(commentBlocks[i])}let afterComments=component.getPositionedComments("after");if(afterComments.length>0){let commentBlocks=this.createCommentBlocks(afterComments);for(let commentBlock of commentBlocks)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(commentBlock)}let componentsWithDuplicationIssues=["CaseExpression","SwitchCaseArgument","CaseKeyValuePair","SelectClause","LiteralValue","IdentifierString","DistinctOn","SourceAliasExpression","SimpleSelectQuery","WhereClause"];token.containerType&&componentsWithDuplicationIssues.includes(token.containerType)&&(component.positionedComments=null)}addCommentsToToken(token,comments){if(!comments?.length)return;let commentBlocks=this.createCommentBlocks(comments);this.insertCommentBlocksWithSpacing(token,commentBlocks)}createInlineCommentSequence(comments){let commentTokens=[];for(let i=0;i<comments.length;i++){let comment=comments[i];if(comment.trim()){let commentToken=new SqlPrintToken(6,this.formatComment(comment));if(commentTokens.push(commentToken),i<comments.length-1){let spaceToken=new SqlPrintToken(10," ");commentTokens.push(spaceToken)}}}return commentTokens}createCommentBlocks(comments,isHeaderComment=!1){let commentBlocks=[];for(let comment of comments){let trimmed=comment.trim(),isSeparatorLine=/^[-=_+*#]+$/.test(trimmed);(trimmed||isSeparatorLine||comment==="")&&commentBlocks.push(this.createSingleCommentBlock(comment,isHeaderComment))}return commentBlocks}shouldMergeComment(trimmed){return!(!/^[-=_+*#]+$/.test(trimmed)&&trimmed.startsWith("--")||trimmed.startsWith("/*")&&trimmed.endsWith("*/")&&(!trimmed.slice(2,-2).trim()||trimmed.includes(`
|
|
14
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]} */`:`/*
|
|
@@ -21,13 +21,13 @@ ${lines.map(line=>` ${line}`).join(`
|
|
|
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){if(option===void 0)return;if(typeof option=="string"){let normalized=option.toLowerCase();if(!Object.prototype.hasOwnProperty.call(IDENTIFIER_ESCAPE_MAP,normalized))throw new Error(`Unknown identifierEscape option: ${option}`);let mapped=IDENTIFIER_ESCAPE_MAP[normalized];return{start:mapped.start,end:mapped.end}}let start=option.start??"",end=option.end??"";return{start,end}}var OnelineFormattingHelper=class{constructor(options){this.options=options}shouldFormatContainer(token,shouldIndentNested){switch(token.containerType){case"ParenExpression":return this.options.parenthesesOneLine&&!shouldIndentNested;case"BetweenExpression":return this.options.betweenOneLine;case"Values":return this.options.valuesOneLine;case"JoinOnClause":return this.options.joinOneLine;case"CaseExpression":return this.options.caseOneLine;case"InlineQuery":return this.options.subqueryOneLine;default:return!1}}isInsertClauseOneline(parentContainerType){return this.options.insertColumnsOneLine?parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction":!1}shouldInsertJoinNewline(insideWithClause){return!(insideWithClause&&this.options.withClauseStyle==="full-oneline")}resolveCommaBreak(parentContainerType,commaBreak,cteCommaBreak,valuesCommaBreak){return parentContainerType==="WithClause"?cteCommaBreak:parentContainerType==="AnalyzeStatement"||parentContainerType==="ExplainStatement"?"none":parentContainerType==="Values"?valuesCommaBreak:this.isInsertClauseOneline(parentContainerType)?"none":commaBreak}shouldSkipInsertClauseSpace(parentContainerType,nextToken,currentLineText){if(!(parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction"))return!1;if(nextToken&&nextToken.type===4&&nextToken.text==="(")return!0;if(!this.options.insertColumnsOneLine)return!1;let lastChar=currentLineText.slice(-1);return lastChar==="("||lastChar===" "||lastChar===""}shouldSkipCommentBlockSpace(parentContainerType,insideWithClause){return parentContainerType==="CommentBlock"&&insideWithClause&&this.options.withClauseStyle==="full-oneline"}formatInsertClauseToken(text,parentContainerType,currentLineText,ensureTrailingSpace){if(!this.isInsertClauseOneline(parentContainerType))return{handled:!1};if(text==="")return{handled:!0};let leadingWhitespace=text.match(/^\s+/)?.[0]??"",trimmed=leadingWhitespace?text.slice(leadingWhitespace.length):text;if(trimmed==="")return{handled:!0};if(leadingWhitespace){let lastChar=currentLineText.slice(-1);lastChar!=="("&&lastChar!==" "&&lastChar!==""&&ensureTrailingSpace()}return{handled:!0,text:trimmed}}};var CREATE_TABLE_SINGLE_PAREN_KEYWORDS=new Set(["unique","check","key","index"]),CREATE_TABLE_MULTI_PAREN_KEYWORDS=new Set(["primary key","foreign key","unique key"]),CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER=new Set(["references"]),SqlPrinter=class _SqlPrinter{constructor(options){this.insideWithClause=!1;this.mergeWhenPredicateDepth=0;this.pendingLineCommentBreak=null;this.smartCommentBlockBuilder=null;let resolvedIndentChar=resolveIndentCharOption(options?.indentChar),resolvedNewline=resolveNewlineOption(options?.newline);this.indentChar=resolvedIndentChar??"",this.indentSize=options?.indentSize??0,this.newline=resolvedNewline??" ",this.commaBreak=options?.commaBreak??"none",this.cteCommaBreak=options?.cteCommaBreak??this.commaBreak,this.valuesCommaBreak=options?.valuesCommaBreak??this.commaBreak,this.andBreak=options?.andBreak??"none",this.orBreak=options?.orBreak??"none",this.keywordCase=options?.keywordCase??"none",this.commentExportMode=this.resolveCommentExportMode(options?.exportComment),this.withClauseStyle=options?.withClauseStyle??"standard",this.commentStyle=options?.commentStyle??"block",this.parenthesesOneLine=options?.parenthesesOneLine??!1,this.betweenOneLine=options?.betweenOneLine??!1,this.valuesOneLine=options?.valuesOneLine??!1,this.joinOneLine=options?.joinOneLine??!1,this.caseOneLine=options?.caseOneLine??!1,this.subqueryOneLine=options?.subqueryOneLine??!1,this.indentNestedParentheses=options?.indentNestedParentheses??!1,this.insertColumnsOneLine=options?.insertColumnsOneLine??!1,this.whenOneLine=options?.whenOneLine??!1;let onelineOptions={parenthesesOneLine:this.parenthesesOneLine,betweenOneLine:this.betweenOneLine,valuesOneLine:this.valuesOneLine,joinOneLine:this.joinOneLine,caseOneLine:this.caseOneLine,subqueryOneLine:this.subqueryOneLine,insertColumnsOneLine:this.insertColumnsOneLine,withClauseStyle:this.withClauseStyle};this.onelineHelper=new OnelineFormattingHelper(onelineOptions),this.linePrinter=new LinePrinter(this.indentChar,this.indentSize,this.newline,this.commaBreak),this.indentIncrementContainers=new Set(options?.indentIncrementContainerTypes??["SelectClause","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.pendingLineCommentBreak=null,this.smartCommentBlockBuilder=null,this.linePrinter.lines.length>0&&level!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=level),this.appendToken(token,level,void 0,0,!1,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"){this.handleCteOnelineToken(token,level);return}else if(this.shouldFormatContainerAsOneline(token,shouldIndentNested)){this.handleOnelineToken(token,level);return}else this.tryAppendInsertClauseTokenText(token.text,parentContainerType)||this.linePrinter.appendText(token.text);if(token.keywordTokens&&token.keywordTokens.length>0)for(let i=0;i<token.keywordTokens.length;i++){let keywordToken=token.keywordTokens[i];this.appendToken(keywordToken,level,token.containerType,nextCaseContextDepth,indentParentActive,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(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;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(),token.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"){this.insideWithClause=!1,this.linePrinter.appendNewline(level);return}increasedIndent&&shouldIncreaseIndent&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&!delayIndentNewline&&this.linePrinter.appendNewline(level)}shouldAlignExplainStatementChild(parentType,childType){if(parentType!=="ExplainStatement")return!1;switch(childType){case"SimpleSelectQuery":case"InsertQuery":case"UpdateQuery":case"DeleteQuery":case"MergeQuery":return!0;default:return!1}}isCaseContext(containerType){switch(containerType){case"CaseExpression":case"CaseKeyValuePair":case"CaseThenValue":case"CaseElseValue":case"SwitchCaseArgument":return!0;default:return!1}}shouldSkipToken(token){return token.type===12?!1:(!token.innerTokens||token.innerTokens.length===0)&&token.text===""}applyKeywordCase(text){return this.keywordCase==="upper"?text.toUpperCase():this.keywordCase==="lower"?text.toLowerCase():text}handleKeywordToken(token,level,parentContainerType,caseContextDepth=0){let lower=token.text.toLowerCase();if(lower==="and"&&(this.andBreak!=="none"||this.whenOneLine&&parentContainerType==="MergeWhenClause")){this.handleAndOperatorToken(token,level,parentContainerType,caseContextDepth);return}else if(lower==="or"&&(this.orBreak!=="none"||this.whenOneLine&&parentContainerType==="MergeWhenClause")){this.handleOrOperatorToken(token,level,parentContainerType,caseContextDepth);return}let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}this.ensureSpaceBeforeKeyword(),this.linePrinter.appendText(text)}ensureSpaceBeforeKeyword(){let currentLine=this.linePrinter.getCurrentLine();currentLine.text===""||currentLine.text[currentLine.text.length-1]==="("||this.ensureTrailingSpace()}ensureTrailingSpace(){let currentLine=this.linePrinter.getCurrentLine();currentLine.text!==""&&(currentLine.text.endsWith(" ")||(currentLine.text+=" "),currentLine.text=currentLine.text.replace(/\s+$/," "))}tryAppendInsertClauseTokenText(text,parentContainerType){let currentLineText=this.linePrinter.getCurrentLine().text,result=this.onelineHelper.formatInsertClauseToken(text,parentContainerType,currentLineText,()=>this.ensureTrailingSpace());return result.handled?(result.text&&this.linePrinter.appendText(result.text),!0):!1}handleCommaToken(token,level,parentContainerType){let text=token.text,isWithinWithClause=parentContainerType==="WithClause",effectiveCommaBreak=this.onelineHelper.resolveCommaBreak(parentContainerType,this.commaBreak,this.cteCommaBreak,this.valuesCommaBreak);if(parentContainerType==="SetClause"&&(effectiveCommaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline")this.linePrinter.appendText(text);else if(this.withClauseStyle==="cte-oneline"&&isWithinWithClause)this.linePrinter.appendText(text),this.linePrinter.appendNewline(level);else if(effectiveCommaBreak==="before"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="before"&&(this.linePrinter.commaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||(this.linePrinter.appendNewline(level),this.newline===" "&&this.linePrinter.trimTrailingWhitespaceFromPreviousLine(),parentContainerType==="InsertClause"&&(this.linePrinter.getCurrentLine().level=level+1)),this.linePrinter.appendText(text),previousCommaBreak!=="before"&&(this.linePrinter.commaBreak=previousCommaBreak)}else if(effectiveCommaBreak==="after"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="after"&&(this.linePrinter.commaBreak="after"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),previousCommaBreak!=="after"&&(this.linePrinter.commaBreak=previousCommaBreak)}else if(effectiveCommaBreak==="none"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="none"&&(this.linePrinter.commaBreak="none"),this.linePrinter.appendText(text),this.onelineHelper.isInsertClauseOneline(parentContainerType)&&this.ensureTrailingSpace(),previousCommaBreak!=="none"&&(this.linePrinter.commaBreak=previousCommaBreak)}else this.linePrinter.appendText(text)}handleAndOperatorToken(token,level,parentContainerType,caseContextDepth=0){let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}if(this.whenOneLine&&(parentContainerType==="MergeWhenClause"||this.mergeWhenPredicateDepth>0)){this.linePrinter.appendText(text);return}this.andBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text)):this.andBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level)):this.linePrinter.appendText(text)}handleParenthesisToken(token,level,indentParentActive,parentContainerType){if(token.text==="("){if(this.linePrinter.appendText(token.text),(parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction")&&this.insertColumnsOneLine)return;this.isOnelineMode()||(this.shouldBreakAfterOpeningParen(parentContainerType)?this.linePrinter.appendNewline(level+1):indentParentActive&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&this.linePrinter.appendNewline(level));return}if(token.text===")"&&!this.isOnelineMode()){if(this.shouldBreakBeforeClosingParen(parentContainerType)){this.linePrinter.appendNewline(Math.max(level,0)),this.linePrinter.appendText(token.text);return}if(indentParentActive&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")){let closingLevel=Math.max(level-1,0);this.linePrinter.appendNewline(closingLevel)}}this.linePrinter.appendText(token.text)}handleOrOperatorToken(token,level,parentContainerType,caseContextDepth=0){let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}if(this.whenOneLine&&(parentContainerType==="MergeWhenClause"||this.mergeWhenPredicateDepth>0)){this.linePrinter.appendText(text);return}this.orBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text)):this.orBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level)):this.linePrinter.appendText(text)}shouldIndentNestedParentheses(token,previousSiblingWasOpenParen=!1){return!this.indentNestedParentheses||token.containerType!=="ParenExpression"?!1: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:`
|
|
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.pendingLineCommentBreak=null;this.smartCommentBlockBuilder=null;let resolvedIndentChar=resolveIndentCharOption(options?.indentChar),resolvedNewline=resolveNewlineOption(options?.newline);this.indentChar=resolvedIndentChar??"",this.indentSize=options?.indentSize??0,this.newline=resolvedNewline??" ",this.commaBreak=options?.commaBreak??"none",this.cteCommaBreak=options?.cteCommaBreak??this.commaBreak,this.valuesCommaBreak=options?.valuesCommaBreak??this.commaBreak,this.andBreak=options?.andBreak??"none",this.orBreak=options?.orBreak??"none",this.keywordCase=options?.keywordCase??"none",this.commentExportMode=this.resolveCommentExportMode(options?.exportComment),this.withClauseStyle=options?.withClauseStyle??"standard",this.commentStyle=options?.commentStyle??"block",this.parenthesesOneLine=options?.parenthesesOneLine??!1,this.betweenOneLine=options?.betweenOneLine??!1,this.valuesOneLine=options?.valuesOneLine??!1,this.joinOneLine=options?.joinOneLine??!1,this.caseOneLine=options?.caseOneLine??!1,this.subqueryOneLine=options?.subqueryOneLine??!1,this.indentNestedParentheses=options?.indentNestedParentheses??!1,this.insertColumnsOneLine=options?.insertColumnsOneLine??!1,this.whenOneLine=options?.whenOneLine??!1;let onelineOptions={parenthesesOneLine:this.parenthesesOneLine,betweenOneLine:this.betweenOneLine,valuesOneLine:this.valuesOneLine,joinOneLine:this.joinOneLine,caseOneLine:this.caseOneLine,subqueryOneLine:this.subqueryOneLine,insertColumnsOneLine:this.insertColumnsOneLine,withClauseStyle:this.withClauseStyle};this.onelineHelper=new OnelineFormattingHelper(onelineOptions),this.linePrinter=new LinePrinter(this.indentChar,this.indentSize,this.newline,this.commaBreak),this.indentIncrementContainers=new Set(options?.indentIncrementContainerTypes??["SelectClause","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.pendingLineCommentBreak=null,this.smartCommentBlockBuilder=null,this.linePrinter.lines.length>0&&level!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=level),this.appendToken(token,level,void 0,0,!1,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"){this.handleCteOnelineToken(token,level);return}else if(this.shouldFormatContainerAsOneline(token,shouldIndentNested)){this.handleOnelineToken(token,level);return}else this.tryAppendInsertClauseTokenText(token.text,parentContainerType)||this.linePrinter.appendText(token.text);if(token.keywordTokens&&token.keywordTokens.length>0)for(let i=0;i<token.keywordTokens.length;i++){let keywordToken=token.keywordTokens[i];this.appendToken(keywordToken,level,token.containerType,nextCaseContextDepth,indentParentActive,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(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;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(),token.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"){this.insideWithClause=!1,this.linePrinter.appendNewline(level);return}increasedIndent&&shouldIncreaseIndent&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&!delayIndentNewline&&this.linePrinter.appendNewline(level)}shouldAlignExplainStatementChild(parentType,childType){if(parentType!=="ExplainStatement")return!1;switch(childType){case"SimpleSelectQuery":case"InsertQuery":case"UpdateQuery":case"DeleteQuery":case"MergeQuery":return!0;default:return!1}}isCaseContext(containerType){switch(containerType){case"CaseExpression":case"CaseKeyValuePair":case"CaseThenValue":case"CaseElseValue":case"SwitchCaseArgument":return!0;default:return!1}}shouldSkipToken(token){return token.type===12?!1:(!token.innerTokens||token.innerTokens.length===0)&&token.text===""}applyKeywordCase(text){return this.keywordCase==="upper"?text.toUpperCase():this.keywordCase==="lower"?text.toLowerCase():text}handleKeywordToken(token,level,parentContainerType,caseContextDepth=0){let lower=token.text.toLowerCase();if(lower==="and"&&(this.andBreak!=="none"||this.whenOneLine&&parentContainerType==="MergeWhenClause")){this.handleAndOperatorToken(token,level,parentContainerType,caseContextDepth);return}else if(lower==="or"&&(this.orBreak!=="none"||this.whenOneLine&&parentContainerType==="MergeWhenClause")){this.handleOrOperatorToken(token,level,parentContainerType,caseContextDepth);return}let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}this.ensureSpaceBeforeKeyword(),this.linePrinter.appendText(text)}ensureSpaceBeforeKeyword(){let currentLine=this.linePrinter.getCurrentLine();currentLine.text===""||currentLine.text[currentLine.text.length-1]==="("||this.ensureTrailingSpace()}ensureTrailingSpace(){let currentLine=this.linePrinter.getCurrentLine();currentLine.text!==""&&(currentLine.text.endsWith(" ")||(currentLine.text+=" "),currentLine.text=currentLine.text.replace(/\s+$/," "))}tryAppendInsertClauseTokenText(text,parentContainerType){let currentLineText=this.linePrinter.getCurrentLine().text,result=this.onelineHelper.formatInsertClauseToken(text,parentContainerType,currentLineText,()=>this.ensureTrailingSpace());return result.handled?(result.text&&this.linePrinter.appendText(result.text),!0):!1}handleCommaToken(token,level,parentContainerType){let text=token.text,isWithinWithClause=parentContainerType==="WithClause",effectiveCommaBreak=this.onelineHelper.resolveCommaBreak(parentContainerType,this.commaBreak,this.cteCommaBreak,this.valuesCommaBreak);if(parentContainerType==="SetClause"&&(effectiveCommaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline")this.linePrinter.appendText(text);else if(this.withClauseStyle==="cte-oneline"&&isWithinWithClause)this.linePrinter.appendText(text),this.linePrinter.appendNewline(level);else if(effectiveCommaBreak==="before"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="before"&&(this.linePrinter.commaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||(this.linePrinter.appendNewline(level),this.newline===" "&&this.linePrinter.trimTrailingWhitespaceFromPreviousLine(),parentContainerType==="InsertClause"&&(this.linePrinter.getCurrentLine().level=level+1)),this.linePrinter.appendText(text),previousCommaBreak!=="before"&&(this.linePrinter.commaBreak=previousCommaBreak)}else if(effectiveCommaBreak==="after"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="after"&&(this.linePrinter.commaBreak="after"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),previousCommaBreak!=="after"&&(this.linePrinter.commaBreak=previousCommaBreak)}else if(effectiveCommaBreak==="none"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="none"&&(this.linePrinter.commaBreak="none"),this.linePrinter.appendText(text),this.onelineHelper.isInsertClauseOneline(parentContainerType)&&this.ensureTrailingSpace(),previousCommaBreak!=="none"&&(this.linePrinter.commaBreak=previousCommaBreak)}else this.linePrinter.appendText(text)}handleAndOperatorToken(token,level,parentContainerType,caseContextDepth=0){let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}if(this.whenOneLine&&(parentContainerType==="MergeWhenClause"||this.mergeWhenPredicateDepth>0)){this.linePrinter.appendText(text);return}this.andBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text)):this.andBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level)):this.linePrinter.appendText(text)}handleParenthesisToken(token,level,indentParentActive,parentContainerType){if(token.text==="("){if(this.linePrinter.appendText(token.text),(parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction")&&this.insertColumnsOneLine)return;this.isOnelineMode()||(this.shouldBreakAfterOpeningParen(parentContainerType)?this.linePrinter.appendNewline(level+1):indentParentActive&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&this.linePrinter.appendNewline(level));return}if(token.text===")"&&!this.isOnelineMode()){if(this.shouldBreakBeforeClosingParen(parentContainerType)){this.linePrinter.appendNewline(Math.max(level,0)),this.linePrinter.appendText(token.text);return}if(indentParentActive&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")){let closingLevel=Math.max(level-1,0);this.linePrinter.appendNewline(closingLevel)}}this.linePrinter.appendText(token.text)}handleOrOperatorToken(token,level,parentContainerType,caseContextDepth=0){let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}if(this.whenOneLine&&(parentContainerType==="MergeWhenClause"||this.mergeWhenPredicateDepth>0)){this.linePrinter.appendText(text);return}this.orBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text)):this.orBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level)):this.linePrinter.appendText(text)}shouldIndentNestedParentheses(token,previousSiblingWasOpenParen=!1){return!this.indentNestedParentheses||token.containerType!=="ParenExpression"?!1: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
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,`
|
|
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===" "}handleCteOnelineToken(token,level){let onelineResult=this.createCteOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);cleanedResult=cleanedResult.replace(/\(\s+/g,"(").replace(/\s+\)/g," )"),this.linePrinter.appendText(cleanedResult.trim())}createCteOnelinePrinter(){return new _SqlPrinter({indentChar:"",indentSize:0,newline:" ",commaBreak:this.commaBreak,cteCommaBreak:this.cteCommaBreak,valuesCommaBreak:this.valuesCommaBreak,andBreak:this.andBreak,orBreak:this.orBreak,keywordCase:this.keywordCase,exportComment:"none",withClauseStyle:"standard",indentNestedParentheses:!1,insertColumnsOneLine:this.insertColumnsOneLine})}handleOnelineToken(token,level){let onelineResult=this.createOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);this.linePrinter.appendText(cleanedResult)}getClauseBreakIndentLevel(parentType,level){if(!parentType)return level;switch(parentType){case"MergeWhenClause":return level+1;case"MergeUpdateAction":case"MergeDeleteAction":case"MergeInsertAction":return level+1;default:return level}}isMergeActionContainer(token){if(!token)return!1;switch(token.containerType){case"MergeUpdateAction":case"MergeDeleteAction":case"MergeInsertAction":case"MergeDoNothingAction":return!0;default:return!1}}shouldBreakAfterOpeningParen(parentType){return parentType&&(parentType==="InsertClause"||parentType==="MergeInsertAction"||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),parserOptions={...presetConfig,identifierEscape:resolvedIdentifierEscape??presetConfig?.identifierEscape,parameterSymbol:options.parameterSymbol??presetConfig?.parameterSymbol,parameterStyle:options.parameterStyle??presetConfig?.parameterStyle,castStyle:options.castStyle??presetConfig?.castStyle,joinConditionOrderByDeclaration:options.joinConditionOrderByDeclaration},constraintStyle=options.constraintStyle??presetConfig?.constraintStyle??"postgres",parserConfig={...parserOptions,constraintStyle};this.parser=new SqlPrintTokenParser({...parserConfig});let normalizedExportComment=options.exportComment===!0?"full":options.exportComment===!1?"none":options.exportComment,printerOptions={...options,exportComment:normalizedExportComment,parenthesesOneLine:options.parenthesesOneLine,betweenOneLine:options.betweenOneLine,valuesOneLine:options.valuesOneLine,joinOneLine:options.joinOneLine,caseOneLine:options.caseOneLine,subqueryOneLine:options.subqueryOneLine,indentNestedParentheses:options.indentNestedParentheses};this.printer=new SqlPrinter(printerOptions)}format(sql){let{token,params}=this.parser.parse(sql);return{formattedSql:this.printer.print(token),params}}};var Formatter=class{constructor(){this.sqlFormatter=new SqlFormatter({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(arg,config=null){return config&&(this.sqlFormatter=new SqlFormatter(config)),this.sqlFormatter.format(arg).formattedSql}formatWithParameters(arg,config=null){config&&(this.sqlFormatter=new SqlFormatter(config));let result=this.sqlFormatter.format(arg);return{sql:result.formattedSql,params:result.params}}visit(arg){return this.format(arg)}};var CTEBuilder=class{constructor(){this.sourceCollector=new TableSourceCollector(!0),this.cteCollector=new CTECollector,this.formatter=new Formatter}build(commonTables){if(commonTables.length===0)return new WithClause(!1,commonTables);let resolvedTables=this.resolveDuplicateNames(commonTables),{tableMap,recursiveCTEs,dependencies}=this.buildDependencyGraph(resolvedTables),sortedTables=this.sortCommonTables(resolvedTables,tableMap,recursiveCTEs,dependencies);return new WithClause(recursiveCTEs.size>0,sortedTables)}resolveDuplicateNames(commonTables){let ctesByName=new Map;for(let table of commonTables){let tableName=table.aliasExpression.table.name;ctesByName.has(tableName)||ctesByName.set(tableName,[]),ctesByName.get(tableName).push(table)}let resolvedTables=[];for(let[name,tables]of Array.from(ctesByName.entries())){if(tables.length===1){resolvedTables.push(tables[0]);continue}let definitions=tables.map(table=>this.formatter.format(table.query));if(new Set(definitions).size===1)resolvedTables.push(tables[0]);else throw new Error(`CTE name conflict detected: '${name}' has multiple different definitions`)}return resolvedTables}buildDependencyGraph(tables){let tableMap=new Map;for(let table of tables)tableMap.set(table.aliasExpression.table.name,table);let recursiveCTEs=new Set,dependencies=new Map,referencedBy=new Map;for(let table of tables){let tableName=table.aliasExpression.table.name,referencedTables=this.sourceCollector.collect(table.query);for(let referencedTable of referencedTables)if(referencedTable.table.name===tableName){recursiveCTEs.add(tableName);break}dependencies.has(tableName)||dependencies.set(tableName,new Set);let referencedCTEs=this.cteCollector.collect(table.query);for(let referencedCTE of referencedCTEs){let referencedName=referencedCTE.aliasExpression.table.name;tableMap.has(referencedName)&&(dependencies.get(tableName).add(referencedName),referencedBy.has(referencedName)||referencedBy.set(referencedName,new Set),referencedBy.get(referencedName).add(tableName))}}return{tableMap,recursiveCTEs,dependencies}}sortCommonTables(tables,tableMap,recursiveCTEs,dependencies){let recursiveResult=[],nonRecursiveResult=[],visited=new Set,visiting=new Set,visit=tableName=>{if(visited.has(tableName))return;if(visiting.has(tableName))throw new Error(`Circular reference detected in CTE: ${tableName}`);visiting.add(tableName);let deps=dependencies.get(tableName)||new Set;for(let dep of Array.from(deps))visit(dep);visiting.delete(tableName),visited.add(tableName),recursiveCTEs.has(tableName)?recursiveResult.push(tableMap.get(tableName)):nonRecursiveResult.push(tableMap.get(tableName))};for(let table of tables){let tableName=table.aliasExpression.table.name;visited.has(tableName)||visit(tableName)}return[...recursiveResult,...nonRecursiveResult]}};var CTEInjector=class{constructor(){this.nameConflictResolver=new CTEBuilder,this.cteCollector=new CTECollector}inject(query,commonTables){if(commonTables.length===0)return query;commonTables.push(...this.cteCollector.collect(query));let resolvedWithCaluse=this.nameConflictResolver.build(commonTables);if(query instanceof SimpleSelectQuery)return this.injectIntoSimpleQuery(query,resolvedWithCaluse);if(query instanceof BinarySelectQuery)return this.injectIntoBinaryQuery(query,resolvedWithCaluse);throw new Error("Unsupported query type")}injectIntoSimpleQuery(query,withClause){if(query.withClause)throw new Error("The query already has a WITH clause. Please remove it before injecting new CTEs.");return query.withClause=withClause,query}injectIntoBinaryQuery(query,withClause){if(query.left instanceof SimpleSelectQuery)return this.injectIntoSimpleQuery(query.left,withClause),query;if(query.left instanceof BinarySelectQuery)return this.injectIntoBinaryQuery(query.left,withClause),query;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var CTENormalizer=class{constructor(){}static normalize(query){let allCommonTables=new CTECollector().collect(query);return allCommonTables.length===0?query:(new CTEDisabler().execute(query),new CTEInjector().inject(query,allCommonTables))}};var DuplicateDetectionMode=(DuplicateDetectionMode2=>(DuplicateDetectionMode2.ColumnNameOnly="columnNameOnly",DuplicateDetectionMode2.FullName="fullName",DuplicateDetectionMode2))(DuplicateDetectionMode||{}),SelectableColumnCollector=class _SelectableColumnCollector{constructor(tableColumnResolver,includeWildCard=!1,duplicateDetection="columnNameOnly",options){this.selectValues=[];this.visitedNodes=new Set;this.uniqueKeys=new Set;this.isRootVisit=!0;this.tableColumnResolver=null;this.commonTables=[];this.initializeProperties(tableColumnResolver,includeWildCard,duplicateDetection,options),this.initializeHandlers()}initializeProperties(tableColumnResolver,includeWildCard,duplicateDetection,options){this.tableColumnResolver=tableColumnResolver??null,this.includeWildCard=includeWildCard,this.commonTableCollector=new CTECollector,this.commonTables=[],this.duplicateDetection=duplicateDetection,this.options=options||{}}initializeHandlers(){this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.initializeClauseHandlers(),this.initializeValueComponentHandlers()}initializeClauseHandlers(){this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.offsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr))}initializeValueComponentHandlers(){this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}getValues(){return this.selectValues}collect(arg){if(!arg)throw new Error("Input argument cannot be null or undefined");this.visit(arg);let items=this.getValues();return this.reset(),items}reset(){this.selectValues=[],this.visitedNodes.clear(),this.uniqueKeys.clear(),this.commonTables=[]}addSelectValueAsUnique(name,value){let key=this.generateUniqueKey(name,value);this.uniqueKeys.has(key)||(this.uniqueKeys.add(key),this.selectValues.push({name,value}))}generateUniqueKey(name,value){if(this.duplicateDetection==="columnNameOnly")return this.normalizeColumnName(name);{let tableName="";value&&typeof value.getNamespace=="function"&&(tableName=value.getNamespace()||"");let fullName=tableName?tableName+"."+name:name;return this.normalizeColumnName(fullName)}}normalizeColumnName(name){if(typeof name!="string")throw new Error("Column name must be a string");return this.options.ignoreCaseAndUnderscore?name.toLowerCase().replace(/_/g,""):name}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}if(!(arg instanceof SimpleSelectQuery||arg instanceof BinarySelectQuery))throw new Error("Root visit requires a SimpleSelectQuery or BinarySelectQuery.");this.reset(),this.isRootVisit=!1,this.commonTables=this.commonTableCollector.collect(arg);try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(!this.visitedNodes.has(arg)){this.visitedNodes.add(arg);try{let handler=this.handlers.get(arg.getKind());handler&&handler(arg)}catch(error){let errorMessage=error instanceof Error?error.message:String(error);throw new Error(`Error processing SQL component of type ${arg.getKind().toString()}: ${errorMessage}`)}}}visitSimpleSelectQuery(query){if(query.selectClause&&query.selectClause.accept(this),query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.orderByClause&&query.orderByClause.accept(this),query.limitClause&&query.limitClause.accept(this),query.offsetClause&&query.offsetClause.accept(this),query.fetchClause&&query.fetchClause.accept(this),query.forClause&&query.forClause.accept(this)}visitBinarySelectQuery(query){query.left instanceof SimpleSelectQuery?this.visitSimpleSelectQuery(query.left):query.left instanceof BinarySelectQuery&&this.visitBinarySelectQuery(query.left),query.right instanceof SimpleSelectQuery?this.visitSimpleSelectQuery(query.right):query.right instanceof BinarySelectQuery&&this.visitBinarySelectQuery(query.right)}visitSelectClause(clause){for(let item of clause.items)if(item.identifier)this.addSelectValueAsUnique(item.identifier.name,item.value);else if(item.value instanceof ColumnReference){let columnName=item.value.column.name;columnName!=="*"?this.addSelectValueAsUnique(columnName,item.value):this.includeWildCard&&this.addSelectValueAsUnique(columnName,item.value)}else item.value.accept(this)}visitFromClause(clause){let sourceValues=new SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(clause);for(let item of sourceValues)this.addSelectValueAsUnique(item.name,item.value);if(this.options.upstream&&this.collectUpstreamColumns(clause),clause.joins)for(let join of clause.joins)join.condition&&join.condition.accept(this)}visitWhereClause(clause){clause.condition&&clause.condition.accept(this)}visitGroupByClause(clause){if(clause.grouping)for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition&&clause.condition.accept(this)}visitOrderByClause(clause){if(clause.order)for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitWindowFrameExpression(expr){expr.partition&&expr.partition.accept(this),expr.order&&expr.order.accept(this),expr.frameSpec&&expr.frameSpec.accept(this)}visitLimitClause(clause){clause.value&&clause.value.accept(this)}offsetClause(clause){clause.value&&clause.value.accept(this)}visitFetchClause(clause){clause.expression&&clause.expression.accept(this)}visitJoinOnClause(joinOnClause){joinOnClause.condition&&joinOnClause.condition.accept(this)}visitJoinUsingClause(joinUsingClause){joinUsingClause.condition&&joinUsingClause.condition.accept(this)}visitColumnReference(columnRef){if(columnRef.column.name!=="*")this.addSelectValueAsUnique(columnRef.column.name,columnRef);else if(this.includeWildCard)this.addSelectValueAsUnique(columnRef.column.name,columnRef);else return}visitBinaryExpression(expr){expr.left&&expr.left.accept(this),expr.right&&expr.right.accept(this)}visitUnaryExpression(expr){expr.expression&&expr.expression.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this),func.withinGroup&&func.withinGroup.accept(this),func.internalOrderBy&&func.internalOrderBy.accept(this)}visitInlineQuery(inlineQuery){inlineQuery.selectQuery&&this.visitNode(inlineQuery.selectQuery)}visitParenExpression(expr){expr.expression&&expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase&&expr.switchCase.accept(this)}visitCastExpression(expr){expr.input&&expr.input.accept(this)}visitBetweenExpression(expr){expr.expression&&expr.expression.accept(this),expr.lower&&expr.lower.accept(this),expr.upper&&expr.upper.accept(this)}visitArrayExpression(expr){expr.expression&&expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitArraySliceExpression(expr){expr.array&&expr.array.accept(this),expr.startIndex&&expr.startIndex.accept(this),expr.endIndex&&expr.endIndex.accept(this)}visitArrayIndexExpression(expr){expr.array&&expr.array.accept(this),expr.index&&expr.index.accept(this)}visitValueList(expr){if(expr.values&&Array.isArray(expr.values))for(let value of expr.values)value&&value.accept(this)}visitPartitionByClause(clause){clause.value.accept(this)}collectUpstreamColumns(clause){if(this.collectAllAvailableCTEColumns(),this.collectUpstreamColumnsFromSource(clause.source),clause.joins)for(let join of clause.joins)this.collectUpstreamColumnsFromSource(join.source)}collectUpstreamColumnsFromSource(source){if(source.datasource instanceof TableSource){let cteTable=this.findCTEByName(source.datasource.table.name);cteTable?this.collectUpstreamColumnsFromCTE(cteTable):this.collectUpstreamColumnsFromTable(source.datasource)}else source.datasource instanceof SubQuerySource?this.collectUpstreamColumnsFromSubquery(source.datasource):source.datasource instanceof ParenSource&&this.collectUpstreamColumnsFromSource(new SourceExpression(source.datasource.source,null))}collectUpstreamColumnsFromTable(tableSource){if(this.tableColumnResolver){let tableName=tableSource.table.name,columns=this.tableColumnResolver(tableName);for(let columnName of columns){let columnRef=new ColumnReference(tableSource.table.name,columnName);this.addSelectValueAsUnique(columnName,columnRef)}}}collectUpstreamColumnsFromSubquery(subquerySource){if(subquerySource.query instanceof SimpleSelectQuery){let subqueryColumns=new _SelectableColumnCollector(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!0}).collect(subquerySource.query);for(let item of subqueryColumns)this.addSelectValueAsUnique(item.name,item.value)}}collectUpstreamColumnsFromCTE(cteTable){if(cteTable.query instanceof SimpleSelectQuery){let cteColumns=new _SelectableColumnCollector(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!1}).collect(cteTable.query);for(let item of cteColumns)item.name!=="*"&&this.addSelectValueAsUnique(item.name,item.value)}}collectAllAvailableCTEColumns(){for(let cte of this.commonTables)this.collectUpstreamColumnsFromCTE(cte)}findCTEByName(name){return this.commonTables.find(cte=>cte.getSourceAliasName()===name)||null}};var SourceParser=class _SourceParser{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The source component is complete but there are additional tokens.`);return result.value}static parseTableSourceFromLexemes(lexemes,index){let fullNameResult=FullNameParser.parseFromLexeme(lexemes,index);return this.parseTableSource(fullNameResult)}static parseFromLexeme(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&4)return this.parseParenSource(lexemes,idx);let fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx);return fullNameResult.lastTokenType&2048?_SourceParser.parseFunctionSource(lexemes,fullNameResult):_SourceParser.parseTableSource(fullNameResult)}static parseTableSource(fullNameResult){let{namespaces,name,newIndex}=fullNameResult,value=new TableSource(namespaces,name.name);return name.positionedComments&&name.positionedComments.length>0?value.positionedComments=name.positionedComments:name.comments&&name.comments.length>0&&(value.comments=name.comments),{value,newIndex}}static parseFunctionSource(lexemes,fullNameResult){let idx=fullNameResult.newIndex,{namespaces,name}=fullNameResult,argument=ValueParser.parseArgument(4,8,lexemes,idx);idx=argument.newIndex;let 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==="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===" "}handleCteOnelineToken(token,level){let onelineResult=this.createCteOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);cleanedResult=cleanedResult.replace(/\(\s+/g,"(").replace(/\s+\)/g," )"),this.linePrinter.appendText(cleanedResult.trim())}createCteOnelinePrinter(){return new _SqlPrinter({indentChar:"",indentSize:0,newline:" ",commaBreak:this.commaBreak,cteCommaBreak:this.cteCommaBreak,valuesCommaBreak:this.valuesCommaBreak,andBreak:this.andBreak,orBreak:this.orBreak,keywordCase:this.keywordCase,exportComment:"none",withClauseStyle:"standard",indentNestedParentheses:!1,insertColumnsOneLine:this.insertColumnsOneLine})}handleOnelineToken(token,level){let onelineResult=this.createOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);this.linePrinter.appendText(cleanedResult)}getClauseBreakIndentLevel(parentType,level){if(!parentType)return level;switch(parentType){case"MergeWhenClause":return level+1;case"MergeUpdateAction":case"MergeDeleteAction":case"MergeInsertAction":return level+1;default:return level}}isMergeActionContainer(token){if(!token)return!1;switch(token.containerType){case"MergeUpdateAction":case"MergeDeleteAction":case"MergeInsertAction":case"MergeDoNothingAction":return!0;default:return!1}}shouldBreakAfterOpeningParen(parentType){return parentType&&(parentType==="InsertClause"||parentType==="MergeInsertAction"||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,joinConditionOrderByDeclaration:options.joinConditionOrderByDeclaration},constraintStyle=options.constraintStyle??presetConfig?.constraintStyle??"postgres",parserConfig={...parserOptions,constraintStyle};this.parser=new SqlPrintTokenParser({...parserConfig});let normalizedExportComment=options.exportComment===!0?"full":options.exportComment===!1?"none":options.exportComment,printerOptions={...options,exportComment:normalizedExportComment,parenthesesOneLine:options.parenthesesOneLine,betweenOneLine:options.betweenOneLine,valuesOneLine:options.valuesOneLine,joinOneLine:options.joinOneLine,caseOneLine:options.caseOneLine,subqueryOneLine:options.subqueryOneLine,indentNestedParentheses:options.indentNestedParentheses};this.printer=new SqlPrinter(printerOptions)}format(sql){let{token,params}=this.parser.parse(sql);return{formattedSql:this.printer.print(token),params}}};var Formatter=class{constructor(){this.sqlFormatter=new SqlFormatter({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(arg,config=null){return config&&(this.sqlFormatter=new SqlFormatter(config)),this.sqlFormatter.format(arg).formattedSql}formatWithParameters(arg,config=null){config&&(this.sqlFormatter=new SqlFormatter(config));let result=this.sqlFormatter.format(arg);return{sql:result.formattedSql,params:result.params}}visit(arg){return this.format(arg)}};var CTEBuilder=class{constructor(){this.sourceCollector=new TableSourceCollector(!0),this.cteCollector=new CTECollector,this.formatter=new Formatter}build(commonTables){if(commonTables.length===0)return new WithClause(!1,commonTables);let resolvedTables=this.resolveDuplicateNames(commonTables),{tableMap,recursiveCTEs,dependencies}=this.buildDependencyGraph(resolvedTables),sortedTables=this.sortCommonTables(resolvedTables,tableMap,recursiveCTEs,dependencies);return new WithClause(recursiveCTEs.size>0,sortedTables)}resolveDuplicateNames(commonTables){let ctesByName=new Map;for(let table of commonTables){let tableName=table.aliasExpression.table.name;ctesByName.has(tableName)||ctesByName.set(tableName,[]),ctesByName.get(tableName).push(table)}let resolvedTables=[];for(let[name,tables]of Array.from(ctesByName.entries())){if(tables.length===1){resolvedTables.push(tables[0]);continue}let definitions=tables.map(table=>this.formatter.format(table.query));if(new Set(definitions).size===1)resolvedTables.push(tables[0]);else throw new Error(`CTE name conflict detected: '${name}' has multiple different definitions`)}return resolvedTables}buildDependencyGraph(tables){let tableMap=new Map;for(let table of tables)tableMap.set(table.aliasExpression.table.name,table);let recursiveCTEs=new Set,dependencies=new Map,referencedBy=new Map;for(let table of tables){let tableName=table.aliasExpression.table.name,referencedTables=this.sourceCollector.collect(table.query);for(let referencedTable of referencedTables)if(referencedTable.table.name===tableName){recursiveCTEs.add(tableName);break}dependencies.has(tableName)||dependencies.set(tableName,new Set);let referencedCTEs=this.cteCollector.collect(table.query);for(let referencedCTE of referencedCTEs){let referencedName=referencedCTE.aliasExpression.table.name;tableMap.has(referencedName)&&(dependencies.get(tableName).add(referencedName),referencedBy.has(referencedName)||referencedBy.set(referencedName,new Set),referencedBy.get(referencedName).add(tableName))}}return{tableMap,recursiveCTEs,dependencies}}sortCommonTables(tables,tableMap,recursiveCTEs,dependencies){let recursiveResult=[],nonRecursiveResult=[],visited=new Set,visiting=new Set,visit=tableName=>{if(visited.has(tableName))return;if(visiting.has(tableName))throw new Error(`Circular reference detected in CTE: ${tableName}`);visiting.add(tableName);let deps=dependencies.get(tableName)||new Set;for(let dep of Array.from(deps))visit(dep);visiting.delete(tableName),visited.add(tableName),recursiveCTEs.has(tableName)?recursiveResult.push(tableMap.get(tableName)):nonRecursiveResult.push(tableMap.get(tableName))};for(let table of tables){let tableName=table.aliasExpression.table.name;visited.has(tableName)||visit(tableName)}return[...recursiveResult,...nonRecursiveResult]}};var CTEInjector=class{constructor(){this.nameConflictResolver=new CTEBuilder,this.cteCollector=new CTECollector}inject(query,commonTables){if(commonTables.length===0)return query;commonTables.push(...this.cteCollector.collect(query));let resolvedWithCaluse=this.nameConflictResolver.build(commonTables);if(query instanceof SimpleSelectQuery)return this.injectIntoSimpleQuery(query,resolvedWithCaluse);if(query instanceof BinarySelectQuery)return this.injectIntoBinaryQuery(query,resolvedWithCaluse);throw new Error("Unsupported query type")}injectIntoSimpleQuery(query,withClause){if(query.withClause)throw new Error("The query already has a WITH clause. Please remove it before injecting new CTEs.");return query.withClause=withClause,query}injectIntoBinaryQuery(query,withClause){if(query.left instanceof SimpleSelectQuery)return this.injectIntoSimpleQuery(query.left,withClause),query;if(query.left instanceof BinarySelectQuery)return this.injectIntoBinaryQuery(query.left,withClause),query;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var CTENormalizer=class{constructor(){}static normalize(query){let allCommonTables=new CTECollector().collect(query);return allCommonTables.length===0?query:(new CTEDisabler().execute(query),new CTEInjector().inject(query,allCommonTables))}};var DuplicateDetectionMode=(DuplicateDetectionMode2=>(DuplicateDetectionMode2.ColumnNameOnly="columnNameOnly",DuplicateDetectionMode2.FullName="fullName",DuplicateDetectionMode2))(DuplicateDetectionMode||{}),SelectableColumnCollector=class _SelectableColumnCollector{constructor(tableColumnResolver,includeWildCard=!1,duplicateDetection="columnNameOnly",options){this.selectValues=[];this.visitedNodes=new Set;this.uniqueKeys=new Set;this.isRootVisit=!0;this.tableColumnResolver=null;this.commonTables=[];this.initializeProperties(tableColumnResolver,includeWildCard,duplicateDetection,options),this.initializeHandlers()}initializeProperties(tableColumnResolver,includeWildCard,duplicateDetection,options){this.tableColumnResolver=tableColumnResolver??null,this.includeWildCard=includeWildCard,this.commonTableCollector=new CTECollector,this.commonTables=[],this.duplicateDetection=duplicateDetection,this.options=options||{}}initializeHandlers(){this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.initializeClauseHandlers(),this.initializeValueComponentHandlers()}initializeClauseHandlers(){this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.offsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr))}initializeValueComponentHandlers(){this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}getValues(){return this.selectValues}collect(arg){if(!arg)throw new Error("Input argument cannot be null or undefined");this.visit(arg);let items=this.getValues();return this.reset(),items}reset(){this.selectValues=[],this.visitedNodes.clear(),this.uniqueKeys.clear(),this.commonTables=[]}addSelectValueAsUnique(name,value){let key=this.generateUniqueKey(name,value);this.uniqueKeys.has(key)||(this.uniqueKeys.add(key),this.selectValues.push({name,value}))}generateUniqueKey(name,value){if(this.duplicateDetection==="columnNameOnly")return this.normalizeColumnName(name);{let tableName="";value&&typeof value.getNamespace=="function"&&(tableName=value.getNamespace()||"");let fullName=tableName?tableName+"."+name:name;return this.normalizeColumnName(fullName)}}normalizeColumnName(name){if(typeof name!="string")throw new Error("Column name must be a string");return this.options.ignoreCaseAndUnderscore?name.toLowerCase().replace(/_/g,""):name}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}if(!(arg instanceof SimpleSelectQuery||arg instanceof BinarySelectQuery))throw new Error("Root visit requires a SimpleSelectQuery or BinarySelectQuery.");this.reset(),this.isRootVisit=!1,this.commonTables=this.commonTableCollector.collect(arg);try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(!this.visitedNodes.has(arg)){this.visitedNodes.add(arg);try{let handler=this.handlers.get(arg.getKind());handler&&handler(arg)}catch(error){let errorMessage=error instanceof Error?error.message:String(error);throw new Error(`Error processing SQL component of type ${arg.getKind().toString()}: ${errorMessage}`)}}}visitSimpleSelectQuery(query){if(query.selectClause&&query.selectClause.accept(this),query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.orderByClause&&query.orderByClause.accept(this),query.limitClause&&query.limitClause.accept(this),query.offsetClause&&query.offsetClause.accept(this),query.fetchClause&&query.fetchClause.accept(this),query.forClause&&query.forClause.accept(this)}visitBinarySelectQuery(query){query.left instanceof SimpleSelectQuery?this.visitSimpleSelectQuery(query.left):query.left instanceof BinarySelectQuery&&this.visitBinarySelectQuery(query.left),query.right instanceof SimpleSelectQuery?this.visitSimpleSelectQuery(query.right):query.right instanceof BinarySelectQuery&&this.visitBinarySelectQuery(query.right)}visitSelectClause(clause){for(let item of clause.items)if(item.identifier)this.addSelectValueAsUnique(item.identifier.name,item.value);else if(item.value instanceof ColumnReference){let columnName=item.value.column.name;columnName!=="*"?this.addSelectValueAsUnique(columnName,item.value):this.includeWildCard&&this.addSelectValueAsUnique(columnName,item.value)}else item.value.accept(this)}visitFromClause(clause){let sourceValues=new SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(clause);for(let item of sourceValues)this.addSelectValueAsUnique(item.name,item.value);if(this.options.upstream&&this.collectUpstreamColumns(clause),clause.joins)for(let join of clause.joins)join.condition&&join.condition.accept(this)}visitWhereClause(clause){clause.condition&&clause.condition.accept(this)}visitGroupByClause(clause){if(clause.grouping)for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition&&clause.condition.accept(this)}visitOrderByClause(clause){if(clause.order)for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitWindowFrameExpression(expr){expr.partition&&expr.partition.accept(this),expr.order&&expr.order.accept(this),expr.frameSpec&&expr.frameSpec.accept(this)}visitLimitClause(clause){clause.value&&clause.value.accept(this)}offsetClause(clause){clause.value&&clause.value.accept(this)}visitFetchClause(clause){clause.expression&&clause.expression.accept(this)}visitJoinOnClause(joinOnClause){joinOnClause.condition&&joinOnClause.condition.accept(this)}visitJoinUsingClause(joinUsingClause){joinUsingClause.condition&&joinUsingClause.condition.accept(this)}visitColumnReference(columnRef){if(columnRef.column.name!=="*")this.addSelectValueAsUnique(columnRef.column.name,columnRef);else if(this.includeWildCard)this.addSelectValueAsUnique(columnRef.column.name,columnRef);else return}visitBinaryExpression(expr){expr.left&&expr.left.accept(this),expr.right&&expr.right.accept(this)}visitUnaryExpression(expr){expr.expression&&expr.expression.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this),func.withinGroup&&func.withinGroup.accept(this),func.internalOrderBy&&func.internalOrderBy.accept(this)}visitInlineQuery(inlineQuery){inlineQuery.selectQuery&&this.visitNode(inlineQuery.selectQuery)}visitParenExpression(expr){expr.expression&&expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase&&expr.switchCase.accept(this)}visitCastExpression(expr){expr.input&&expr.input.accept(this)}visitBetweenExpression(expr){expr.expression&&expr.expression.accept(this),expr.lower&&expr.lower.accept(this),expr.upper&&expr.upper.accept(this)}visitArrayExpression(expr){expr.expression&&expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitArraySliceExpression(expr){expr.array&&expr.array.accept(this),expr.startIndex&&expr.startIndex.accept(this),expr.endIndex&&expr.endIndex.accept(this)}visitArrayIndexExpression(expr){expr.array&&expr.array.accept(this),expr.index&&expr.index.accept(this)}visitValueList(expr){if(expr.values&&Array.isArray(expr.values))for(let value of expr.values)value&&value.accept(this)}visitPartitionByClause(clause){clause.value.accept(this)}collectUpstreamColumns(clause){if(this.collectAllAvailableCTEColumns(),this.collectUpstreamColumnsFromSource(clause.source),clause.joins)for(let join of clause.joins)this.collectUpstreamColumnsFromSource(join.source)}collectUpstreamColumnsFromSource(source){if(source.datasource instanceof TableSource){let cteTable=this.findCTEByName(source.datasource.table.name);cteTable?this.collectUpstreamColumnsFromCTE(cteTable):this.collectUpstreamColumnsFromTable(source.datasource)}else source.datasource instanceof SubQuerySource?this.collectUpstreamColumnsFromSubquery(source.datasource):source.datasource instanceof ParenSource&&this.collectUpstreamColumnsFromSource(new SourceExpression(source.datasource.source,null))}collectUpstreamColumnsFromTable(tableSource){if(this.tableColumnResolver){let tableName=tableSource.table.name,columns=this.tableColumnResolver(tableName);for(let columnName of columns){let columnRef=new ColumnReference(tableSource.table.name,columnName);this.addSelectValueAsUnique(columnName,columnRef)}}}collectUpstreamColumnsFromSubquery(subquerySource){if(subquerySource.query instanceof SimpleSelectQuery){let subqueryColumns=new _SelectableColumnCollector(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!0}).collect(subquerySource.query);for(let item of subqueryColumns)this.addSelectValueAsUnique(item.name,item.value)}}collectUpstreamColumnsFromCTE(cteTable){if(cteTable.query instanceof SimpleSelectQuery){let cteColumns=new _SelectableColumnCollector(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!1}).collect(cteTable.query);for(let item of cteColumns)item.name!=="*"&&this.addSelectValueAsUnique(item.name,item.value)}}collectAllAvailableCTEColumns(){for(let cte of this.commonTables)this.collectUpstreamColumnsFromCTE(cte)}findCTEByName(name){return this.commonTables.find(cte=>cte.getSourceAliasName()===name)||null}};var SourceParser=class _SourceParser{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The source component is complete but there are additional tokens.`);return result.value}static parseTableSourceFromLexemes(lexemes,index){let fullNameResult=FullNameParser.parseFromLexeme(lexemes,index);return this.parseTableSource(fullNameResult)}static parseFromLexeme(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&4)return this.parseParenSource(lexemes,idx);let fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx);return fullNameResult.lastTokenType&2048?_SourceParser.parseFunctionSource(lexemes,fullNameResult):_SourceParser.parseTableSource(fullNameResult)}static parseTableSource(fullNameResult){let{namespaces,name,newIndex}=fullNameResult,value=new TableSource(namespaces,name.name);return name.positionedComments&&name.positionedComments.length>0?value.positionedComments=name.positionedComments:name.comments&&name.comments.length>0&&(value.comments=name.comments),{value,newIndex}}static parseFunctionSource(lexemes,fullNameResult){let idx=fullNameResult.newIndex,{namespaces,name}=fullNameResult,argument=ValueParser.parseArgument(4,8,lexemes,idx);idx=argument.newIndex;let 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(`
|