rawsql-ts 0.24.1 → 0.24.2
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 +2 -2
- package/dist/esm/index.min.js.map +2 -2
- package/dist/esm/transformers/SqlFormatter.d.ts +7 -1
- package/dist/esm/transformers/SqlFormatter.js.map +1 -1
- package/dist/esm/transformers/SqlPrinter.d.ts +23 -2
- package/dist/esm/transformers/SqlPrinter.js +112 -28
- package/dist/esm/transformers/SqlPrinter.js.map +1 -1
- package/dist/index.min.js +2 -2
- package/dist/index.min.js.map +2 -2
- package/dist/src/transformers/SqlFormatter.d.ts +7 -1
- package/dist/src/transformers/SqlPrinter.d.ts +23 -2
- package/dist/transformers/SqlFormatter.js.map +1 -1
- package/dist/transformers/SqlPrinter.js +112 -28
- package/dist/transformers/SqlPrinter.js.map +1 -1
- package/dist/tsconfig.browser.tsbuildinfo +1 -1
- package/package.json +1 -1
package/dist/index.min.js
CHANGED
|
@@ -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,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:`
|
|
24
|
+
`,cr:"\r"},IDENTIFIER_ESCAPE_MAP={quote:{start:'"',end:'"'},backtick:{start:"`",end:"`"},bracket:{start:"[",end:"]"},none:{start:"",end:""}};function resolveIndentCharOption(option){if(option===void 0)return;let normalized=typeof option=="string"?option.toLowerCase():option;return typeof normalized=="string"&&Object.prototype.hasOwnProperty.call(INDENT_CHAR_MAP,normalized)?INDENT_CHAR_MAP[normalized]:option}function resolveNewlineOption(option){if(option===void 0)return;let normalized=typeof option=="string"?option.toLowerCase():option;return typeof normalized=="string"&&Object.prototype.hasOwnProperty.call(NEWLINE_MAP,normalized)?NEWLINE_MAP[normalized]:option}function resolveIdentifierEscapeOption(option,target="all"){if(option===void 0)return;if(typeof option=="string"){let normalized=option.toLowerCase();if(!Object.prototype.hasOwnProperty.call(IDENTIFIER_ESCAPE_MAP,normalized))throw new Error(`Unknown identifierEscape option: ${option}`);let mapped=IDENTIFIER_ESCAPE_MAP[normalized];return{start:mapped.start,end:mapped.end,target}}let start=option.start??"",end=option.end??"";return{start,end,target}}var OnelineFormattingHelper=class{constructor(options){this.options=options}shouldFormatContainer(token,shouldIndentNested){switch(token.containerType){case"ParenExpression":return this.options.parenthesesOneLine&&!shouldIndentNested;case"BetweenExpression":return this.options.betweenOneLine;case"Values":return this.options.valuesOneLine;case"JoinOnClause":return this.options.joinOneLine;case"CaseExpression":return this.options.caseOneLine;case"InlineQuery":return this.options.subqueryOneLine;default:return!1}}isInsertClauseOneline(parentContainerType){return this.options.insertColumnsOneLine?parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction":!1}shouldInsertJoinNewline(insideWithClause){return!(insideWithClause&&this.options.withClauseStyle==="full-oneline")}resolveCommaBreak(parentContainerType,commaBreak,cteCommaBreak,valuesCommaBreak){return parentContainerType==="WithClause"?cteCommaBreak:parentContainerType==="AnalyzeStatement"||parentContainerType==="ExplainStatement"?"none":parentContainerType==="Values"?valuesCommaBreak:this.isInsertClauseOneline(parentContainerType)?"none":commaBreak}shouldSkipInsertClauseSpace(parentContainerType,nextToken,currentLineText){if(!(parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction"))return!1;if(nextToken&&nextToken.type===4&&nextToken.text==="(")return!0;if(!this.options.insertColumnsOneLine)return!1;let lastChar=currentLineText.slice(-1);return lastChar==="("||lastChar===" "||lastChar===""}shouldSkipCommentBlockSpace(parentContainerType,insideWithClause){return parentContainerType==="CommentBlock"&&insideWithClause&&this.options.withClauseStyle==="full-oneline"}formatInsertClauseToken(text,parentContainerType,currentLineText,ensureTrailingSpace){if(!this.isInsertClauseOneline(parentContainerType))return{handled:!1};if(text==="")return{handled:!0};let leadingWhitespace=text.match(/^\s+/)?.[0]??"",trimmed=leadingWhitespace?text.slice(leadingWhitespace.length):text;if(trimmed==="")return{handled:!0};if(leadingWhitespace){let lastChar=currentLineText.slice(-1);lastChar!=="("&&lastChar!==" "&&lastChar!==""&&ensureTrailingSpace()}return{handled:!0,text:trimmed}}};var CREATE_TABLE_SINGLE_PAREN_KEYWORDS=new Set(["unique","check","key","index"]),CREATE_TABLE_MULTI_PAREN_KEYWORDS=new Set(["primary key","foreign key","unique key"]),CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER=new Set(["references"]),SqlPrinter=class _SqlPrinter{constructor(options){this.insideWithClause=!1;this.mergeWhenPredicateDepth=0;this.joinOnClauseDepth=0;this.expandedOneLineFallbackTokens=new WeakSet;this.pendingLineCommentBreak=null;this.smartCommentBlockBuilder=null;let resolvedIndentChar=resolveIndentCharOption(options?.indentChar),resolvedNewline=resolveNewlineOption(options?.newline);this.indentChar=resolvedIndentChar??"",this.indentSize=options?.indentSize??0,this.newline=resolvedNewline??" ",this.commaBreak=options?.commaBreak??"none",this.cteCommaBreak=options?.cteCommaBreak??this.commaBreak,this.valuesCommaBreak=options?.valuesCommaBreak??this.commaBreak,this.andBreak=options?.andBreak??"none",this.orBreak=options?.orBreak??"none",this.joinOnBreak=options?.joinOnBreak??"none",this.keywordCase=options?.keywordCase??"none",this.commentExportMode=this.resolveCommentExportMode(options?.exportComment),this.withClauseStyle=options?.withClauseStyle??"standard",this.commentStyle=options?.commentStyle??"block",this.parenthesesOneLine=options?.parenthesesOneLine??!1,this.betweenOneLine=options?.betweenOneLine??!1,this.valuesOneLine=options?.valuesOneLine??!1,this.joinOneLine=options?.joinOneLine??!1,this.caseOneLine=options?.caseOneLine??!1,this.subqueryOneLine=options?.subqueryOneLine??!1,this.indentNestedParentheses=options?.indentNestedParentheses??!1,this.insertColumnsOneLine=options?.insertColumnsOneLine??!1,this.whenOneLine=options?.whenOneLine??!1,this.oneLineMaxLength=this.normalizeOneLineMaxLength(options?.oneLineMaxLength),this.joinConditionContinuationIndent=options?.joinConditionContinuationIndent??!1;let onelineOptions={parenthesesOneLine:this.parenthesesOneLine,betweenOneLine:this.betweenOneLine,valuesOneLine:this.valuesOneLine,joinOneLine:this.joinOneLine,caseOneLine:this.caseOneLine,subqueryOneLine:this.subqueryOneLine,insertColumnsOneLine:this.insertColumnsOneLine,withClauseStyle:this.withClauseStyle};this.onelineHelper=new OnelineFormattingHelper(onelineOptions),this.linePrinter=new LinePrinter(this.indentChar,this.indentSize,this.newline,this.commaBreak),this.indentIncrementContainers=new Set(options?.indentIncrementContainerTypes??["SelectClause","ReturningClause","FromClause","WhereClause","GroupByClause","HavingClause","WindowFrameExpression","PartitionByClause","OrderByClause","WindowClause","LimitClause","OffsetClause","SubQuerySource","BinarySelectQueryOperator","Values","WithClause","SwitchCaseArgument","CaseKeyValuePair","CaseThenValue","ElseClause","CaseElseValue","SimpleSelectQuery","CreateTableDefinition","AlterTableStatement","IndexColumnList","SetClause"])}print(token,level=0){return this.linePrinter=new LinePrinter(this.indentChar,this.indentSize,this.newline,this.commaBreak),this.insideWithClause=!1,this.joinOnClauseDepth=0,this.pendingLineCommentBreak=null,this.smartCommentBlockBuilder=null,this.expandedOneLineFallbackTokens=new WeakSet,this.linePrinter.lines.length>0&&level!==this.linePrinter.lines[0].level&&(this.linePrinter.lines[0].level=level),this.appendToken(token,level,void 0,0,!1,void 0,!1),this.linePrinter.print()}resolveCommentExportMode(option){return option===void 0?"none":option===!0?"full":option===!1?"none":option}rendersInlineComments(){return this.commentExportMode==="full"}shouldRenderComment(token,context){if(context?.forceRender)return this.commentExportMode!=="none";switch(this.commentExportMode){case"full":return!0;case"none":return!1;case"header-only":return token.isHeaderComment===!0;case"top-header-only":return token.isHeaderComment===!0&&!!context?.isTopLevelContainer;default:return!1}}appendToken(token,level,parentContainerType,caseContextDepth=0,indentParentActive=!1,commentContext,previousSiblingWasOpenParen=!1){let wasInsideWithClause=this.insideWithClause;if(token.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"&&(this.insideWithClause=!0),this.shouldSkipToken(token))return;let containerIsTopLevel=parentContainerType===void 0,leadingCommentCount=0,leadingCommentContexts=[];if(token.innerTokens&&token.innerTokens.length>0)for(;leadingCommentCount<token.innerTokens.length;){let leadingCandidate=token.innerTokens[leadingCommentCount];if(leadingCandidate.containerType!=="CommentBlock")break;let context={position:"leading",isTopLevelContainer:containerIsTopLevel},shouldRender=this.shouldRenderComment(leadingCandidate,context);leadingCommentContexts.push({token:leadingCandidate,context,shouldRender}),leadingCommentCount++}let hasRenderableLeadingComment=leadingCommentContexts.some(item=>item.shouldRender),leadingCommentIndentLevel=hasRenderableLeadingComment?this.getLeadingCommentIndentLevel(parentContainerType,level):null;hasRenderableLeadingComment&&!this.isOnelineMode()&&this.shouldAddNewlineBeforeLeadingComments(parentContainerType)&&this.linePrinter.getCurrentLine().text.trim().length>0&&this.linePrinter.appendNewline(leadingCommentIndentLevel??level);for(let leading of leadingCommentContexts)leading.shouldRender&&this.appendToken(leading.token,leadingCommentIndentLevel??level,token.containerType,caseContextDepth,indentParentActive,leading.context,!1);if(this.smartCommentBlockBuilder&&token.containerType!=="CommentBlock"&&token.type!==12&&this.flushSmartCommentBlockBuilder(),this.pendingLineCommentBreak!==null){this.isOnelineMode()||this.linePrinter.appendNewline(this.pendingLineCommentBreak);let shouldSkipToken=token.type===12;if(this.pendingLineCommentBreak=null,shouldSkipToken)return}let effectiveCommentContext=commentContext??{position:"inline",isTopLevelContainer:containerIsTopLevel};if(token.containerType==="CommentBlock"){if(!this.shouldRenderComment(token,effectiveCommentContext))return;let commentLevel=this.getCommentBaseIndentLevel(level,parentContainerType);this.handleCommentBlockContainer(token,commentLevel,effectiveCommentContext);return}let current=this.linePrinter.getCurrentLine(),nextCaseContextDepth=this.isCaseContext(token.containerType)?caseContextDepth+1:caseContextDepth,shouldIndentNested=this.shouldIndentNestedParentheses(token,previousSiblingWasOpenParen);if(token.type===1)this.handleKeywordToken(token,level,parentContainerType,caseContextDepth);else if(token.type===3)this.handleCommaToken(token,level,parentContainerType);else if(token.type===4)this.handleParenthesisToken(token,level,indentParentActive,parentContainerType);else if(token.type===5&&token.text.toLowerCase()==="and")this.handleAndOperatorToken(token,level,parentContainerType,caseContextDepth);else if(token.type===5&&token.text.toLowerCase()==="or")this.handleOrOperatorToken(token,level,parentContainerType,caseContextDepth);else if(token.containerType==="JoinClause")this.handleJoinClauseToken(token,level);else if(token.type===6){if(this.shouldRenderComment(token,effectiveCommentContext)){let commentLevel=this.getCommentBaseIndentLevel(level,parentContainerType);this.printCommentToken(token.text,commentLevel,parentContainerType)}}else if(token.type===10)this.handleSpaceToken(token,parentContainerType);else if(token.type===12){if(this.whenOneLine&&parentContainerType==="MergeWhenClause")return;let commentLevel=this.getCommentBaseIndentLevel(level,parentContainerType);this.handleCommentNewlineToken(token,commentLevel)}else if(token.containerType==="CommonTable"&&this.withClauseStyle==="cte-oneline"){if(this.tryHandleCteOnelineToken(token,level))return}else{if(this.shouldFormatContainerAsOneline(token,shouldIndentNested)&&this.tryHandleOnelineToken(token,level))return;this.tryAppendInsertClauseTokenText(token.text,parentContainerType)||this.linePrinter.appendText(token.text)}if(token.containerType==="JoinOnClause"&&this.joinOnBreak==="before"&&!this.isOnelineMode()&&this.linePrinter.getCurrentLine().text.trim().length>0&&this.linePrinter.appendNewline(level+1),this.expandedOneLineFallbackTokens.has(token)&&(shouldIndentNested=!0),token.keywordTokens&&token.keywordTokens.length>0)for(let i=0;i<token.keywordTokens.length;i++){let keywordToken=token.keywordTokens[i];this.appendToken(keywordToken,level,token.containerType,nextCaseContextDepth,indentParentActive,void 0,!1)}let innerLevel=level,increasedIndent=!1,shouldIncreaseIndent=this.indentIncrementContainers.has(token.containerType)||shouldIndentNested,delayIndentNewline=shouldIndentNested&&token.containerType==="ParenExpression",isAlterTableStatement=token.containerType==="AlterTableStatement",deferAlterTableIndent=!1;if(token.containerType==="JoinOnClause"&&this.joinOnBreak==="before"&&!this.isOnelineMode()&&(innerLevel=level+1),this.shouldAlignExplainStatementChild(parentContainerType,token.containerType))!this.isOnelineMode()&¤t.text!==""&&this.linePrinter.appendNewline(level),innerLevel=level,increasedIndent=!1;else if(!this.isOnelineMode()&&shouldIncreaseIndent&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline"))if(delayIndentNewline)innerLevel=level+1,increasedIndent=!0;else if(current.text!=="")if(isAlterTableStatement)innerLevel=level+1,increasedIndent=!0,deferAlterTableIndent=!0;else{let targetIndentLevel=level+1;token.containerType==="SetClause"&&parentContainerType==="MergeUpdateAction"&&(targetIndentLevel=level+2),this.shouldAlignCreateTableSelect(token.containerType,parentContainerType)?(innerLevel=level,increasedIndent=!1,this.linePrinter.appendNewline(level)):(innerLevel=targetIndentLevel,increasedIndent=!0,this.linePrinter.appendNewline(innerLevel))}else token.containerType==="SetClause"&&(innerLevel=parentContainerType==="MergeUpdateAction"?level+2:level+1,increasedIndent=!0,current.level=innerLevel);let isMergeWhenClause=this.whenOneLine&&token.containerType==="MergeWhenClause",mergePredicateActive=isMergeWhenClause,alterTableTableRendered=!1,alterTableIndentInserted=!1,enteredJoinOnClause=token.containerType==="JoinOnClause";enteredJoinOnClause&&this.joinOnClauseDepth++;for(let i=leadingCommentCount;i<token.innerTokens.length;i++){let child=token.innerTokens[i],nextChild=token.innerTokens[i+1],previousEntry=this.findPreviousSignificantToken(token.innerTokens,i),previousChild=previousEntry?.token,priorChild=(previousEntry?this.findPreviousSignificantToken(token.innerTokens,previousEntry.index):void 0)?.token,childIsAction=this.isMergeActionContainer(child),nextIsAction=this.isMergeActionContainer(nextChild),inMergePredicate=mergePredicateActive&&!childIsAction;if(isAlterTableStatement){if(child.containerType==="QualifiedName")alterTableTableRendered=!0;else if(deferAlterTableIndent&&alterTableTableRendered&&!alterTableIndentInserted&&(this.isOnelineMode()||this.linePrinter.appendNewline(innerLevel),alterTableIndentInserted=!0,deferAlterTableIndent=!1,!this.isOnelineMode()&&child.type===10))continue}if(child.type===10){if(this.shouldConvertSpaceToClauseBreak(token.containerType,nextChild)){if(!this.isOnelineMode()){let clauseBreakIndent=this.getClauseBreakIndentLevel(token.containerType,innerLevel);this.linePrinter.appendNewline(clauseBreakIndent)}isMergeWhenClause&&nextIsAction&&(mergePredicateActive=!1);continue}this.handleSpaceToken(child,token.containerType,nextChild,previousChild,priorChild);continue}let previousChildWasOpenParen=previousChild?.type===4&&previousChild.text.trim()==="(",childIndentParentActive=token.containerType==="ParenExpression"?shouldIndentNested:indentParentActive;inMergePredicate&&this.mergeWhenPredicateDepth++;let childCommentContext=child.containerType==="CommentBlock"?{position:"inline",isTopLevelContainer:containerIsTopLevel}:void 0;this.appendToken(child,innerLevel,token.containerType,nextCaseContextDepth,childIndentParentActive,childCommentContext,previousChildWasOpenParen),inMergePredicate&&this.mergeWhenPredicateDepth--,childIsAction&&isMergeWhenClause&&(mergePredicateActive=!1)}if(this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder(),enteredJoinOnClause&&this.joinOnClauseDepth--,token.containerType==="WithClause"&&this.withClauseStyle==="full-oneline"){this.insideWithClause=!1,this.linePrinter.appendNewline(level);return}increasedIndent&&shouldIncreaseIndent&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&!delayIndentNewline&&this.linePrinter.appendNewline(level)}shouldAlignExplainStatementChild(parentType,childType){if(parentType!=="ExplainStatement")return!1;switch(childType){case"SimpleSelectQuery":case"InsertQuery":case"UpdateQuery":case"DeleteQuery":case"MergeQuery":return!0;default:return!1}}isCaseContext(containerType){switch(containerType){case"CaseExpression":case"CaseKeyValuePair":case"CaseThenValue":case"CaseElseValue":case"SwitchCaseArgument":return!0;default:return!1}}shouldSkipToken(token){return token.type===12?!1:(!token.innerTokens||token.innerTokens.length===0)&&token.text===""}applyKeywordCase(text){return this.keywordCase==="upper"?text.toUpperCase():this.keywordCase==="lower"?text.toLowerCase():text}handleKeywordToken(token,level,parentContainerType,caseContextDepth=0){let lower=token.text.toLowerCase();if(lower==="and"&&(this.andBreak!=="none"||this.whenOneLine&&parentContainerType==="MergeWhenClause")){this.handleAndOperatorToken(token,level,parentContainerType,caseContextDepth);return}else if(lower==="or"&&(this.orBreak!=="none"||this.whenOneLine&&parentContainerType==="MergeWhenClause")){this.handleOrOperatorToken(token,level,parentContainerType,caseContextDepth);return}let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}this.ensureSpaceBeforeKeyword(),this.linePrinter.appendText(text)}ensureSpaceBeforeKeyword(){let currentLine=this.linePrinter.getCurrentLine();currentLine.text===""||currentLine.text[currentLine.text.length-1]==="("||this.ensureTrailingSpace()}ensureTrailingSpace(){let currentLine=this.linePrinter.getCurrentLine();currentLine.text!==""&&(currentLine.text.endsWith(" ")||(currentLine.text+=" "),currentLine.text=currentLine.text.replace(/\s+$/," "))}tryAppendInsertClauseTokenText(text,parentContainerType){let currentLineText=this.linePrinter.getCurrentLine().text,result=this.onelineHelper.formatInsertClauseToken(text,parentContainerType,currentLineText,()=>this.ensureTrailingSpace());return result.handled?(result.text&&this.linePrinter.appendText(result.text),!0):!1}handleCommaToken(token,level,parentContainerType){let text=token.text,isWithinWithClause=parentContainerType==="WithClause",effectiveCommaBreak=this.onelineHelper.resolveCommaBreak(parentContainerType,this.commaBreak,this.cteCommaBreak,this.valuesCommaBreak);if(parentContainerType==="SetClause"&&(effectiveCommaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline")this.linePrinter.appendText(text);else if(this.withClauseStyle==="cte-oneline"&&isWithinWithClause)this.linePrinter.appendText(text),this.linePrinter.appendNewline(level);else if(effectiveCommaBreak==="before"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="before"&&(this.linePrinter.commaBreak="before"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||(this.linePrinter.appendNewline(level),this.newline===" "&&this.linePrinter.trimTrailingWhitespaceFromPreviousLine(),parentContainerType==="InsertClause"&&(this.linePrinter.getCurrentLine().level=level+1)),this.linePrinter.appendText(text),previousCommaBreak!=="before"&&(this.linePrinter.commaBreak=previousCommaBreak)}else if(effectiveCommaBreak==="after"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="after"&&(this.linePrinter.commaBreak="after"),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(level),previousCommaBreak!=="after"&&(this.linePrinter.commaBreak=previousCommaBreak)}else if(effectiveCommaBreak==="none"){let previousCommaBreak=this.linePrinter.commaBreak;previousCommaBreak!=="none"&&(this.linePrinter.commaBreak="none"),this.linePrinter.appendText(text),this.onelineHelper.isInsertClauseOneline(parentContainerType)&&this.ensureTrailingSpace(),previousCommaBreak!=="none"&&(this.linePrinter.commaBreak=previousCommaBreak)}else this.linePrinter.appendText(text)}handleAndOperatorToken(token,level,parentContainerType,caseContextDepth=0){let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}if(this.whenOneLine&&(parentContainerType==="MergeWhenClause"||this.mergeWhenPredicateDepth>0)){this.linePrinter.appendText(text);return}this.andBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(this.getJoinConditionContinuationLevel(level)),this.linePrinter.appendText(text)):this.andBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(this.getJoinConditionContinuationLevel(level))):this.linePrinter.appendText(text)}handleParenthesisToken(token,level,indentParentActive,parentContainerType){if(token.text==="("){if(this.linePrinter.appendText(token.text),(parentContainerType==="InsertClause"||parentContainerType==="MergeInsertAction")&&this.insertColumnsOneLine)return;this.isOnelineMode()||(this.shouldBreakAfterOpeningParen(parentContainerType)?this.linePrinter.appendNewline(level+1):indentParentActive&&parentContainerType==="ParenExpression"&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")&&this.linePrinter.appendNewline(level));return}if(token.text===")"&&!this.isOnelineMode()){if(this.shouldBreakBeforeClosingParen(parentContainerType)){this.linePrinter.appendNewline(Math.max(level,0)),this.linePrinter.appendText(token.text);return}if(indentParentActive&&parentContainerType==="ParenExpression"&&!(this.insideWithClause&&this.withClauseStyle==="full-oneline")){let closingLevel=Math.max(level-1,0);this.linePrinter.appendNewline(closingLevel)}}this.linePrinter.appendText(token.text)}handleOrOperatorToken(token,level,parentContainerType,caseContextDepth=0){let text=this.applyKeywordCase(token.text);if(caseContextDepth>0){this.linePrinter.appendText(text);return}if(this.whenOneLine&&(parentContainerType==="MergeWhenClause"||this.mergeWhenPredicateDepth>0)){this.linePrinter.appendText(text);return}this.orBreak==="before"?(this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(this.getJoinConditionContinuationLevel(level)),this.linePrinter.appendText(text)):this.orBreak==="after"?(this.linePrinter.appendText(text),this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.linePrinter.appendNewline(this.getJoinConditionContinuationLevel(level))):this.linePrinter.appendText(text)}getJoinConditionContinuationLevel(level){return this.joinOnClauseDepth===0||this.joinOnBreak==="before"?level:this.joinConditionContinuationIndent?level+1:level}shouldIndentNestedParentheses(token,previousSiblingWasOpenParen=!1){return!this.indentNestedParentheses||token.containerType!=="ParenExpression"?!1:this.expandedOneLineFallbackTokens.has(token)?!0:previousSiblingWasOpenParen||token.innerTokens.some(child=>this.containsParenExpression(child))}containsParenExpression(token){if(token.containerType==="ParenExpression")return!0;for(let child of token.innerTokens)if(this.containsParenExpression(child))return!0;return!1}handleJoinClauseToken(token,level){let text=this.applyKeywordCase(token.text);this.onelineHelper.shouldInsertJoinNewline(this.insideWithClause)&&this.linePrinter.appendNewline(level),this.linePrinter.appendText(text)}shouldFormatContainerAsOneline(token,shouldIndentNested){return this.onelineHelper.shouldFormatContainer(token,shouldIndentNested)}isInsertClauseOneline(parentContainerType){return this.onelineHelper.isInsertClauseOneline(parentContainerType)}handleSpaceToken(token,parentContainerType,nextToken,previousToken,priorToken){this.smartCommentBlockBuilder&&this.smartCommentBlockBuilder.mode==="line"&&this.flushSmartCommentBlockBuilder();let currentLineText=this.linePrinter.getCurrentLine().text;if(!this.onelineHelper.shouldSkipInsertClauseSpace(parentContainerType,nextToken,currentLineText)){if(this.onelineHelper.shouldSkipCommentBlockSpace(parentContainerType,this.insideWithClause)){let currentLine=this.linePrinter.getCurrentLine();currentLine.text!==""&&!currentLine.text.endsWith(" ")&&this.linePrinter.appendText(" ");return}this.shouldSkipSpaceBeforeParenthesis(parentContainerType,nextToken,previousToken,priorToken)||this.linePrinter.appendText(token.text)}}findPreviousSignificantToken(tokens,index){for(let i=index-1;i>=0;i--){let candidate=tokens[i];if(!(candidate.type===10||candidate.type===12)&&!(candidate.type===6&&!this.rendersInlineComments()))return{token:candidate,index:i}}}shouldSkipSpaceBeforeParenthesis(parentContainerType,nextToken,previousToken,priorToken){return!nextToken||nextToken.type!==4||nextToken.text!=="("||!parentContainerType||!this.isCreateTableSpacingContext(parentContainerType)||!previousToken?!1:!!(this.isCreateTableNameToken(previousToken,parentContainerType)||this.isCreateTableConstraintKeyword(previousToken,parentContainerType)||priorToken&&this.isCreateTableConstraintKeyword(priorToken,parentContainerType)&&this.isIdentifierAttachedToConstraint(previousToken,priorToken,parentContainerType))}shouldAlignCreateTableSelect(containerType,parentContainerType){return containerType==="SimpleSelectQuery"&&parentContainerType==="CreateTableQuery"}isCreateTableSpacingContext(parentContainerType){switch(parentContainerType){case"CreateTableQuery":case"CreateTableDefinition":case"TableConstraintDefinition":case"ColumnConstraintDefinition":case"ReferenceDefinition":return!0;default:return!1}}isCreateTableNameToken(previousToken,parentContainerType){return parentContainerType!=="CreateTableQuery"?!1:previousToken.containerType==="QualifiedName"}isCreateTableConstraintKeyword(token,parentContainerType){if(token.type!==1)return!1;let text=token.text.toLowerCase();return parentContainerType==="ReferenceDefinition"?CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER.has(text):!!(CREATE_TABLE_SINGLE_PAREN_KEYWORDS.has(text)||CREATE_TABLE_MULTI_PAREN_KEYWORDS.has(text))}isIdentifierAttachedToConstraint(token,keywordToken,parentContainerType){if(!token)return!1;if(parentContainerType==="ReferenceDefinition")return token.containerType==="QualifiedName"&&CREATE_TABLE_PAREN_KEYWORDS_WITH_IDENTIFIER.has(keywordToken.text.toLowerCase());if(parentContainerType==="TableConstraintDefinition"||parentContainerType==="ColumnConstraintDefinition"){let normalized=keywordToken.text.toLowerCase();if(CREATE_TABLE_SINGLE_PAREN_KEYWORDS.has(normalized)||CREATE_TABLE_MULTI_PAREN_KEYWORDS.has(normalized))return token.containerType==="IdentifierString"}return!1}printCommentToken(text,level,parentContainerType){let trimmed=text.trim();if(trimmed&&!(this.commentStyle==="smart"&&parentContainerType==="CommentBlock"&&this.handleSmartCommentBlockToken(text,trimmed,level)))if(this.commentStyle==="smart"){let normalized=this.normalizeCommentForSmart(trimmed);if(normalized.lines.length>1||normalized.forceBlock){let blockText=this.buildBlockComment(normalized.lines,level);this.linePrinter.appendText(blockText)}else{let content=normalized.lines[0],lineText=content?`-- ${content}`:"--";if(parentContainerType==="CommentBlock")this.linePrinter.appendText(lineText),this.pendingLineCommentBreak=this.resolveCommentIndentLevel(level,parentContainerType);else{this.linePrinter.appendText(lineText);let effectiveLevel=this.resolveCommentIndentLevel(level,parentContainerType);this.linePrinter.appendNewline(effectiveLevel)}}}else{if(trimmed.startsWith("/*")&&trimmed.endsWith("*/"))if(/\r?\n/.test(trimmed)){let newlineReplacement=this.isOnelineMode()?" ":typeof this.newline=="string"?this.newline:`
|
|
25
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,options.identifierEscapeTarget??"all"),parserOptions={...presetConfig,identifierEscape:resolvedIdentifierEscape??presetConfig?.identifierEscape,parameterSymbol:options.parameterSymbol??presetConfig?.parameterSymbol,parameterStyle:options.parameterStyle??presetConfig?.parameterStyle,castStyle:options.castStyle??presetConfig?.castStyle,sourceAliasStyle:options.sourceAliasStyle??presetConfig?.sourceAliasStyle,orderByDefaultDirectionStyle:options.orderByDefaultDirectionStyle??presetConfig?.orderByDefaultDirectionStyle,joinConditionOrderByDeclaration:options.joinConditionOrderByDeclaration},constraintStyle=options.constraintStyle??presetConfig?.constraintStyle??"postgres",parserConfig={...parserOptions,constraintStyle};this.parser=new SqlPrintTokenParser({...parserConfig});let normalizedExportComment=options.exportComment===!0?"full":options.exportComment===!1?"none":options.exportComment,printerOptions={...options,exportComment:normalizedExportComment,parenthesesOneLine:options.parenthesesOneLine,betweenOneLine:options.betweenOneLine,valuesOneLine:options.valuesOneLine,joinOneLine:options.joinOneLine,caseOneLine:options.caseOneLine,subqueryOneLine:options.subqueryOneLine,indentNestedParentheses:options.indentNestedParentheses};this.printer=new SqlPrinter(printerOptions)}format(sql){let{token,params}=this.parser.parse(sql);return{formattedSql:this.printer.print(token),params}}};var Formatter=class{constructor(){this.sqlFormatter=new SqlFormatter({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(arg,config=null){return config&&(this.sqlFormatter=new SqlFormatter(config)),this.sqlFormatter.format(arg).formattedSql}formatWithParameters(arg,config=null){config&&(this.sqlFormatter=new SqlFormatter(config));let result=this.sqlFormatter.format(arg);return{sql:result.formattedSql,params:result.params}}visit(arg){return this.format(arg)}};var CTEBuilder=class{constructor(){this.sourceCollector=new TableSourceCollector(!0),this.cteCollector=new CTECollector,this.formatter=new Formatter}build(commonTables){if(commonTables.length===0)return new WithClause(!1,commonTables);let resolvedTables=this.resolveDuplicateNames(commonTables),{tableMap,recursiveCTEs,dependencies}=this.buildDependencyGraph(resolvedTables),sortedTables=this.sortCommonTables(resolvedTables,tableMap,recursiveCTEs,dependencies);return new WithClause(recursiveCTEs.size>0,sortedTables)}resolveDuplicateNames(commonTables){let ctesByName=new Map;for(let table of commonTables){let tableName=table.aliasExpression.table.name;ctesByName.has(tableName)||ctesByName.set(tableName,[]),ctesByName.get(tableName).push(table)}let resolvedTables=[];for(let[name,tables]of Array.from(ctesByName.entries())){if(tables.length===1){resolvedTables.push(tables[0]);continue}let definitions=tables.map(table=>this.formatter.format(table.query));if(new Set(definitions).size===1)resolvedTables.push(tables[0]);else throw new Error(`CTE name conflict detected: '${name}' has multiple different definitions`)}return resolvedTables}buildDependencyGraph(tables){let tableMap=new Map;for(let table of tables)tableMap.set(table.aliasExpression.table.name,table);let recursiveCTEs=new Set,dependencies=new Map,referencedBy=new Map;for(let table of tables){let tableName=table.aliasExpression.table.name,referencedTables=this.sourceCollector.collect(table.query);for(let referencedTable of referencedTables)if(referencedTable.table.name===tableName){recursiveCTEs.add(tableName);break}dependencies.has(tableName)||dependencies.set(tableName,new Set);let referencedCTEs=this.cteCollector.collect(table.query);for(let referencedCTE of referencedCTEs){let referencedName=referencedCTE.aliasExpression.table.name;tableMap.has(referencedName)&&(dependencies.get(tableName).add(referencedName),referencedBy.has(referencedName)||referencedBy.set(referencedName,new Set),referencedBy.get(referencedName).add(tableName))}}return{tableMap,recursiveCTEs,dependencies}}sortCommonTables(tables,tableMap,recursiveCTEs,dependencies){let recursiveResult=[],nonRecursiveResult=[],visited=new Set,visiting=new Set,visit=tableName=>{if(visited.has(tableName))return;if(visiting.has(tableName))throw new Error(`Circular reference detected in CTE: ${tableName}`);visiting.add(tableName);let deps=dependencies.get(tableName)||new Set;for(let dep of Array.from(deps))visit(dep);visiting.delete(tableName),visited.add(tableName),recursiveCTEs.has(tableName)?recursiveResult.push(tableMap.get(tableName)):nonRecursiveResult.push(tableMap.get(tableName))};for(let table of tables){let tableName=table.aliasExpression.table.name;visited.has(tableName)||visit(tableName)}return[...recursiveResult,...nonRecursiveResult]}};var CTEInjector=class{constructor(){this.nameConflictResolver=new CTEBuilder,this.cteCollector=new CTECollector}inject(query,commonTables){if(commonTables.length===0)return query;commonTables.push(...this.cteCollector.collect(query));let resolvedWithCaluse=this.nameConflictResolver.build(commonTables);if(query instanceof SimpleSelectQuery)return this.injectIntoSimpleQuery(query,resolvedWithCaluse);if(query instanceof BinarySelectQuery)return this.injectIntoBinaryQuery(query,resolvedWithCaluse);throw new Error("Unsupported query type")}injectIntoSimpleQuery(query,withClause){if(query.withClause)throw new Error("The query already has a WITH clause. Please remove it before injecting new CTEs.");return query.withClause=withClause,query}injectIntoBinaryQuery(query,withClause){if(query.left instanceof SimpleSelectQuery)return this.injectIntoSimpleQuery(query.left,withClause),query;if(query.left instanceof BinarySelectQuery)return this.injectIntoBinaryQuery(query.left,withClause),query;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var CTENormalizer=class{constructor(){}static normalize(query){let allCommonTables=new CTECollector().collect(query);return allCommonTables.length===0?query:(new CTEDisabler().execute(query),new CTEInjector().inject(query,allCommonTables))}};var DuplicateDetectionMode=(DuplicateDetectionMode2=>(DuplicateDetectionMode2.ColumnNameOnly="columnNameOnly",DuplicateDetectionMode2.FullName="fullName",DuplicateDetectionMode2))(DuplicateDetectionMode||{}),SelectableColumnCollector=class _SelectableColumnCollector{constructor(tableColumnResolver,includeWildCard=!1,duplicateDetection="columnNameOnly",options){this.selectValues=[];this.visitedNodes=new Set;this.uniqueKeys=new Set;this.isRootVisit=!0;this.tableColumnResolver=null;this.commonTables=[];this.initializeProperties(tableColumnResolver,includeWildCard,duplicateDetection,options),this.initializeHandlers()}initializeProperties(tableColumnResolver,includeWildCard,duplicateDetection,options){this.tableColumnResolver=tableColumnResolver??null,this.includeWildCard=includeWildCard,this.commonTableCollector=new CTECollector,this.commonTables=[],this.duplicateDetection=duplicateDetection,this.options=options||{}}initializeHandlers(){this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.initializeClauseHandlers(),this.initializeValueComponentHandlers()}initializeClauseHandlers(){this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.offsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr))}initializeValueComponentHandlers(){this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}getValues(){return this.selectValues}collect(arg){if(!arg)throw new Error("Input argument cannot be null or undefined");this.visit(arg);let items=this.getValues();return this.reset(),items}reset(){this.selectValues=[],this.visitedNodes.clear(),this.uniqueKeys.clear(),this.commonTables=[]}addSelectValueAsUnique(name,value){let key=this.generateUniqueKey(name,value);this.uniqueKeys.has(key)||(this.uniqueKeys.add(key),this.selectValues.push({name,value}))}generateUniqueKey(name,value){if(this.duplicateDetection==="columnNameOnly")return this.normalizeColumnName(name);{let tableName="";value&&typeof value.getNamespace=="function"&&(tableName=value.getNamespace()||"");let fullName=tableName?tableName+"."+name:name;return this.normalizeColumnName(fullName)}}normalizeColumnName(name){if(typeof name!="string")throw new Error("Column name must be a string");return this.options.ignoreCaseAndUnderscore?name.toLowerCase().replace(/_/g,""):name}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}if(!(arg instanceof SimpleSelectQuery||arg instanceof BinarySelectQuery))throw new Error("Root visit requires a SimpleSelectQuery or BinarySelectQuery.");this.reset(),this.isRootVisit=!1,this.commonTables=this.commonTableCollector.collect(arg);try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(!this.visitedNodes.has(arg)){this.visitedNodes.add(arg);try{let handler=this.handlers.get(arg.getKind());handler&&handler(arg)}catch(error){let errorMessage=error instanceof Error?error.message:String(error);throw new Error(`Error processing SQL component of type ${arg.getKind().toString()}: ${errorMessage}`)}}}visitSimpleSelectQuery(query){if(query.selectClause&&query.selectClause.accept(this),query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.orderByClause&&query.orderByClause.accept(this),query.limitClause&&query.limitClause.accept(this),query.offsetClause&&query.offsetClause.accept(this),query.fetchClause&&query.fetchClause.accept(this),query.forClause&&query.forClause.accept(this)}visitBinarySelectQuery(query){query.left instanceof SimpleSelectQuery?this.visitSimpleSelectQuery(query.left):query.left instanceof BinarySelectQuery&&this.visitBinarySelectQuery(query.left),query.right instanceof SimpleSelectQuery?this.visitSimpleSelectQuery(query.right):query.right instanceof BinarySelectQuery&&this.visitBinarySelectQuery(query.right)}visitSelectClause(clause){for(let item of clause.items)if(item.identifier)this.addSelectValueAsUnique(item.identifier.name,item.value);else if(item.value instanceof ColumnReference){let columnName=item.value.column.name;columnName!=="*"?this.addSelectValueAsUnique(columnName,item.value):this.includeWildCard&&this.addSelectValueAsUnique(columnName,item.value)}else item.value.accept(this)}visitFromClause(clause){let sourceValues=new SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(clause);for(let item of sourceValues)this.addSelectValueAsUnique(item.name,item.value);if(this.options.upstream&&this.collectUpstreamColumns(clause),clause.joins)for(let join of clause.joins)join.condition&&join.condition.accept(this)}visitWhereClause(clause){clause.condition&&clause.condition.accept(this)}visitGroupByClause(clause){if(clause.grouping)for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition&&clause.condition.accept(this)}visitOrderByClause(clause){if(clause.order)for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitWindowFrameExpression(expr){expr.partition&&expr.partition.accept(this),expr.order&&expr.order.accept(this),expr.frameSpec&&expr.frameSpec.accept(this)}visitLimitClause(clause){clause.value&&clause.value.accept(this)}offsetClause(clause){clause.value&&clause.value.accept(this)}visitFetchClause(clause){clause.expression&&clause.expression.accept(this)}visitJoinOnClause(joinOnClause){joinOnClause.condition&&joinOnClause.condition.accept(this)}visitJoinUsingClause(joinUsingClause){joinUsingClause.condition&&joinUsingClause.condition.accept(this)}visitColumnReference(columnRef){if(columnRef.column.name!=="*")this.addSelectValueAsUnique(columnRef.column.name,columnRef);else if(this.includeWildCard)this.addSelectValueAsUnique(columnRef.column.name,columnRef);else return}visitBinaryExpression(expr){expr.left&&expr.left.accept(this),expr.right&&expr.right.accept(this)}visitJsonPredicateExpression(expr){expr.expression.accept(this)}visitUnaryExpression(expr){expr.expression&&expr.expression.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this),func.withinGroup&&func.withinGroup.accept(this),func.internalOrderBy&&func.internalOrderBy.accept(this)}visitInlineQuery(inlineQuery){inlineQuery.selectQuery&&this.visitNode(inlineQuery.selectQuery)}visitParenExpression(expr){expr.expression&&expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase&&expr.switchCase.accept(this)}visitCastExpression(expr){expr.input&&expr.input.accept(this)}visitBetweenExpression(expr){expr.expression&&expr.expression.accept(this),expr.lower&&expr.lower.accept(this),expr.upper&&expr.upper.accept(this)}visitArrayExpression(expr){expr.expression&&expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitArraySliceExpression(expr){expr.array&&expr.array.accept(this),expr.startIndex&&expr.startIndex.accept(this),expr.endIndex&&expr.endIndex.accept(this)}visitArrayIndexExpression(expr){expr.array&&expr.array.accept(this),expr.index&&expr.index.accept(this)}visitValueList(expr){if(expr.values&&Array.isArray(expr.values))for(let value of expr.values)value&&value.accept(this)}visitPartitionByClause(clause){clause.value.accept(this)}collectUpstreamColumns(clause){if(this.collectAllAvailableCTEColumns(),this.collectUpstreamColumnsFromSource(clause.source),clause.joins)for(let join of clause.joins)this.collectUpstreamColumnsFromSource(join.source)}collectUpstreamColumnsFromSource(source){if(source.datasource instanceof TableSource){let cteTable=this.findCTEByName(source.datasource.table.name);cteTable?this.collectUpstreamColumnsFromCTE(cteTable):this.collectUpstreamColumnsFromTable(source.datasource)}else source.datasource instanceof SubQuerySource?this.collectUpstreamColumnsFromSubquery(source.datasource):source.datasource instanceof ParenSource&&this.collectUpstreamColumnsFromSource(new SourceExpression(source.datasource.source,null))}collectUpstreamColumnsFromTable(tableSource){if(this.tableColumnResolver){let tableName=tableSource.table.name,columns=this.tableColumnResolver(tableName);for(let columnName of columns){let columnRef=new ColumnReference(tableSource.table.name,columnName);this.addSelectValueAsUnique(columnName,columnRef)}}}collectUpstreamColumnsFromSubquery(subquerySource){if(subquerySource.query instanceof SimpleSelectQuery){let subqueryColumns=new _SelectableColumnCollector(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!0}).collect(subquerySource.query);for(let item of subqueryColumns)this.addSelectValueAsUnique(item.name,item.value)}}collectUpstreamColumnsFromCTE(cteTable){if(cteTable.query instanceof SimpleSelectQuery){let cteColumns=new _SelectableColumnCollector(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!1}).collect(cteTable.query);for(let item of cteColumns)item.name!=="*"&&this.addSelectValueAsUnique(item.name,item.value)}}collectAllAvailableCTEColumns(){for(let cte of this.commonTables)this.collectUpstreamColumnsFromCTE(cte)}findCTEByName(name){return this.commonTables.find(cte=>cte.getSourceAliasName()===name)||null}};var SourceParser=class _SourceParser{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The source component is complete but there are additional tokens.`);return result.value}static parseTableSourceFromLexemes(lexemes,index){let fullNameResult=FullNameParser.parseFromLexeme(lexemes,index);return this.parseTableSource(fullNameResult)}static parseFromLexeme(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&4)return this.parseParenSource(lexemes,idx);let fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx);return fullNameResult.lastTokenType&2048?_SourceParser.parseFunctionSource(lexemes,fullNameResult):_SourceParser.parseTableSource(fullNameResult)}static parseTableSource(fullNameResult){let{namespaces,name,newIndex}=fullNameResult,value=new TableSource(namespaces,name.name);return name.positionedComments&&name.positionedComments.length>0?value.positionedComments=name.positionedComments:name.comments&&name.comments.length>0&&(value.comments=name.comments),{value,newIndex}}static parseFunctionSource(lexemes,fullNameResult){let idx=fullNameResult.newIndex,{namespaces,name}=fullNameResult,argument=ValueParser.parseArgument(4,8,lexemes,idx);idx=argument.newIndex;let withOrdinality=!1;idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++);let functionName=name.name;return{value:new FunctionSource({namespaces,name:functionName},argument.value,withOrdinality),newIndex:idx}}static parseParenSource(lexemes,index){let idx=index,openParenToken=lexemes[idx];if(idx++,idx>=lexemes.length)throw new Error(`Syntax error: Unexpected end of input at position ${idx}. Expected a subquery or nested expression after opening parenthesis.`);let keyword=lexemes[idx].value;if(keyword==="select"||keyword==="values"||keyword==="with"){let result=this.parseSubQuerySource(lexemes,idx,openParenToken);if(idx=result.newIndex,idx<lexemes.length&&lexemes[idx].type==8)idx++;else throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:result.value,newIndex:idx}}else if(lexemes[idx].type==4){let result=this.parseParenSource(lexemes,idx);if(idx=result.newIndex,idx<lexemes.length&&lexemes[idx].type==8)idx++;else throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:result.value,newIndex:idx}}throw new Error(`Syntax error at position ${idx}: Expected 'SELECT' keyword, 'VALUES' keyword, or opening parenthesis '(' but found "${lexemes[idx].value}".`)}static parseSubQuerySource(lexemes,index,openParenToken){let idx=index,{value:selectQuery,newIndex}=SelectQueryParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,openParenToken&&openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let afterComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){let beforeComments=afterComments.map(pc=>({position:"before",comments:pc.comments}));selectQuery.positionedComments?selectQuery.positionedComments=[...beforeComments,...selectQuery.positionedComments]:selectQuery.positionedComments=beforeComments,selectQuery.comments&&(selectQuery.comments=null)}}return{value:new SubQuerySource(selectQuery),newIndex:idx}}};var DuplicateCTEError=class extends Error{constructor(cteName){super(`CTE '${cteName}' already exists in the query`);this.cteName=cteName;this.name="DuplicateCTEError"}},InvalidCTENameError=class extends Error{constructor(cteName,reason){super(`Invalid CTE name '${cteName}': ${reason}`);this.cteName=cteName;this.name="InvalidCTENameError"}},CTENotFoundError=class extends Error{constructor(cteName){super(`CTE '${cteName}' not found in the query`);this.cteName=cteName;this.name="CTENotFoundError"}};var UpstreamSelectQueryFinder=class{constructor(tableColumnResolver,options){this.options=options||{},this.tableColumnResolver=tableColumnResolver,this.columnCollector=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0})}find(query,columnNames){let namesArray=typeof columnNames=="string"?[columnNames]:columnNames,ctes=new CTECollector().collect(query),cteMap=new Map;for(let cte of ctes)cteMap.set(cte.getSourceAliasName(),cte);return this.findUpstream(query,namesArray,cteMap)}handleTableSource(src,columnNames,cteMap){let cte=cteMap.get(src.table.name);if(cte){let nextCteMap=new Map(cteMap);if(nextCteMap.delete(src.table.name),!this.isSelectQuery(cte.query))return null;let result=this.findUpstream(cte.query,columnNames,nextCteMap);return result.length===0?null:result}return null}handleSubQuerySource(src,columnNames,cteMap){let result=this.findUpstream(src.query,columnNames,cteMap);return result.length===0?null:result}processFromClauseBranches(fromClause,columnNames,cteMap){let sources=fromClause.getSources();if(sources.length===0)return null;let allBranchResults=[],allBranchesOk=!0,validBranchCount=0;for(let sourceExpr of sources){let src=sourceExpr.datasource,branchResult=null;if(src instanceof TableSource)branchResult=this.handleTableSource(src,columnNames,cteMap),validBranchCount++;else if(src instanceof SubQuerySource)branchResult=this.handleSubQuerySource(src,columnNames,cteMap),validBranchCount++;else{if(src instanceof ValuesQuery)continue;allBranchesOk=!1;break}if(branchResult===null){allBranchesOk=!1;break}allBranchResults.push(branchResult)}return allBranchesOk&&allBranchResults.length===validBranchCount?allBranchResults.flat():null}findUpstream(query,columnNames,cteMap){if(query instanceof SimpleSelectQuery){let fromClause=query.fromClause;if(fromClause){let branchResult=this.processFromClauseBranches(fromClause,columnNames,cteMap);if(branchResult&&branchResult.length>0)return branchResult}let columns=this.columnCollector.collect(query).map(col=>col.name),cteColumns=this.collectCTEColumns(query,cteMap),allColumns=[...columns,...cteColumns],normalize=s=>this.options.ignoreCaseAndUnderscore?s.toLowerCase().replace(/_/g,""):s;return columnNames.every(name=>allColumns.some(col=>normalize(col)===normalize(name)))?[query]:[]}else if(query instanceof BinarySelectQuery){let left=this.findUpstream(query.left,columnNames,cteMap),right=this.findUpstream(query.right,columnNames,cteMap);return[...left,...right]}return[]}collectCTEColumns(query,cteMap){let cteColumns=[];if(query.withClause)for(let cte of query.withClause.tables){let columns=this.collectColumnsFromCteQuery(cte.query);cteColumns.push(...columns)}return cteColumns}collectColumnsFromCteQuery(query){return this.isSelectQuery(query)?this.collectColumnsFromSelectQuery(query):this.collectColumnsFromReturning(query)}collectColumnsFromSelectQuery(query){if(query instanceof SimpleSelectQuery)try{return this.columnCollector.collect(query).map(col=>col.name)}catch(error){return console.warn("Failed to collect columns from SimpleSelectQuery:",error),[]}else if(query instanceof BinarySelectQuery)return this.collectColumnsFromSelectQuery(query.left);return[]}collectColumnsFromReturning(query){return query instanceof InsertQuery||query instanceof UpdateQuery||query instanceof DeleteQuery||query instanceof MergeQuery?this.extractReturningColumns(query.returningClause):[]}extractReturningColumns(returningClause){if(!returningClause)return[];let columns=[];for(let item of returningClause.items){let name=item.identifier?.name??this.extractColumnName(item);name&&columns.push(name)}return columns}extractColumnName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}};var SourceAliasExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(idx<lexemes.length&&(lexemes[idx].type&64||lexemes[idx].type&2048)){let aliasToken=lexemes[idx],table=aliasToken.value;if(idx++,idx<lexemes.length&&lexemes[idx].type&4){let columns=[];for(idx++;idx<lexemes.length&&lexemes[idx].type&64&&(columns.push(lexemes[idx].value),idx++,idx<lexemes.length&&lexemes[idx].type&16);)idx++;if(lexemes[idx].type&8)idx++;else throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis ')' for column alias list. Each opening parenthesis must have a matching closing parenthesis.`);if(columns.length===0)throw new Error(`Syntax error at position ${index}: No column aliases found. Column alias declarations must contain at least one column name.`);let sourceAlias2=new SourceAliasExpression(table,columns);return aliasToken.positionedComments&&aliasToken.positionedComments.length>0&&(sourceAlias2.positionedComments=aliasToken.positionedComments),{value:sourceAlias2,newIndex:idx}}let sourceAlias=new SourceAliasExpression(table,null);return aliasToken.positionedComments&&aliasToken.positionedComments.length>0&&(sourceAlias.positionedComments=aliasToken.positionedComments),{value:sourceAlias,newIndex:idx}}throw new Error(`Syntax error at position ${index}: Expected an identifier for table alias but found "${lexemes[index]?.value||"end of input"}".`)}};var SourceExpressionParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The source expression is complete but there are additional tokens.`);return result.value}static parseTableSourceFromLexemes(lexemes,index){let result=SourceParser.parseTableSourceFromLexemes(lexemes,index);return{value:new SourceExpression(result.value,null),newIndex:result.newIndex}}static parseFromLexeme(lexemes,index){let idx=index,sourceResult=SourceParser.parseFromLexeme(lexemes,idx);if(idx=sourceResult.newIndex,idx<lexemes.length){if(lexemes[idx].value==="as"){idx++;let aliasResult=SourceAliasExpressionParser.parseFromLexeme(lexemes,idx);return idx=aliasResult.newIndex,{value:new SourceExpression(sourceResult.value,aliasResult.value),newIndex:idx}}if(idx<lexemes.length&&this.isTokenTypeAliasCandidate(lexemes[idx].type)){let aliasResult=SourceAliasExpressionParser.parseFromLexeme(lexemes,idx);return idx=aliasResult.newIndex,{value:new SourceExpression(sourceResult.value,aliasResult.value),newIndex:idx}}}return{value:new SourceExpression(sourceResult.value,null),newIndex:idx}}static isTokenTypeAliasCandidate(type){return(type&64)!==0||(type&2048)!==0}};var ParameterHelper=class{static set(query,name,value){let params=ParameterCollector.collect(query),found=!1;for(let p of params)p.name.value===name&&(p.value=value,found=!0);if(!found)throw new Error(`Parameter '${name}' not found in query.`)}};var ValuesQuery=class extends SqlComponent{constructor(tuples,columnAliases=null){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.withClause=null;this.tuples=tuples,this.columnAliases=columnAliases}static{this.kind=Symbol("ValuesQuery")}toSimpleQuery(){return QueryBuilder.buildSimpleQuery(this)}toInsertQuery(options){return this.toSimpleQuery().toInsertQuery(options)}toUpdateQuery(options){return this.toSimpleQuery().toUpdateQuery(options)}toDeleteQuery(options){return this.toSimpleQuery().toDeleteQuery(options)}toMergeQuery(options){return this.toSimpleQuery().toMergeQuery(options)}setParameter(name,value){return ParameterHelper.set(this,name,value),this}};var BinarySelectQuery=class _BinarySelectQuery extends SqlComponent{constructor(left,operator,right){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.left=left,this.operator=new RawString(operator),this.right=right}static{this.kind=Symbol("BinarySelectQuery")}union(query){return this.appendSelectQuery("union",query)}unionAll(query){return this.appendSelectQuery("union all",query)}intersect(query){return this.appendSelectQuery("intersect",query)}intersectAll(query){return this.appendSelectQuery("intersect all",query)}except(query){return this.appendSelectQuery("except",query)}exceptAll(query){return this.appendSelectQuery("except all",query)}appendSelectQuery(operator,query){return this.left=new _BinarySelectQuery(this.left,this.operator.value,this.right),this.operator=new RawString(operator),this.right=query,CTENormalizer.normalize(this),this}unionRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.union(parsedQuery)}unionAllRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.unionAll(parsedQuery)}intersectRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.intersect(parsedQuery)}intersectAllRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.intersectAll(parsedQuery)}exceptRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.except(parsedQuery)}exceptAllRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.exceptAll(parsedQuery)}toInsertQuery(options){return this.toSimpleQuery().toInsertQuery(options)}toUpdateQuery(options){return this.toSimpleQuery().toUpdateQuery(options)}toDeleteQuery(options){return this.toSimpleQuery().toDeleteQuery(options)}toMergeQuery(options){return this.toSimpleQuery().toMergeQuery(options)}toSource(alias="subq"){return new SourceExpression(new SubQuerySource(this),new SourceAliasExpression(alias,null))}setParameter(name,value){return ParameterHelper.set(this,name,value),this}toSimpleQuery(){return QueryBuilder.buildSimpleQuery(this)}};var InsertQuerySelectValuesConverter=class{static toSelectUnion(insertQuery){let valuesQuery=insertQuery.selectQuery;if(!(valuesQuery instanceof ValuesQuery))throw new Error("InsertQuery selectQuery is not a VALUES query.");if(!valuesQuery.tuples.length)throw new Error("VALUES query does not contain any tuples.");let preservedWithClause=SelectQueryWithClauseHelper.getWithClause(valuesQuery),columns=insertQuery.insertClause.columns;if(!columns||columns.length===0)throw new Error("Cannot convert to SELECT form without explicit column list.");let columnNames=columns.map(col=>col.name),selectQueries=valuesQuery.tuples.map(tuple=>{if(tuple.values.length!==columnNames.length)throw new Error("Tuple value count does not match column count.");let items=columnNames.map((name,idx)=>new SelectItem(tuple.values[idx],name)),selectClause=new SelectClause(items);return new SimpleSelectQuery({selectClause})}),combined=selectQueries[0];for(let i=1;i<selectQueries.length;i++)if(combined instanceof SimpleSelectQuery)combined=combined.toUnionAll(selectQueries[i]);else if(combined instanceof BinarySelectQuery)combined.appendSelectQuery("union all",selectQueries[i]);else throw new Error("Unsupported SelectQuery type during UNION ALL construction.");return SelectQueryWithClauseHelper.setWithClause(combined,preservedWithClause),new InsertQuery({insertClause:insertQuery.insertClause,selectQuery:combined,returning:insertQuery.returningClause})}static toValues(insertQuery){let columns=insertQuery.insertClause.columns;if(!columns||columns.length===0)throw new Error("Cannot convert to VALUES form without explicit column list.");if(!insertQuery.selectQuery)throw new Error("InsertQuery does not have a selectQuery to convert.");let preservedWithClause=SelectQueryWithClauseHelper.getWithClause(insertQuery.selectQuery),columnNames=columns.map(col=>col.name),simpleQueries=this.flattenSelectQueries(insertQuery.selectQuery);if(!simpleQueries.length)throw new Error("No SELECT components found to convert.");let tuples=simpleQueries.map(query=>{if(query.fromClause||query.whereClause&&query.whereClause.condition)throw new Error("SELECT queries with FROM or WHERE clauses cannot be converted to VALUES.");let valueMap=new Map;for(let item of query.selectClause.items){let identifier=item.identifier?.name??null;if(!identifier)throw new Error("Each SELECT item must have an alias matching target columns.");valueMap.has(identifier)||valueMap.set(identifier,item.value)}let rowValues=columnNames.map(name=>{let value=valueMap.get(name);if(!value)throw new Error(`Column '${name}' is not provided by the SELECT query.`);return value});return new TupleExpression(rowValues)}),valuesQuery=new ValuesQuery(tuples,columnNames);return SelectQueryWithClauseHelper.setWithClause(valuesQuery,preservedWithClause),new InsertQuery({insertClause:insertQuery.insertClause,selectQuery:valuesQuery,returning:insertQuery.returningClause})}static flattenSelectQueries(selectQuery){if(selectQuery instanceof SimpleSelectQuery)return[selectQuery];if(selectQuery instanceof BinarySelectQuery)return[...this.flattenSelectQueries(selectQuery.left),...this.flattenSelectQueries(selectQuery.right)];throw new Error("Unsupported SelectQuery subtype for conversion.")}};var TextPositionUtils=class{static lineColumnToCharOffset(text,position){if(position.line<1||position.column<1)return-1;let lines=text.split(`
|
|
30
|
+
`:this.newline,currentLevel=this.linePrinter.getCurrentLine()?.level??level,baseIndent=this.getIndentString(currentLevel),innerIndent=baseIndent+" ",body=lines.map(line=>`${innerIndent}${line}`).join(newline),closing=`${baseIndent}*/`;return`/*${newline}${body}${newline}${closing}`}getIndentString(level){return level<=0?"":this.indentSize<=0?" ".repeat(level):(typeof this.indentChar=="string"?this.indentChar:"").repeat(this.indentSize*level)}sanitizeCommentLine(content){let sanitized=content;return sanitized=sanitized.replace(/\u2028|\u2029/g," "),sanitized=sanitized.replace(/\s+/g," ").trim(),sanitized}escapeCommentDelimiters(content){return content.replace(/\/\*/g,"\\/\\*").replace(/\*\//g,"*\\/")}getCommentBaseIndentLevel(level,parentContainerType){if(!parentContainerType)return level;let clauseAlignedLevel=this.getClauseBreakIndentLevel(parentContainerType,level);return Math.max(level,clauseAlignedLevel)}resolveCommentIndentLevel(level,parentContainerType){let baseLevel=this.getCommentBaseIndentLevel(level,parentContainerType),currentLevel=this.linePrinter.getCurrentLine().level??baseLevel;return Math.max(baseLevel,currentLevel)}handleCommentNewlineToken(token,level){if(!this.smartCommentBlockBuilder){if(this.pendingLineCommentBreak!==null){this.linePrinter.appendNewline(this.pendingLineCommentBreak),this.pendingLineCommentBreak=null;return}this.shouldSkipCommentNewline()||this.isOnelineMode()||this.linePrinter.appendNewline(level)}}shouldSkipCommentNewline(){return this.insideWithClause&&this.withClauseStyle==="full-oneline"||this.withClauseStyle==="cte-oneline"}shouldAddNewlineBeforeLeadingComments(parentType){return parentType?parentType==="TupleExpression"?!0:parentType==="InsertClause"||parentType==="MergeInsertAction"?!this.insertColumnsOneLine:parentType==="SetClause"||parentType==="SelectClause"||parentType==="ExplainStatement"||parentType==="ReturningClause":!1}getLeadingCommentIndentLevel(parentType,currentLevel){return parentType==="TupleExpression"||parentType==="InsertClause"||parentType==="MergeInsertAction"||parentType==="SelectClause"||parentType==="ReturningClause"||parentType==="SetClause"?currentLevel+1:currentLevel}isOnelineMode(){return this.newline===" "}normalizeOneLineMaxLength(value){if(value===void 0||!Number.isFinite(value)||value<=0)return;let normalized=Math.floor(value);return normalized>0?normalized:void 0}fitsOneLineMaxLength(text){if(this.oneLineMaxLength===void 0)return!0;let currentLine=this.linePrinter.getCurrentLine();return currentLine.level*this.indentSize*String(this.indentChar).length+currentLine.text.length+text.length<=this.oneLineMaxLength}tryHandleCteOnelineToken(token,level){let onelineResult=this.createCteOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);cleanedResult=cleanedResult.replace(/\(\s+/g,"(").replace(/\s+\)/g," )");let trimmedResult=cleanedResult.trim();return this.fitsOneLineMaxLength(trimmedResult)?(this.linePrinter.appendText(trimmedResult),!0):!1}createCteOnelinePrinter(){return new _SqlPrinter({indentChar:"",indentSize:0,newline:" ",commaBreak:this.commaBreak,cteCommaBreak:this.cteCommaBreak,valuesCommaBreak:this.valuesCommaBreak,andBreak:this.andBreak,orBreak:this.orBreak,keywordCase:this.keywordCase,exportComment:"none",withClauseStyle:"standard",indentNestedParentheses:!1,insertColumnsOneLine:this.insertColumnsOneLine})}tryHandleOnelineToken(token,level){let onelineResult=this.createOnelinePrinter().print(token,level),cleanedResult=this.cleanDuplicateSpaces(onelineResult);return this.fitsOneLineMaxLength(cleanedResult)?(this.linePrinter.appendText(cleanedResult),!0):(this.isBooleanParenExpression(token)&&this.expandedOneLineFallbackTokens.add(token),!1)}isBooleanParenExpression(token){return token.containerType!=="ParenExpression"?!1:this.containsLogicalOperator(token)}containsLogicalOperator(token){return(token.type===5||token.type===1)&&["and","or"].includes(token.text.toLowerCase())?!0:token.innerTokens.some(child=>this.containsLogicalOperator(child))}getClauseBreakIndentLevel(parentType,level){if(!parentType)return level;switch(parentType){case"MergeWhenClause":return level+1;case"MergeUpdateAction":case"MergeDeleteAction":case"MergeInsertAction":return level+1;default:return level}}isMergeActionContainer(token){if(!token)return!1;switch(token.containerType){case"MergeUpdateAction":case"MergeDeleteAction":case"MergeInsertAction":case"MergeDoNothingAction":return!0;default:return!1}}shouldBreakAfterOpeningParen(parentType){return parentType&&(parentType==="InsertClause"||parentType==="MergeInsertAction"||parentType==="ReturningClause")?!this.isInsertClauseOneline(parentType):!1}shouldBreakBeforeClosingParen(parentType){return parentType&&(parentType==="InsertClause"||parentType==="MergeInsertAction")?!this.isInsertClauseOneline(parentType):!1}shouldConvertSpaceToClauseBreak(parentType,nextToken){if(!parentType||!nextToken)return!1;let nextKeyword=nextToken.type===1?nextToken.text.toLowerCase():null,nextContainer=nextToken.containerType;return!!(parentType==="MergeQuery"&&(nextKeyword==="using"||nextContainer==="MergeWhenClause")||parentType==="MergeWhenClause"&&(nextContainer==="MergeUpdateAction"||nextContainer==="MergeDeleteAction"||nextContainer==="MergeInsertAction"||nextContainer==="MergeDoNothingAction")||parentType==="UpdateQuery"&&(nextKeyword==="set"||nextKeyword==="from"||nextKeyword==="where"||nextKeyword==="returning")||parentType==="InsertQuery"&&(nextKeyword==="returning"||nextKeyword&&(nextKeyword.startsWith("select")||nextKeyword.startsWith("values"))||nextContainer==="ValuesQuery"||nextContainer==="SimpleSelectQuery"||nextContainer==="InsertClause")||parentType==="DeleteQuery"&&(nextKeyword==="using"||nextKeyword==="where"||nextKeyword==="returning")||(parentType==="MergeUpdateAction"||parentType==="MergeDeleteAction")&&nextKeyword==="where"||parentType==="MergeInsertAction"&&nextKeyword&&(nextKeyword.startsWith("values")||nextKeyword==="default values"))}createOnelinePrinter(){return new _SqlPrinter({indentChar:"",indentSize:0,newline:" ",commaBreak:"none",cteCommaBreak:this.cteCommaBreak,valuesCommaBreak:"none",andBreak:"none",orBreak:"none",keywordCase:this.keywordCase,exportComment:this.commentExportMode,commentStyle:this.commentStyle,withClauseStyle:"standard",parenthesesOneLine:!1,betweenOneLine:!1,valuesOneLine:!1,joinOneLine:!1,caseOneLine:!1,subqueryOneLine:!1,indentNestedParentheses:!1,insertColumnsOneLine:this.insertColumnsOneLine})}cleanDuplicateSpaces(text){return text.replace(/\s{2,}/g," ")}};var VALID_PRESETS=["mysql","postgres","sqlserver","sqlite"],SqlFormatter=class{constructor(options={}){let presetConfig=options.preset?PRESETS[options.preset]:void 0;if(options.preset&&!presetConfig)throw new Error(`Invalid preset: ${options.preset}`);let resolvedIdentifierEscape=resolveIdentifierEscapeOption(options.identifierEscape??presetConfig?.identifierEscape,options.identifierEscapeTarget??"all"),parserOptions={...presetConfig,identifierEscape:resolvedIdentifierEscape??presetConfig?.identifierEscape,parameterSymbol:options.parameterSymbol??presetConfig?.parameterSymbol,parameterStyle:options.parameterStyle??presetConfig?.parameterStyle,castStyle:options.castStyle??presetConfig?.castStyle,sourceAliasStyle:options.sourceAliasStyle??presetConfig?.sourceAliasStyle,orderByDefaultDirectionStyle:options.orderByDefaultDirectionStyle??presetConfig?.orderByDefaultDirectionStyle,joinConditionOrderByDeclaration:options.joinConditionOrderByDeclaration},constraintStyle=options.constraintStyle??presetConfig?.constraintStyle??"postgres",parserConfig={...parserOptions,constraintStyle};this.parser=new SqlPrintTokenParser({...parserConfig});let normalizedExportComment=options.exportComment===!0?"full":options.exportComment===!1?"none":options.exportComment,printerOptions={...options,exportComment:normalizedExportComment,parenthesesOneLine:options.parenthesesOneLine,betweenOneLine:options.betweenOneLine,valuesOneLine:options.valuesOneLine,joinOneLine:options.joinOneLine,caseOneLine:options.caseOneLine,subqueryOneLine:options.subqueryOneLine,indentNestedParentheses:options.indentNestedParentheses};this.printer=new SqlPrinter(printerOptions)}format(sql){let{token,params}=this.parser.parse(sql);return{formattedSql:this.printer.print(token),params}}};var Formatter=class{constructor(){this.sqlFormatter=new SqlFormatter({identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named"})}format(arg,config=null){return config&&(this.sqlFormatter=new SqlFormatter(config)),this.sqlFormatter.format(arg).formattedSql}formatWithParameters(arg,config=null){config&&(this.sqlFormatter=new SqlFormatter(config));let result=this.sqlFormatter.format(arg);return{sql:result.formattedSql,params:result.params}}visit(arg){return this.format(arg)}};var CTEBuilder=class{constructor(){this.sourceCollector=new TableSourceCollector(!0),this.cteCollector=new CTECollector,this.formatter=new Formatter}build(commonTables){if(commonTables.length===0)return new WithClause(!1,commonTables);let resolvedTables=this.resolveDuplicateNames(commonTables),{tableMap,recursiveCTEs,dependencies}=this.buildDependencyGraph(resolvedTables),sortedTables=this.sortCommonTables(resolvedTables,tableMap,recursiveCTEs,dependencies);return new WithClause(recursiveCTEs.size>0,sortedTables)}resolveDuplicateNames(commonTables){let ctesByName=new Map;for(let table of commonTables){let tableName=table.aliasExpression.table.name;ctesByName.has(tableName)||ctesByName.set(tableName,[]),ctesByName.get(tableName).push(table)}let resolvedTables=[];for(let[name,tables]of Array.from(ctesByName.entries())){if(tables.length===1){resolvedTables.push(tables[0]);continue}let definitions=tables.map(table=>this.formatter.format(table.query));if(new Set(definitions).size===1)resolvedTables.push(tables[0]);else throw new Error(`CTE name conflict detected: '${name}' has multiple different definitions`)}return resolvedTables}buildDependencyGraph(tables){let tableMap=new Map;for(let table of tables)tableMap.set(table.aliasExpression.table.name,table);let recursiveCTEs=new Set,dependencies=new Map,referencedBy=new Map;for(let table of tables){let tableName=table.aliasExpression.table.name,referencedTables=this.sourceCollector.collect(table.query);for(let referencedTable of referencedTables)if(referencedTable.table.name===tableName){recursiveCTEs.add(tableName);break}dependencies.has(tableName)||dependencies.set(tableName,new Set);let referencedCTEs=this.cteCollector.collect(table.query);for(let referencedCTE of referencedCTEs){let referencedName=referencedCTE.aliasExpression.table.name;tableMap.has(referencedName)&&(dependencies.get(tableName).add(referencedName),referencedBy.has(referencedName)||referencedBy.set(referencedName,new Set),referencedBy.get(referencedName).add(tableName))}}return{tableMap,recursiveCTEs,dependencies}}sortCommonTables(tables,tableMap,recursiveCTEs,dependencies){let recursiveResult=[],nonRecursiveResult=[],visited=new Set,visiting=new Set,visit=tableName=>{if(visited.has(tableName))return;if(visiting.has(tableName))throw new Error(`Circular reference detected in CTE: ${tableName}`);visiting.add(tableName);let deps=dependencies.get(tableName)||new Set;for(let dep of Array.from(deps))visit(dep);visiting.delete(tableName),visited.add(tableName),recursiveCTEs.has(tableName)?recursiveResult.push(tableMap.get(tableName)):nonRecursiveResult.push(tableMap.get(tableName))};for(let table of tables){let tableName=table.aliasExpression.table.name;visited.has(tableName)||visit(tableName)}return[...recursiveResult,...nonRecursiveResult]}};var CTEInjector=class{constructor(){this.nameConflictResolver=new CTEBuilder,this.cteCollector=new CTECollector}inject(query,commonTables){if(commonTables.length===0)return query;commonTables.push(...this.cteCollector.collect(query));let resolvedWithCaluse=this.nameConflictResolver.build(commonTables);if(query instanceof SimpleSelectQuery)return this.injectIntoSimpleQuery(query,resolvedWithCaluse);if(query instanceof BinarySelectQuery)return this.injectIntoBinaryQuery(query,resolvedWithCaluse);throw new Error("Unsupported query type")}injectIntoSimpleQuery(query,withClause){if(query.withClause)throw new Error("The query already has a WITH clause. Please remove it before injecting new CTEs.");return query.withClause=withClause,query}injectIntoBinaryQuery(query,withClause){if(query.left instanceof SimpleSelectQuery)return this.injectIntoSimpleQuery(query.left,withClause),query;if(query.left instanceof BinarySelectQuery)return this.injectIntoBinaryQuery(query.left,withClause),query;throw new Error("Unsupported query type for BinarySelectQuery left side")}};var CTENormalizer=class{constructor(){}static normalize(query){let allCommonTables=new CTECollector().collect(query);return allCommonTables.length===0?query:(new CTEDisabler().execute(query),new CTEInjector().inject(query,allCommonTables))}};var DuplicateDetectionMode=(DuplicateDetectionMode2=>(DuplicateDetectionMode2.ColumnNameOnly="columnNameOnly",DuplicateDetectionMode2.FullName="fullName",DuplicateDetectionMode2))(DuplicateDetectionMode||{}),SelectableColumnCollector=class _SelectableColumnCollector{constructor(tableColumnResolver,includeWildCard=!1,duplicateDetection="columnNameOnly",options){this.selectValues=[];this.visitedNodes=new Set;this.uniqueKeys=new Set;this.isRootVisit=!0;this.tableColumnResolver=null;this.commonTables=[];this.initializeProperties(tableColumnResolver,includeWildCard,duplicateDetection,options),this.initializeHandlers()}initializeProperties(tableColumnResolver,includeWildCard,duplicateDetection,options){this.tableColumnResolver=tableColumnResolver??null,this.includeWildCard=includeWildCard,this.commonTableCollector=new CTECollector,this.commonTables=[],this.duplicateDetection=duplicateDetection,this.options=options||{}}initializeHandlers(){this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.initializeClauseHandlers(),this.initializeValueComponentHandlers()}initializeClauseHandlers(){this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.offsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr))}initializeValueComponentHandlers(){this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(JsonPredicateExpression.kind,expr=>this.visitJsonPredicateExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}getValues(){return this.selectValues}collect(arg){if(!arg)throw new Error("Input argument cannot be null or undefined");this.visit(arg);let items=this.getValues();return this.reset(),items}reset(){this.selectValues=[],this.visitedNodes.clear(),this.uniqueKeys.clear(),this.commonTables=[]}addSelectValueAsUnique(name,value){let key=this.generateUniqueKey(name,value);this.uniqueKeys.has(key)||(this.uniqueKeys.add(key),this.selectValues.push({name,value}))}generateUniqueKey(name,value){if(this.duplicateDetection==="columnNameOnly")return this.normalizeColumnName(name);{let tableName="";value&&typeof value.getNamespace=="function"&&(tableName=value.getNamespace()||"");let fullName=tableName?tableName+"."+name:name;return this.normalizeColumnName(fullName)}}normalizeColumnName(name){if(typeof name!="string")throw new Error("Column name must be a string");return this.options.ignoreCaseAndUnderscore?name.toLowerCase().replace(/_/g,""):name}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}if(!(arg instanceof SimpleSelectQuery||arg instanceof BinarySelectQuery))throw new Error("Root visit requires a SimpleSelectQuery or BinarySelectQuery.");this.reset(),this.isRootVisit=!1,this.commonTables=this.commonTableCollector.collect(arg);try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(!this.visitedNodes.has(arg)){this.visitedNodes.add(arg);try{let handler=this.handlers.get(arg.getKind());handler&&handler(arg)}catch(error){let errorMessage=error instanceof Error?error.message:String(error);throw new Error(`Error processing SQL component of type ${arg.getKind().toString()}: ${errorMessage}`)}}}visitSimpleSelectQuery(query){if(query.selectClause&&query.selectClause.accept(this),query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.orderByClause&&query.orderByClause.accept(this),query.limitClause&&query.limitClause.accept(this),query.offsetClause&&query.offsetClause.accept(this),query.fetchClause&&query.fetchClause.accept(this),query.forClause&&query.forClause.accept(this)}visitBinarySelectQuery(query){query.left instanceof SimpleSelectQuery?this.visitSimpleSelectQuery(query.left):query.left instanceof BinarySelectQuery&&this.visitBinarySelectQuery(query.left),query.right instanceof SimpleSelectQuery?this.visitSimpleSelectQuery(query.right):query.right instanceof BinarySelectQuery&&this.visitBinarySelectQuery(query.right)}visitSelectClause(clause){for(let item of clause.items)if(item.identifier)this.addSelectValueAsUnique(item.identifier.name,item.value);else if(item.value instanceof ColumnReference){let columnName=item.value.column.name;columnName!=="*"?this.addSelectValueAsUnique(columnName,item.value):this.includeWildCard&&this.addSelectValueAsUnique(columnName,item.value)}else item.value.accept(this)}visitFromClause(clause){let sourceValues=new SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(clause);for(let item of sourceValues)this.addSelectValueAsUnique(item.name,item.value);if(this.options.upstream&&this.collectUpstreamColumns(clause),clause.joins)for(let join of clause.joins)join.condition&&join.condition.accept(this)}visitWhereClause(clause){clause.condition&&clause.condition.accept(this)}visitGroupByClause(clause){if(clause.grouping)for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition&&clause.condition.accept(this)}visitOrderByClause(clause){if(clause.order)for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitWindowFrameExpression(expr){expr.partition&&expr.partition.accept(this),expr.order&&expr.order.accept(this),expr.frameSpec&&expr.frameSpec.accept(this)}visitLimitClause(clause){clause.value&&clause.value.accept(this)}offsetClause(clause){clause.value&&clause.value.accept(this)}visitFetchClause(clause){clause.expression&&clause.expression.accept(this)}visitJoinOnClause(joinOnClause){joinOnClause.condition&&joinOnClause.condition.accept(this)}visitJoinUsingClause(joinUsingClause){joinUsingClause.condition&&joinUsingClause.condition.accept(this)}visitColumnReference(columnRef){if(columnRef.column.name!=="*")this.addSelectValueAsUnique(columnRef.column.name,columnRef);else if(this.includeWildCard)this.addSelectValueAsUnique(columnRef.column.name,columnRef);else return}visitBinaryExpression(expr){expr.left&&expr.left.accept(this),expr.right&&expr.right.accept(this)}visitJsonPredicateExpression(expr){expr.expression.accept(this)}visitUnaryExpression(expr){expr.expression&&expr.expression.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this),func.withinGroup&&func.withinGroup.accept(this),func.internalOrderBy&&func.internalOrderBy.accept(this)}visitInlineQuery(inlineQuery){inlineQuery.selectQuery&&this.visitNode(inlineQuery.selectQuery)}visitParenExpression(expr){expr.expression&&expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase&&expr.switchCase.accept(this)}visitCastExpression(expr){expr.input&&expr.input.accept(this)}visitBetweenExpression(expr){expr.expression&&expr.expression.accept(this),expr.lower&&expr.lower.accept(this),expr.upper&&expr.upper.accept(this)}visitArrayExpression(expr){expr.expression&&expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitArraySliceExpression(expr){expr.array&&expr.array.accept(this),expr.startIndex&&expr.startIndex.accept(this),expr.endIndex&&expr.endIndex.accept(this)}visitArrayIndexExpression(expr){expr.array&&expr.array.accept(this),expr.index&&expr.index.accept(this)}visitValueList(expr){if(expr.values&&Array.isArray(expr.values))for(let value of expr.values)value&&value.accept(this)}visitPartitionByClause(clause){clause.value.accept(this)}collectUpstreamColumns(clause){if(this.collectAllAvailableCTEColumns(),this.collectUpstreamColumnsFromSource(clause.source),clause.joins)for(let join of clause.joins)this.collectUpstreamColumnsFromSource(join.source)}collectUpstreamColumnsFromSource(source){if(source.datasource instanceof TableSource){let cteTable=this.findCTEByName(source.datasource.table.name);cteTable?this.collectUpstreamColumnsFromCTE(cteTable):this.collectUpstreamColumnsFromTable(source.datasource)}else source.datasource instanceof SubQuerySource?this.collectUpstreamColumnsFromSubquery(source.datasource):source.datasource instanceof ParenSource&&this.collectUpstreamColumnsFromSource(new SourceExpression(source.datasource.source,null))}collectUpstreamColumnsFromTable(tableSource){if(this.tableColumnResolver){let tableName=tableSource.table.name,columns=this.tableColumnResolver(tableName);for(let columnName of columns){let columnRef=new ColumnReference(tableSource.table.name,columnName);this.addSelectValueAsUnique(columnName,columnRef)}}}collectUpstreamColumnsFromSubquery(subquerySource){if(subquerySource.query instanceof SimpleSelectQuery){let subqueryColumns=new _SelectableColumnCollector(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!0}).collect(subquerySource.query);for(let item of subqueryColumns)this.addSelectValueAsUnique(item.name,item.value)}}collectUpstreamColumnsFromCTE(cteTable){if(cteTable.query instanceof SimpleSelectQuery){let cteColumns=new _SelectableColumnCollector(this.tableColumnResolver,this.includeWildCard,this.duplicateDetection,{...this.options,upstream:!1}).collect(cteTable.query);for(let item of cteColumns)item.name!=="*"&&this.addSelectValueAsUnique(item.name,item.value)}}collectAllAvailableCTEColumns(){for(let cte of this.commonTables)this.collectUpstreamColumnsFromCTE(cte)}findCTEByName(name){return this.commonTables.find(cte=>cte.getSourceAliasName()===name)||null}};var SourceParser=class _SourceParser{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The source component is complete but there are additional tokens.`);return result.value}static parseTableSourceFromLexemes(lexemes,index){let fullNameResult=FullNameParser.parseFromLexeme(lexemes,index);return this.parseTableSource(fullNameResult)}static parseFromLexeme(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&4)return this.parseParenSource(lexemes,idx);let fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx);return fullNameResult.lastTokenType&2048?_SourceParser.parseFunctionSource(lexemes,fullNameResult):_SourceParser.parseTableSource(fullNameResult)}static parseTableSource(fullNameResult){let{namespaces,name,newIndex}=fullNameResult,value=new TableSource(namespaces,name.name);return name.positionedComments&&name.positionedComments.length>0?value.positionedComments=name.positionedComments:name.comments&&name.comments.length>0&&(value.comments=name.comments),{value,newIndex}}static parseFunctionSource(lexemes,fullNameResult){let idx=fullNameResult.newIndex,{namespaces,name}=fullNameResult,argument=ValueParser.parseArgument(4,8,lexemes,idx);idx=argument.newIndex;let withOrdinality=!1;idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++);let functionName=name.name;return{value:new FunctionSource({namespaces,name:functionName},argument.value,withOrdinality),newIndex:idx}}static parseParenSource(lexemes,index){let idx=index,openParenToken=lexemes[idx];if(idx++,idx>=lexemes.length)throw new Error(`Syntax error: Unexpected end of input at position ${idx}. Expected a subquery or nested expression after opening parenthesis.`);let keyword=lexemes[idx].value;if(keyword==="select"||keyword==="values"||keyword==="with"){let result=this.parseSubQuerySource(lexemes,idx,openParenToken);if(idx=result.newIndex,idx<lexemes.length&&lexemes[idx].type==8)idx++;else throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:result.value,newIndex:idx}}else if(lexemes[idx].type==4){let result=this.parseParenSource(lexemes,idx);if(idx=result.newIndex,idx<lexemes.length&&lexemes[idx].type==8)idx++;else throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis. Each opening parenthesis must have a matching closing parenthesis.`);return{value:result.value,newIndex:idx}}throw new Error(`Syntax error at position ${idx}: Expected 'SELECT' keyword, 'VALUES' keyword, or opening parenthesis '(' but found "${lexemes[idx].value}".`)}static parseSubQuerySource(lexemes,index,openParenToken){let idx=index,{value:selectQuery,newIndex}=SelectQueryParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,openParenToken&&openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let afterComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){let beforeComments=afterComments.map(pc=>({position:"before",comments:pc.comments}));selectQuery.positionedComments?selectQuery.positionedComments=[...beforeComments,...selectQuery.positionedComments]:selectQuery.positionedComments=beforeComments,selectQuery.comments&&(selectQuery.comments=null)}}return{value:new SubQuerySource(selectQuery),newIndex:idx}}};var DuplicateCTEError=class extends Error{constructor(cteName){super(`CTE '${cteName}' already exists in the query`);this.cteName=cteName;this.name="DuplicateCTEError"}},InvalidCTENameError=class extends Error{constructor(cteName,reason){super(`Invalid CTE name '${cteName}': ${reason}`);this.cteName=cteName;this.name="InvalidCTENameError"}},CTENotFoundError=class extends Error{constructor(cteName){super(`CTE '${cteName}' not found in the query`);this.cteName=cteName;this.name="CTENotFoundError"}};var UpstreamSelectQueryFinder=class{constructor(tableColumnResolver,options){this.options=options||{},this.tableColumnResolver=tableColumnResolver,this.columnCollector=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0})}find(query,columnNames){let namesArray=typeof columnNames=="string"?[columnNames]:columnNames,ctes=new CTECollector().collect(query),cteMap=new Map;for(let cte of ctes)cteMap.set(cte.getSourceAliasName(),cte);return this.findUpstream(query,namesArray,cteMap)}handleTableSource(src,columnNames,cteMap){let cte=cteMap.get(src.table.name);if(cte){let nextCteMap=new Map(cteMap);if(nextCteMap.delete(src.table.name),!this.isSelectQuery(cte.query))return null;let result=this.findUpstream(cte.query,columnNames,nextCteMap);return result.length===0?null:result}return null}handleSubQuerySource(src,columnNames,cteMap){let result=this.findUpstream(src.query,columnNames,cteMap);return result.length===0?null:result}processFromClauseBranches(fromClause,columnNames,cteMap){let sources=fromClause.getSources();if(sources.length===0)return null;let allBranchResults=[],allBranchesOk=!0,validBranchCount=0;for(let sourceExpr of sources){let src=sourceExpr.datasource,branchResult=null;if(src instanceof TableSource)branchResult=this.handleTableSource(src,columnNames,cteMap),validBranchCount++;else if(src instanceof SubQuerySource)branchResult=this.handleSubQuerySource(src,columnNames,cteMap),validBranchCount++;else{if(src instanceof ValuesQuery)continue;allBranchesOk=!1;break}if(branchResult===null){allBranchesOk=!1;break}allBranchResults.push(branchResult)}return allBranchesOk&&allBranchResults.length===validBranchCount?allBranchResults.flat():null}findUpstream(query,columnNames,cteMap){if(query instanceof SimpleSelectQuery){let fromClause=query.fromClause;if(fromClause){let branchResult=this.processFromClauseBranches(fromClause,columnNames,cteMap);if(branchResult&&branchResult.length>0)return branchResult}let columns=this.columnCollector.collect(query).map(col=>col.name),cteColumns=this.collectCTEColumns(query,cteMap),allColumns=[...columns,...cteColumns],normalize=s=>this.options.ignoreCaseAndUnderscore?s.toLowerCase().replace(/_/g,""):s;return columnNames.every(name=>allColumns.some(col=>normalize(col)===normalize(name)))?[query]:[]}else if(query instanceof BinarySelectQuery){let left=this.findUpstream(query.left,columnNames,cteMap),right=this.findUpstream(query.right,columnNames,cteMap);return[...left,...right]}return[]}collectCTEColumns(query,cteMap){let cteColumns=[];if(query.withClause)for(let cte of query.withClause.tables){let columns=this.collectColumnsFromCteQuery(cte.query);cteColumns.push(...columns)}return cteColumns}collectColumnsFromCteQuery(query){return this.isSelectQuery(query)?this.collectColumnsFromSelectQuery(query):this.collectColumnsFromReturning(query)}collectColumnsFromSelectQuery(query){if(query instanceof SimpleSelectQuery)try{return this.columnCollector.collect(query).map(col=>col.name)}catch(error){return console.warn("Failed to collect columns from SimpleSelectQuery:",error),[]}else if(query instanceof BinarySelectQuery)return this.collectColumnsFromSelectQuery(query.left);return[]}collectColumnsFromReturning(query){return query instanceof InsertQuery||query instanceof UpdateQuery||query instanceof DeleteQuery||query instanceof MergeQuery?this.extractReturningColumns(query.returningClause):[]}extractReturningColumns(returningClause){if(!returningClause)return[];let columns=[];for(let item of returningClause.items){let name=item.identifier?.name??this.extractColumnName(item);name&&columns.push(name)}return columns}extractColumnName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}};var SourceAliasExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(idx<lexemes.length&&(lexemes[idx].type&64||lexemes[idx].type&2048)){let aliasToken=lexemes[idx],table=aliasToken.value;if(idx++,idx<lexemes.length&&lexemes[idx].type&4){let columns=[];for(idx++;idx<lexemes.length&&lexemes[idx].type&64&&(columns.push(lexemes[idx].value),idx++,idx<lexemes.length&&lexemes[idx].type&16);)idx++;if(lexemes[idx].type&8)idx++;else throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis ')' for column alias list. Each opening parenthesis must have a matching closing parenthesis.`);if(columns.length===0)throw new Error(`Syntax error at position ${index}: No column aliases found. Column alias declarations must contain at least one column name.`);let sourceAlias2=new SourceAliasExpression(table,columns);return aliasToken.positionedComments&&aliasToken.positionedComments.length>0&&(sourceAlias2.positionedComments=aliasToken.positionedComments),{value:sourceAlias2,newIndex:idx}}let sourceAlias=new SourceAliasExpression(table,null);return aliasToken.positionedComments&&aliasToken.positionedComments.length>0&&(sourceAlias.positionedComments=aliasToken.positionedComments),{value:sourceAlias,newIndex:idx}}throw new Error(`Syntax error at position ${index}: Expected an identifier for table alias but found "${lexemes[index]?.value||"end of input"}".`)}};var SourceExpressionParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The source expression is complete but there are additional tokens.`);return result.value}static parseTableSourceFromLexemes(lexemes,index){let result=SourceParser.parseTableSourceFromLexemes(lexemes,index);return{value:new SourceExpression(result.value,null),newIndex:result.newIndex}}static parseFromLexeme(lexemes,index){let idx=index,sourceResult=SourceParser.parseFromLexeme(lexemes,idx);if(idx=sourceResult.newIndex,idx<lexemes.length){if(lexemes[idx].value==="as"){idx++;let aliasResult=SourceAliasExpressionParser.parseFromLexeme(lexemes,idx);return idx=aliasResult.newIndex,{value:new SourceExpression(sourceResult.value,aliasResult.value),newIndex:idx}}if(idx<lexemes.length&&this.isTokenTypeAliasCandidate(lexemes[idx].type)){let aliasResult=SourceAliasExpressionParser.parseFromLexeme(lexemes,idx);return idx=aliasResult.newIndex,{value:new SourceExpression(sourceResult.value,aliasResult.value),newIndex:idx}}}return{value:new SourceExpression(sourceResult.value,null),newIndex:idx}}static isTokenTypeAliasCandidate(type){return(type&64)!==0||(type&2048)!==0}};var ParameterHelper=class{static set(query,name,value){let params=ParameterCollector.collect(query),found=!1;for(let p of params)p.name.value===name&&(p.value=value,found=!0);if(!found)throw new Error(`Parameter '${name}' not found in query.`)}};var ValuesQuery=class extends SqlComponent{constructor(tuples,columnAliases=null){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.withClause=null;this.tuples=tuples,this.columnAliases=columnAliases}static{this.kind=Symbol("ValuesQuery")}toSimpleQuery(){return QueryBuilder.buildSimpleQuery(this)}toInsertQuery(options){return this.toSimpleQuery().toInsertQuery(options)}toUpdateQuery(options){return this.toSimpleQuery().toUpdateQuery(options)}toDeleteQuery(options){return this.toSimpleQuery().toDeleteQuery(options)}toMergeQuery(options){return this.toSimpleQuery().toMergeQuery(options)}setParameter(name,value){return ParameterHelper.set(this,name,value),this}};var BinarySelectQuery=class _BinarySelectQuery extends SqlComponent{constructor(left,operator,right){super();this.__selectQueryType="SelectQuery";this.headerComments=null;this.left=left,this.operator=new RawString(operator),this.right=right}static{this.kind=Symbol("BinarySelectQuery")}union(query){return this.appendSelectQuery("union",query)}unionAll(query){return this.appendSelectQuery("union all",query)}intersect(query){return this.appendSelectQuery("intersect",query)}intersectAll(query){return this.appendSelectQuery("intersect all",query)}except(query){return this.appendSelectQuery("except",query)}exceptAll(query){return this.appendSelectQuery("except all",query)}appendSelectQuery(operator,query){return this.left=new _BinarySelectQuery(this.left,this.operator.value,this.right),this.operator=new RawString(operator),this.right=query,CTENormalizer.normalize(this),this}unionRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.union(parsedQuery)}unionAllRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.unionAll(parsedQuery)}intersectRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.intersect(parsedQuery)}intersectAllRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.intersectAll(parsedQuery)}exceptRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.except(parsedQuery)}exceptAllRaw(sql){let parsedQuery=SelectQueryParser.parse(sql);return this.exceptAll(parsedQuery)}toInsertQuery(options){return this.toSimpleQuery().toInsertQuery(options)}toUpdateQuery(options){return this.toSimpleQuery().toUpdateQuery(options)}toDeleteQuery(options){return this.toSimpleQuery().toDeleteQuery(options)}toMergeQuery(options){return this.toSimpleQuery().toMergeQuery(options)}toSource(alias="subq"){return new SourceExpression(new SubQuerySource(this),new SourceAliasExpression(alias,null))}setParameter(name,value){return ParameterHelper.set(this,name,value),this}toSimpleQuery(){return QueryBuilder.buildSimpleQuery(this)}};var InsertQuerySelectValuesConverter=class{static toSelectUnion(insertQuery){let valuesQuery=insertQuery.selectQuery;if(!(valuesQuery instanceof ValuesQuery))throw new Error("InsertQuery selectQuery is not a VALUES query.");if(!valuesQuery.tuples.length)throw new Error("VALUES query does not contain any tuples.");let preservedWithClause=SelectQueryWithClauseHelper.getWithClause(valuesQuery),columns=insertQuery.insertClause.columns;if(!columns||columns.length===0)throw new Error("Cannot convert to SELECT form without explicit column list.");let columnNames=columns.map(col=>col.name),selectQueries=valuesQuery.tuples.map(tuple=>{if(tuple.values.length!==columnNames.length)throw new Error("Tuple value count does not match column count.");let items=columnNames.map((name,idx)=>new SelectItem(tuple.values[idx],name)),selectClause=new SelectClause(items);return new SimpleSelectQuery({selectClause})}),combined=selectQueries[0];for(let i=1;i<selectQueries.length;i++)if(combined instanceof SimpleSelectQuery)combined=combined.toUnionAll(selectQueries[i]);else if(combined instanceof BinarySelectQuery)combined.appendSelectQuery("union all",selectQueries[i]);else throw new Error("Unsupported SelectQuery type during UNION ALL construction.");return SelectQueryWithClauseHelper.setWithClause(combined,preservedWithClause),new InsertQuery({insertClause:insertQuery.insertClause,selectQuery:combined,returning:insertQuery.returningClause})}static toValues(insertQuery){let columns=insertQuery.insertClause.columns;if(!columns||columns.length===0)throw new Error("Cannot convert to VALUES form without explicit column list.");if(!insertQuery.selectQuery)throw new Error("InsertQuery does not have a selectQuery to convert.");let preservedWithClause=SelectQueryWithClauseHelper.getWithClause(insertQuery.selectQuery),columnNames=columns.map(col=>col.name),simpleQueries=this.flattenSelectQueries(insertQuery.selectQuery);if(!simpleQueries.length)throw new Error("No SELECT components found to convert.");let tuples=simpleQueries.map(query=>{if(query.fromClause||query.whereClause&&query.whereClause.condition)throw new Error("SELECT queries with FROM or WHERE clauses cannot be converted to VALUES.");let valueMap=new Map;for(let item of query.selectClause.items){let identifier=item.identifier?.name??null;if(!identifier)throw new Error("Each SELECT item must have an alias matching target columns.");valueMap.has(identifier)||valueMap.set(identifier,item.value)}let rowValues=columnNames.map(name=>{let value=valueMap.get(name);if(!value)throw new Error(`Column '${name}' is not provided by the SELECT query.`);return value});return new TupleExpression(rowValues)}),valuesQuery=new ValuesQuery(tuples,columnNames);return SelectQueryWithClauseHelper.setWithClause(valuesQuery,preservedWithClause),new InsertQuery({insertClause:insertQuery.insertClause,selectQuery:valuesQuery,returning:insertQuery.returningClause})}static flattenSelectQueries(selectQuery){if(selectQuery instanceof SimpleSelectQuery)return[selectQuery];if(selectQuery instanceof BinarySelectQuery)return[...this.flattenSelectQueries(selectQuery.left),...this.flattenSelectQueries(selectQuery.right)];throw new Error("Unsupported SelectQuery subtype for conversion.")}};var TextPositionUtils=class{static lineColumnToCharOffset(text,position){if(position.line<1||position.column<1)return-1;let lines=text.split(`
|
|
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(`
|