rawsql-ts 0.23.0 → 0.23.1

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/index.min.js CHANGED
@@ -10,7 +10,7 @@ ${this.getDebugPositionInfo(start)}`);return this.input.slice(start,this.positio
10
10
  ${this.getDebugPositionInfo(this.position)}`);let tokenStartPos=this.position,tokenEndPos=this.position=this.readerManager.getMaxPosition(),suffixComment=this.readComment();this.position=suffixComment.position;let prefixComments=this.mergeComments(pendingLeading,prefixComment.lines);pendingLeading=null,tokenData.push({lexeme,startPos:tokenStartPos,endPos:tokenEndPos,prefixComments,suffixComments:suffixComment.lines}),previous=lexeme}let statementEnd=this.position,lexemes=this.hasCommentMetadata(tokenData)?this.buildLexemesFromTokenData(tokenData):this.extractLexemes(tokenData),nextPosition=this.skipPastTerminator(statementEnd);return{lexemes,statementStart,statementEnd,nextPosition,rawText:this.input.slice(statementStart,statementEnd),leadingComments:pendingLeading}}hasCommentMetadata(tokenData){for(let i=0;i<tokenData.length;i++){let token=tokenData[i];if(token.prefixComments&&token.prefixComments.length>0||token.suffixComments&&token.suffixComments.length>0||token.lexeme.comments&&token.lexeme.comments.length>0||token.lexeme.positionedComments&&token.lexeme.positionedComments.length>0)return!0}return!1}extractLexemes(tokenData){let lexemes=new Array(tokenData.length),resolveLineColumn=this.createOrderedLineColumnResolver();for(let i=0;i<tokenData.length;i++){let token=tokenData[i],lexeme=token.lexeme,startInfo=resolveLineColumn(token.startPos),endInfo=resolveLineColumn(token.endPos);lexeme.position={startPosition:token.startPos,endPosition:token.endPos,startLine:startInfo.line,startColumn:startInfo.column,endLine:endInfo.line,endColumn:endInfo.column},lexemes[i]=lexeme}return lexemes}buildLexemesFromTokenData(tokenData){let lexemes=new Array(tokenData.length),resolveLineColumn=this.createOrderedLineColumnResolver(),hasPositionedComments=!1;for(let i=0;i<tokenData.length;i++){let current=tokenData[i],lexeme=current.lexeme,lexemeValue=lexeme.value;if(current.suffixComments&&current.suffixComments.length>0){if(lexemeValue==="select"){let suffixComments=current.suffixComments,targetIndex=i+1;for(;targetIndex<tokenData.length;){let target=tokenData[targetIndex];if(this.isMeaningfulSelectItemToken(target.lexeme)){target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null;break}targetIndex++}}if(lexemeValue==="from"){let suffixComments=current.suffixComments,targetIndex=i+1;for(;targetIndex<tokenData.length;){let target=tokenData[targetIndex];if(!((target.lexeme.type&128)!==0)){target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null;break}targetIndex++}}if(lexeme.type&16){let suffixComments=current.suffixComments,targetIndex=i+1;if(targetIndex<tokenData.length){let target=tokenData[targetIndex];target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null}}if(current.suffixComments){let normalized=lexemeValue.toLowerCase();if(normalized==="union"||normalized==="intersect"||normalized==="except"){let suffixComments=current.suffixComments,targetIndex=i+1;for(;targetIndex<tokenData.length;){let target=tokenData[targetIndex];if(target.lexeme.value.toLowerCase()==="select"){target.prefixComments||(target.prefixComments=[]),target.prefixComments.unshift(...suffixComments),current.suffixComments=null;break}targetIndex++}}}}this.attachCommentsToLexeme(lexeme,current);let startInfo=resolveLineColumn(current.startPos),endInfo=resolveLineColumn(current.endPos);lexeme.position={startPosition:current.startPos,endPosition:current.endPos,startLine:startInfo.line,startColumn:startInfo.column,endLine:endInfo.line,endColumn:endInfo.column},lexeme.positionedComments&&lexeme.positionedComments.length>0&&(hasPositionedComments=!0),lexemes[i]=lexeme}return hasPositionedComments&&this.relocateOrderByComments(lexemes),lexemes}skipPastTerminator(position){let next=position;return next<this.input.length&&this.input[next]===";"&&next++,this.skipWhitespaceAndComments(next)}mergeComments(base,addition){return addition&&addition.length>0?!base||base.length===0?[...addition]:[...base,...addition]:base?[...base]:null}relocateOrderByComments(lexemes){for(let i=0;i<lexemes.length-1;i++){let current=lexemes[i];if(current.value.toLowerCase()!=="order by"||!current.positionedComments)continue;let afterComments=current.positionedComments.filter(comment=>comment.position==="after"&&comment.comments&&comment.comments.length>0);if(afterComments.length===0)continue;current.positionedComments=current.positionedComments.filter(comment=>comment.position!=="after"),current.positionedComments.length===0&&(current.positionedComments=void 0);let target=lexemes[i+1],beforeComments=afterComments.map(comment=>({position:"before",comments:[...comment.comments]}));target.positionedComments&&target.positionedComments.length>0?target.positionedComments=[...beforeComments,...target.positionedComments]:target.positionedComments=beforeComments}}attachCommentsToLexeme(lexeme,tokenData){let newPositionedComments=[],existingLegacyComments=[],allLegacyComments=[];lexeme.positionedComments&&lexeme.positionedComments.length>0&&newPositionedComments.push(...lexeme.positionedComments),lexeme.comments&&lexeme.comments.length>0&&(existingLegacyComments.push(...lexeme.comments),allLegacyComments.push(...lexeme.comments)),tokenData.prefixComments&&tokenData.prefixComments.length>0&&(allLegacyComments.push(...tokenData.prefixComments),newPositionedComments.push({position:"before",comments:[...tokenData.prefixComments]})),tokenData.suffixComments&&tokenData.suffixComments.length>0&&(allLegacyComments.push(...tokenData.suffixComments),newPositionedComments.push({position:"after",comments:[...tokenData.suffixComments]})),newPositionedComments.length>0?(lexeme.positionedComments=newPositionedComments,lexeme.comments=existingLegacyComments.length>0?existingLegacyComments:null):allLegacyComments.length>0?(lexeme.comments=allLegacyComments,lexeme.positionedComments=void 0):(lexeme.comments=null,lexeme.positionedComments=void 0)}readComment(){let pos=this.position,inputLength=this.input.length;if(pos>=inputLength)return{position:pos,lines:null};let code=this.input.charCodeAt(pos);if(code!==32&&code!==9&&code!==10&&code!==13)if(code===45){if(pos+1>=inputLength||this.input.charCodeAt(pos+1)!==45)return{position:pos,lines:null}}else if(code===47){if(pos+1>=inputLength||this.input.charCodeAt(pos+1)!==42)return{position:pos,lines:null}}else return{position:pos,lines:null};return StringUtils.readWhiteSpaceAndComment(this.input,pos)}getDebugPositionInfo(errPosition){return StringUtils.getDebugPositionInfo(this.input,errPosition)}tokenizeWithFormatting(){let regularLexemes=this.tokenizeBasic();return this.mapToFormattingLexemes(regularLexemes)}mapToFormattingLexemes(regularLexemes){if(regularLexemes.length===0)return[];let lexemePositions=[],searchPos=0;for(let lexeme of regularLexemes){searchPos=this.skipWhitespaceAndComments(searchPos);let lexemeInfo=this.findLexemeAtPosition(lexeme,searchPos);if(lexemeInfo)lexemePositions.push(lexemeInfo),searchPos=lexemeInfo.endPosition;else{let fallbackInfo={startPosition:searchPos,endPosition:searchPos+lexeme.value.length};lexemePositions.push(fallbackInfo),searchPos=fallbackInfo.endPosition}}let formattingLexemes=[];for(let i=0;i<regularLexemes.length;i++){let lexeme=regularLexemes[i],lexemeInfo=lexemePositions[i],nextLexemeStartPos=i<regularLexemes.length-1?lexemePositions[i+1].startPosition:this.input.length,whitespaceSegment=this.input.slice(lexemeInfo.endPosition,nextLexemeStartPos),inlineComments=this.extractCommentsFromWhitespace(whitespaceSegment),formattingLexeme={...lexeme,followingWhitespace:whitespaceSegment,inlineComments,position:{startPosition:lexemeInfo.startPosition,endPosition:lexemeInfo.endPosition,...this.getLineColumnInfo(lexemeInfo.startPosition,lexemeInfo.endPosition)}};formattingLexemes.push(formattingLexeme)}return formattingLexemes}findLexemeAtPosition(lexeme,expectedPos){if(expectedPos>=this.input.length)return null;let valuesToTry=[lexeme.value,lexeme.value.toUpperCase(),lexeme.value.toLowerCase()];for(let valueToTry of valuesToTry)if(expectedPos+valueToTry.length<=this.input.length&&this.input.substring(expectedPos,expectedPos+valueToTry.length)===valueToTry&&this.isValidLexemeMatch(valueToTry,expectedPos))return{startPosition:expectedPos,endPosition:expectedPos+valueToTry.length};return null}isValidLexemeMatch(value,position){if(position>0){let charBefore=this.input[position-1];if(this.isAlphanumericUnderscore(charBefore))return!1}let endPosition=position+value.length;if(endPosition<this.input.length){let charAfter=this.input[endPosition];if(this.isAlphanumericUnderscore(charAfter))return!1}return!0}isAlphanumericUnderscore(char){let code=char.charCodeAt(0);return code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122||code===95}isWhitespace(char){let code=char.charCodeAt(0);return code===32||code===9||code===10||code===13}extractCommentsFromWhitespace(whitespaceSegment){let inlineComments=[],pos=0;for(;pos<whitespaceSegment.length;){let oldPos=pos,result=StringUtils.readWhiteSpaceAndComment(whitespaceSegment,pos),lines=result.lines;lines&&lines.length>0&&inlineComments.push(...lines),pos=result.position,pos===oldPos&&pos++}return inlineComments}skipWhitespaceAndComments(pos){return StringUtils.readWhiteSpaceAndComment(this.input,pos).position}getLineColumnInfo(startPos,endPos){let startInfo=this.getLineColumn(startPos),endInfo=this.getLineColumn(endPos);return{startLine:startInfo.line,startColumn:startInfo.column,endLine:endInfo.line,endColumn:endInfo.column}}getLineColumn(position){let starts=this.ensureLineStartPositions(),low=0,high=starts.length-1;for(;low<=high;){let mid=low+high>>>1;starts[mid]<=position?low=mid+1:high=mid-1}let lineIndex=high>=0?high:0,lineStart=starts[lineIndex];return{line:lineIndex+1,column:position-lineStart+1}}createOrderedLineColumnResolver(){let starts=this.ensureLineStartPositions(),lineIndex=0;return position=>{for(;lineIndex+1<starts.length&&starts[lineIndex+1]<=position;)lineIndex++;let lineStart=starts[lineIndex];return{line:lineIndex+1,column:position-lineStart+1}}}ensureLineStartPositions(){if(this.lineStartPositions)return this.lineStartPositions;let starts=[0];for(let i=0;i<this.input.length;i++)this.input.charCodeAt(i)===10&&starts.push(i+1);return this.lineStartPositions=starts,starts}};var SqlComponent=class{constructor(){this.comments=null;this.positionedComments=null}getKind(){return this.constructor.kind}accept(visitor){return visitor.visit(this)}toSqlString(formatter2){return this.accept(formatter2)}addPositionedComments(position,comments){if(!comments||comments.length===0)return;this.positionedComments||(this.positionedComments=[]);let existing=this.positionedComments.find(pc=>pc.position===position);existing?existing.comments.push(...comments):this.positionedComments.push({position,comments:[...comments]})}getPositionedComments(position){if(!this.positionedComments)return[];let positioned=this.positionedComments.find(pc=>pc.position===position);return positioned?positioned.comments:[]}getAllPositionedComments(){if(!this.positionedComments)return[];let result=[],beforeComments=this.getPositionedComments("before");result.push(...beforeComments);let afterComments=this.getPositionedComments("after");return result.push(...afterComments),result}},SqlDialectConfiguration=class{constructor(){this.parameterSymbol=":";this.identifierEscape={start:'"',end:'"'};this.exportComment="none"}};var InsertQuery=class extends SqlComponent{static{this.kind=Symbol("InsertQuery")}constructor(params){super(),this.insertClause=params.insertClause,this.selectQuery=params.selectQuery??null,this.returningClause=params.returning??null}};var InlineQuery=class extends SqlComponent{static{this.kind=Symbol("InlineQuery")}constructor(selectQuery){super(),this.selectQuery=selectQuery}},ValueList=class extends SqlComponent{static{this.kind=Symbol("ValueList")}constructor(values){super(),this.values=values}},ColumnReference=class extends SqlComponent{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof IdentifierString?this.qualifiedName.name:new IdentifierString(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(namespaces,column){super();let col=typeof column=="string"?new IdentifierString(column):column;this.qualifiedName=new QualifiedName(toIdentifierStringArray(namespaces),col)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(namespace=>namespace.name).join("."):""}},FunctionCall=class extends SqlComponent{static{this.kind=Symbol("FunctionCall")}constructor(namespaces,name,argument,over,withinGroup=null,withOrdinality=!1,internalOrderBy=null,filterCondition=null){super(),this.qualifiedName=new QualifiedName(namespaces,name),this.argument=argument,this.over=over,this.withinGroup=withinGroup,this.withOrdinality=withOrdinality,this.internalOrderBy=internalOrderBy,this.filterCondition=filterCondition}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},WindowFrameType=(WindowFrameType2=>(WindowFrameType2.Rows="rows",WindowFrameType2.Range="range",WindowFrameType2.Groups="groups",WindowFrameType2))(WindowFrameType||{}),WindowFrameBound=(WindowFrameBound2=>(WindowFrameBound2.UnboundedPreceding="unbounded preceding",WindowFrameBound2.UnboundedFollowing="unbounded following",WindowFrameBound2.CurrentRow="current row",WindowFrameBound2))(WindowFrameBound||{}),WindowFrameBoundStatic=class extends SqlComponent{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(bound){super(),this.bound=bound}},WindowFrameBoundaryValue=class extends SqlComponent{static{this.kind=Symbol("WindowFrameBoundary")}constructor(value,isFollowing){super(),this.value=value,this.isFollowing=isFollowing}},WindowFrameSpec=class extends SqlComponent{static{this.kind=Symbol("WindowFrameSpec")}constructor(frameType,startBound,endBound){super(),this.frameType=frameType,this.startBound=startBound,this.endBound=endBound}},WindowFrameExpression=class extends SqlComponent{static{this.kind=Symbol("WindowFrameExpression")}constructor(partition,order,frameSpec=null){super(),this.partition=partition,this.order=order,this.frameSpec=frameSpec}},UnaryExpression=class extends SqlComponent{static{this.kind=Symbol("UnaryExpression")}constructor(operator,expression){super(),this.operator=new RawString(operator),this.expression=expression}},BinaryExpression=class extends SqlComponent{static{this.kind=Symbol("BinaryExpression")}constructor(left,operator,right){super(),this.left=left,this.operator=new RawString(operator),this.right=right}},LiteralValue=class extends SqlComponent{static{this.kind=Symbol("LiteralExpression")}constructor(value,_deprecated,isStringLiteral){super(),this.value=value,this.isStringLiteral=isStringLiteral}},ParameterExpression=class extends SqlComponent{static{this.kind=Symbol("ParameterExpression")}constructor(name,value=null){super(),this.name=new RawString(name),this.value=value,this.index=null}},SwitchCaseArgument=class extends SqlComponent{static{this.kind=Symbol("SwitchCaseArgument")}constructor(cases,elseValue=null){super(),this.cases=cases,this.elseValue=elseValue}},CaseKeyValuePair=class extends SqlComponent{static{this.kind=Symbol("CaseKeyValuePair")}constructor(key,value){super(),this.key=key,this.value=value}},RawString=class extends SqlComponent{static{this.kind=Symbol("RawString")}constructor(value){super(),this.value=value}},IdentifierString=class extends SqlComponent{static{this.kind=Symbol("IdentifierString")}constructor(alias){super(),this.name=alias}},ParenExpression=class extends SqlComponent{static{this.kind=Symbol("ParenExpression")}constructor(expression){super(),this.expression=expression}},CastExpression=class extends SqlComponent{static{this.kind=Symbol("CastExpression")}constructor(input,castType){super(),this.input=input,this.castType=castType}},CaseExpression=class extends SqlComponent{static{this.kind=Symbol("CaseExpression")}constructor(condition,switchCase){super(),this.condition=condition,this.switchCase=switchCase}},ArrayExpression=class extends SqlComponent{static{this.kind=Symbol("ArrayExpression")}constructor(expression){super(),this.expression=expression}},ArrayQueryExpression=class extends SqlComponent{static{this.kind=Symbol("ArrayQueryExpression")}constructor(query){super(),this.query=query}},BetweenExpression=class extends SqlComponent{static{this.kind=Symbol("BetweenExpression")}constructor(expression,lower,upper,negated){super(),this.expression=expression,this.lower=lower,this.upper=upper,this.negated=negated}},StringSpecifierExpression=class extends SqlComponent{static{this.kind=Symbol("StringSpecifierExpression")}constructor(specifier,value){super(),this.specifier=new RawString(specifier),this.value=new LiteralValue(value)}},TypeValue=class extends SqlComponent{static{this.kind=Symbol("TypeValue")}constructor(namespaces,name,argument=null){super(),this.qualifiedName=new QualifiedName(namespaces,name),this.argument=argument}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let nameValue=this.qualifiedName.name instanceof RawString?this.qualifiedName.name.value:this.qualifiedName.name.name;return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(ns=>ns.name).join(".")+"."+nameValue:nameValue}},TupleExpression=class extends SqlComponent{static{this.kind=Symbol("TupleExpression")}constructor(values){super(),this.values=values}},ArraySliceExpression=class extends SqlComponent{static{this.kind=Symbol("ArraySliceExpression")}constructor(array,startIndex,endIndex){super(),this.array=array,this.startIndex=startIndex,this.endIndex=endIndex}},ArrayIndexExpression=class extends SqlComponent{static{this.kind=Symbol("ArrayIndexExpression")}constructor(array,index){super(),this.array=array,this.index=index}};function toIdentifierStringArray(input){if(input==null)return null;if(typeof input=="string")return input.trim()===""?null:[new IdentifierString(input)];if(Array.isArray(input)){if(input.length===0)return null;if(typeof input[0]=="string"){let filteredStrings=input.filter(ns=>ns.trim()!=="");return filteredStrings.length===0?null:filteredStrings.map(ns=>new IdentifierString(ns))}else{let filteredIdentifiers=input.filter(ns=>ns.name.trim()!=="");return filteredIdentifiers.length===0?null:filteredIdentifiers}}return null}var QualifiedName=class extends SqlComponent{static{this.kind=Symbol("QualifiedName")}constructor(namespaces,name){super(),this.namespaces=toIdentifierStringArray(namespaces),typeof name=="string"?this.name=new RawString(name):this.name=name}toString(){let nameValue=this.name instanceof RawString?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(ns=>ns.name).join(".")+"."+nameValue:nameValue}};var SelectItem=class extends SqlComponent{static{this.kind=Symbol("SelectItem")}constructor(value,name=null){super(),this.value=value,this.identifier=name?new IdentifierString(name):null}},SelectClause=class extends SqlComponent{static{this.kind=Symbol("SelectClause")}constructor(items,distinct=null,hints=[]){super(),this.items=items,this.distinct=distinct,this.hints=hints}},Distinct=class extends SqlComponent{static{this.kind=Symbol("Distinct")}constructor(){super()}},DistinctOn=class extends SqlComponent{static{this.kind=Symbol("DistinctOn")}constructor(value){super(),this.value=value}},WhereClause=class extends SqlComponent{static{this.kind=Symbol("WhereClause")}constructor(condition){super(),this.condition=condition}},PartitionByClause=class extends SqlComponent{static{this.kind=Symbol("PartitionByClause")}constructor(value){super(),this.value=value}},WindowFrameClause=class extends SqlComponent{static{this.kind=Symbol("WindowFrameClause")}constructor(name,expression){super(),this.name=new IdentifierString(name),this.expression=expression}},WindowsClause=class extends SqlComponent{static{this.kind=Symbol("WindowsClause")}constructor(windows){super(),this.windows=windows}},SortDirection=(SortDirection2=>(SortDirection2.Ascending="asc",SortDirection2.Descending="desc",SortDirection2))(SortDirection||{}),NullsSortDirection=(NullsSortDirection2=>(NullsSortDirection2.First="first",NullsSortDirection2.Last="last",NullsSortDirection2))(NullsSortDirection||{}),OrderByClause=class extends SqlComponent{static{this.kind=Symbol("OrderByClause")}constructor(items){super(),this.order=items}},OrderByItem=class extends SqlComponent{static{this.kind=Symbol("OrderByItem")}constructor(expression,sortDirection,nullsPosition){super(),this.value=expression,this.sortDirection=sortDirection===null?"asc":sortDirection,this.nullsPosition=nullsPosition}},GroupByClause=class extends SqlComponent{static{this.kind=Symbol("GroupByClause")}constructor(expression){super(),this.grouping=expression}},HavingClause=class extends SqlComponent{static{this.kind=Symbol("HavingClause")}constructor(condition){super(),this.condition=condition}},TableSource=class extends SqlComponent{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof IdentifierString?this.qualifiedName.name:new IdentifierString(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(namespaces,table){super();let tbl=typeof table=="string"?new IdentifierString(table):table;this.qualifiedName=new QualifiedName(namespaces,tbl)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(namespace=>namespace.name).join(".")+"."+(this.qualifiedName.name instanceof RawString?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof RawString?this.qualifiedName.name.value:this.qualifiedName.name.name}},FunctionSource=class extends SqlComponent{static{this.kind=Symbol("FunctionSource")}constructor(name,argument,withOrdinality=!1){if(super(),typeof name=="object"&&name!==null&&"name"in name){let nameObj=name;this.qualifiedName=new QualifiedName(nameObj.namespaces,nameObj.name)}else this.qualifiedName=new QualifiedName(null,name);this.argument=argument,this.withOrdinality=withOrdinality}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},ParenSource=class extends SqlComponent{static{this.kind=Symbol("ParenSource")}constructor(source){super(),this.source=source}},SubQuerySource=class extends SqlComponent{static{this.kind=Symbol("SubQuerySource")}constructor(query){super(),this.query=query}},SourceExpression=class extends SqlComponent{static{this.kind=Symbol("SourceExpression")}constructor(datasource,aliasExpression){super(),this.datasource=datasource,this.aliasExpression=aliasExpression}getAliasName(){return this.aliasExpression?this.aliasExpression.table.name:this.datasource instanceof TableSource?this.datasource.getSourceName():null}},JoinOnClause=class extends SqlComponent{static{this.kind=Symbol("JoinOnClause")}constructor(condition){super(),this.condition=condition}},JoinUsingClause=class extends SqlComponent{static{this.kind=Symbol("JoinUsingClause")}constructor(condition){super(),this.condition=condition}},JoinClause=class extends SqlComponent{static{this.kind=Symbol("JoinItem")}constructor(joinType,source,condition,lateral){super(),this.joinType=new RawString(joinType),this.source=source,this.condition=condition,this.lateral=lateral}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof TableSource?this.source.table.name:null}},FromClause=class extends SqlComponent{static{this.kind=Symbol("FromClause")}constructor(source,join){super(),this.source=source,this.joins=join}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof TableSource?this.source.datasource.table.name:null}getSources(){let sources=[this.source];if(this.joins)for(let join of this.joins)sources.push(join.source);return sources}},UsingClause=class extends SqlComponent{static{this.kind=Symbol("UsingClause")}constructor(sources){super(),this.sources=sources}getSources(){return[...this.sources]}},CommonTable=class extends SqlComponent{static{this.kind=Symbol("CommonTable")}constructor(query,aliasExpression,materialized){super(),this.query=query,this.materialized=materialized,typeof aliasExpression=="string"?this.aliasExpression=new SourceAliasExpression(aliasExpression,null):this.aliasExpression=aliasExpression}getSourceAliasName(){return this.aliasExpression.table.name}},WithClause=class extends SqlComponent{constructor(recursive,tables){super();this.trailingComments=null;this.globalComments=null;this.recursive=recursive,this.tables=tables}static{this.kind=Symbol("WithClause")}},LimitClause=class extends SqlComponent{static{this.kind=Symbol("LimitClause")}constructor(limit){super(),this.value=limit}},FetchType=(FetchType2=>(FetchType2.Next="next",FetchType2.First="first",FetchType2))(FetchType||{}),FetchUnit=(FetchUnit2=>(FetchUnit2.RowsOnly="rows only",FetchUnit2.Percent="percent",FetchUnit2.PercentWithTies="percent with ties",FetchUnit2))(FetchUnit||{}),OffsetClause=class extends SqlComponent{static{this.kind=Symbol("OffsetClause")}constructor(value){super(),this.value=value}},FetchClause=class extends SqlComponent{static{this.kind=Symbol("FetchClause")}constructor(expression){super(),this.expression=expression}},FetchExpression=class extends SqlComponent{static{this.kind=Symbol("FetchExpression")}constructor(type,count,unit){super(),this.type=type,this.count=count,this.unit=unit}},LockMode=(LockMode2=>(LockMode2.Update="update",LockMode2.Share="share",LockMode2.KeyShare="key share",LockMode2.NokeyUpdate="no key update",LockMode2))(LockMode||{}),ForClause=class extends SqlComponent{static{this.kind=Symbol("ForClause")}constructor(lockMode){super(),this.lockMode=lockMode}},SourceAliasExpression=class extends SqlComponent{static{this.kind=Symbol("SourceAliasExpression")}constructor(alias,columnAlias){super(),this.table=new IdentifierString(alias),this.columns=columnAlias!==null?columnAlias.map(alias2=>new IdentifierString(alias2)):null}},ReturningClause=class extends SqlComponent{static{this.kind=Symbol("ReturningClause")}constructor(items){super(),this.items=items}get columns(){return this.items.map(item=>item.value instanceof ColumnReference?item.value.column:new IdentifierString(item.identifier?.name??""))}},SetClause=class extends SqlComponent{static{this.kind=Symbol("SetClause")}constructor(items){super(),this.items=items.map(item=>item instanceof SetClauseItem?item:new SetClauseItem(item.column,item.value))}},SetClauseItem=class extends SqlComponent{static{this.kind=Symbol("SetClauseItem")}constructor(column,value){if(super(),typeof column=="object"&&column!==null&&"column"in column){let colObj=column,col=typeof colObj.column=="string"?new IdentifierString(colObj.column):colObj.column;this.qualifiedName=new QualifiedName(colObj.namespaces,col)}else{let col=typeof column=="string"?new IdentifierString(column):column;this.qualifiedName=new QualifiedName(null,col)}this.value=value}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof IdentifierString?this.qualifiedName.name:new IdentifierString(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},UpdateClause=class extends SqlComponent{static{this.kind=Symbol("UpdateClause")}constructor(source){super(),this.source=source}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof TableSource?this.source.datasource.table.name:null}},DeleteClause=class extends SqlComponent{static{this.kind=Symbol("DeleteClause")}constructor(source){super(),this.source=source}getSourceAliasName(){return this.source.getAliasName()}},InsertClause=class extends SqlComponent{constructor(source,columns){super(),this.source=source,columns&&columns.length>0?this.columns=columns.map(col=>typeof col=="string"?new IdentifierString(col):col):this.columns=null}};var POSTGRESQL_COMMAND_KEYWORDS_ALLOWED_AS_IDENTIFIER=new Set(["groups","rows","range","window","over","following","preceding","within","ordinality","lateral","recursive","materialized","partition"]),FullNameParser=class _FullNameParser{static parseFromLexeme(lexemes,index){let{identifiers,newIndex}=_FullNameParser.parseEscapedOrDotSeparatedIdentifiers(lexemes,index),{namespaces,name}=_FullNameParser.extractNamespacesAndName(identifiers),identifierString=new IdentifierString(name);if(newIndex>index){let lastLexeme=lexemes[newIndex-1];lastLexeme.positionedComments&&lastLexeme.positionedComments.length>0&&(identifierString.positionedComments=[...lastLexeme.positionedComments]),(!identifierString.positionedComments||identifierString.positionedComments.length===0)&&lastLexeme.comments&&lastLexeme.comments.length>0&&(identifierString.comments=[...lastLexeme.comments])}let lastTokenType=0;return newIndex>index&&(lastTokenType=lexemes[newIndex-1].type),{namespaces,name:identifierString,newIndex,lastTokenType}}static parse(str){let lexemes=new SqlTokenizer(str).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The name is complete but additional tokens were found.`);return{namespaces:result.namespaces,name:result.name}}static parseEscapedOrDotSeparatedIdentifiers(lexemes,index){let idx=index,identifiers=[];for(;idx<lexemes.length;){if(lexemes[idx].type&512){if(idx++,idx>=lexemes.length||!(lexemes[idx].type&64||lexemes[idx].type&128))throw new Error(`Expected identifier after '[' at position ${idx}`);if(identifiers.push(lexemes[idx].value),idx++,idx>=lexemes.length||lexemes[idx].value!=="]")throw new Error(`Expected closing ']' after identifier at position ${idx}`);idx++}else if(lexemes[idx].type&64)identifiers.push(lexemes[idx].value),idx++;else if(lexemes[idx].type&2048)identifiers.push(lexemes[idx].value),idx++;else if(lexemes[idx].type&8192)identifiers.push(lexemes[idx].value),idx++;else if(lexemes[idx].type&1&&SQL_SPECIAL_VALUE_KEYWORD_SET.has(lexemes[idx].value.toLowerCase()))identifiers.push(lexemes[idx].value),idx++;else if(lexemes[idx].type&128&&POSTGRESQL_COMMAND_KEYWORDS_ALLOWED_AS_IDENTIFIER.has(lexemes[idx].value.toLowerCase()))identifiers.push(lexemes[idx].value),idx++;else if(lexemes[idx].value==="*"){identifiers.push(lexemes[idx].value),idx++;break}if(idx<lexemes.length&&lexemes[idx].type&32)idx++;else break}return{identifiers,newIndex:idx}}static extractNamespacesAndName(identifiers){if(!identifiers||identifiers.length===0)throw new Error("Identifier list is empty");return identifiers.length===1?{namespaces:null,name:identifiers[0]}:{namespaces:identifiers.slice(0,-1),name:identifiers[identifiers.length-1]}}};var IdentifierParser=class{static parseFromLexeme(lexemes,index){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,index);return{value:new ColumnReference(namespaces,name),newIndex}}};var LiteralParser=class{static parseFromLexeme(lexemes,index){let idx=index,valueText=lexemes[idx].value,parsedValue,lex=literalKeywordParser.parse(valueText.toLowerCase(),0);if(lex){let value=new RawString(lex.keyword);return idx++,{value,newIndex:idx}}if(/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(valueText))return parsedValue=Number(valueText),idx++,{value:new LiteralValue(parsedValue),newIndex:idx};{/^\$[^$]*\$[\s\S]*\$[^$]*\$$/.test(valueText)?parsedValue=valueText:valueText.startsWith("'")&&valueText.endsWith("'")?parsedValue=valueText.slice(1,-1):parsedValue=valueText;let isStringLiteral=valueText.startsWith("'")&&valueText.endsWith("'");return idx++,{value:new LiteralValue(parsedValue,void 0,isStringLiteral),newIndex:idx}}}};var ParenExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(idx+1<lexemes.length&&lexemes[idx].type&4&&(lexemes[idx+1].value==="select"||lexemes[idx+1].value==="values"||lexemes[idx+1].value==="with")){let openLexeme=lexemes[idx],openPositionedComments=openLexeme.positionedComments?openLexeme.positionedComments.map(comment=>({position:comment.position,comments:[...comment.comments]})):null,openLegacyComments=openLexeme.comments?[...openLexeme.comments]:null;idx+=1;let result2=SelectQueryParser.parseFromLexeme(lexemes,idx);if(idx=result2.newIndex,idx>=lexemes.length||lexemes[idx].type!==8)throw new Error(`Expected ')' at index ${idx}, but found ${lexemes[idx].value}`);let closingLexeme=lexemes[idx],closingLegacyComments=closingLexeme.comments,closingPositionedComments=closingLexeme.positionedComments;idx++;let value2=new InlineQuery(result2.value);if(openPositionedComments&&openPositionedComments.length>0){let beforeComments=openPositionedComments.filter(comment=>comment.position==="after"&&comment.comments.length>0).map(comment=>({position:"before",comments:[...comment.comments]}));beforeComments.length>0&&(value2.positionedComments=value2.positionedComments?[...beforeComments,...value2.positionedComments]:beforeComments)}else if(openLegacyComments&&openLegacyComments.length>0){let beforeCommentBlock={position:"before",comments:[...openLegacyComments]};value2.positionedComments=value2.positionedComments?[beforeCommentBlock,...value2.positionedComments]:[beforeCommentBlock]}if(closingPositionedComments&&closingPositionedComments.length>0){let afterComments=closingPositionedComments.filter(comment=>comment.position==="after"&&comment.comments.length>0).map(comment=>({position:comment.position,comments:[...comment.comments]}));afterComments.length>0&&(value2.positionedComments=value2.positionedComments?[...value2.positionedComments,...afterComments]:afterComments)}else closingLegacyComments&&closingLegacyComments.length>0&&(value2.comments=closingLegacyComments);return{value:value2,newIndex:idx}}let result=ValueParser.parseArgument(4,8,lexemes,index);idx=result.newIndex;let value=new ParenExpression(result.value),closingIndex=idx-1;if(closingIndex>=0&&closingIndex<lexemes.length){let closingLexeme=lexemes[closingIndex];if(closingLexeme.type&8)if(closingLexeme.positionedComments&&closingLexeme.positionedComments.length>0){let afterComments=closingLexeme.positionedComments.filter(comment=>comment.position==="after"&&comment.comments.length>0).map(comment=>({position:comment.position,comments:[...comment.comments]}));afterComments.length>0&&(value.positionedComments=value.positionedComments?[...value.positionedComments,...afterComments]:afterComments)}else closingLexeme.comments&&closingLexeme.comments.length>0&&(value.comments=value.comments?value.comments.concat(closingLexeme.comments):[...closingLexeme.comments])}return{value,newIndex:idx}}};var UnaryExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&2){let operatorLexeme=lexemes[idx],operator=operatorLexeme.value;if(idx++,operator==="*")return{value:new ColumnReference(null,"*"),newIndex:idx};let result=ValueParser.parseFromLexeme(lexemes,idx);idx=result.newIndex;let value=new UnaryExpression(operator,result.value);return operatorLexeme.positionedComments&&operatorLexeme.positionedComments.length>0?value.positionedComments=operatorLexeme.positionedComments:operatorLexeme.comments&&operatorLexeme.comments.length>0&&(value.comments=operatorLexeme.comments),{value,newIndex:idx}}throw new Error(`Invalid unary expression at index ${index}: ${lexemes[index].value}`)}};var ParameterExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index,paramName=lexemes[idx].value;paramName.startsWith("${")&&paramName.endsWith("}")?paramName=paramName.slice(2,-1):paramName=paramName.slice(1);let value=new ParameterExpression(paramName);return idx++,{value,newIndex:idx}}};var StringSpecifierExpressionParser=class{static parseFromLexeme(lexemes,index){let idx=index,specifer=lexemes[idx].value;if(idx++,idx>=lexemes.length||lexemes[idx].type!==1)throw new Error(`Expected string literal after string specifier at index ${idx}`);let value=lexemes[idx].value;return idx++,{value:new StringSpecifierExpression(specifer,value),newIndex:idx}}};var CommandExpressionParser=class _CommandExpressionParser{static parseFromLexeme(lexemes,index){let idx=index,current=lexemes[idx];if(current.value==="case"){let caseKeywordComments=current.comments,caseKeywordPositionedComments=current.positionedComments;return idx++,this.parseCaseExpression(lexemes,idx,caseKeywordComments,caseKeywordPositionedComments)}else if(current.value==="case when"){let caseWhenKeywordComments=current.comments,caseWhenKeywordPositionedComments=current.positionedComments;return idx++,this.parseCaseWhenExpression(lexemes,idx,caseWhenKeywordComments,caseWhenKeywordPositionedComments)}return this.parseModifierUnaryExpression(lexemes,idx)}static parseModifierUnaryExpression(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&128){let command=lexemes[idx].value;idx++;let result=ValueParser.parseFromLexeme(lexemes,idx);return{value:new UnaryExpression(command,result.value),newIndex:result.newIndex}}throw new Error(`Invalid modifier unary expression at index ${idx}, Lexeme: ${lexemes[idx].value}`)}static parseCaseExpression(lexemes,index,caseKeywordComments,caseKeywordPositionedComments){let idx=index,condition=ValueParser.parseFromLexeme(lexemes,idx);idx=condition.newIndex;let switchCaseResult=this.parseSwitchCaseArgument(lexemes,idx,[]);idx=switchCaseResult.newIndex;let result=new CaseExpression(condition.value,switchCaseResult.value);return caseKeywordPositionedComments&&caseKeywordPositionedComments.length>0?result.positionedComments=caseKeywordPositionedComments:caseKeywordComments&&caseKeywordComments.length>0&&(result.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(caseKeywordComments,"before")]),{value:result,newIndex:idx}}static parseCaseWhenExpression(lexemes,index,caseWhenKeywordComments,caseWhenKeywordPositionedComments){let idx=index,casewhenResult=this.parseCaseConditionValuePair(lexemes,idx);idx=casewhenResult.newIndex;let caseWhenList=[casewhenResult.value],switchCaseResult=this.parseSwitchCaseArgument(lexemes,idx,caseWhenList);idx=switchCaseResult.newIndex;let result=new CaseExpression(null,switchCaseResult.value);return caseWhenKeywordPositionedComments&&caseWhenKeywordPositionedComments.length>0?result.positionedComments=caseWhenKeywordPositionedComments:caseWhenKeywordComments&&caseWhenKeywordComments.length>0&&(result.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(caseWhenKeywordComments,"before")]),{value:result,newIndex:idx}}static parseSwitchCaseArgument(lexemes,index,initialWhenThenList){let idx=index,whenThenList=[...initialWhenThenList];idx=this.parseAdditionalWhenClauses(lexemes,idx,whenThenList);let{elseValue,elseComments,newIndex:elseIndex}=this.parseElseClause(lexemes,idx);idx=elseIndex;let{endComments,newIndex:endIndex}=this.parseEndClause(lexemes,idx);if(idx=endIndex,whenThenList.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${idx})`);let switchCaseArg=new SwitchCaseArgument(whenThenList,elseValue);return this.applySwitchCaseComments(switchCaseArg,elseComments,endComments),{value:switchCaseArg,newIndex:idx}}static parseAdditionalWhenClauses(lexemes,index,whenThenList){let idx=index;for(;idx<lexemes.length&&this.isCommandWithValue(lexemes[idx],"when");){idx++;let whenResult=this.parseCaseConditionValuePair(lexemes,idx);idx=whenResult.newIndex,whenThenList.push(whenResult.value)}return idx}static parseElseClause(lexemes,index){let elseValue=null,elseComments=null,idx=index;if(idx<lexemes.length&&this.isCommandWithValue(lexemes[idx],"else")){elseComments=this.extractKeywordComments(lexemes[idx]),idx++;let elseResult=ValueParser.parseFromLexeme(lexemes,idx);elseValue=elseResult.value,idx=elseResult.newIndex}return{elseValue,elseComments,newIndex:idx}}static parseEndClause(lexemes,index){let idx=index,endComments=null;if(idx<lexemes.length&&this.isCommandWithValue(lexemes[idx],"end"))endComments=this.extractKeywordComments(lexemes[idx]),idx++;else throw new Error(`The CASE expression requires 'end' keyword at the end (index ${idx})`);return{endComments,newIndex:idx}}static extractKeywordComments(token){return{legacy:token.comments,positioned:token.positionedComments}}static applySwitchCaseComments(switchCaseArg,elseComments,endComments){let allPositionedComments=[],allLegacyComments=[];elseComments?.positioned&&elseComments.positioned.length>0&&allPositionedComments.push(...elseComments.positioned),elseComments?.legacy&&elseComments.legacy.length>0&&allLegacyComments.push(...elseComments.legacy),endComments?.positioned&&endComments.positioned.length>0&&allPositionedComments.push(...endComments.positioned),endComments?.legacy&&endComments.legacy.length>0&&allLegacyComments.push(...endComments.legacy),allPositionedComments.length>0?switchCaseArg.positionedComments=allPositionedComments:allLegacyComments.length>0&&(switchCaseArg.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(allLegacyComments,"after")])}static isCommandWithValue(lexeme,value){return(lexeme.type&128)!==0&&lexeme.value===value}static parseCaseConditionValuePair(lexemes,index){let idx=index,condition=ValueParser.parseFromLexeme(lexemes,idx);if(idx=condition.newIndex,idx>=lexemes.length||!(lexemes[idx].type&128)||lexemes[idx].value!=="then")throw new Error(`Expected 'then' after WHEN condition at index ${idx}`);let thenKeywordComments=lexemes[idx].comments,thenKeywordPositionedComments=lexemes[idx].positionedComments;idx++;let value=ValueParser.parseFromLexeme(lexemes,idx);idx=value.newIndex;let keyValuePair=new CaseKeyValuePair(condition.value,value.value);return thenKeywordPositionedComments&&thenKeywordPositionedComments.length>0?keyValuePair.positionedComments=thenKeywordPositionedComments:thenKeywordComments&&thenKeywordComments.length>0&&(keyValuePair.positionedComments=[_CommandExpressionParser.convertLegacyToPositioned(thenKeywordComments,"after")]),{value:keyValuePair,newIndex:idx}}static convertLegacyToPositioned(legacyComments,position="before"){return{position,comments:legacyComments}}};var OrderByClauseParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The ORDER BY clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="order by")throw new Error(`Syntax error at position ${idx}: Expected 'ORDER BY' keyword but found "${lexemes[idx].value}". ORDER BY clauses must start with the ORDER BY keywords.`);idx++;let items=[],item=this.parseItem(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=this.parseItem(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No ordering expressions found. The ORDER BY clause requires at least one expression to order by.`);return{value:new OrderByClause(items),newIndex:idx}}static parseItem(lexemes,index){let idx=index,parsedValue=ValueParser.parseFromLexeme(lexemes,idx),value=parsedValue.value;if(idx=parsedValue.newIndex,idx>=lexemes.length)return{value,newIndex:idx};let sortDirectionComments=null,sortDirection=null;if(idx<lexemes.length){let token=lexemes[idx];if(token.value==="asc"?(sortDirection="asc",idx++):token.value==="desc"&&(sortDirection="desc",idx++),sortDirection!==null){if(token.positionedComments&&token.positionedComments.length>0){sortDirectionComments=[];for(let posComment of token.positionedComments)posComment.comments&&posComment.comments.length>0&&sortDirectionComments.push(...posComment.comments)}token.comments&&token.comments.length>0&&(sortDirectionComments||(sortDirectionComments=[]),sortDirectionComments.push(...token.comments))}}let nullsSortDirection=idx>=lexemes.length?null:lexemes[idx].value==="nulls first"?(idx++,"first"):lexemes[idx].value==="nulls last"?(idx++,"last"):null;return sortDirectionComments&&sortDirectionComments.length>0&&(value.comments?value.comments.push(...sortDirectionComments):value.comments=sortDirectionComments),sortDirection===null&&nullsSortDirection===null?{value,newIndex:idx}:{value:new OrderByItem(value,sortDirection,nullsSortDirection),newIndex:idx}}};var PartitionByParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The PARTITION BY clause is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="partition by")throw new Error(`Syntax error at position ${idx}: Expected 'PARTITION BY' keyword but found "${lexemes[idx].value}". PARTITION BY clauses must start with the PARTITION BY keywords.`);idx++;let items=[],item=ValueParser.parseFromLexeme(lexemes,idx);for(items.push(item.value),idx=item.newIndex;idx<lexemes.length&&lexemes[idx].type&16;){idx++;let item2=ValueParser.parseFromLexeme(lexemes,idx);items.push(item2.value),idx=item2.newIndex}if(items.length===0)throw new Error(`Syntax error at position ${index}: No partition expressions found. The PARTITION BY clause requires at least one expression to partition by.`);return items.length===1?{value:new PartitionByClause(items[0]),newIndex:idx}:{value:new PartitionByClause(new ValueList(items)),newIndex:idx}}};var WindowExpressionParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The window frame expression is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].type!==4)throw new Error(`Syntax error at position ${idx}: Expected opening parenthesis '(' but found "${lexemes[idx].value}".`);idx++;let partition=null,order=null,frameSpec=null;if(idx<lexemes.length&&lexemes[idx].value==="partition by"){let partitionResult=PartitionByParser.parseFromLexeme(lexemes,idx);partition=partitionResult.value,idx=partitionResult.newIndex}if(idx<lexemes.length&&lexemes[idx].value==="order by"){let orderResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);order=orderResult.value,idx=orderResult.newIndex}if(idx<lexemes.length&&this.isFrameTypeKeyword(lexemes[idx].value)){let frameSpecResult=this.parseFrameSpec(lexemes,idx);frameSpec=frameSpecResult.value,idx=frameSpecResult.newIndex}if(idx>=lexemes.length||lexemes[idx].type!==8)throw new Error(`Syntax error at position ${idx}: Missing closing parenthesis ')' for window frame. Each opening parenthesis must have a matching closing parenthesis.`);return idx++,{value:new WindowFrameExpression(partition,order,frameSpec),newIndex:idx}}static isFrameTypeKeyword(value){let lowerValue=value;return lowerValue==="rows"||lowerValue==="range"||lowerValue==="groups"}static parseFrameSpec(lexemes,index){let idx=index,frameTypeStr=lexemes[idx].value,frameType;switch(frameTypeStr){case"rows":frameType="rows";break;case"range":frameType="range";break;case"groups":frameType="groups";break;default:throw new Error(`Syntax error at position ${idx}: Invalid frame type "${lexemes[idx].value}". Expected one of: ROWS, RANGE, GROUPS.`)}if(idx++,idx<lexemes.length&&lexemes[idx].value==="between"){idx++;let startBoundResult=this.parseFrameBoundary(lexemes,idx),startBound=startBoundResult.value;if(idx=startBoundResult.newIndex,idx>=lexemes.length||lexemes[idx].value!=="and")throw new Error(`Syntax error at position ${idx}: Expected 'AND' keyword in BETWEEN clause.`);idx++;let endBoundResult=this.parseFrameBoundary(lexemes,idx),endBound=endBoundResult.value;return idx=endBoundResult.newIndex,{value:new WindowFrameSpec(frameType,startBound,endBound),newIndex:idx}}else{let boundaryResult=this.parseFrameBoundary(lexemes,idx),startBound=boundaryResult.value;return idx=boundaryResult.newIndex,{value:new WindowFrameSpec(frameType,startBound,null),newIndex:idx}}}static parseFrameBoundary(lexemes,index){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&128){let currentValue=lexemes[idx].value,frameBound;switch(currentValue){case"current row":frameBound="current row";break;case"unbounded preceding":frameBound="unbounded preceding";break;case"unbounded following":frameBound="unbounded following";break;default:throw new Error(`Syntax error at position ${idx}: Invalid frame type "${lexemes[idx].value}". Expected one of: ROWS, RANGE, GROUPS.`)}return{value:new WindowFrameBoundStatic(frameBound),newIndex:idx+1}}else if(idx<lexemes.length&&lexemes[idx].type&1){let valueResult=ValueParser.parseFromLexeme(lexemes,idx);if(idx=valueResult.newIndex,idx<lexemes.length&&lexemes[idx].type&128){let direction=lexemes[idx].value,isFollowing;if(direction==="preceding")isFollowing=!1;else if(direction==="following")isFollowing=!0;else throw new Error(`Syntax error at position ${idx}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`);return idx++,{value:new WindowFrameBoundaryValue(valueResult.value,isFollowing),newIndex:idx}}else throw new Error(`Syntax error at position ${idx}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`)}throw new Error(`Syntax error at position ${idx}: Expected a valid frame boundary component.`)}};var OverExpressionParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw new Error(`Syntax error: Unexpected token "${lexemes[result.newIndex].value}" at position ${result.newIndex}. The OVER expression is complete but there are additional tokens.`);return result.value}static parseFromLexeme(lexemes,index){let idx=index;if(lexemes[idx].value!=="over")throw new Error(`Syntax error at position ${idx}: Expected 'OVER' keyword but found "${lexemes[idx].value}". OVER expressions must start with the OVER keyword.`);if(idx++,idx>=lexemes.length)throw new Error("Syntax error: Unexpected end of input after 'OVER' keyword. Expected either a window name or an opening parenthesis '('.");if(lexemes[idx].type&64){let name=lexemes[idx].value;return idx++,{value:new IdentifierString(name),newIndex:idx}}if(lexemes[idx].type&4)return WindowExpressionParser.parseFromLexeme(lexemes,idx);throw new Error(`Syntax error at position ${idx}: Expected a window name or opening parenthesis '(' after OVER keyword, but found "${lexemes[idx].value}".`)}};var ParseError=class _ParseError extends Error{constructor(message,index,context){super(message);this.index=index;this.context=context;this.name="ParseError"}static fromUnparsedLexemes(lexemes,index,messagePrefix){let start=Math.max(0,index-2),end=Math.min(lexemes.length,index+3),context=lexemes.slice(start,end).map((lexeme,idx)=>{let marker=idx+start===index?">":" ",typeName=TokenType[lexeme.type]||lexeme.type;return`${marker} ${idx+start}:${lexeme.value} [${typeName}]`}).join(`
11
11
  `),message=`${messagePrefix} Unparsed lexeme remains at index ${index}: ${lexemes[index].value}
12
12
  Context:
13
- ${context}`;return new _ParseError(message,index,context)}};function extractLexemeComments(lexeme){let before=[],after=[];if(!lexeme)return{before,after};if(lexeme.positionedComments&&lexeme.positionedComments.length>0)for(let positioned of lexeme.positionedComments)!positioned.comments||positioned.comments.length===0||(positioned.position==="before"?before.push(...positioned.comments):positioned.position==="after"&&after.push(...positioned.comments));else lexeme.comments&&lexeme.comments.length>0&&before.push(...lexeme.comments);return{before,after}}var FunctionExpressionParser=class{static{this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY=new Set(["string_agg","array_agg","json_agg","jsonb_agg","json_object_agg","jsonb_object_agg","xmlagg"])}static parseArrayExpression(lexemes,index){let idx=index;if(idx+1<lexemes.length&&lexemes[idx+1].type&512){idx++;let arg=ValueParser.parseArgument(512,1024,lexemes,idx);return idx=arg.newIndex,{value:new ArrayExpression(arg.value),newIndex:idx}}else if(idx+1<lexemes.length&&lexemes[idx+1].type&4){idx++,idx++;let arg=SelectQueryParser.parseFromLexeme(lexemes,idx);return idx=arg.newIndex,idx++,{value:new ArrayQueryExpression(arg.value),newIndex:idx}}throw new Error(`Invalid ARRAY syntax at index ${idx}, expected ARRAY[... or ARRAY(...)`)}static parseFromLexeme(lexemes,index){let idx=index,current=lexemes[idx];return current.value==="array"?this.parseArrayExpression(lexemes,idx):current.value==="substring"||current.value==="overlay"?this.parseKeywordFunction(lexemes,idx,[{key:"from",required:!1},{key:"for",required:!1}]):current.value==="cast"?this.parseKeywordFunction(lexemes,idx,[{key:"as",required:!0}]):current.value==="trim"?this.parseKeywordFunction(lexemes,idx,[{key:"from",required:!1}]):this.parseFunctionCall(lexemes,idx)}static tryParseBinaryExpression(lexemes,index,left,allowAndOperator=!0,allowOrOperator=!0){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&2){let operator=lexemes[idx].value.toLowerCase();if(!allowAndOperator&&operator==="and"||!allowOrOperator&&operator==="or")return null;if(idx++,operator==="between")return this.parseBetweenExpression(lexemes,idx,left,!1);if(operator==="not between")return this.parseBetweenExpression(lexemes,idx,left,!0);if(operator==="::"){let typeValue=this.parseTypeValue(lexemes,idx);return idx=typeValue.newIndex,{value:new CastExpression(left,typeValue.value),newIndex:idx}}let rightResult=ValueParser.parseFromLexeme(lexemes,idx);return idx=rightResult.newIndex,{value:new BinaryExpression(left,operator,rightResult.value),newIndex:idx}}return null}static parseBetweenExpression(lexemes,index,value,negated){let idx=index,lower=ValueParser.parseFromLexeme(lexemes,idx,!1);if(idx=lower.newIndex,idx<lexemes.length&&lexemes[idx].type&2&&lexemes[idx].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${idx}`);idx++;let upper=this.parseBetweenUpperBound(lexemes,idx);return idx=upper.newIndex,{value:new BetweenExpression(value,lower.value,upper.value,negated),newIndex:idx}}static parseBetweenUpperBound(lexemes,index){return ValueParser.parseFromLexeme(lexemes,index,!1,!1)}static parseFunctionCall(lexemes,index){let idx=index,fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx),namespaces=fullNameResult.namespaces,name=fullNameResult.name;if(idx=fullNameResult.newIndex,idx<lexemes.length&&lexemes[idx].type&4){let functionName=name.name.toLowerCase(),arg,closingComments=null,internalOrderBy=null;if(this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY.has(functionName)){let result=this.parseAggregateArguments(lexemes,idx);arg={value:result.arguments,newIndex:result.newIndex},internalOrderBy=result.orderByClause,closingComments=result.closingComments}else{let argWithComments=this.parseArgumentWithComments(lexemes,idx);arg={value:argWithComments.value,newIndex:argWithComments.newIndex},closingComments=argWithComments.closingComments}idx=arg.newIndex;let withinGroup=null;if(idx<lexemes.length&&lexemes[idx].value==="within group"){let withinGroupResult=this.parseWithinGroupClause(lexemes,idx);withinGroup=withinGroupResult.value,idx=withinGroupResult.newIndex}let filterCondition=null;if(idx<lexemes.length&&lexemes[idx].value==="filter"){let filterResult=this.parseFilterClause(lexemes,idx);filterCondition=filterResult.condition,idx=filterResult.newIndex}let withOrdinality=!1;if(idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++),idx<lexemes.length&&lexemes[idx].value==="over"){let over=OverExpressionParser.parseFromLexeme(lexemes,idx);idx=over.newIndex;let value=new FunctionCall(namespaces,name.name,arg.value,over.value,withinGroup,withOrdinality,internalOrderBy,filterCondition);return closingComments&&closingComments.length>0&&value.addPositionedComments("after",closingComments),{value,newIndex:idx}}else{let value=new FunctionCall(namespaces,name.name,arg.value,null,withinGroup,withOrdinality,internalOrderBy,filterCondition);return closingComments&&closingComments.length>0&&value.addPositionedComments("after",closingComments),{value,newIndex:idx}}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Expected opening parenthesis after function name '${name.name}'.`)}static parseKeywordFunction(lexemes,index,keywords2){let idx=index,fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx),namespaces=fullNameResult.namespaces,name=fullNameResult.name;if(idx=fullNameResult.newIndex,idx<lexemes.length&&lexemes[idx].type&4){idx++;let input=ValueParser.parseFromLexeme(lexemes,idx),arg=input.value;if(idx=input.newIndex,idx<lexemes.length&&lexemes[idx].type&16)return this.parseFunctionCall(lexemes,index);for(let{key,required}of keywords2)if(idx<lexemes.length&&lexemes[idx].type&128&&lexemes[idx].value===key)if(idx++,idx<lexemes.length&&lexemes[idx].type&8192){let typeValue=this.parseTypeValue(lexemes,idx);arg=new BinaryExpression(arg,key,typeValue.value),idx=typeValue.newIndex}else{let right=ValueParser.parseFromLexeme(lexemes,idx);arg=new BinaryExpression(arg,key,right.value),idx=right.newIndex}else if(required)throw ParseError.fromUnparsedLexemes(lexemes,idx,`Keyword '${key}' is required for ${name.name} function.`);if(idx<lexemes.length&&lexemes[idx].type&8){idx++;let withinGroup=null;if(idx<lexemes.length&&lexemes[idx].value==="within group"){let withinGroupResult=this.parseWithinGroupClause(lexemes,idx);withinGroup=withinGroupResult.value,idx=withinGroupResult.newIndex}let withOrdinality=!1;if(idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++),idx<lexemes.length&&lexemes[idx].value==="over"){idx++;let over=OverExpressionParser.parseFromLexeme(lexemes,idx);return idx=over.newIndex,{value:new FunctionCall(namespaces,name.name,arg,over.value,withinGroup,withOrdinality,null),newIndex:idx}}else return{value:new FunctionCall(namespaces,name.name,arg,null,withinGroup,withOrdinality,null),newIndex:idx}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Missing closing parenthesis for function '${name.name}'.`)}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Missing opening parenthesis for function '${name.name}'.`)}static parseTypeValue(lexemes,index){let idx=index,{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,idx<lexemes.length&&lexemes[idx].type&4){let arg=ValueParser.parseArgument(4,8,lexemes,idx);idx=arg.newIndex;let value=new TypeValue(namespaces,new RawString(name.name),arg.value);return arg.value.positionedComments&&(value.positionedComments=arg.value.positionedComments),arg.value.comments,{value,newIndex:idx}}else return{value:new TypeValue(namespaces,new RawString(name.name)),newIndex:idx}}static parseWithinGroupClause(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].value!=="within group")throw new Error(`Expected 'WITHIN GROUP' at index ${idx}`);if(idx++,idx>=lexemes.length||!(lexemes[idx].type&4))throw new Error(`Expected '(' after 'WITHIN GROUP' at index ${idx}`);idx++;let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);if(idx=orderByResult.newIndex,idx>=lexemes.length||!(lexemes[idx].type&8))throw new Error(`Expected ')' after WITHIN GROUP ORDER BY clause at index ${idx}`);return idx++,{value:orderByResult.value,newIndex:idx}}static parseFilterClause(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].value!=="filter")throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected 'FILTER' keyword.");if(idx++,idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected '(' after FILTER.");if(idx++,idx>=lexemes.length||lexemes[idx].value!=="where")throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected 'WHERE' inside FILTER clause.");idx++;let conditionResult=ValueParser.parseFromLexeme(lexemes,idx);if(idx=conditionResult.newIndex,idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected ')' after FILTER predicate.");return idx++,{condition:conditionResult.value,newIndex:idx}}static parseAggregateArguments(lexemes,index){let idx=index,args=[],orderByClause=null;if(idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected opening parenthesis.");if(idx++,idx<lexemes.length&&lexemes[idx].type&8){let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{arguments:new ValueList([]),orderByClause:null,closingComments:closingComments2,newIndex:idx}}if(idx<lexemes.length&&lexemes[idx].value==="*"){let wildcard=new ColumnReference(null,"*");if(idx++,idx<lexemes.length&&lexemes[idx].type&8){let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{arguments:wildcard,orderByClause:null,closingComments:closingComments2,newIndex:idx}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis after wildcard '*'.")}let firstArg=ValueParser.parseFromLexeme(lexemes,idx);for(idx=firstArg.newIndex,args.push(firstArg.value);idx<lexemes.length&&(lexemes[idx].type&16||lexemes[idx].value==="order by");){if(lexemes[idx].value==="order by"){let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);idx=orderByResult.newIndex,orderByClause=orderByResult.value;break}if(lexemes[idx].type&16){if(idx++,idx<lexemes.length&&lexemes[idx].value==="order by"){let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);idx=orderByResult.newIndex,orderByClause=orderByResult.value;break}let argResult=ValueParser.parseFromLexeme(lexemes,idx);idx=argResult.newIndex,args.push(argResult.value)}}if(idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis.");let closingComments=this.getClosingComments(lexemes[idx]);return idx++,{arguments:args.length===1?args[0]:new ValueList(args),orderByClause,closingComments,newIndex:idx}}static parseArgumentWithComments(lexemes,index){let idx=index;if(idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected opening parenthesis.");let openParenToken=lexemes[idx];idx++;let args=[];if(idx<lexemes.length&&lexemes[idx].type&8){let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{value:new ValueList([]),closingComments:closingComments2,newIndex:idx}}if(idx<lexemes.length&&lexemes[idx].value==="*"){let wildcard=new ColumnReference(null,"*");if(idx++,idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis after wildcard '*'.");let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{value:wildcard,closingComments:closingComments2,newIndex:idx}}let result=ValueParser.parseFromLexeme(lexemes,idx);if(idx=result.newIndex,openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let afterComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){let beforeComments=afterComments.map(pc=>({position:"before",comments:pc.comments}));result.value.positionedComments=[...beforeComments,...result.value.positionedComments||[]],result.value,"qualifiedName"in result.value&&result.value.qualifiedName&&"name"in result.value.qualifiedName&&result.value.qualifiedName.name&&(result.value.qualifiedName.name.positionedComments=null,result.value.qualifiedName.name)}}for(args.push(result.value);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let argResult=ValueParser.parseFromLexeme(lexemes,idx);idx=argResult.newIndex,args.push(argResult.value)}if(idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis.");let closingComments=this.getClosingComments(lexemes[idx]);return idx++,{value:args.length===1?args[0]:new ValueList(args),closingComments,newIndex:idx}}static getClosingComments(lexeme){if(!lexeme)return null;let commentInfo=extractLexemeComments(lexeme);return commentInfo.after.length>0?commentInfo.after:commentInfo.before.length>0?commentInfo.before:null}};var OperatorPrecedence=class{static{this.precedenceMap={or:1,and:2,"=":10,"!=":10,"<>":10,"<":10,"<=":10,">":10,">=":10,like:10,ilike:10,"not like":10,"not ilike":10,"similar to":10,"not similar to":10,in:10,"not in":10,is:10,"is not":10,"->":10,"->>":10,"#>":10,"#>>":10,"@>":10,"<@":10,"?":10,"?|":10,"?&":10,"~":10,"~*":10,"!~":10,"!~*":10,rlike:10,regexp:10,mod:30,xor:2,between:15,"not between":15,"+":20,"-":20,"*":30,"/":30,"%":30,"^":40,"::":50,"unary+":100,"unary-":100,not:100}}static getPrecedence(operator){let precedence=this.precedenceMap[operator.toLowerCase()];return precedence!==void 0?precedence:0}static hasHigherOrEqualPrecedence(operator1,operator2){return this.getPrecedence(operator1)>=this.getPrecedence(operator2)}static isLogicalOperator(operator){let op=operator.toLowerCase();return op==="and"||op==="or"}static isBetweenOperator(operator){let op=operator.toLowerCase();return op==="between"||op==="not between"}static isComparisonOperator(operator){let lowerOp=operator.toLowerCase();return["=","!=","<>","<",">","<=",">=","like","ilike","similar to","in","not in","->","->>","#>","#>>","@>","<@","?","?|","?&","~","~*","!~","!~*","rlike","regexp"].includes(lowerOp)}};var ValueParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw ParseError.fromUnparsedLexemes(lexemes,result.newIndex,"[ValueParser]");return result.value}static parseFromLexeme(lexemes,index,allowAndOperator=!0,allowOrOperator=!0){return this.parseExpressionWithPrecedence(lexemes,index,0,allowAndOperator,allowOrOperator)}static parseExpressionWithPrecedence(lexemes,index,minPrecedence,allowAndOperator=!0,allowOrOperator=!0){let idx=index,comment=lexemes[idx].comments,positionedComments=lexemes[idx].positionedComments,left=this.parseItem(lexemes,idx);positionedComments&&positionedComments.length>0&&!left.value.positionedComments?left.value.positionedComments=positionedComments:left.value.comments===null&&comment&&comment.length>0&&(left.value.comments=comment),idx=left.newIndex;let result=left.value,arrayAccessResult=this.parseArrayAccess(lexemes,idx,result);for(result=arrayAccessResult.value,idx=arrayAccessResult.newIndex;idx<lexemes.length&&lexemes[idx].type&2;){let operatorToken=lexemes[idx],operator=operatorToken.value;if(!allowAndOperator&&operator.toLowerCase()==="and"||!allowOrOperator&&operator.toLowerCase()==="or")break;let precedence=OperatorPrecedence.getPrecedence(operator);if(precedence<minPrecedence)break;if(idx++,OperatorPrecedence.isBetweenOperator(operator)){let betweenResult=FunctionExpressionParser.parseBetweenExpression(lexemes,idx,result,operator.toLowerCase().includes("not"));result=betweenResult.value,idx=betweenResult.newIndex;continue}if(operator==="::"){let typeValue=FunctionExpressionParser.parseTypeValue(lexemes,idx);result=new CastExpression(result,typeValue.value),idx=typeValue.newIndex;continue}let nextMinPrecedence=precedence+1,rightResult=this.parseExpressionWithPrecedence(lexemes,idx,nextMinPrecedence,allowAndOperator,allowOrOperator);idx=rightResult.newIndex;let binaryExpr=new BinaryExpression(result,operator,rightResult.value);operatorToken.comments&&operatorToken.comments.length>0&&(binaryExpr.operator.comments=operatorToken.comments),operatorToken.positionedComments&&operatorToken.positionedComments.length>0&&(binaryExpr.operator.positionedComments=operatorToken.positionedComments),result=binaryExpr}return{value:result,newIndex:idx}}static transferPositionedComments(lexeme,value){if(lexeme.positionedComments&&lexeme.positionedComments.length>0){let beforeComments=lexeme.positionedComments.filter(comment=>comment.position==="before"),afterComments=lexeme.positionedComments.filter(comment=>comment.position==="after");if(beforeComments.length>0){let clonedBefore=beforeComments.map(comment=>({position:comment.position,comments:[...comment.comments]}));value.positionedComments=value.positionedComments?[...clonedBefore,...value.positionedComments]:clonedBefore}if(afterComments.length>0){let clonedAfter=afterComments.map(comment=>({position:comment.position,comments:[...comment.comments]}));value.positionedComments=value.positionedComments?[...value.positionedComments,...clonedAfter]:clonedAfter}!beforeComments.length&&!afterComments.length&&!value.positionedComments&&(value.positionedComments=lexeme.positionedComments.map(comment=>({position:comment.position,comments:[...comment.comments]})));return}else value.comments===null&&lexeme.comments&&lexeme.comments.length>0&&(value.comments=lexeme.comments)}static parseItem(lexemes,index){let idx=index;if(idx>=lexemes.length)throw new Error(`Unexpected end of lexemes at index ${index}`);let current=lexemes[idx];if(current.type&64&&current.type&2&&current.type&8192){if(idx+1<lexemes.length&&lexemes[idx+1].type&4)if(this.isTypeConstructor(lexemes,idx+1,current.value)){let result=FunctionExpressionParser.parseTypeValue(lexemes,idx);return this.transferPositionedComments(current,result.value),{value:result.value,newIndex:result.newIndex}}else{let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}let first=IdentifierParser.parseFromLexeme(lexemes,idx);if(first.newIndex>=lexemes.length)return this.transferPositionedComments(current,first.value),first;if(lexemes[first.newIndex].type&1){let literalIndex=first.newIndex,literalLexeme=lexemes[literalIndex],second=LiteralParser.parseFromLexeme(lexemes,literalIndex);this.transferPositionedComments(literalLexeme,second.value);let result=new UnaryExpression(lexemes[idx].value,second.value);return this.transferPositionedComments(current,result),{value:result,newIndex:second.newIndex}}return this.transferPositionedComments(current,first.value),first}else if(current.type&64){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(lexemes[newIndex-1].type&2048){let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(lexemes[newIndex-1].type&8192)if(newIndex<lexemes.length&&lexemes[newIndex].type&4)if(this.isTypeConstructor(lexemes,newIndex,name.name)){let result=FunctionExpressionParser.parseTypeValue(lexemes,idx);return this.transferPositionedComments(current,result.value),{value:result.value,newIndex:result.newIndex}}else{let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else{let value2=new TypeValue(namespaces,name);return this.transferPositionedComments(current,value2),{value:value2,newIndex}}let value=new ColumnReference(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}else if(current.type&1&&this.isQualifiedSpecialValueIdentifier(lexemes,idx)){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx),value=new ColumnReference(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}else if(current.type&1){let result=LiteralParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&4){let result=ParenExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&2048){let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&2){let result=UnaryExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&256){let result=ParameterExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&4096){let result=StringSpecifierExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&128){let result=CommandExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&512){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx),value=new ColumnReference(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}else if(current.type&8192){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(newIndex<lexemes.length&&lexemes[newIndex].type&4)if(this.isTypeConstructor(lexemes,newIndex,name.name)){let result=FunctionExpressionParser.parseTypeValue(lexemes,idx);return this.transferPositionedComments(current,result.value),{value:result.value,newIndex:result.newIndex}}else{let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else{let value=new TypeValue(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}}throw ParseError.fromUnparsedLexemes(lexemes,idx,"[ValueParser] Invalid lexeme.")}static isQualifiedSpecialValueIdentifier(lexemes,index){return SQL_SPECIAL_VALUE_KEYWORD_SET.has(lexemes[index].value.toLowerCase())&&index+1<lexemes.length&&(lexemes[index+1].type&32)!==0}static parseArgument(openToken,closeToken,lexemes,index){let idx=index,args=[];if(idx<lexemes.length&&lexemes[idx].type===openToken){let openParenToken=lexemes[idx];if(idx++,idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,{value:new ValueList([]),newIndex:idx};if(idx<lexemes.length&&lexemes[idx].value==="*"){let wildcard=new ColumnReference(null,"*");if(openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let beforeComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");beforeComments.length>0&&(wildcard.positionedComments=beforeComments.map(pc=>({position:"before",comments:pc.comments})))}else openParenToken.comments&&openParenToken.comments.length>0&&(wildcard.comments=openParenToken.comments);if(idx++,idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,{value:wildcard,newIndex:idx};throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis after wildcard '*'.")}let result=this.parseFromLexeme(lexemes,idx);if(idx=result.newIndex,openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let afterComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){let beforeComments=afterComments.map(pc=>({position:"before",comments:pc.comments}));result.value.positionedComments?result.value.positionedComments=[...beforeComments,...result.value.positionedComments]:result.value.positionedComments=beforeComments}}else openParenToken.comments&&openParenToken.comments.length>0&&(result.value.comments?result.value.comments=openParenToken.comments.concat(result.value.comments):result.value.comments=openParenToken.comments);for(args.push(result.value);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let argResult=this.parseFromLexeme(lexemes,idx);idx=argResult.newIndex,args.push(argResult.value)}if(idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,args.length===1?{value:args[0],newIndex:idx}:{value:new ValueList(args),newIndex:idx};throw ParseError.fromUnparsedLexemes(lexemes,idx,"Missing closing parenthesis.")}throw ParseError.fromUnparsedLexemes(lexemes,index,"Expected opening parenthesis.")}static parseArrayAccess(lexemes,index,baseExpression){let idx=index,result=baseExpression;for(;idx<lexemes.length&&lexemes[idx].type&512&&!this.isSqlServerBracketIdentifier(lexemes,idx);){if(idx++,idx>=lexemes.length)throw new Error(`Expected array index or slice after '[' at index ${idx-1}`);if(lexemes[idx].type&1024)throw new Error(`Empty array access brackets not supported at index ${idx}`);let startExpr=null,isSlice=!1;if(lexemes[idx].type&2&&lexemes[idx].value===":")isSlice=!0,idx++;else{let colonPrecedence=OperatorPrecedence.getPrecedence(":"),firstResult=this.parseExpressionWithPrecedence(lexemes,idx,colonPrecedence+1);startExpr=firstResult.value,idx=firstResult.newIndex,idx<lexemes.length&&lexemes[idx].type&2&&lexemes[idx].value===":"&&(isSlice=!0,idx++)}if(isSlice){let endExpr=null;if(idx<lexemes.length&&!(lexemes[idx].type&1024)){let colonPrecedence=OperatorPrecedence.getPrecedence(":"),endResult=this.parseExpressionWithPrecedence(lexemes,idx,colonPrecedence+1);endExpr=endResult.value,idx=endResult.newIndex}if(idx>=lexemes.length||!(lexemes[idx].type&1024))throw new Error(`Expected ']' after array slice at index ${idx}`);idx++,result=new ArraySliceExpression(result,startExpr,endExpr)}else{if(!startExpr){let indexResult=this.parseFromLexeme(lexemes,idx);startExpr=indexResult.value,idx=indexResult.newIndex}if(idx>=lexemes.length||!(lexemes[idx].type&1024))throw new Error(`Expected ']' after array index at index ${idx}`);idx++,result=new ArrayIndexExpression(result,startExpr)}}return{value:result,newIndex:idx}}static isSqlServerBracketIdentifier(lexemes,bracketIndex){let idx=bracketIndex+1;if(idx>=lexemes.length)return!1;for(;idx<lexemes.length&&!(lexemes[idx].type&1024);){let token=lexemes[idx];if(token.type&64||token.type&2&&token.value==="."){idx++;continue}return!1}if(idx>=lexemes.length)return!1;let closingBracketIndex=idx;if(closingBracketIndex+1<lexemes.length){let nextToken=lexemes[closingBracketIndex+1];if(nextToken.type&2&&nextToken.value===".")return!0}idx=bracketIndex+1;let hasOnlyIdentifiersAndDots=!0;for(;idx<closingBracketIndex;){let token=lexemes[idx];if(!(token.type&64||token.type&2&&token.value===".")){hasOnlyIdentifiersAndDots=!1;break}idx++}return hasOnlyIdentifiersAndDots}static isTypeConstructor(lexemes,openParenIndex,typeName){let alwaysTypeConstructors=["NUMERIC","DECIMAL","VARCHAR","CHAR","CHARACTER","TIMESTAMP","TIME","INTERVAL"],upperTypeName=typeName.toUpperCase();if(alwaysTypeConstructors.includes(upperTypeName))return!0;if(upperTypeName==="DATE"){let firstArgIndex=openParenIndex+1;if(firstArgIndex<lexemes.length){let firstArg=lexemes[firstArgIndex];return!(firstArg.type&1&&typeof firstArg.value=="string"&&isNaN(Number(firstArg.value)))}}return!1}};var UpdateQuery=class extends SqlComponent{static{this.kind=Symbol("UpdateQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.updateClause=params.updateClause,this.setClause=params.setClause instanceof SetClause?params.setClause:new SetClause(params.setClause),this.whereClause=params.whereClause??null,this.fromClause=params.fromClause??null,this.returningClause=params.returning??null}};var DeleteQuery=class extends SqlComponent{static{this.kind=Symbol("DeleteQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.deleteClause=params.deleteClause,this.usingClause=params.usingClause??null,this.whereClause=params.whereClause??null,this.returningClause=params.returning??null}};var MergeAction=class extends SqlComponent{static{this.kind=Symbol("MergeAction")}},MergeUpdateAction=class extends MergeAction{static{this.kind=Symbol("MergeUpdateAction")}constructor(setClause,whereClause){super(),this.setClause=setClause instanceof SetClause?setClause:new SetClause(setClause),this.whereClause=whereClause??null}},MergeDeleteAction=class extends MergeAction{static{this.kind=Symbol("MergeDeleteAction")}constructor(whereClause){super(),this.whereClause=whereClause??null}},MergeInsertAction=class extends MergeAction{static{this.kind=Symbol("MergeInsertAction")}constructor(params){super(),this.columns=params.columns?params.columns.map(col=>typeof col=="string"?new IdentifierString(col):col):null,this.values=params.values??null,this.defaultValues=params.defaultValues??!1,this.valuesLeadingComments=params.valuesLeadingComments?[...params.valuesLeadingComments]:null}addValuesLeadingComments(comments){if(!(!comments||comments.length===0)){this.valuesLeadingComments||(this.valuesLeadingComments=[]);for(let comment of comments)this.valuesLeadingComments.includes(comment)||this.valuesLeadingComments.push(comment)}}getValuesLeadingComments(){return this.valuesLeadingComments?[...this.valuesLeadingComments]:[]}},MergeDoNothingAction=class extends MergeAction{static{this.kind=Symbol("MergeDoNothingAction")}},MergeWhenClause=class extends SqlComponent{static{this.kind=Symbol("MergeWhenClause")}constructor(matchType,action,condition,options){super(),this.matchType=matchType,this.action=action,this.condition=condition??null,this.thenLeadingComments=options?.thenLeadingComments?[...options.thenLeadingComments]:null}addThenLeadingComments(comments){if(!(!comments||comments.length===0)){this.thenLeadingComments||(this.thenLeadingComments=[]);for(let comment of comments)this.thenLeadingComments.includes(comment)||this.thenLeadingComments.push(comment)}}getThenLeadingComments(){return this.thenLeadingComments?[...this.thenLeadingComments]:[]}},MergeQuery=class extends SqlComponent{static{this.kind=Symbol("MergeQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.target=params.target,this.source=params.source,this.onCondition=params.onCondition,this.whenClauses=params.whenClauses,this.returningClause=params.returningClause??null}};var CTECollector=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(MergeQuery.kind,expr=>this.visitMergeQuery(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}getCommonTables(){return this.commonTables}reset(){this.commonTables=[],this.visitedNodes.clear()}collect(query){return this.visit(query),this.getCommonTables()}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}let kindSymbol=arg.getKind()?.toString()||"unknown",constructor=arg.constructor?.name||"unknown";throw new Error(`[CTECollector] No handler for ${constructor} with kind ${kindSymbol}.`)}visitSimpleSelectQuery(query){if(query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.orderByClause&&query.orderByClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.limitClause&&query.limitClause.accept(this),query.forClause&&query.forClause.accept(this),query.selectClause.accept(this),query.withClause&&query.withClause.accept(this)}visitBinarySelectQuery(query){query.left.accept(this),query.right.accept(this)}visitValuesQuery(query){for(let tuple of query.tuples)tuple.accept(this)}visitInsertQuery(query){query.selectQuery&&query.selectQuery.accept(this)}visitUpdateQuery(query){query.withClause&&query.withClause.accept(this),query.updateClause.source.accept(this),query.setClause.items.forEach(item=>item.value.accept(this)),query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.returningClause&&this.visitReturningClause(query.returningClause)}visitDeleteQuery(query){query.withClause&&query.withClause.accept(this),query.deleteClause.source.accept(this),query.usingClause&&query.usingClause.sources.forEach(source=>source.accept(this)),query.whereClause&&query.whereClause.accept(this),query.returningClause&&this.visitReturningClause(query.returningClause)}visitMergeQuery(query){query.withClause&&query.withClause.accept(this),query.target.accept(this),query.source.accept(this),query.onCondition.accept(this);for(let clause of query.whenClauses)if(clause.condition&&clause.condition.accept(this),clause.action instanceof MergeUpdateAction)clause.action.setClause.items.forEach(item=>item.value.accept(this)),clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeDeleteAction)clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeInsertAction&&clause.action.values)clause.action.values.accept(this);else if(!(clause.action instanceof MergeInsertAction)){let actionName=clause.action?.constructor?.name??"UnknownMergeAction";throw new Error(`[CTECollector] Unsupported MERGE action type: ${actionName}.`)}query.returningClause&&this.visitReturningClause(query.returningClause)}visitReturningClause(clause){for(let item of clause.items)item.accept(this)}visitWithClause(withClause){for(let i=0;i<withClause.tables.length;i++)withClause.tables[i].accept(this)}visitCommonTable(commonTable){commonTable.query.accept(this),this.commonTables.push(commonTable)}visitSelectClause(clause){for(let item of clause.items)item.accept(this)}visitSelectItem(item){item.value.accept(this)}visitFromClause(fromClause){if(fromClause.source.accept(this),fromClause.joins)for(let join of fromClause.joins)join.accept(this)}visitSourceExpression(source){source.datasource.accept(this)}visitTableSource(source){}visitFunctionSource(source){source.argument&&source.argument.accept(this)}visitParenSource(source){source.source.accept(this)}visitSubQuerySource(subQuery){subQuery.query.accept(this)}visitInlineQuery(inlineQuery){inlineQuery.selectQuery.accept(this)}visitJoinClause(joinClause){joinClause.source.accept(this),joinClause.condition&&joinClause.condition.accept(this)}visitJoinOnClause(joinOn){joinOn.condition.accept(this)}visitJoinUsingClause(joinUsing){joinUsing.condition.accept(this)}visitWhereClause(whereClause){whereClause.condition.accept(this)}visitGroupByClause(clause){for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition.accept(this)}visitOrderByClause(clause){for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitLimitClause(clause){clause.value.accept(this)}visitForClause(clause){}visitOrderByItem(item){item.value.accept(this)}visitParenExpression(expr){expr.expression.accept(this)}visitBinaryExpression(expr){expr.left.accept(this),expr.right.accept(this)}visitUnaryExpression(expr){expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase.accept(this)}visitSwitchCaseArgument(switchCase){for(let caseItem of switchCase.cases)caseItem.accept(this);switchCase.elseValue&&switchCase.elseValue.accept(this)}visitCaseKeyValuePair(pair){pair.key.accept(this),pair.value.accept(this)}visitBetweenExpression(expr){expr.expression.accept(this),expr.lower.accept(this),expr.upper.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this)}visitArrayExpression(expr){expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitTupleExpression(expr){for(let value of expr.values)value.accept(this)}visitCastExpression(expr){expr.input.accept(this),expr.castType.accept(this)}visitTypeValue(expr){expr.argument&&expr.argument.accept(this)}visitWindowFrameExpression(expr){expr.partition&&expr.partition.accept(this),expr.order&&expr.order.accept(this),expr.frameSpec&&expr.frameSpec.accept(this)}visitWindowFrameSpec(spec){}visitIdentifierString(ident){}visitRawString(raw){}visitColumnReference(column){}visitParameterExpression(param){}visitLiteralValue(value){}visitPartitionByClause(partitionBy){}visitValueList(valueList){for(let value of valueList.values)value.accept(this)}visitStringSpecifierExpression(expr){}};var CTEDisabler=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}reset(){this.visitedNodes.clear()}execute(arg){return this.reset(),this.visit(arg)}visit(arg){if(!this.isRootVisit)return this.visitNode(arg);this.reset(),this.isRootVisit=!1;try{return this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return arg;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler)return handler(arg);let kindSymbol=arg.getKind()?.toString()||"unknown",constructor=arg.constructor?.name||"unknown";throw new Error(`[CTEDisabler] No handler for ${constructor} with kind ${kindSymbol}.`)}visitSimpleSelectQuery(arg){return arg.withClause&&arg.withClause.tables.forEach(table=>{this.visit(table.query)}),arg.withClause=null,arg.selectClause=this.visit(arg.selectClause),arg.fromClause=arg.fromClause?this.visit(arg.fromClause):null,arg.whereClause=arg.whereClause?this.visit(arg.whereClause):null,arg.groupByClause=arg.groupByClause?this.visit(arg.groupByClause):null,arg.havingClause=arg.havingClause?this.visit(arg.havingClause):null,arg.orderByClause=arg.orderByClause?this.visit(arg.orderByClause):null,arg.windowClause&&(arg.windowClause=new WindowsClause(arg.windowClause.windows.map(w=>this.visit(w)))),arg.limitClause=arg.limitClause?this.visit(arg.limitClause):null,arg.forClause=arg.forClause?this.visit(arg.forClause):null,arg}visitBinarySelectQuery(query){return query.left=this.visit(query.left),query.right=this.visit(query.right),query}visitValuesQuery(query){let newTuples=query.tuples.map(tuple=>this.visit(tuple));return new ValuesQuery(newTuples)}visitInsertQuery(query){return query}visitUpdateQuery(query){return query}visitDeleteQuery(query){return query}visitSelectClause(clause){let newItems=clause.items.map(item=>this.visit(item));return new SelectClause(newItems,clause.distinct)}visitFromClause(clause){let newSource=this.visit(clause.source),newJoins=clause.joins?clause.joins.map(join=>this.visit(join)):null;return new FromClause(newSource,newJoins)}visitSubQuerySource(subQuery){let newQuery=this.visit(subQuery.query);return new SubQuerySource(newQuery)}visitInlineQuery(inlineQuery){let newQuery=this.visit(inlineQuery.selectQuery);return new InlineQuery(newQuery)}visitJoinClause(joinClause){let newSource=this.visit(joinClause.source),newCondition=joinClause.condition?this.visit(joinClause.condition):null;return new JoinClause(joinClause.joinType.value,newSource,newCondition,joinClause.lateral)}visitJoinOnClause(joinOn){let newCondition=this.visit(joinOn.condition);return new JoinOnClause(newCondition)}visitJoinUsingClause(joinUsing){let newCondition=this.visit(joinUsing.condition);return new JoinUsingClause(newCondition)}visitWhereClause(whereClause){let newCondition=this.visit(whereClause.condition);return new WhereClause(newCondition)}visitGroupByClause(clause){let newGrouping=clause.grouping.map(item=>this.visit(item));return new GroupByClause(newGrouping)}visitHavingClause(clause){let newCondition=this.visit(clause.condition);return new HavingClause(newCondition)}visitOrderByClause(clause){let newOrder=clause.order.map(item=>this.visit(item));return new OrderByClause(newOrder)}visitWindowFrameClause(clause){let newExpression=this.visit(clause.expression);return new WindowFrameClause(clause.name.name,newExpression)}visitLimitClause(clause){let newLimit=this.visit(clause.value);return new LimitClause(newLimit)}visitForClause(clause){return new ForClause(clause.lockMode)}visitParenExpression(expr){let newExpression=this.visit(expr.expression);return new ParenExpression(newExpression)}visitBinaryExpression(expr){let newLeft=this.visit(expr.left),newRight=this.visit(expr.right);return new BinaryExpression(newLeft,expr.operator.value,newRight)}visitUnaryExpression(expr){let newExpression=this.visit(expr.expression);return new UnaryExpression(expr.operator.value,newExpression)}visitCaseExpression(expr){let newCondition=expr.condition?this.visit(expr.condition):null,newSwitchCase=this.visit(expr.switchCase);return new CaseExpression(newCondition,newSwitchCase)}visitSwitchCaseArgument(switchCase){let newCases=switchCase.cases.map(caseItem=>this.visit(caseItem)),newElseValue=switchCase.elseValue?this.visit(switchCase.elseValue):null;return new SwitchCaseArgument(newCases,newElseValue)}visitCaseKeyValuePair(pair){let newKey=this.visit(pair.key),newValue=this.visit(pair.value);return new CaseKeyValuePair(newKey,newValue)}visitBetweenExpression(expr){let newExpression=this.visit(expr.expression),newLower=this.visit(expr.lower),newUpper=this.visit(expr.upper);return new BetweenExpression(newExpression,newLower,newUpper,expr.negated)}visitFunctionCall(func){let newArgument=func.argument?this.visit(func.argument):null,newOver=func.over?this.visit(func.over):null;return new FunctionCall(func.namespaces,func.name,newArgument,newOver)}visitArrayExpression(expr){let newExpression=this.visit(expr.expression);return new ArrayExpression(newExpression)}visitArrayQueryExpression(expr){let newQuery=this.visit(expr.query);return new ArrayQueryExpression(newQuery)}visitTupleExpression(expr){let newValues=expr.values.map(value=>this.visit(value));return new TupleExpression(newValues)}visitCastExpression(expr){let newInput=this.visit(expr.input),newCastType=this.visit(expr.castType);return new CastExpression(newInput,newCastType)}visitTypeValue(typeValue){let newArgument=typeValue.argument?this.visit(typeValue.argument):null;return new TypeValue(typeValue.namespaces,typeValue.name,newArgument)}visitSelectItem(item){let newValue=this.visit(item.value);return new SelectItem(newValue,item.identifier?.name)}visitIdentifierString(ident){return ident}visitRawString(raw){return raw}visitColumnReference(column){return column}visitSourceExpression(source){let newSource=this.visit(source.datasource),newAlias=source.aliasExpression;return new SourceExpression(newSource,newAlias)}visitTableSource(source){return source}visitParenSource(source){let newSource=this.visit(source.source);return new ParenSource(newSource)}visitParameterExpression(param){return param}visitWindowFrameExpression(expr){let newPartition=expr.partition?this.visit(expr.partition):null,newOrder=expr.order?this.visit(expr.order):null,newFrameSpec=expr.frameSpec?this.visit(expr.frameSpec):null;return new WindowFrameExpression(newPartition,newOrder,newFrameSpec)}visitWindowFrameSpec(spec){return spec}visitLiteralValue(value){return value}visitOrderByItem(item){let newValue=this.visit(item.value);return new OrderByItem(newValue,item.sortDirection,item.nullsPosition)}visitValueList(valueList){let newValues=valueList.values.map(value=>this.visit(value));return new ValueList(newValues)}visitArraySliceExpression(expr){return expr}visitArrayIndexExpression(expr){return expr}visitStringSpecifierExpression(expr){return expr}visitPartitionByClause(clause){let newValue=this.visit(clause.value);return new PartitionByClause(newValue)}};var TableSourceCollector=class{constructor(selectableOnly=!0,dedupe=!0){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.cteNames=new Set;this.isRootVisit=!0;this.selectableOnly=selectableOnly,this.dedupe=dedupe,this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(MergeQuery.kind,expr=>this.visitMergeQuery(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),selectableOnly||(this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.visitOffsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)))}getTableSources(){return this.tableSources}reset(){this.tableSources=[],this.tableNameMap.clear(),this.visitedNodes.clear(),this.cteNames.clear()}getTableIdentifier(source){return source.qualifiedName.namespaces&&source.qualifiedName.namespaces.length>0?source.qualifiedName.namespaces.map(ns=>ns.name).join(".")+"."+(source.qualifiedName.name instanceof RawString?source.qualifiedName.name.value:source.qualifiedName.name.name):source.qualifiedName.name instanceof RawString?source.qualifiedName.name.value:source.qualifiedName.name.name}collect(query){return this.visit(query),this.getTableSources()}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.selectableOnly||this.collectCTEs(arg),this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}}collectCTEs(query){let cteCollector=new CTECollector;cteCollector.visit(query);let commonTables=cteCollector.getCommonTables();for(let cte of commonTables)this.cteNames.add(cte.aliasExpression.table.name)}visitSimpleSelectQuery(query){if(query.fromClause&&query.fromClause.accept(this),!this.selectableOnly){if(query.withClause&&query.withClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.orderByClause&&query.orderByClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.limitClause&&query.limitClause.accept(this),query.offsetClause&&query.offsetClause.accept(this),query.fetchClause&&query.fetchClause.accept(this),query.forClause&&query.forClause.accept(this),query.selectClause.accept(this)}}visitBinarySelectQuery(query){query.left.accept(this),query.right.accept(this)}visitValuesQuery(query){if(!this.selectableOnly)for(let tuple of query.tuples)tuple.accept(this)}visitInsertQuery(query){query.insertClause.source.accept(this),query.selectQuery&&query.selectQuery.accept(this),!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitUpdateQuery(query){!this.selectableOnly&&query.withClause&&query.withClause.accept(this),query.updateClause.source.accept(this),this.selectableOnly||query.setClause.items.forEach(item=>item.value.accept(this)),query.fromClause&&query.fromClause.accept(this),!this.selectableOnly&&query.whereClause&&query.whereClause.accept(this),!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitDeleteQuery(query){!this.selectableOnly&&query.withClause&&query.withClause.accept(this),query.deleteClause.source.accept(this),query.usingClause&&query.usingClause.sources.forEach(source=>source.accept(this)),!this.selectableOnly&&query.whereClause&&query.whereClause.accept(this),!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitMergeQuery(query){if(query.withClause&&this.registerCteNames(query.withClause),!this.selectableOnly&&query.withClause&&query.withClause.accept(this),query.target.accept(this),query.source.accept(this),!this.selectableOnly){query.onCondition.accept(this);for(let clause of query.whenClauses)if(clause.condition&&clause.condition.accept(this),clause.action instanceof MergeUpdateAction)clause.action.setClause.items.forEach(item=>item.value.accept(this)),clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeDeleteAction)clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeInsertAction&&clause.action.values)clause.action.values.accept(this);else if(!(clause.action instanceof MergeInsertAction)){let actionName=clause.action?.constructor?.name??"UnknownMergeAction";throw new Error(`[TableSourceCollector] Unsupported MERGE action type: ${actionName}.`)}}!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitReturningClause(clause){for(let item of clause.items)item.value.accept(this)}visitWithClause(withClause){if(!this.selectableOnly)for(let table of withClause.tables)table.accept(this)}visitCommonTable(commonTable){this.selectableOnly||commonTable.query.accept(this)}visitFromClause(fromClause){if(fromClause.source.accept(this),fromClause.joins)for(let join of fromClause.joins)join.accept(this)}visitSourceExpression(source){source.datasource.accept(this)}visitTableSource(source){let identifier=this.getTableIdentifier(source);if(!this.isCTETable(source.table.name)){if(this.dedupe){if(this.tableNameMap.has(identifier))return;this.tableNameMap.set(identifier,!0)}this.tableSources.push(source)}}visitFunctionSource(source){source.argument&&this.visitValueComponent(source.argument)}visitValueComponent(value){value.accept(this)}isCTETable(tableName){return this.cteNames.has(tableName)}registerCteNames(withClause){for(let table of withClause.tables)this.cteNames.add(table.aliasExpression.table.name)}visitParenSource(source){source.source.accept(this)}visitSubQuerySource(subQuery){this.selectableOnly||subQuery.query.accept(this)}visitInlineQuery(inlineQuery){this.selectableOnly||inlineQuery.selectQuery.accept(this)}visitJoinClause(joinClause){joinClause.source.accept(this),!this.selectableOnly&&joinClause.condition&&joinClause.condition.accept(this)}visitJoinOnClause(joinOn){this.selectableOnly||joinOn.condition.accept(this)}visitJoinUsingClause(joinUsing){this.selectableOnly||joinUsing.condition.accept(this)}visitWhereClause(whereClause){whereClause.condition.accept(this)}visitGroupByClause(clause){for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition.accept(this)}visitOrderByClause(clause){for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitLimitClause(clause){clause.value.accept(this)}visitOffsetClause(clause){clause.value.accept(this)}visitFetchClause(clause){clause.expression.accept(this)}visitForClause(_clause){}visitOrderByItem(item){item.value.accept(this)}visitSelectClause(clause){for(let item of clause.items)item.accept(this)}visitSelectItem(item){item.value.accept(this)}visitParenExpression(expr){expr.expression.accept(this)}visitBinaryExpression(expr){expr.left.accept(this),expr.right.accept(this)}visitUnaryExpression(expr){expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase.accept(this)}visitSwitchCaseArgument(switchCase){for(let caseItem of switchCase.cases)caseItem.accept(this);switchCase.elseValue&&switchCase.elseValue.accept(this)}visitCaseKeyValuePair(pair){pair.key.accept(this),pair.value.accept(this)}visitBetweenExpression(expr){expr.expression.accept(this),expr.lower.accept(this),expr.upper.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.filterCondition&&func.filterCondition.accept(this),func.over&&func.over.accept(this)}visitArrayExpression(expr){expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitTupleExpression(expr){for(let value of expr.values)value.accept(this)}visitCastExpression(expr){expr.input.accept(this),expr.castType.accept(this)}visitValueList(valueList){for(let value of valueList.values)value.accept(this)}visitStringSpecifierExpression(_expr){}};var HintClause=class extends SqlComponent{static{this.kind=Symbol("HintClause")}constructor(hintContent){super(),this.hintContent=hintContent}getFullHint(){return"/*+ "+this.hintContent+" */"}static isHintClause(value){let trimmed=value.trim();return trimmed.length>=5&&trimmed.substring(0,3)==="/*+"&&trimmed.substring(trimmed.length-2)==="*/"}static extractHintContent(hintClause){let trimmed=hintClause.trim();if(!this.isHintClause(trimmed))throw new Error("Not a valid hint clause: "+hintClause);return trimmed.slice(3,-2).trim()}};var SqlPrintToken=class{constructor(type,text="",containerType=""){this.innerTokens=[];this.type=type,this.text=text,this.containerType=containerType}markAsHeaderComment(){if(this.containerType!=="CommentBlock")throw new Error("Header comment flag must only be applied to CommentBlock containers.");this.isHeaderComment=!0}};var SelectQueryWithClauseHelper=class{static getWithClause(selectQuery){let owner=this.findClauseOwner(selectQuery);return owner?owner.withClause:null}static setWithClause(selectQuery,withClause){let owner=this.findClauseOwner(selectQuery);if(!owner)throw new Error("Cannot attach WITH clause to the provided select query.");owner.withClause=withClause}static detachWithClause(selectQuery){let owner=this.findClauseOwner(selectQuery);if(!owner)return null;let clause=owner.withClause;return owner.withClause=null,clause}static findClauseOwner(selectQuery){if(!selectQuery)return null;if(selectQuery instanceof SimpleSelectQuery||selectQuery instanceof ValuesQuery)return selectQuery;if(selectQuery instanceof BinarySelectQuery)return this.findClauseOwner(selectQuery.left);throw new Error("Unsupported select query type for WITH clause management.")}};var ParameterCollector=class{static collect(node){let result=[];function walk(n){if(!(!n||typeof n!="object")){n.constructor&&n.constructor.kind===ParameterExpression.kind&&result.push(n);for(let key of Object.keys(n)){let v=n[key];Array.isArray(v)?v.forEach(walk):v&&typeof v=="object"&&v.constructor&&v.constructor.kind&&walk(v)}}}return walk(node),result}};var IdentifierDecorator=class{constructor(identifierEscape){this.start=identifierEscape?.start??'"',this.end=identifierEscape?.end??'"',this.target=identifierEscape?.target??"all"}decorate(text){return this.target==="minimal"&&this.canRenderBare(text)?text:this.start+this.escapeIdentifierText(text)+this.end}canRenderBare(text){return/^[a-z_][a-z0-9_]*$/.test(text)&&!UNSAFE_BARE_IDENTIFIERS.has(text)&&this.isPlainIdentifierToken(text)}isPlainIdentifierToken(text){let lexemes=new SqlTokenizer(text).readLexmes();return lexemes.length===1&&lexemes[0].type===64&&lexemes[0].value===text}escapeIdentifierText(text){return this.end?text.split(this.end).join(this.end+this.end):text}},UNSAFE_BARE_IDENTIFIERS=new Set(["all","and","any","as","between","by","case","cross","delete","distinct","else","end","except","exists","false","fetch","for","from","full","group","having","in","inner","insert","intersect","into","is","join","left","like","limit","not","null","offset","on","or","order","outer","right","select","set","table","then","true","union","update","using","values","when","where","with",...SQL_SPECIAL_VALUE_KEYWORDS]);var ParameterDecorator=class{constructor(options){this.prefix=options?.prefix??":",this.suffix=options?.suffix??"",this.style=options?.style??"named"}decorate(text,index){let paramText="";return this.style==="anonymous"?paramText=this.prefix:this.style==="indexed"?paramText=this.prefix+index:this.style==="named"&&(paramText=this.prefix+text+this.suffix),text=paramText,text}};var SelectValueCollector=class _SelectValueCollector{constructor(tableColumnResolver=null,initialCommonTables=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=tableColumnResolver??null,this.commonTableCollector=new CTECollector,this.commonTables=[],this.initialCommonTables=initialCommonTables,this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr))}getValues(){return this.selectValues}reset(){this.selectValues=[],this.visitedNodes.clear(),this.initialCommonTables?this.commonTables=this.initialCommonTables:this.commonTables=[]}collect(arg){this.visit(arg);let items=this.getValues();return this.reset(),items}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}}visitSimpleSelectQuery(query){this.commonTables.length===0&&this.initialCommonTables===null&&(this.commonTables=this.commonTableCollector.collect(query)),query.selectClause&&query.selectClause.accept(this);let wildcards=this.selectValues.filter(item=>item.name==="*");if(wildcards.length===0)return;if(this.selectValues.some(item=>item.value instanceof ColumnReference&&item.value.namespaces===null)){query.fromClause&&this.processFromClause(query.fromClause,!0),this.selectValues=this.selectValues.filter(item=>item.name!=="*");return}let wildSourceNames=wildcards.filter(item=>item.value instanceof ColumnReference&&item.value.namespaces).map(item=>item.value.getNamespace());if(query.fromClause){let fromSourceName=query.fromClause.getSourceAliasName();if(fromSourceName&&wildSourceNames.includes(fromSourceName)&&this.processFromClause(query.fromClause,!1),query.fromClause.joins)for(let join of query.fromClause.joins){let joinSourceName=join.getSourceAliasName();joinSourceName&&wildSourceNames.includes(joinSourceName)&&this.processJoinClause(join)}}this.selectValues=this.selectValues.filter(item=>item.name!=="*")}processFromClause(clause,joinCascade){if(clause){let fromSourceName=clause.getSourceAliasName();if(this.processSourceExpression(fromSourceName,clause.source),clause.joins&&joinCascade)for(let join of clause.joins)this.processJoinClause(join)}}processJoinClause(clause){let sourceName=clause.getSourceAliasName();this.processSourceExpression(sourceName,clause.source)}processSourceExpression(sourceName,source){let commonTable=this.commonTables.find(item=>item.aliasExpression.table.name===sourceName);if(commonTable){let innerCommonTables=this.commonTables.filter(item=>item.aliasExpression.table.name!==sourceName);this.collectValuesFromCteQuery(commonTable.query,innerCommonTables).forEach(item=>{this.addSelectValueAsUnique(item.name,new ColumnReference(sourceName?[sourceName]:null,item.name))})}else new _SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(source).forEach(item=>{this.addSelectValueAsUnique(item.name,new ColumnReference(sourceName?[sourceName]:null,item.name))})}visitSelectClause(clause){for(let item of clause.items)this.processSelectItem(item)}processSelectItem(item){if(item.identifier)this.addSelectValueAsUnique(item.identifier.name,item.value);else if(item.value instanceof ColumnReference){let columnName=item.value.column.name;columnName==="*"?this.selectValues.push({name:columnName,value:item.value}):this.addSelectValueAsUnique(columnName,item.value)}}visitSourceExpression(source){if(source.aliasExpression&&source.aliasExpression.columns){let sourceName=source.getAliasName();source.aliasExpression.columns.forEach(column=>{this.addSelectValueAsUnique(column.name,new ColumnReference(sourceName?[sourceName]:null,column.name))});return}else if(source.datasource instanceof TableSource){if(this.tableColumnResolver){let sourceName=source.datasource.getSourceName();this.tableColumnResolver(sourceName).forEach(column=>{this.addSelectValueAsUnique(column,new ColumnReference([sourceName],column))})}return}else if(source.datasource instanceof SubQuerySource){let sourceName=source.getAliasName();new _SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(source.datasource.query).forEach(item=>{this.addSelectValueAsUnique(item.name,new ColumnReference(sourceName?[sourceName]:null,item.name))});return}else if(source.datasource instanceof ParenSource)return this.visit(source.datasource.source)}visitFromClause(clause){clause&&this.processFromClause(clause,!0)}addSelectValueAsUnique(name,value){this.selectValues.some(item=>item.name===name)||this.selectValues.push({name,value})}collectValuesFromCteQuery(query,commonTables){return this.isSelectQuery(query)?new _SelectValueCollector(this.tableColumnResolver,commonTables).collect(query):this.collectValuesFromReturning(query)}collectValuesFromReturning(query){return query instanceof InsertQuery||query instanceof UpdateQuery||query instanceof DeleteQuery||query instanceof MergeQuery?query.returningClause?this.extractValuesFromReturningClause(query.returningClause):[]:[]}extractValuesFromReturningClause(clause){let values=[];for(let item of clause.items){let name=item.identifier?.name??this.extractSelectItemName(item);name&&values.push({name,value:item.value})}return values}extractSelectItemName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}};var ReferenceDefinition=class extends SqlComponent{static{this.kind=Symbol("ReferenceDefinition")}constructor(params){super(),this.targetTable=params.targetTable,this.columns=params.columns?[...params.columns]:null,this.matchType=params.matchType??null,this.onDelete=params.onDelete??null,this.onUpdate=params.onUpdate??null,this.deferrable=params.deferrable??null,this.initially=params.initially??null}},ColumnConstraintDefinition=class extends SqlComponent{static{this.kind=Symbol("ColumnConstraintDefinition")}constructor(params){super(),this.kind=params.kind,this.constraintName=params.constraintName,this.defaultValue=params.defaultValue,this.checkExpression=params.checkExpression,this.reference=params.reference,this.rawClause=params.rawClause}},TableConstraintDefinition=class extends SqlComponent{static{this.kind=Symbol("TableConstraintDefinition")}constructor(params){super(),this.kind=params.kind,this.constraintName=params.constraintName,this.columns=params.columns?[...params.columns]:null,this.reference=params.reference,this.checkExpression=params.checkExpression,this.rawClause=params.rawClause,this.deferrable=params.deferrable??null,this.initially=params.initially??null}},TableColumnDefinition=class extends SqlComponent{static{this.kind=Symbol("TableColumnDefinition")}constructor(params){super(),this.name=params.name,this.dataType=params.dataType,this.constraints=params.constraints?[...params.constraints]:[]}},CreateTableQuery=class extends SqlComponent{static{this.kind=Symbol("CreateTableQuery")}constructor(params){super(),this.tableName=new IdentifierString(params.tableName),this.namespaces=params.namespaces?[...params.namespaces]:null,this.isTemporary=params.isTemporary??!1,this.isUnlogged=params.isUnlogged??!1,this.ifNotExists=params.ifNotExists??!1,this.columns=params.columns?[...params.columns]:[],this.tableConstraints=params.tableConstraints?[...params.tableConstraints]:[],this.tableOptions=params.tableOptions??null,this.asSelectQuery=params.asSelectQuery,this.withDataOption=params.withDataOption??null}getSelectQuery(){let selectItems;this.asSelectQuery?selectItems=new SelectValueCollector().collect(this.asSelectQuery).map(val=>new SelectItem(val.value,val.name)):this.columns.length>0?selectItems=this.columns.map(column=>new SelectItem(new ColumnReference(null,column.name),column.name.name)):selectItems=[new SelectItem(new RawString("*"))];let qualifiedName=this.namespaces&&this.namespaces.length>0?[...this.namespaces,this.tableName.name].join("."):this.tableName.name;return new SimpleSelectQuery({selectClause:new SelectClause(selectItems),fromClause:new FromClause(new SourceExpression(new TableSource(null,qualifiedName),null),null)})}getCountQuery(){let qualifiedName=this.namespaces&&this.namespaces.length>0?[...this.namespaces,this.tableName.name].join("."):this.tableName.name;return new SimpleSelectQuery({selectClause:new SelectClause([new SelectItem(new FunctionCall(null,"count",new ColumnReference(null,"*"),null))]),fromClause:new FromClause(new SourceExpression(new TableSource(null,qualifiedName),null),null)})}};function cloneIdentifierWithComments(identifier){let clone=new IdentifierString(identifier.name);return identifier.positionedComments?clone.positionedComments=identifier.positionedComments.map(entry=>({position:entry.position,comments:[...entry.comments]})):identifier.comments&&identifier.comments.length>0&&(clone.comments=[...identifier.comments]),clone}var DropTableStatement=class extends SqlComponent{static{this.kind=Symbol("DropTableStatement")}constructor(params){super(),this.tables=params.tables.map(table=>new QualifiedName(table.namespaces,table.name)),this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},DropIndexStatement=class extends SqlComponent{static{this.kind=Symbol("DropIndexStatement")}constructor(params){super(),this.indexNames=params.indexNames.map(index=>new QualifiedName(index.namespaces,index.name)),this.ifExists=params.ifExists??!1,this.concurrently=params.concurrently??!1,this.behavior=params.behavior??null}},CreateSchemaStatement=class extends SqlComponent{static{this.kind=Symbol("CreateSchemaStatement")}constructor(params){super(),this.schemaName=new QualifiedName(params.schemaName.namespaces,params.schemaName.name),this.ifNotExists=params.ifNotExists??!1,this.authorization=params.authorization?cloneIdentifierWithComments(params.authorization):null}},DropSchemaStatement=class extends SqlComponent{static{this.kind=Symbol("DropSchemaStatement")}constructor(params){super(),this.schemaNames=params.schemaNames.map(schema=>new QualifiedName(schema.namespaces,schema.name)),this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},CommentOnStatement=class extends SqlComponent{static{this.kind=Symbol("CommentOnStatement")}constructor(params){super(),this.targetKind=params.targetKind,this.target=new QualifiedName(params.target.namespaces,params.target.name),this.comment=params.comment}},IndexColumnDefinition=class extends SqlComponent{static{this.kind=Symbol("IndexColumnDefinition")}constructor(params){super(),this.expression=params.expression,this.sortOrder=params.sortOrder??null,this.nullsOrder=params.nullsOrder??null,this.collation=params.collation??null,this.operatorClass=params.operatorClass??null}},CreateIndexStatement=class extends SqlComponent{static{this.kind=Symbol("CreateIndexStatement")}constructor(params){super(),this.unique=params.unique??!1,this.concurrently=params.concurrently??!1,this.ifNotExists=params.ifNotExists??!1,this.indexName=new QualifiedName(params.indexName.namespaces,params.indexName.name),this.tableName=new QualifiedName(params.tableName.namespaces,params.tableName.name),this.usingMethod=params.usingMethod??null,this.columns=params.columns.map(col=>new IndexColumnDefinition({expression:col.expression,sortOrder:col.sortOrder,nullsOrder:col.nullsOrder,collation:col.collation??null,operatorClass:col.operatorClass??null})),this.include=params.include?[...params.include]:null,this.where=params.where,this.withOptions=params.withOptions??null,this.tablespace=params.tablespace??null}},AlterTableAddConstraint=class extends SqlComponent{static{this.kind=Symbol("AlterTableAddConstraint")}constructor(params){super(),this.constraint=params.constraint,this.ifNotExists=params.ifNotExists??!1,this.notValid=params.notValid??!1}},AlterTableDropConstraint=class extends SqlComponent{static{this.kind=Symbol("AlterTableDropConstraint")}constructor(params){super(),this.constraintName=params.constraintName,this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},AlterTableDropColumn=class extends SqlComponent{static{this.kind=Symbol("AlterTableDropColumn")}constructor(params){super(),this.columnName=params.columnName,this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},AlterTableAddColumn=class extends SqlComponent{static{this.kind=Symbol("AlterTableAddColumn")}constructor(params){super(),this.column=params.column,this.ifNotExists=params.ifNotExists??!1}},AlterTableAlterColumnDefault=class extends SqlComponent{static{this.kind=Symbol("AlterTableAlterColumnDefault")}constructor(params){if(super(),this.columnName=params.columnName,this.setDefault=params.setDefault??null,this.dropDefault=params.dropDefault??!1,this.setDefault!==null&&this.dropDefault)throw new Error("[AlterTableAlterColumnDefault] Cannot set and drop a default at the same time.")}},AlterTableStatement=class extends SqlComponent{static{this.kind=Symbol("AlterTableStatement")}constructor(params){super(),this.table=new QualifiedName(params.table.namespaces,params.table.name),this.only=params.only??!1,this.ifExists=params.ifExists??!1,this.actions=params.actions.map(action=>action)}},DropConstraintStatement=class extends SqlComponent{static{this.kind=Symbol("DropConstraintStatement")}constructor(params){super(),this.constraintName=params.constraintName,this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},ExplainOption=class extends SqlComponent{static{this.kind=Symbol("ExplainOption")}constructor(params){super(),this.name=cloneIdentifierWithComments(params.name),this.value=params.value??null}},ExplainStatement=class extends SqlComponent{static{this.kind=Symbol("ExplainStatement")}constructor(params){super(),this.options=params.options?params.options.map(option=>new ExplainOption(option)):null,this.statement=params.statement}},AnalyzeStatement=class extends SqlComponent{static{this.kind=Symbol("AnalyzeStatement")}constructor(params){super(),this.verbose=params?.verbose??!1,this.target=params?.target?new QualifiedName(params.target.namespaces,params.target.name):null,params?.columns?this.columns=params.columns.map(cloneIdentifierWithComments):this.columns=null}},CreateSequenceStatement=class extends SqlComponent{static{this.kind=Symbol("CreateSequenceStatement")}constructor(params){super(),this.sequenceName=new QualifiedName(params.sequenceName.namespaces,params.sequenceName.name),this.ifNotExists=params.ifNotExists??!1,this.clauses=params.clauses?[...params.clauses]:[]}},AlterSequenceStatement=class extends SqlComponent{static{this.kind=Symbol("AlterSequenceStatement")}constructor(params){super(),this.sequenceName=new QualifiedName(params.sequenceName.namespaces,params.sequenceName.name),this.ifExists=params.ifExists??!1,this.clauses=params.clauses?[...params.clauses]:[]}},VacuumStatement=class extends SqlComponent{static{this.kind=Symbol("VacuumStatement")}constructor(params){super(),this.full=params?.full??!1,this.verbose=params?.verbose??!1,this.freeze=params?.freeze??!1,this.analyze=params?.analyze??!1,this.targets=params?.targets?[...params.targets]:[]}},ReindexStatement=class extends SqlComponent{static{this.kind=Symbol("ReindexStatement")}constructor(params){super(),this.concurrently=params?.concurrently??!1,this.targets=params?.targets?[...params.targets]:[],this.targetType=params?.targetType??null}},ClusterStatement=class extends SqlComponent{static{this.kind=Symbol("ClusterStatement")}constructor(params){super(),this.verbose=params?.verbose??!1,this.table=params?.table??null,this.index=params?.index??null}},CheckpointStatement=class extends SqlComponent{static{this.kind=Symbol("CheckpointStatement")}constructor(params){super(),this.options=params?.options?[...params.options]:[]}};var PRESETS={mysql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous",constraintStyle:"mysql"},postgres:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed",castStyle:"postgres",constraintStyle:"postgres"},postgresWithNamedParams:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named",castStyle:"postgres",constraintStyle:"postgres"},sqlserver:{identifierEscape:{start:"[",end:"]"},parameterSymbol:"@",parameterStyle:"named",constraintStyle:"postgres"},sqlite:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named",constraintStyle:"postgres"},oracle:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named",constraintStyle:"postgres"},clickhouse:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous",constraintStyle:"postgres"},firebird:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},db2:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},snowflake:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},cloudspanner:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"@",parameterStyle:"named"},duckdb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},cockroachdb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed",castStyle:"postgres"},athena:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},bigquery:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"@",parameterStyle:"named"},hive:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},mariadb:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},redshift:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed",castStyle:"postgres"},flinksql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},mongodb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"}},SqlPrintTokenParser=class _SqlPrintTokenParser{constructor(options){this.handlers=new Map;this.index=1;this.joinConditionContexts=[];options?.preset&&(options={...options.preset,...options}),this.parameterDecorator=new ParameterDecorator({prefix:typeof options?.parameterSymbol=="string"?options.parameterSymbol:options?.parameterSymbol?.start??":",suffix:typeof options?.parameterSymbol=="object"?options.parameterSymbol.end:"",style:options?.parameterStyle??"named"}),this.identifierDecorator=new IdentifierDecorator({start:options?.identifierEscape?.start??'"',end:options?.identifierEscape?.end??'"',target:options?.identifierEscape?.target}),this.castStyle=options?.castStyle??"standard",this.constraintStyle=options?.constraintStyle??"postgres",this.normalizeJoinConditionOrder=options?.joinConditionOrderByDeclaration??!1,this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(QualifiedName.kind,expr=>this.visitQualifiedName(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(WindowFrameBoundStatic.kind,expr=>this.visitWindowFrameBoundStatic(expr)),this.handlers.set(WindowFrameBoundaryValue.kind,expr=>this.visitWindowFrameBoundaryValue(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(Distinct.kind,expr=>this.visitDistinct(expr)),this.handlers.set(DistinctOn.kind,expr=>this.visitDistinctOn(expr)),this.handlers.set(HintClause.kind,expr=>this.visitHintClause(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(SourceAliasExpression.kind,expr=>this.visitSourceAliasExpression(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(WindowsClause.kind,expr=>this.visitWindowClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.visitOffsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(FetchExpression.kind,expr=>this.visitFetchExpression(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleQuery(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(InsertClause.kind,expr=>this.visitInsertClause(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(UpdateClause.kind,expr=>this.visitUpdateClause(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(DeleteClause.kind,expr=>this.visitDeleteClause(expr)),this.handlers.set(UsingClause.kind,expr=>this.visitUsingClause(expr)),this.handlers.set(SetClause.kind,expr=>this.visitSetClause(expr)),this.handlers.set(SetClauseItem.kind,expr=>this.visitSetClauseItem(expr)),this.handlers.set(ReturningClause.kind,expr=>this.visitReturningClause(expr)),this.handlers.set(CreateTableQuery.kind,expr=>this.visitCreateTableQuery(expr)),this.handlers.set(TableColumnDefinition.kind,expr=>this.visitTableColumnDefinition(expr)),this.handlers.set(ColumnConstraintDefinition.kind,expr=>this.visitColumnConstraintDefinition(expr)),this.handlers.set(TableConstraintDefinition.kind,expr=>this.visitTableConstraintDefinition(expr)),this.handlers.set(ReferenceDefinition.kind,expr=>this.visitReferenceDefinition(expr)),this.handlers.set(CreateIndexStatement.kind,expr=>this.visitCreateIndexStatement(expr)),this.handlers.set(CreateSchemaStatement.kind,expr=>this.visitCreateSchemaStatement(expr)),this.handlers.set(IndexColumnDefinition.kind,expr=>this.visitIndexColumnDefinition(expr)),this.handlers.set(CreateSequenceStatement.kind,expr=>this.visitCreateSequenceStatement(expr)),this.handlers.set(AlterSequenceStatement.kind,expr=>this.visitAlterSequenceStatement(expr)),this.handlers.set(DropTableStatement.kind,expr=>this.visitDropTableStatement(expr)),this.handlers.set(DropIndexStatement.kind,expr=>this.visitDropIndexStatement(expr)),this.handlers.set(DropSchemaStatement.kind,expr=>this.visitDropSchemaStatement(expr)),this.handlers.set(CommentOnStatement.kind,expr=>this.visitCommentOnStatement(expr)),this.handlers.set(AlterTableStatement.kind,expr=>this.visitAlterTableStatement(expr)),this.handlers.set(AlterTableAddConstraint.kind,expr=>this.visitAlterTableAddConstraint(expr)),this.handlers.set(AlterTableDropConstraint.kind,expr=>this.visitAlterTableDropConstraint(expr)),this.handlers.set(AlterTableAddColumn.kind,expr=>this.visitAlterTableAddColumn(expr)),this.handlers.set(AlterTableDropColumn.kind,expr=>this.visitAlterTableDropColumn(expr)),this.handlers.set(AlterTableAlterColumnDefault.kind,expr=>this.visitAlterTableAlterColumnDefault(expr)),this.handlers.set(DropConstraintStatement.kind,expr=>this.visitDropConstraintStatement(expr)),this.handlers.set(ExplainStatement.kind,expr=>this.visitExplainStatement(expr)),this.handlers.set(AnalyzeStatement.kind,expr=>this.visitAnalyzeStatement(expr)),this.handlers.set(MergeQuery.kind,expr=>this.visitMergeQuery(expr)),this.handlers.set(MergeWhenClause.kind,expr=>this.visitMergeWhenClause(expr)),this.handlers.set(MergeUpdateAction.kind,expr=>this.visitMergeUpdateAction(expr)),this.handlers.set(MergeDeleteAction.kind,expr=>this.visitMergeDeleteAction(expr)),this.handlers.set(MergeInsertAction.kind,expr=>this.visitMergeInsertAction(expr)),this.handlers.set(MergeDoNothingAction.kind,expr=>this.visitMergeDoNothingAction(expr))}static{this.SPACE_TOKEN=new SqlPrintToken(10," ")}static{this.COMMA_TOKEN=new SqlPrintToken(3,",")}static{this.ARGUMENT_SPLIT_COMMA_TOKEN=new SqlPrintToken(11,",")}static{this.PAREN_OPEN_TOKEN=new SqlPrintToken(4,"(")}static{this.PAREN_CLOSE_TOKEN=new SqlPrintToken(4,")")}static{this.DOT_TOKEN=new SqlPrintToken(8,".")}static{this._selfHandlingComponentTypes=null}static getSelfHandlingComponentTypes(){return this._selfHandlingComponentTypes||(this._selfHandlingComponentTypes=new Set([SimpleSelectQuery.kind,SelectItem.kind,CaseKeyValuePair.kind,SwitchCaseArgument.kind,ColumnReference.kind,LiteralValue.kind,ParameterExpression.kind,TableSource.kind,SourceAliasExpression.kind,TypeValue.kind,FunctionCall.kind,IdentifierString.kind,QualifiedName.kind])),this._selfHandlingComponentTypes}visitBinarySelectQuery(arg){let token=new SqlPrintToken(0,"");if(arg.positionedComments&&arg.positionedComments.length>0)this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null;else if(arg.headerComments&&arg.headerComments.length>0){if(this.shouldMergeHeaderComments(arg.headerComments)){let mergedHeaderComment=this.createHeaderMultiLineCommentBlock(arg.headerComments);token.innerTokens.push(mergedHeaderComment)}else{let headerCommentBlocks=this.createCommentBlocks(arg.headerComments,!0);token.innerTokens.push(...headerCommentBlocks)}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}return token.innerTokens.push(this.visit(arg.left)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.operator.value,"BinarySelectQueryOperator")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.right)),token}visitCreateSchemaStatement(arg){let keywordParts=["create","schema"];arg.ifNotExists&&keywordParts.push("if not exists");let token=new SqlPrintToken(1,keywordParts.join(" "),"CreateSchemaStatement");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.schemaName.accept(this)),arg.authorization&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"authorization")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.authorization.accept(this))),token}static commaSpaceTokens(){return[_SqlPrintTokenParser.COMMA_TOKEN,_SqlPrintTokenParser.SPACE_TOKEN]}static argumentCommaSpaceTokens(){return[_SqlPrintTokenParser.ARGUMENT_SPLIT_COMMA_TOKEN,_SqlPrintTokenParser.SPACE_TOKEN]}visitQualifiedName(arg){let token=new SqlPrintToken(0,"","QualifiedName");if(arg.namespaces)for(let i=0;i<arg.namespaces.length;i++)token.innerTokens.push(arg.namespaces[i].accept(this)),token.innerTokens.push(_SqlPrintTokenParser.DOT_TOKEN);let originalNameComments=arg.name.positionedComments,originalNameLegacyComments=arg.name.comments;arg.name.positionedComments=null,arg.name.comments=null;let nameToken=arg.name.accept(this);return token.innerTokens.push(nameToken),arg.name.positionedComments=originalNameComments,arg.name.comments=originalNameLegacyComments,(this.hasPositionedComments(arg.name)||this.hasLegacyComments(arg.name))&&this.addComponentComments(token,arg.name),this.addComponentComments(token,arg),token}visitPartitionByClause(arg){let token=new SqlPrintToken(1,"partition by","PartitionByClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.value)),token}visitOrderByClause(arg){let token=new SqlPrintToken(1,"order by","OrderByClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.order.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.order[i]));return token}visitOrderByItem(arg){let token=new SqlPrintToken(0,"","OrderByItem");return token.innerTokens.push(this.visit(arg.value)),arg.sortDirection&&arg.sortDirection!=="asc"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"desc"))),arg.nullsPosition&&(arg.nullsPosition==="first"?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"nulls first"))):arg.nullsPosition==="last"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"nulls last")))),token}parse(arg){this.index=1;let token=this.visit(arg),paramsRaw=ParameterCollector.collect(arg).sort((a,b)=>(a.index??0)-(b.index??0)),style=this.parameterDecorator.style;if(style==="named"){let paramsObj={};for(let p of paramsRaw){let key=p.name.value;if(paramsObj.hasOwnProperty(key)){if(paramsObj[key]!==p.value)throw new Error(`Duplicate parameter name '${key}' with different values detected during query composition.`);continue}paramsObj[key]=p.value}return{token,params:paramsObj}}else if(style==="indexed"){let paramsArr=paramsRaw.map(p=>p.value);return{token,params:paramsArr}}else if(style==="anonymous"){let paramsArr=paramsRaw.map(p=>p.value);return{token,params:paramsArr}}return{token,params:[]}}componentHandlesOwnComments(component){return"handlesOwnComments"in component&&typeof component.handlesOwnComments=="function"?component.handlesOwnComments():_SqlPrintTokenParser.getSelfHandlingComponentTypes().has(component.getKind())}visit(arg){let handler=this.handlers.get(arg.getKind());if(handler){let token=handler(arg);return this.componentHandlesOwnComments(arg)||this.addComponentComments(token,arg),token}throw new Error(`[SqlPrintTokenParser] No handler for kind: ${arg.getKind().toString()}`)}hasPositionedComments(component){return(component.positionedComments?.length??0)>0}hasLegacyComments(component){return(component.comments?.length??0)>0}addComponentComments(token,component){this.hasPositionedComments(component)?this.addPositionedCommentsToToken(token,component):this.hasLegacyComments(component)&&this.addCommentsToToken(token,component.comments)}addPositionedCommentsToToken(token,component){if(!this.hasPositionedComments(component))return;let beforeComments=component.getPositionedComments("before");if(beforeComments.length>0){let commentBlocks=this.createCommentBlocks(beforeComments);for(let i=commentBlocks.length-1;i>=0;i--)token.innerTokens.unshift(commentBlocks[i])}let afterComments=component.getPositionedComments("after");if(afterComments.length>0){let commentBlocks=this.createCommentBlocks(afterComments);for(let commentBlock of commentBlocks)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(commentBlock)}let componentsWithDuplicationIssues=["CaseExpression","SwitchCaseArgument","CaseKeyValuePair","SelectClause","LiteralValue","IdentifierString","DistinctOn","SourceAliasExpression","SimpleSelectQuery","WhereClause"];token.containerType&&componentsWithDuplicationIssues.includes(token.containerType)&&(component.positionedComments=null)}addCommentsToToken(token,comments){if(!comments?.length)return;let commentBlocks=this.createCommentBlocks(comments);this.insertCommentBlocksWithSpacing(token,commentBlocks)}createInlineCommentSequence(comments){let commentTokens=[];for(let i=0;i<comments.length;i++){let comment=comments[i];if(comment.trim()){let commentToken=new SqlPrintToken(6,this.formatComment(comment));if(commentTokens.push(commentToken),i<comments.length-1){let spaceToken=new SqlPrintToken(10," ");commentTokens.push(spaceToken)}}}return commentTokens}createCommentBlocks(comments,isHeaderComment=!1){let commentBlocks=[];for(let comment of comments){let trimmed=comment.trim(),isSeparatorLine=/^[-=_+*#]+$/.test(trimmed);(trimmed||isSeparatorLine||comment==="")&&commentBlocks.push(this.createSingleCommentBlock(comment,isHeaderComment))}return commentBlocks}shouldMergeComment(trimmed){return!(!/^[-=_+*#]+$/.test(trimmed)&&trimmed.startsWith("--")||trimmed.startsWith("/*")&&trimmed.endsWith("*/")&&(!trimmed.slice(2,-2).trim()||trimmed.includes(`
13
+ ${context}`;return new _ParseError(message,index,context)}};function extractLexemeComments(lexeme){let before=[],after=[];if(!lexeme)return{before,after};if(lexeme.positionedComments&&lexeme.positionedComments.length>0)for(let positioned of lexeme.positionedComments)!positioned.comments||positioned.comments.length===0||(positioned.position==="before"?before.push(...positioned.comments):positioned.position==="after"&&after.push(...positioned.comments));else lexeme.comments&&lexeme.comments.length>0&&before.push(...lexeme.comments);return{before,after}}var FunctionExpressionParser=class{static{this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY=new Set(["string_agg","array_agg","json_agg","jsonb_agg","json_object_agg","jsonb_object_agg","xmlagg"])}static parseArrayExpression(lexemes,index){let idx=index;if(idx+1<lexemes.length&&lexemes[idx+1].type&512){idx++;let arg=ValueParser.parseArgument(512,1024,lexemes,idx);return idx=arg.newIndex,{value:new ArrayExpression(arg.value),newIndex:idx}}else if(idx+1<lexemes.length&&lexemes[idx+1].type&4){idx++,idx++;let arg=SelectQueryParser.parseFromLexeme(lexemes,idx);return idx=arg.newIndex,idx++,{value:new ArrayQueryExpression(arg.value),newIndex:idx}}throw new Error(`Invalid ARRAY syntax at index ${idx}, expected ARRAY[... or ARRAY(...)`)}static parseFromLexeme(lexemes,index){let idx=index,current=lexemes[idx];return current.value==="array"?this.parseArrayExpression(lexemes,idx):current.value==="substring"||current.value==="overlay"?this.parseKeywordFunction(lexemes,idx,[{key:"from",required:!1},{key:"for",required:!1}]):current.value==="cast"?this.parseKeywordFunction(lexemes,idx,[{key:"as",required:!0}]):current.value==="trim"?this.parseKeywordFunction(lexemes,idx,[{key:"from",required:!1}]):this.parseFunctionCall(lexemes,idx)}static tryParseBinaryExpression(lexemes,index,left,allowAndOperator=!0,allowOrOperator=!0){let idx=index;if(idx<lexemes.length&&lexemes[idx].type&2){let operator=lexemes[idx].value.toLowerCase();if(!allowAndOperator&&operator==="and"||!allowOrOperator&&operator==="or")return null;if(idx++,operator==="between")return this.parseBetweenExpression(lexemes,idx,left,!1);if(operator==="not between")return this.parseBetweenExpression(lexemes,idx,left,!0);if(operator==="::"){let typeValue=this.parseTypeValue(lexemes,idx);return idx=typeValue.newIndex,{value:new CastExpression(left,typeValue.value),newIndex:idx}}let rightResult=ValueParser.parseFromLexeme(lexemes,idx);return idx=rightResult.newIndex,{value:new BinaryExpression(left,operator,rightResult.value),newIndex:idx}}return null}static parseBetweenExpression(lexemes,index,value,negated){let idx=index,lower=ValueParser.parseFromLexeme(lexemes,idx,!1);if(idx=lower.newIndex,idx<lexemes.length&&lexemes[idx].type&2&&lexemes[idx].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${idx}`);idx++;let upper=this.parseBetweenUpperBound(lexemes,idx);return idx=upper.newIndex,{value:new BetweenExpression(value,lower.value,upper.value,negated),newIndex:idx}}static parseBetweenUpperBound(lexemes,index){return ValueParser.parseFromLexeme(lexemes,index,!1,!1)}static parseFunctionCall(lexemes,index){let idx=index,fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx),namespaces=fullNameResult.namespaces,name=fullNameResult.name;if(idx=fullNameResult.newIndex,idx<lexemes.length&&lexemes[idx].type&4){let functionName=name.name.toLowerCase(),arg,closingComments=null,internalOrderBy=null;if(this.AGGREGATE_FUNCTIONS_WITH_ORDER_BY.has(functionName)){let result=this.parseAggregateArguments(lexemes,idx);arg={value:result.arguments,newIndex:result.newIndex},internalOrderBy=result.orderByClause,closingComments=result.closingComments}else{let argWithComments=this.parseArgumentWithComments(lexemes,idx);arg={value:argWithComments.value,newIndex:argWithComments.newIndex},closingComments=argWithComments.closingComments}idx=arg.newIndex;let withinGroup=null;if(idx<lexemes.length&&lexemes[idx].value==="within group"){let withinGroupResult=this.parseWithinGroupClause(lexemes,idx);withinGroup=withinGroupResult.value,idx=withinGroupResult.newIndex}let filterCondition=null;if(idx<lexemes.length&&lexemes[idx].value==="filter"){let filterResult=this.parseFilterClause(lexemes,idx);filterCondition=filterResult.condition,idx=filterResult.newIndex}let withOrdinality=!1;if(idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++),idx<lexemes.length&&lexemes[idx].value==="over"){let over=OverExpressionParser.parseFromLexeme(lexemes,idx);idx=over.newIndex;let value=new FunctionCall(namespaces,name.name,arg.value,over.value,withinGroup,withOrdinality,internalOrderBy,filterCondition);return closingComments&&closingComments.length>0&&value.addPositionedComments("after",closingComments),{value,newIndex:idx}}else{let value=new FunctionCall(namespaces,name.name,arg.value,null,withinGroup,withOrdinality,internalOrderBy,filterCondition);return closingComments&&closingComments.length>0&&value.addPositionedComments("after",closingComments),{value,newIndex:idx}}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Expected opening parenthesis after function name '${name.name}'.`)}static parseKeywordFunction(lexemes,index,keywords2){let idx=index,fullNameResult=FullNameParser.parseFromLexeme(lexemes,idx),namespaces=fullNameResult.namespaces,name=fullNameResult.name;if(idx=fullNameResult.newIndex,idx<lexemes.length&&lexemes[idx].type&4){idx++;let input=ValueParser.parseFromLexeme(lexemes,idx),arg=input.value;if(idx=input.newIndex,idx<lexemes.length&&lexemes[idx].type&16)return this.parseFunctionCall(lexemes,index);for(let{key,required}of keywords2)if(idx<lexemes.length&&lexemes[idx].type&128&&lexemes[idx].value===key)if(idx++,idx<lexemes.length&&lexemes[idx].type&8192){let typeValue=this.parseTypeValue(lexemes,idx);arg=new BinaryExpression(arg,key,typeValue.value),idx=typeValue.newIndex}else{let right=ValueParser.parseFromLexeme(lexemes,idx);arg=new BinaryExpression(arg,key,right.value),idx=right.newIndex}else if(required)throw ParseError.fromUnparsedLexemes(lexemes,idx,`Keyword '${key}' is required for ${name.name} function.`);if(idx<lexemes.length&&lexemes[idx].type&8){idx++;let withinGroup=null;if(idx<lexemes.length&&lexemes[idx].value==="within group"){let withinGroupResult=this.parseWithinGroupClause(lexemes,idx);withinGroup=withinGroupResult.value,idx=withinGroupResult.newIndex}let withOrdinality=!1;if(idx<lexemes.length&&lexemes[idx].value==="with ordinality"&&(withOrdinality=!0,idx++),idx<lexemes.length&&lexemes[idx].value==="over"){idx++;let over=OverExpressionParser.parseFromLexeme(lexemes,idx);return idx=over.newIndex,{value:new FunctionCall(namespaces,name.name,arg,over.value,withinGroup,withOrdinality,null),newIndex:idx}}else return{value:new FunctionCall(namespaces,name.name,arg,null,withinGroup,withOrdinality,null),newIndex:idx}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Missing closing parenthesis for function '${name.name}'.`)}else throw ParseError.fromUnparsedLexemes(lexemes,idx,`Missing opening parenthesis for function '${name.name}'.`)}static parseTypeValue(lexemes,index){let idx=index,{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(idx=newIndex,idx<lexemes.length&&lexemes[idx].type&4){let arg=ValueParser.parseArgument(4,8,lexemes,idx);idx=arg.newIndex;let value=new TypeValue(namespaces,new RawString(name.name),arg.value);return arg.value.positionedComments&&(value.positionedComments=arg.value.positionedComments),arg.value.comments,{value,newIndex:idx}}else return{value:new TypeValue(namespaces,new RawString(name.name)),newIndex:idx}}static parseWithinGroupClause(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].value!=="within group")throw new Error(`Expected 'WITHIN GROUP' at index ${idx}`);if(idx++,idx>=lexemes.length||!(lexemes[idx].type&4))throw new Error(`Expected '(' after 'WITHIN GROUP' at index ${idx}`);idx++;let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);if(idx=orderByResult.newIndex,idx>=lexemes.length||!(lexemes[idx].type&8))throw new Error(`Expected ')' after WITHIN GROUP ORDER BY clause at index ${idx}`);return idx++,{value:orderByResult.value,newIndex:idx}}static parseFilterClause(lexemes,index){let idx=index;if(idx>=lexemes.length||lexemes[idx].value!=="filter")throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected 'FILTER' keyword.");if(idx++,idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected '(' after FILTER.");if(idx++,idx>=lexemes.length||lexemes[idx].value!=="where")throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected 'WHERE' inside FILTER clause.");idx++;let conditionResult=ValueParser.parseFromLexeme(lexemes,idx);if(idx=conditionResult.newIndex,idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected ')' after FILTER predicate.");return idx++,{condition:conditionResult.value,newIndex:idx}}static parseAggregateArguments(lexemes,index){let idx=index,args=[],orderByClause=null;if(idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected opening parenthesis.");if(idx++,idx<lexemes.length&&lexemes[idx].type&8){let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{arguments:new ValueList([]),orderByClause:null,closingComments:closingComments2,newIndex:idx}}if(idx<lexemes.length&&lexemes[idx].value==="*"){let wildcard=new ColumnReference(null,"*");if(idx++,idx<lexemes.length&&lexemes[idx].type&8){let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{arguments:wildcard,orderByClause:null,closingComments:closingComments2,newIndex:idx}}else throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis after wildcard '*'.")}let firstArg=ValueParser.parseFromLexeme(lexemes,idx);for(idx=firstArg.newIndex,args.push(firstArg.value);idx<lexemes.length&&(lexemes[idx].type&16||lexemes[idx].value==="order by");){if(lexemes[idx].value==="order by"){let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);idx=orderByResult.newIndex,orderByClause=orderByResult.value;break}if(lexemes[idx].type&16){if(idx++,idx<lexemes.length&&lexemes[idx].value==="order by"){let orderByResult=OrderByClauseParser.parseFromLexeme(lexemes,idx);idx=orderByResult.newIndex,orderByClause=orderByResult.value;break}let argResult=ValueParser.parseFromLexeme(lexemes,idx);idx=argResult.newIndex,args.push(argResult.value)}}if(idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis.");let closingComments=this.getClosingComments(lexemes[idx]);return idx++,{arguments:args.length===1?args[0]:new ValueList(args),orderByClause,closingComments,newIndex:idx}}static parseArgumentWithComments(lexemes,index){let idx=index;if(idx>=lexemes.length||!(lexemes[idx].type&4))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected opening parenthesis.");let openParenToken=lexemes[idx];idx++;let args=[];if(idx<lexemes.length&&lexemes[idx].type&8){let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{value:new ValueList([]),closingComments:closingComments2,newIndex:idx}}if(idx<lexemes.length&&lexemes[idx].value==="*"){let wildcard=new ColumnReference(null,"*");if(idx++,idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis after wildcard '*'.");let closingComments2=this.getClosingComments(lexemes[idx]);return idx++,{value:wildcard,closingComments:closingComments2,newIndex:idx}}let result=ValueParser.parseFromLexeme(lexemes,idx);if(idx=result.newIndex,openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let afterComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){let beforeComments=afterComments.map(pc=>({position:"before",comments:pc.comments}));result.value.positionedComments=[...beforeComments,...result.value.positionedComments||[]],result.value,"qualifiedName"in result.value&&result.value.qualifiedName&&"name"in result.value.qualifiedName&&result.value.qualifiedName.name&&(result.value.qualifiedName.name.positionedComments=null,result.value.qualifiedName.name)}}for(args.push(result.value);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let argResult=ValueParser.parseFromLexeme(lexemes,idx);idx=argResult.newIndex,args.push(argResult.value)}if(idx>=lexemes.length||!(lexemes[idx].type&8))throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis.");let closingComments=this.getClosingComments(lexemes[idx]);return idx++,{value:args.length===1?args[0]:new ValueList(args),closingComments,newIndex:idx}}static getClosingComments(lexeme){if(!lexeme)return null;let commentInfo=extractLexemeComments(lexeme);return commentInfo.after.length>0?commentInfo.after:commentInfo.before.length>0?commentInfo.before:null}};var OperatorPrecedence=class{static{this.precedenceMap={or:1,and:2,"=":10,"!=":10,"<>":10,"<":10,"<=":10,">":10,">=":10,like:10,ilike:10,"not like":10,"not ilike":10,"similar to":10,"not similar to":10,in:10,"not in":10,is:10,"is not":10,"->":10,"->>":10,"#>":10,"#>>":10,"@>":10,"<@":10,"?":10,"?|":10,"?&":10,"~":10,"~*":10,"!~":10,"!~*":10,rlike:10,regexp:10,mod:30,xor:2,between:15,"not between":15,"+":20,"-":20,"||":20,"*":30,"/":30,"%":30,"^":40,"::":50,"unary+":100,"unary-":100,not:100}}static getPrecedence(operator){let precedence=this.precedenceMap[operator.toLowerCase()];return precedence!==void 0?precedence:0}static hasHigherOrEqualPrecedence(operator1,operator2){return this.getPrecedence(operator1)>=this.getPrecedence(operator2)}static isLogicalOperator(operator){let op=operator.toLowerCase();return op==="and"||op==="or"}static isBetweenOperator(operator){let op=operator.toLowerCase();return op==="between"||op==="not between"}static isComparisonOperator(operator){let lowerOp=operator.toLowerCase();return["=","!=","<>","<",">","<=",">=","like","ilike","similar to","in","not in","->","->>","#>","#>>","@>","<@","?","?|","?&","~","~*","!~","!~*","rlike","regexp"].includes(lowerOp)}};var ValueParser=class{static parse(query){let lexemes=new SqlTokenizer(query).readLexmes(),result=this.parseFromLexeme(lexemes,0);if(result.newIndex<lexemes.length)throw ParseError.fromUnparsedLexemes(lexemes,result.newIndex,"[ValueParser]");return result.value}static parseFromLexeme(lexemes,index,allowAndOperator=!0,allowOrOperator=!0){return this.parseExpressionWithPrecedence(lexemes,index,0,allowAndOperator,allowOrOperator)}static parseExpressionWithPrecedence(lexemes,index,minPrecedence,allowAndOperator=!0,allowOrOperator=!0){let idx=index,comment=lexemes[idx].comments,positionedComments=lexemes[idx].positionedComments,left=this.parseItem(lexemes,idx);positionedComments&&positionedComments.length>0&&!left.value.positionedComments?left.value.positionedComments=positionedComments:left.value.comments===null&&comment&&comment.length>0&&(left.value.comments=comment),idx=left.newIndex;let result=left.value,arrayAccessResult=this.parseArrayAccess(lexemes,idx,result);for(result=arrayAccessResult.value,idx=arrayAccessResult.newIndex;idx<lexemes.length&&lexemes[idx].type&2;){let operatorToken=lexemes[idx],operator=operatorToken.value;if(!allowAndOperator&&operator.toLowerCase()==="and"||!allowOrOperator&&operator.toLowerCase()==="or")break;let precedence=OperatorPrecedence.getPrecedence(operator);if(precedence<minPrecedence)break;if(idx++,OperatorPrecedence.isBetweenOperator(operator)){let betweenResult=FunctionExpressionParser.parseBetweenExpression(lexemes,idx,result,operator.toLowerCase().includes("not"));result=betweenResult.value,idx=betweenResult.newIndex;continue}if(operator==="::"){let typeValue=FunctionExpressionParser.parseTypeValue(lexemes,idx);result=new CastExpression(result,typeValue.value),idx=typeValue.newIndex;continue}let nextMinPrecedence=precedence+1,rightResult=this.parseExpressionWithPrecedence(lexemes,idx,nextMinPrecedence,allowAndOperator,allowOrOperator);idx=rightResult.newIndex;let binaryExpr=new BinaryExpression(result,operator,rightResult.value);operatorToken.comments&&operatorToken.comments.length>0&&(binaryExpr.operator.comments=operatorToken.comments),operatorToken.positionedComments&&operatorToken.positionedComments.length>0&&(binaryExpr.operator.positionedComments=operatorToken.positionedComments),result=binaryExpr}return{value:result,newIndex:idx}}static transferPositionedComments(lexeme,value){if(lexeme.positionedComments&&lexeme.positionedComments.length>0){let beforeComments=lexeme.positionedComments.filter(comment=>comment.position==="before"),afterComments=lexeme.positionedComments.filter(comment=>comment.position==="after");if(beforeComments.length>0){let clonedBefore=beforeComments.map(comment=>({position:comment.position,comments:[...comment.comments]}));value.positionedComments=value.positionedComments?[...clonedBefore,...value.positionedComments]:clonedBefore}if(afterComments.length>0){let clonedAfter=afterComments.map(comment=>({position:comment.position,comments:[...comment.comments]}));value.positionedComments=value.positionedComments?[...value.positionedComments,...clonedAfter]:clonedAfter}!beforeComments.length&&!afterComments.length&&!value.positionedComments&&(value.positionedComments=lexeme.positionedComments.map(comment=>({position:comment.position,comments:[...comment.comments]})));return}else value.comments===null&&lexeme.comments&&lexeme.comments.length>0&&(value.comments=lexeme.comments)}static parseItem(lexemes,index){let idx=index;if(idx>=lexemes.length)throw new Error(`Unexpected end of lexemes at index ${index}`);let current=lexemes[idx];if(current.type&64&&current.type&2&&current.type&8192){if(idx+1<lexemes.length&&lexemes[idx+1].type&4)if(this.isTypeConstructor(lexemes,idx+1,current.value)){let result=FunctionExpressionParser.parseTypeValue(lexemes,idx);return this.transferPositionedComments(current,result.value),{value:result.value,newIndex:result.newIndex}}else{let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}let first=IdentifierParser.parseFromLexeme(lexemes,idx);if(first.newIndex>=lexemes.length)return this.transferPositionedComments(current,first.value),first;if(lexemes[first.newIndex].type&1){let literalIndex=first.newIndex,literalLexeme=lexemes[literalIndex],second=LiteralParser.parseFromLexeme(lexemes,literalIndex);this.transferPositionedComments(literalLexeme,second.value);let result=new UnaryExpression(lexemes[idx].value,second.value);return this.transferPositionedComments(current,result),{value:result,newIndex:second.newIndex}}return this.transferPositionedComments(current,first.value),first}else if(current.type&64){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(lexemes[newIndex-1].type&2048){let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(lexemes[newIndex-1].type&8192)if(newIndex<lexemes.length&&lexemes[newIndex].type&4)if(this.isTypeConstructor(lexemes,newIndex,name.name)){let result=FunctionExpressionParser.parseTypeValue(lexemes,idx);return this.transferPositionedComments(current,result.value),{value:result.value,newIndex:result.newIndex}}else{let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else{let value2=new TypeValue(namespaces,name);return this.transferPositionedComments(current,value2),{value:value2,newIndex}}let value=new ColumnReference(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}else if(current.type&1&&this.isQualifiedSpecialValueIdentifier(lexemes,idx)){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx),value=new ColumnReference(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}else if(current.type&1){let result=LiteralParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&4){let result=ParenExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&2048){let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&2){let result=UnaryExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&256){let result=ParameterExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&4096){let result=StringSpecifierExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&128){let result=CommandExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else if(current.type&512){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx),value=new ColumnReference(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}else if(current.type&8192){let{namespaces,name,newIndex}=FullNameParser.parseFromLexeme(lexemes,idx);if(newIndex<lexemes.length&&lexemes[newIndex].type&4)if(this.isTypeConstructor(lexemes,newIndex,name.name)){let result=FunctionExpressionParser.parseTypeValue(lexemes,idx);return this.transferPositionedComments(current,result.value),{value:result.value,newIndex:result.newIndex}}else{let result=FunctionExpressionParser.parseFromLexeme(lexemes,idx);return this.transferPositionedComments(current,result.value),result}else{let value=new TypeValue(namespaces,name);return this.transferPositionedComments(current,value),{value,newIndex}}}throw ParseError.fromUnparsedLexemes(lexemes,idx,"[ValueParser] Invalid lexeme.")}static isQualifiedSpecialValueIdentifier(lexemes,index){return SQL_SPECIAL_VALUE_KEYWORD_SET.has(lexemes[index].value.toLowerCase())&&index+1<lexemes.length&&(lexemes[index+1].type&32)!==0}static parseArgument(openToken,closeToken,lexemes,index){let idx=index,args=[];if(idx<lexemes.length&&lexemes[idx].type===openToken){let openParenToken=lexemes[idx];if(idx++,idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,{value:new ValueList([]),newIndex:idx};if(idx<lexemes.length&&lexemes[idx].value==="*"){let wildcard=new ColumnReference(null,"*");if(openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let beforeComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");beforeComments.length>0&&(wildcard.positionedComments=beforeComments.map(pc=>({position:"before",comments:pc.comments})))}else openParenToken.comments&&openParenToken.comments.length>0&&(wildcard.comments=openParenToken.comments);if(idx++,idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,{value:wildcard,newIndex:idx};throw ParseError.fromUnparsedLexemes(lexemes,idx,"Expected closing parenthesis after wildcard '*'.")}let result=this.parseFromLexeme(lexemes,idx);if(idx=result.newIndex,openParenToken.positionedComments&&openParenToken.positionedComments.length>0){let afterComments=openParenToken.positionedComments.filter(pc=>pc.position==="after");if(afterComments.length>0){let beforeComments=afterComments.map(pc=>({position:"before",comments:pc.comments}));result.value.positionedComments?result.value.positionedComments=[...beforeComments,...result.value.positionedComments]:result.value.positionedComments=beforeComments}}else openParenToken.comments&&openParenToken.comments.length>0&&(result.value.comments?result.value.comments=openParenToken.comments.concat(result.value.comments):result.value.comments=openParenToken.comments);for(args.push(result.value);idx<lexemes.length&&lexemes[idx].type&16;){idx++;let argResult=this.parseFromLexeme(lexemes,idx);idx=argResult.newIndex,args.push(argResult.value)}if(idx<lexemes.length&&lexemes[idx].type===closeToken)return idx++,args.length===1?{value:args[0],newIndex:idx}:{value:new ValueList(args),newIndex:idx};throw ParseError.fromUnparsedLexemes(lexemes,idx,"Missing closing parenthesis.")}throw ParseError.fromUnparsedLexemes(lexemes,index,"Expected opening parenthesis.")}static parseArrayAccess(lexemes,index,baseExpression){let idx=index,result=baseExpression;for(;idx<lexemes.length&&lexemes[idx].type&512&&!this.isSqlServerBracketIdentifier(lexemes,idx);){if(idx++,idx>=lexemes.length)throw new Error(`Expected array index or slice after '[' at index ${idx-1}`);if(lexemes[idx].type&1024)throw new Error(`Empty array access brackets not supported at index ${idx}`);let startExpr=null,isSlice=!1;if(lexemes[idx].type&2&&lexemes[idx].value===":")isSlice=!0,idx++;else{let colonPrecedence=OperatorPrecedence.getPrecedence(":"),firstResult=this.parseExpressionWithPrecedence(lexemes,idx,colonPrecedence+1);startExpr=firstResult.value,idx=firstResult.newIndex,idx<lexemes.length&&lexemes[idx].type&2&&lexemes[idx].value===":"&&(isSlice=!0,idx++)}if(isSlice){let endExpr=null;if(idx<lexemes.length&&!(lexemes[idx].type&1024)){let colonPrecedence=OperatorPrecedence.getPrecedence(":"),endResult=this.parseExpressionWithPrecedence(lexemes,idx,colonPrecedence+1);endExpr=endResult.value,idx=endResult.newIndex}if(idx>=lexemes.length||!(lexemes[idx].type&1024))throw new Error(`Expected ']' after array slice at index ${idx}`);idx++,result=new ArraySliceExpression(result,startExpr,endExpr)}else{if(!startExpr){let indexResult=this.parseFromLexeme(lexemes,idx);startExpr=indexResult.value,idx=indexResult.newIndex}if(idx>=lexemes.length||!(lexemes[idx].type&1024))throw new Error(`Expected ']' after array index at index ${idx}`);idx++,result=new ArrayIndexExpression(result,startExpr)}}return{value:result,newIndex:idx}}static isSqlServerBracketIdentifier(lexemes,bracketIndex){let idx=bracketIndex+1;if(idx>=lexemes.length)return!1;for(;idx<lexemes.length&&!(lexemes[idx].type&1024);){let token=lexemes[idx];if(token.type&64||token.type&2&&token.value==="."){idx++;continue}return!1}if(idx>=lexemes.length)return!1;let closingBracketIndex=idx;if(closingBracketIndex+1<lexemes.length){let nextToken=lexemes[closingBracketIndex+1];if(nextToken.type&2&&nextToken.value===".")return!0}idx=bracketIndex+1;let hasOnlyIdentifiersAndDots=!0;for(;idx<closingBracketIndex;){let token=lexemes[idx];if(!(token.type&64||token.type&2&&token.value===".")){hasOnlyIdentifiersAndDots=!1;break}idx++}return hasOnlyIdentifiersAndDots}static isTypeConstructor(lexemes,openParenIndex,typeName){let alwaysTypeConstructors=["NUMERIC","DECIMAL","VARCHAR","CHAR","CHARACTER","TIMESTAMP","TIME","INTERVAL"],upperTypeName=typeName.toUpperCase();if(alwaysTypeConstructors.includes(upperTypeName))return!0;if(upperTypeName==="DATE"){let firstArgIndex=openParenIndex+1;if(firstArgIndex<lexemes.length){let firstArg=lexemes[firstArgIndex];return!(firstArg.type&1&&typeof firstArg.value=="string"&&isNaN(Number(firstArg.value)))}}return!1}};var UpdateQuery=class extends SqlComponent{static{this.kind=Symbol("UpdateQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.updateClause=params.updateClause,this.setClause=params.setClause instanceof SetClause?params.setClause:new SetClause(params.setClause),this.whereClause=params.whereClause??null,this.fromClause=params.fromClause??null,this.returningClause=params.returning??null}};var DeleteQuery=class extends SqlComponent{static{this.kind=Symbol("DeleteQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.deleteClause=params.deleteClause,this.usingClause=params.usingClause??null,this.whereClause=params.whereClause??null,this.returningClause=params.returning??null}};var MergeAction=class extends SqlComponent{static{this.kind=Symbol("MergeAction")}},MergeUpdateAction=class extends MergeAction{static{this.kind=Symbol("MergeUpdateAction")}constructor(setClause,whereClause){super(),this.setClause=setClause instanceof SetClause?setClause:new SetClause(setClause),this.whereClause=whereClause??null}},MergeDeleteAction=class extends MergeAction{static{this.kind=Symbol("MergeDeleteAction")}constructor(whereClause){super(),this.whereClause=whereClause??null}},MergeInsertAction=class extends MergeAction{static{this.kind=Symbol("MergeInsertAction")}constructor(params){super(),this.columns=params.columns?params.columns.map(col=>typeof col=="string"?new IdentifierString(col):col):null,this.values=params.values??null,this.defaultValues=params.defaultValues??!1,this.valuesLeadingComments=params.valuesLeadingComments?[...params.valuesLeadingComments]:null}addValuesLeadingComments(comments){if(!(!comments||comments.length===0)){this.valuesLeadingComments||(this.valuesLeadingComments=[]);for(let comment of comments)this.valuesLeadingComments.includes(comment)||this.valuesLeadingComments.push(comment)}}getValuesLeadingComments(){return this.valuesLeadingComments?[...this.valuesLeadingComments]:[]}},MergeDoNothingAction=class extends MergeAction{static{this.kind=Symbol("MergeDoNothingAction")}},MergeWhenClause=class extends SqlComponent{static{this.kind=Symbol("MergeWhenClause")}constructor(matchType,action,condition,options){super(),this.matchType=matchType,this.action=action,this.condition=condition??null,this.thenLeadingComments=options?.thenLeadingComments?[...options.thenLeadingComments]:null}addThenLeadingComments(comments){if(!(!comments||comments.length===0)){this.thenLeadingComments||(this.thenLeadingComments=[]);for(let comment of comments)this.thenLeadingComments.includes(comment)||this.thenLeadingComments.push(comment)}}getThenLeadingComments(){return this.thenLeadingComments?[...this.thenLeadingComments]:[]}},MergeQuery=class extends SqlComponent{static{this.kind=Symbol("MergeQuery")}constructor(params){super(),this.withClause=params.withClause??null,this.target=params.target,this.source=params.source,this.onCondition=params.onCondition,this.whenClauses=params.whenClauses,this.returningClause=params.returningClause??null}};var CTECollector=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(MergeQuery.kind,expr=>this.visitMergeQuery(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}getCommonTables(){return this.commonTables}reset(){this.commonTables=[],this.visitedNodes.clear()}collect(query){return this.visit(query),this.getCommonTables()}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}let kindSymbol=arg.getKind()?.toString()||"unknown",constructor=arg.constructor?.name||"unknown";throw new Error(`[CTECollector] No handler for ${constructor} with kind ${kindSymbol}.`)}visitSimpleSelectQuery(query){if(query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.orderByClause&&query.orderByClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.limitClause&&query.limitClause.accept(this),query.forClause&&query.forClause.accept(this),query.selectClause.accept(this),query.withClause&&query.withClause.accept(this)}visitBinarySelectQuery(query){query.left.accept(this),query.right.accept(this)}visitValuesQuery(query){for(let tuple of query.tuples)tuple.accept(this)}visitInsertQuery(query){query.selectQuery&&query.selectQuery.accept(this)}visitUpdateQuery(query){query.withClause&&query.withClause.accept(this),query.updateClause.source.accept(this),query.setClause.items.forEach(item=>item.value.accept(this)),query.fromClause&&query.fromClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.returningClause&&this.visitReturningClause(query.returningClause)}visitDeleteQuery(query){query.withClause&&query.withClause.accept(this),query.deleteClause.source.accept(this),query.usingClause&&query.usingClause.sources.forEach(source=>source.accept(this)),query.whereClause&&query.whereClause.accept(this),query.returningClause&&this.visitReturningClause(query.returningClause)}visitMergeQuery(query){query.withClause&&query.withClause.accept(this),query.target.accept(this),query.source.accept(this),query.onCondition.accept(this);for(let clause of query.whenClauses)if(clause.condition&&clause.condition.accept(this),clause.action instanceof MergeUpdateAction)clause.action.setClause.items.forEach(item=>item.value.accept(this)),clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeDeleteAction)clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeInsertAction&&clause.action.values)clause.action.values.accept(this);else if(!(clause.action instanceof MergeInsertAction)){let actionName=clause.action?.constructor?.name??"UnknownMergeAction";throw new Error(`[CTECollector] Unsupported MERGE action type: ${actionName}.`)}query.returningClause&&this.visitReturningClause(query.returningClause)}visitReturningClause(clause){for(let item of clause.items)item.accept(this)}visitWithClause(withClause){for(let i=0;i<withClause.tables.length;i++)withClause.tables[i].accept(this)}visitCommonTable(commonTable){commonTable.query.accept(this),this.commonTables.push(commonTable)}visitSelectClause(clause){for(let item of clause.items)item.accept(this)}visitSelectItem(item){item.value.accept(this)}visitFromClause(fromClause){if(fromClause.source.accept(this),fromClause.joins)for(let join of fromClause.joins)join.accept(this)}visitSourceExpression(source){source.datasource.accept(this)}visitTableSource(source){}visitFunctionSource(source){source.argument&&source.argument.accept(this)}visitParenSource(source){source.source.accept(this)}visitSubQuerySource(subQuery){subQuery.query.accept(this)}visitInlineQuery(inlineQuery){inlineQuery.selectQuery.accept(this)}visitJoinClause(joinClause){joinClause.source.accept(this),joinClause.condition&&joinClause.condition.accept(this)}visitJoinOnClause(joinOn){joinOn.condition.accept(this)}visitJoinUsingClause(joinUsing){joinUsing.condition.accept(this)}visitWhereClause(whereClause){whereClause.condition.accept(this)}visitGroupByClause(clause){for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition.accept(this)}visitOrderByClause(clause){for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitLimitClause(clause){clause.value.accept(this)}visitForClause(clause){}visitOrderByItem(item){item.value.accept(this)}visitParenExpression(expr){expr.expression.accept(this)}visitBinaryExpression(expr){expr.left.accept(this),expr.right.accept(this)}visitUnaryExpression(expr){expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase.accept(this)}visitSwitchCaseArgument(switchCase){for(let caseItem of switchCase.cases)caseItem.accept(this);switchCase.elseValue&&switchCase.elseValue.accept(this)}visitCaseKeyValuePair(pair){pair.key.accept(this),pair.value.accept(this)}visitBetweenExpression(expr){expr.expression.accept(this),expr.lower.accept(this),expr.upper.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.over&&func.over.accept(this)}visitArrayExpression(expr){expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitTupleExpression(expr){for(let value of expr.values)value.accept(this)}visitCastExpression(expr){expr.input.accept(this),expr.castType.accept(this)}visitTypeValue(expr){expr.argument&&expr.argument.accept(this)}visitWindowFrameExpression(expr){expr.partition&&expr.partition.accept(this),expr.order&&expr.order.accept(this),expr.frameSpec&&expr.frameSpec.accept(this)}visitWindowFrameSpec(spec){}visitIdentifierString(ident){}visitRawString(raw){}visitColumnReference(column){}visitParameterExpression(param){}visitLiteralValue(value){}visitPartitionByClause(partitionBy){}visitValueList(valueList){for(let value of valueList.values)value.accept(this)}visitStringSpecifierExpression(expr){}};var CTEDisabler=class{constructor(){this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr))}reset(){this.visitedNodes.clear()}execute(arg){return this.reset(),this.visit(arg)}visit(arg){if(!this.isRootVisit)return this.visitNode(arg);this.reset(),this.isRootVisit=!1;try{return this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return arg;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler)return handler(arg);let kindSymbol=arg.getKind()?.toString()||"unknown",constructor=arg.constructor?.name||"unknown";throw new Error(`[CTEDisabler] No handler for ${constructor} with kind ${kindSymbol}.`)}visitSimpleSelectQuery(arg){return arg.withClause&&arg.withClause.tables.forEach(table=>{this.visit(table.query)}),arg.withClause=null,arg.selectClause=this.visit(arg.selectClause),arg.fromClause=arg.fromClause?this.visit(arg.fromClause):null,arg.whereClause=arg.whereClause?this.visit(arg.whereClause):null,arg.groupByClause=arg.groupByClause?this.visit(arg.groupByClause):null,arg.havingClause=arg.havingClause?this.visit(arg.havingClause):null,arg.orderByClause=arg.orderByClause?this.visit(arg.orderByClause):null,arg.windowClause&&(arg.windowClause=new WindowsClause(arg.windowClause.windows.map(w=>this.visit(w)))),arg.limitClause=arg.limitClause?this.visit(arg.limitClause):null,arg.forClause=arg.forClause?this.visit(arg.forClause):null,arg}visitBinarySelectQuery(query){return query.left=this.visit(query.left),query.right=this.visit(query.right),query}visitValuesQuery(query){let newTuples=query.tuples.map(tuple=>this.visit(tuple));return new ValuesQuery(newTuples)}visitInsertQuery(query){return query}visitUpdateQuery(query){return query}visitDeleteQuery(query){return query}visitSelectClause(clause){let newItems=clause.items.map(item=>this.visit(item));return new SelectClause(newItems,clause.distinct)}visitFromClause(clause){let newSource=this.visit(clause.source),newJoins=clause.joins?clause.joins.map(join=>this.visit(join)):null;return new FromClause(newSource,newJoins)}visitSubQuerySource(subQuery){let newQuery=this.visit(subQuery.query);return new SubQuerySource(newQuery)}visitInlineQuery(inlineQuery){let newQuery=this.visit(inlineQuery.selectQuery);return new InlineQuery(newQuery)}visitJoinClause(joinClause){let newSource=this.visit(joinClause.source),newCondition=joinClause.condition?this.visit(joinClause.condition):null;return new JoinClause(joinClause.joinType.value,newSource,newCondition,joinClause.lateral)}visitJoinOnClause(joinOn){let newCondition=this.visit(joinOn.condition);return new JoinOnClause(newCondition)}visitJoinUsingClause(joinUsing){let newCondition=this.visit(joinUsing.condition);return new JoinUsingClause(newCondition)}visitWhereClause(whereClause){let newCondition=this.visit(whereClause.condition);return new WhereClause(newCondition)}visitGroupByClause(clause){let newGrouping=clause.grouping.map(item=>this.visit(item));return new GroupByClause(newGrouping)}visitHavingClause(clause){let newCondition=this.visit(clause.condition);return new HavingClause(newCondition)}visitOrderByClause(clause){let newOrder=clause.order.map(item=>this.visit(item));return new OrderByClause(newOrder)}visitWindowFrameClause(clause){let newExpression=this.visit(clause.expression);return new WindowFrameClause(clause.name.name,newExpression)}visitLimitClause(clause){let newLimit=this.visit(clause.value);return new LimitClause(newLimit)}visitForClause(clause){return new ForClause(clause.lockMode)}visitParenExpression(expr){let newExpression=this.visit(expr.expression);return new ParenExpression(newExpression)}visitBinaryExpression(expr){let newLeft=this.visit(expr.left),newRight=this.visit(expr.right);return new BinaryExpression(newLeft,expr.operator.value,newRight)}visitUnaryExpression(expr){let newExpression=this.visit(expr.expression);return new UnaryExpression(expr.operator.value,newExpression)}visitCaseExpression(expr){let newCondition=expr.condition?this.visit(expr.condition):null,newSwitchCase=this.visit(expr.switchCase);return new CaseExpression(newCondition,newSwitchCase)}visitSwitchCaseArgument(switchCase){let newCases=switchCase.cases.map(caseItem=>this.visit(caseItem)),newElseValue=switchCase.elseValue?this.visit(switchCase.elseValue):null;return new SwitchCaseArgument(newCases,newElseValue)}visitCaseKeyValuePair(pair){let newKey=this.visit(pair.key),newValue=this.visit(pair.value);return new CaseKeyValuePair(newKey,newValue)}visitBetweenExpression(expr){let newExpression=this.visit(expr.expression),newLower=this.visit(expr.lower),newUpper=this.visit(expr.upper);return new BetweenExpression(newExpression,newLower,newUpper,expr.negated)}visitFunctionCall(func){let newArgument=func.argument?this.visit(func.argument):null,newOver=func.over?this.visit(func.over):null;return new FunctionCall(func.namespaces,func.name,newArgument,newOver)}visitArrayExpression(expr){let newExpression=this.visit(expr.expression);return new ArrayExpression(newExpression)}visitArrayQueryExpression(expr){let newQuery=this.visit(expr.query);return new ArrayQueryExpression(newQuery)}visitTupleExpression(expr){let newValues=expr.values.map(value=>this.visit(value));return new TupleExpression(newValues)}visitCastExpression(expr){let newInput=this.visit(expr.input),newCastType=this.visit(expr.castType);return new CastExpression(newInput,newCastType)}visitTypeValue(typeValue){let newArgument=typeValue.argument?this.visit(typeValue.argument):null;return new TypeValue(typeValue.namespaces,typeValue.name,newArgument)}visitSelectItem(item){let newValue=this.visit(item.value);return new SelectItem(newValue,item.identifier?.name)}visitIdentifierString(ident){return ident}visitRawString(raw){return raw}visitColumnReference(column){return column}visitSourceExpression(source){let newSource=this.visit(source.datasource),newAlias=source.aliasExpression;return new SourceExpression(newSource,newAlias)}visitTableSource(source){return source}visitParenSource(source){let newSource=this.visit(source.source);return new ParenSource(newSource)}visitParameterExpression(param){return param}visitWindowFrameExpression(expr){let newPartition=expr.partition?this.visit(expr.partition):null,newOrder=expr.order?this.visit(expr.order):null,newFrameSpec=expr.frameSpec?this.visit(expr.frameSpec):null;return new WindowFrameExpression(newPartition,newOrder,newFrameSpec)}visitWindowFrameSpec(spec){return spec}visitLiteralValue(value){return value}visitOrderByItem(item){let newValue=this.visit(item.value);return new OrderByItem(newValue,item.sortDirection,item.nullsPosition)}visitValueList(valueList){let newValues=valueList.values.map(value=>this.visit(value));return new ValueList(newValues)}visitArraySliceExpression(expr){return expr}visitArrayIndexExpression(expr){return expr}visitStringSpecifierExpression(expr){return expr}visitPartitionByClause(clause){let newValue=this.visit(clause.value);return new PartitionByClause(newValue)}};var TableSourceCollector=class{constructor(selectableOnly=!0,dedupe=!0){this.tableSources=[];this.visitedNodes=new Set;this.tableNameMap=new Map;this.cteNames=new Set;this.isRootVisit=!0;this.selectableOnly=selectableOnly,this.dedupe=dedupe,this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(MergeQuery.kind,expr=>this.visitMergeQuery(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(ParenSource.kind,expr=>this.visitParenSource(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),selectableOnly||(this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.visitOffsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)))}getTableSources(){return this.tableSources}reset(){this.tableSources=[],this.tableNameMap.clear(),this.visitedNodes.clear(),this.cteNames.clear()}getTableIdentifier(source){return source.qualifiedName.namespaces&&source.qualifiedName.namespaces.length>0?source.qualifiedName.namespaces.map(ns=>ns.name).join(".")+"."+(source.qualifiedName.name instanceof RawString?source.qualifiedName.name.value:source.qualifiedName.name.name):source.qualifiedName.name instanceof RawString?source.qualifiedName.name.value:source.qualifiedName.name.name}collect(query){return this.visit(query),this.getTableSources()}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.selectableOnly||this.collectCTEs(arg),this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}}collectCTEs(query){let cteCollector=new CTECollector;cteCollector.visit(query);let commonTables=cteCollector.getCommonTables();for(let cte of commonTables)this.cteNames.add(cte.aliasExpression.table.name)}visitSimpleSelectQuery(query){if(query.fromClause&&query.fromClause.accept(this),!this.selectableOnly){if(query.withClause&&query.withClause.accept(this),query.whereClause&&query.whereClause.accept(this),query.groupByClause&&query.groupByClause.accept(this),query.havingClause&&query.havingClause.accept(this),query.orderByClause&&query.orderByClause.accept(this),query.windowClause)for(let win of query.windowClause.windows)win.accept(this);query.limitClause&&query.limitClause.accept(this),query.offsetClause&&query.offsetClause.accept(this),query.fetchClause&&query.fetchClause.accept(this),query.forClause&&query.forClause.accept(this),query.selectClause.accept(this)}}visitBinarySelectQuery(query){query.left.accept(this),query.right.accept(this)}visitValuesQuery(query){if(!this.selectableOnly)for(let tuple of query.tuples)tuple.accept(this)}visitInsertQuery(query){query.insertClause.source.accept(this),query.selectQuery&&query.selectQuery.accept(this),!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitUpdateQuery(query){!this.selectableOnly&&query.withClause&&query.withClause.accept(this),query.updateClause.source.accept(this),this.selectableOnly||query.setClause.items.forEach(item=>item.value.accept(this)),query.fromClause&&query.fromClause.accept(this),!this.selectableOnly&&query.whereClause&&query.whereClause.accept(this),!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitDeleteQuery(query){!this.selectableOnly&&query.withClause&&query.withClause.accept(this),query.deleteClause.source.accept(this),query.usingClause&&query.usingClause.sources.forEach(source=>source.accept(this)),!this.selectableOnly&&query.whereClause&&query.whereClause.accept(this),!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitMergeQuery(query){if(query.withClause&&this.registerCteNames(query.withClause),!this.selectableOnly&&query.withClause&&query.withClause.accept(this),query.target.accept(this),query.source.accept(this),!this.selectableOnly){query.onCondition.accept(this);for(let clause of query.whenClauses)if(clause.condition&&clause.condition.accept(this),clause.action instanceof MergeUpdateAction)clause.action.setClause.items.forEach(item=>item.value.accept(this)),clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeDeleteAction)clause.action.whereClause&&clause.action.whereClause.accept(this);else if(clause.action instanceof MergeInsertAction&&clause.action.values)clause.action.values.accept(this);else if(!(clause.action instanceof MergeInsertAction)){let actionName=clause.action?.constructor?.name??"UnknownMergeAction";throw new Error(`[TableSourceCollector] Unsupported MERGE action type: ${actionName}.`)}}!this.selectableOnly&&query.returningClause&&this.visitReturningClause(query.returningClause)}visitReturningClause(clause){for(let item of clause.items)item.value.accept(this)}visitWithClause(withClause){if(!this.selectableOnly)for(let table of withClause.tables)table.accept(this)}visitCommonTable(commonTable){this.selectableOnly||commonTable.query.accept(this)}visitFromClause(fromClause){if(fromClause.source.accept(this),fromClause.joins)for(let join of fromClause.joins)join.accept(this)}visitSourceExpression(source){source.datasource.accept(this)}visitTableSource(source){let identifier=this.getTableIdentifier(source);if(!this.isCTETable(source.table.name)){if(this.dedupe){if(this.tableNameMap.has(identifier))return;this.tableNameMap.set(identifier,!0)}this.tableSources.push(source)}}visitFunctionSource(source){source.argument&&this.visitValueComponent(source.argument)}visitValueComponent(value){value.accept(this)}isCTETable(tableName){return this.cteNames.has(tableName)}registerCteNames(withClause){for(let table of withClause.tables)this.cteNames.add(table.aliasExpression.table.name)}visitParenSource(source){source.source.accept(this)}visitSubQuerySource(subQuery){this.selectableOnly||subQuery.query.accept(this)}visitInlineQuery(inlineQuery){this.selectableOnly||inlineQuery.selectQuery.accept(this)}visitJoinClause(joinClause){joinClause.source.accept(this),!this.selectableOnly&&joinClause.condition&&joinClause.condition.accept(this)}visitJoinOnClause(joinOn){this.selectableOnly||joinOn.condition.accept(this)}visitJoinUsingClause(joinUsing){this.selectableOnly||joinUsing.condition.accept(this)}visitWhereClause(whereClause){whereClause.condition.accept(this)}visitGroupByClause(clause){for(let item of clause.grouping)item.accept(this)}visitHavingClause(clause){clause.condition.accept(this)}visitOrderByClause(clause){for(let item of clause.order)item.accept(this)}visitWindowFrameClause(clause){clause.expression.accept(this)}visitLimitClause(clause){clause.value.accept(this)}visitOffsetClause(clause){clause.value.accept(this)}visitFetchClause(clause){clause.expression.accept(this)}visitForClause(_clause){}visitOrderByItem(item){item.value.accept(this)}visitSelectClause(clause){for(let item of clause.items)item.accept(this)}visitSelectItem(item){item.value.accept(this)}visitParenExpression(expr){expr.expression.accept(this)}visitBinaryExpression(expr){expr.left.accept(this),expr.right.accept(this)}visitUnaryExpression(expr){expr.expression.accept(this)}visitCaseExpression(expr){expr.condition&&expr.condition.accept(this),expr.switchCase.accept(this)}visitSwitchCaseArgument(switchCase){for(let caseItem of switchCase.cases)caseItem.accept(this);switchCase.elseValue&&switchCase.elseValue.accept(this)}visitCaseKeyValuePair(pair){pair.key.accept(this),pair.value.accept(this)}visitBetweenExpression(expr){expr.expression.accept(this),expr.lower.accept(this),expr.upper.accept(this)}visitFunctionCall(func){func.argument&&func.argument.accept(this),func.filterCondition&&func.filterCondition.accept(this),func.over&&func.over.accept(this)}visitArrayExpression(expr){expr.expression.accept(this)}visitArrayQueryExpression(expr){expr.query.accept(this)}visitTupleExpression(expr){for(let value of expr.values)value.accept(this)}visitCastExpression(expr){expr.input.accept(this),expr.castType.accept(this)}visitValueList(valueList){for(let value of valueList.values)value.accept(this)}visitStringSpecifierExpression(_expr){}};var HintClause=class extends SqlComponent{static{this.kind=Symbol("HintClause")}constructor(hintContent){super(),this.hintContent=hintContent}getFullHint(){return"/*+ "+this.hintContent+" */"}static isHintClause(value){let trimmed=value.trim();return trimmed.length>=5&&trimmed.substring(0,3)==="/*+"&&trimmed.substring(trimmed.length-2)==="*/"}static extractHintContent(hintClause){let trimmed=hintClause.trim();if(!this.isHintClause(trimmed))throw new Error("Not a valid hint clause: "+hintClause);return trimmed.slice(3,-2).trim()}};var SqlPrintToken=class{constructor(type,text="",containerType=""){this.innerTokens=[];this.type=type,this.text=text,this.containerType=containerType}markAsHeaderComment(){if(this.containerType!=="CommentBlock")throw new Error("Header comment flag must only be applied to CommentBlock containers.");this.isHeaderComment=!0}};var SelectQueryWithClauseHelper=class{static getWithClause(selectQuery){let owner=this.findClauseOwner(selectQuery);return owner?owner.withClause:null}static setWithClause(selectQuery,withClause){let owner=this.findClauseOwner(selectQuery);if(!owner)throw new Error("Cannot attach WITH clause to the provided select query.");owner.withClause=withClause}static detachWithClause(selectQuery){let owner=this.findClauseOwner(selectQuery);if(!owner)return null;let clause=owner.withClause;return owner.withClause=null,clause}static findClauseOwner(selectQuery){if(!selectQuery)return null;if(selectQuery instanceof SimpleSelectQuery||selectQuery instanceof ValuesQuery)return selectQuery;if(selectQuery instanceof BinarySelectQuery)return this.findClauseOwner(selectQuery.left);throw new Error("Unsupported select query type for WITH clause management.")}};var ParameterCollector=class{static collect(node){let result=[];function walk(n){if(!(!n||typeof n!="object")){n.constructor&&n.constructor.kind===ParameterExpression.kind&&result.push(n);for(let key of Object.keys(n)){let v=n[key];Array.isArray(v)?v.forEach(walk):v&&typeof v=="object"&&v.constructor&&v.constructor.kind&&walk(v)}}}return walk(node),result}};var IdentifierDecorator=class{constructor(identifierEscape){this.start=identifierEscape?.start??'"',this.end=identifierEscape?.end??'"',this.target=identifierEscape?.target??"all"}decorate(text){return this.target==="minimal"&&this.canRenderBare(text)?text:this.start+this.escapeIdentifierText(text)+this.end}canRenderBare(text){return/^[a-z_][a-z0-9_]*$/.test(text)&&!UNSAFE_BARE_IDENTIFIERS.has(text)&&this.isPlainIdentifierToken(text)}isPlainIdentifierToken(text){let lexemes=new SqlTokenizer(text).readLexmes();return lexemes.length===1&&lexemes[0].type===64&&lexemes[0].value===text}escapeIdentifierText(text){return this.end?text.split(this.end).join(this.end+this.end):text}},UNSAFE_BARE_IDENTIFIERS=new Set(["all","and","any","as","between","by","case","cross","delete","distinct","else","end","except","exists","false","fetch","for","from","full","group","having","in","inner","insert","intersect","into","is","join","left","like","limit","not","null","offset","on","or","order","outer","right","select","set","table","then","true","union","update","using","values","when","where","with",...SQL_SPECIAL_VALUE_KEYWORDS]);var ParameterDecorator=class{constructor(options){this.prefix=options?.prefix??":",this.suffix=options?.suffix??"",this.style=options?.style??"named"}decorate(text,index){let paramText="";return this.style==="anonymous"?paramText=this.prefix:this.style==="indexed"?paramText=this.prefix+index:this.style==="named"&&(paramText=this.prefix+text+this.suffix),text=paramText,text}};var SelectValueCollector=class _SelectValueCollector{constructor(tableColumnResolver=null,initialCommonTables=null){this.selectValues=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.tableColumnResolver=tableColumnResolver??null,this.commonTableCollector=new CTECollector,this.commonTables=[],this.initialCommonTables=initialCommonTables,this.handlers=new Map,this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleSelectQuery(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr))}getValues(){return this.selectValues}reset(){this.selectValues=[],this.visitedNodes.clear(),this.initialCommonTables?this.commonTables=this.initialCommonTables:this.commonTables=[]}collect(arg){this.visit(arg);let items=this.getValues();return this.reset(),items}visit(arg){if(!this.isRootVisit){this.visitNode(arg);return}this.reset(),this.isRootVisit=!1;try{this.visitNode(arg)}finally{this.isRootVisit=!0}}visitNode(arg){if(this.visitedNodes.has(arg))return;this.visitedNodes.add(arg);let handler=this.handlers.get(arg.getKind());if(handler){handler(arg);return}}visitSimpleSelectQuery(query){this.commonTables.length===0&&this.initialCommonTables===null&&(this.commonTables=this.commonTableCollector.collect(query)),query.selectClause&&query.selectClause.accept(this);let wildcards=this.selectValues.filter(item=>item.name==="*");if(wildcards.length===0)return;if(this.selectValues.some(item=>item.value instanceof ColumnReference&&item.value.namespaces===null)){query.fromClause&&this.processFromClause(query.fromClause,!0),this.selectValues=this.selectValues.filter(item=>item.name!=="*");return}let wildSourceNames=wildcards.filter(item=>item.value instanceof ColumnReference&&item.value.namespaces).map(item=>item.value.getNamespace());if(query.fromClause){let fromSourceName=query.fromClause.getSourceAliasName();if(fromSourceName&&wildSourceNames.includes(fromSourceName)&&this.processFromClause(query.fromClause,!1),query.fromClause.joins)for(let join of query.fromClause.joins){let joinSourceName=join.getSourceAliasName();joinSourceName&&wildSourceNames.includes(joinSourceName)&&this.processJoinClause(join)}}this.selectValues=this.selectValues.filter(item=>item.name!=="*")}processFromClause(clause,joinCascade){if(clause){let fromSourceName=clause.getSourceAliasName();if(this.processSourceExpression(fromSourceName,clause.source),clause.joins&&joinCascade)for(let join of clause.joins)this.processJoinClause(join)}}processJoinClause(clause){let sourceName=clause.getSourceAliasName();this.processSourceExpression(sourceName,clause.source)}processSourceExpression(sourceName,source){let commonTable=this.commonTables.find(item=>item.aliasExpression.table.name===sourceName);if(commonTable){let innerCommonTables=this.commonTables.filter(item=>item.aliasExpression.table.name!==sourceName);this.collectValuesFromCteQuery(commonTable.query,innerCommonTables).forEach(item=>{this.addSelectValueAsUnique(item.name,new ColumnReference(sourceName?[sourceName]:null,item.name))})}else new _SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(source).forEach(item=>{this.addSelectValueAsUnique(item.name,new ColumnReference(sourceName?[sourceName]:null,item.name))})}visitSelectClause(clause){for(let item of clause.items)this.processSelectItem(item)}processSelectItem(item){if(item.identifier)this.addSelectValueAsUnique(item.identifier.name,item.value);else if(item.value instanceof ColumnReference){let columnName=item.value.column.name;columnName==="*"?this.selectValues.push({name:columnName,value:item.value}):this.addSelectValueAsUnique(columnName,item.value)}}visitSourceExpression(source){if(source.aliasExpression&&source.aliasExpression.columns){let sourceName=source.getAliasName();source.aliasExpression.columns.forEach(column=>{this.addSelectValueAsUnique(column.name,new ColumnReference(sourceName?[sourceName]:null,column.name))});return}else if(source.datasource instanceof TableSource){if(this.tableColumnResolver){let sourceName=source.datasource.getSourceName();this.tableColumnResolver(sourceName).forEach(column=>{this.addSelectValueAsUnique(column,new ColumnReference([sourceName],column))})}return}else if(source.datasource instanceof SubQuerySource){let sourceName=source.getAliasName();new _SelectValueCollector(this.tableColumnResolver,this.commonTables).collect(source.datasource.query).forEach(item=>{this.addSelectValueAsUnique(item.name,new ColumnReference(sourceName?[sourceName]:null,item.name))});return}else if(source.datasource instanceof ParenSource)return this.visit(source.datasource.source)}visitFromClause(clause){clause&&this.processFromClause(clause,!0)}addSelectValueAsUnique(name,value){this.selectValues.some(item=>item.name===name)||this.selectValues.push({name,value})}collectValuesFromCteQuery(query,commonTables){return this.isSelectQuery(query)?new _SelectValueCollector(this.tableColumnResolver,commonTables).collect(query):this.collectValuesFromReturning(query)}collectValuesFromReturning(query){return query instanceof InsertQuery||query instanceof UpdateQuery||query instanceof DeleteQuery||query instanceof MergeQuery?query.returningClause?this.extractValuesFromReturningClause(query.returningClause):[]:[]}extractValuesFromReturningClause(clause){let values=[];for(let item of clause.items){let name=item.identifier?.name??this.extractSelectItemName(item);name&&values.push({name,value:item.value})}return values}extractSelectItemName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}isSelectQuery(query){return"__selectQueryType"in query&&query.__selectQueryType==="SelectQuery"}};var ReferenceDefinition=class extends SqlComponent{static{this.kind=Symbol("ReferenceDefinition")}constructor(params){super(),this.targetTable=params.targetTable,this.columns=params.columns?[...params.columns]:null,this.matchType=params.matchType??null,this.onDelete=params.onDelete??null,this.onUpdate=params.onUpdate??null,this.deferrable=params.deferrable??null,this.initially=params.initially??null}},ColumnConstraintDefinition=class extends SqlComponent{static{this.kind=Symbol("ColumnConstraintDefinition")}constructor(params){super(),this.kind=params.kind,this.constraintName=params.constraintName,this.defaultValue=params.defaultValue,this.checkExpression=params.checkExpression,this.reference=params.reference,this.rawClause=params.rawClause}},TableConstraintDefinition=class extends SqlComponent{static{this.kind=Symbol("TableConstraintDefinition")}constructor(params){super(),this.kind=params.kind,this.constraintName=params.constraintName,this.columns=params.columns?[...params.columns]:null,this.reference=params.reference,this.checkExpression=params.checkExpression,this.rawClause=params.rawClause,this.deferrable=params.deferrable??null,this.initially=params.initially??null}},TableColumnDefinition=class extends SqlComponent{static{this.kind=Symbol("TableColumnDefinition")}constructor(params){super(),this.name=params.name,this.dataType=params.dataType,this.constraints=params.constraints?[...params.constraints]:[]}},CreateTableQuery=class extends SqlComponent{static{this.kind=Symbol("CreateTableQuery")}constructor(params){super(),this.tableName=new IdentifierString(params.tableName),this.namespaces=params.namespaces?[...params.namespaces]:null,this.isTemporary=params.isTemporary??!1,this.isUnlogged=params.isUnlogged??!1,this.ifNotExists=params.ifNotExists??!1,this.columns=params.columns?[...params.columns]:[],this.tableConstraints=params.tableConstraints?[...params.tableConstraints]:[],this.tableOptions=params.tableOptions??null,this.asSelectQuery=params.asSelectQuery,this.withDataOption=params.withDataOption??null}getSelectQuery(){let selectItems;this.asSelectQuery?selectItems=new SelectValueCollector().collect(this.asSelectQuery).map(val=>new SelectItem(val.value,val.name)):this.columns.length>0?selectItems=this.columns.map(column=>new SelectItem(new ColumnReference(null,column.name),column.name.name)):selectItems=[new SelectItem(new RawString("*"))];let qualifiedName=this.namespaces&&this.namespaces.length>0?[...this.namespaces,this.tableName.name].join("."):this.tableName.name;return new SimpleSelectQuery({selectClause:new SelectClause(selectItems),fromClause:new FromClause(new SourceExpression(new TableSource(null,qualifiedName),null),null)})}getCountQuery(){let qualifiedName=this.namespaces&&this.namespaces.length>0?[...this.namespaces,this.tableName.name].join("."):this.tableName.name;return new SimpleSelectQuery({selectClause:new SelectClause([new SelectItem(new FunctionCall(null,"count",new ColumnReference(null,"*"),null))]),fromClause:new FromClause(new SourceExpression(new TableSource(null,qualifiedName),null),null)})}};function cloneIdentifierWithComments(identifier){let clone=new IdentifierString(identifier.name);return identifier.positionedComments?clone.positionedComments=identifier.positionedComments.map(entry=>({position:entry.position,comments:[...entry.comments]})):identifier.comments&&identifier.comments.length>0&&(clone.comments=[...identifier.comments]),clone}var DropTableStatement=class extends SqlComponent{static{this.kind=Symbol("DropTableStatement")}constructor(params){super(),this.tables=params.tables.map(table=>new QualifiedName(table.namespaces,table.name)),this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},DropIndexStatement=class extends SqlComponent{static{this.kind=Symbol("DropIndexStatement")}constructor(params){super(),this.indexNames=params.indexNames.map(index=>new QualifiedName(index.namespaces,index.name)),this.ifExists=params.ifExists??!1,this.concurrently=params.concurrently??!1,this.behavior=params.behavior??null}},CreateSchemaStatement=class extends SqlComponent{static{this.kind=Symbol("CreateSchemaStatement")}constructor(params){super(),this.schemaName=new QualifiedName(params.schemaName.namespaces,params.schemaName.name),this.ifNotExists=params.ifNotExists??!1,this.authorization=params.authorization?cloneIdentifierWithComments(params.authorization):null}},DropSchemaStatement=class extends SqlComponent{static{this.kind=Symbol("DropSchemaStatement")}constructor(params){super(),this.schemaNames=params.schemaNames.map(schema=>new QualifiedName(schema.namespaces,schema.name)),this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},CommentOnStatement=class extends SqlComponent{static{this.kind=Symbol("CommentOnStatement")}constructor(params){super(),this.targetKind=params.targetKind,this.target=new QualifiedName(params.target.namespaces,params.target.name),this.comment=params.comment}},IndexColumnDefinition=class extends SqlComponent{static{this.kind=Symbol("IndexColumnDefinition")}constructor(params){super(),this.expression=params.expression,this.sortOrder=params.sortOrder??null,this.nullsOrder=params.nullsOrder??null,this.collation=params.collation??null,this.operatorClass=params.operatorClass??null}},CreateIndexStatement=class extends SqlComponent{static{this.kind=Symbol("CreateIndexStatement")}constructor(params){super(),this.unique=params.unique??!1,this.concurrently=params.concurrently??!1,this.ifNotExists=params.ifNotExists??!1,this.indexName=new QualifiedName(params.indexName.namespaces,params.indexName.name),this.tableName=new QualifiedName(params.tableName.namespaces,params.tableName.name),this.usingMethod=params.usingMethod??null,this.columns=params.columns.map(col=>new IndexColumnDefinition({expression:col.expression,sortOrder:col.sortOrder,nullsOrder:col.nullsOrder,collation:col.collation??null,operatorClass:col.operatorClass??null})),this.include=params.include?[...params.include]:null,this.where=params.where,this.withOptions=params.withOptions??null,this.tablespace=params.tablespace??null}},AlterTableAddConstraint=class extends SqlComponent{static{this.kind=Symbol("AlterTableAddConstraint")}constructor(params){super(),this.constraint=params.constraint,this.ifNotExists=params.ifNotExists??!1,this.notValid=params.notValid??!1}},AlterTableDropConstraint=class extends SqlComponent{static{this.kind=Symbol("AlterTableDropConstraint")}constructor(params){super(),this.constraintName=params.constraintName,this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},AlterTableDropColumn=class extends SqlComponent{static{this.kind=Symbol("AlterTableDropColumn")}constructor(params){super(),this.columnName=params.columnName,this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},AlterTableAddColumn=class extends SqlComponent{static{this.kind=Symbol("AlterTableAddColumn")}constructor(params){super(),this.column=params.column,this.ifNotExists=params.ifNotExists??!1}},AlterTableAlterColumnDefault=class extends SqlComponent{static{this.kind=Symbol("AlterTableAlterColumnDefault")}constructor(params){if(super(),this.columnName=params.columnName,this.setDefault=params.setDefault??null,this.dropDefault=params.dropDefault??!1,this.setDefault!==null&&this.dropDefault)throw new Error("[AlterTableAlterColumnDefault] Cannot set and drop a default at the same time.")}},AlterTableStatement=class extends SqlComponent{static{this.kind=Symbol("AlterTableStatement")}constructor(params){super(),this.table=new QualifiedName(params.table.namespaces,params.table.name),this.only=params.only??!1,this.ifExists=params.ifExists??!1,this.actions=params.actions.map(action=>action)}},DropConstraintStatement=class extends SqlComponent{static{this.kind=Symbol("DropConstraintStatement")}constructor(params){super(),this.constraintName=params.constraintName,this.ifExists=params.ifExists??!1,this.behavior=params.behavior??null}},ExplainOption=class extends SqlComponent{static{this.kind=Symbol("ExplainOption")}constructor(params){super(),this.name=cloneIdentifierWithComments(params.name),this.value=params.value??null}},ExplainStatement=class extends SqlComponent{static{this.kind=Symbol("ExplainStatement")}constructor(params){super(),this.options=params.options?params.options.map(option=>new ExplainOption(option)):null,this.statement=params.statement}},AnalyzeStatement=class extends SqlComponent{static{this.kind=Symbol("AnalyzeStatement")}constructor(params){super(),this.verbose=params?.verbose??!1,this.target=params?.target?new QualifiedName(params.target.namespaces,params.target.name):null,params?.columns?this.columns=params.columns.map(cloneIdentifierWithComments):this.columns=null}},CreateSequenceStatement=class extends SqlComponent{static{this.kind=Symbol("CreateSequenceStatement")}constructor(params){super(),this.sequenceName=new QualifiedName(params.sequenceName.namespaces,params.sequenceName.name),this.ifNotExists=params.ifNotExists??!1,this.clauses=params.clauses?[...params.clauses]:[]}},AlterSequenceStatement=class extends SqlComponent{static{this.kind=Symbol("AlterSequenceStatement")}constructor(params){super(),this.sequenceName=new QualifiedName(params.sequenceName.namespaces,params.sequenceName.name),this.ifExists=params.ifExists??!1,this.clauses=params.clauses?[...params.clauses]:[]}},VacuumStatement=class extends SqlComponent{static{this.kind=Symbol("VacuumStatement")}constructor(params){super(),this.full=params?.full??!1,this.verbose=params?.verbose??!1,this.freeze=params?.freeze??!1,this.analyze=params?.analyze??!1,this.targets=params?.targets?[...params.targets]:[]}},ReindexStatement=class extends SqlComponent{static{this.kind=Symbol("ReindexStatement")}constructor(params){super(),this.concurrently=params?.concurrently??!1,this.targets=params?.targets?[...params.targets]:[],this.targetType=params?.targetType??null}},ClusterStatement=class extends SqlComponent{static{this.kind=Symbol("ClusterStatement")}constructor(params){super(),this.verbose=params?.verbose??!1,this.table=params?.table??null,this.index=params?.index??null}},CheckpointStatement=class extends SqlComponent{static{this.kind=Symbol("CheckpointStatement")}constructor(params){super(),this.options=params?.options?[...params.options]:[]}};var PRESETS={mysql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous",constraintStyle:"mysql"},postgres:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed",castStyle:"postgres",constraintStyle:"postgres"},postgresWithNamedParams:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named",castStyle:"postgres",constraintStyle:"postgres"},sqlserver:{identifierEscape:{start:"[",end:"]"},parameterSymbol:"@",parameterStyle:"named",constraintStyle:"postgres"},sqlite:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named",constraintStyle:"postgres"},oracle:{identifierEscape:{start:'"',end:'"'},parameterSymbol:":",parameterStyle:"named",constraintStyle:"postgres"},clickhouse:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous",constraintStyle:"postgres"},firebird:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},db2:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},snowflake:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},cloudspanner:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"@",parameterStyle:"named"},duckdb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},cockroachdb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed",castStyle:"postgres"},athena:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"},bigquery:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"@",parameterStyle:"named"},hive:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},mariadb:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},redshift:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"$",parameterStyle:"indexed",castStyle:"postgres"},flinksql:{identifierEscape:{start:"`",end:"`"},parameterSymbol:"?",parameterStyle:"anonymous"},mongodb:{identifierEscape:{start:'"',end:'"'},parameterSymbol:"?",parameterStyle:"anonymous"}},SqlPrintTokenParser=class _SqlPrintTokenParser{constructor(options){this.handlers=new Map;this.index=1;this.joinConditionContexts=[];options?.preset&&(options={...options.preset,...options}),this.parameterDecorator=new ParameterDecorator({prefix:typeof options?.parameterSymbol=="string"?options.parameterSymbol:options?.parameterSymbol?.start??":",suffix:typeof options?.parameterSymbol=="object"?options.parameterSymbol.end:"",style:options?.parameterStyle??"named"}),this.identifierDecorator=new IdentifierDecorator({start:options?.identifierEscape?.start??'"',end:options?.identifierEscape?.end??'"',target:options?.identifierEscape?.target}),this.castStyle=options?.castStyle??"standard",this.constraintStyle=options?.constraintStyle??"postgres",this.normalizeJoinConditionOrder=options?.joinConditionOrderByDeclaration??!1,this.handlers.set(ValueList.kind,expr=>this.visitValueList(expr)),this.handlers.set(ColumnReference.kind,expr=>this.visitColumnReference(expr)),this.handlers.set(QualifiedName.kind,expr=>this.visitQualifiedName(expr)),this.handlers.set(FunctionCall.kind,expr=>this.visitFunctionCall(expr)),this.handlers.set(UnaryExpression.kind,expr=>this.visitUnaryExpression(expr)),this.handlers.set(BinaryExpression.kind,expr=>this.visitBinaryExpression(expr)),this.handlers.set(LiteralValue.kind,expr=>this.visitLiteralValue(expr)),this.handlers.set(ParameterExpression.kind,expr=>this.visitParameterExpression(expr)),this.handlers.set(SwitchCaseArgument.kind,expr=>this.visitSwitchCaseArgument(expr)),this.handlers.set(CaseKeyValuePair.kind,expr=>this.visitCaseKeyValuePair(expr)),this.handlers.set(RawString.kind,expr=>this.visitRawString(expr)),this.handlers.set(IdentifierString.kind,expr=>this.visitIdentifierString(expr)),this.handlers.set(ParenExpression.kind,expr=>this.visitParenExpression(expr)),this.handlers.set(CastExpression.kind,expr=>this.visitCastExpression(expr)),this.handlers.set(CaseExpression.kind,expr=>this.visitCaseExpression(expr)),this.handlers.set(ArrayExpression.kind,expr=>this.visitArrayExpression(expr)),this.handlers.set(ArrayQueryExpression.kind,expr=>this.visitArrayQueryExpression(expr)),this.handlers.set(ArraySliceExpression.kind,expr=>this.visitArraySliceExpression(expr)),this.handlers.set(ArrayIndexExpression.kind,expr=>this.visitArrayIndexExpression(expr)),this.handlers.set(BetweenExpression.kind,expr=>this.visitBetweenExpression(expr)),this.handlers.set(StringSpecifierExpression.kind,expr=>this.visitStringSpecifierExpression(expr)),this.handlers.set(TypeValue.kind,expr=>this.visitTypeValue(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(InlineQuery.kind,expr=>this.visitInlineQuery(expr)),this.handlers.set(WindowFrameExpression.kind,expr=>this.visitWindowFrameExpression(expr)),this.handlers.set(WindowFrameSpec.kind,expr=>this.visitWindowFrameSpec(expr)),this.handlers.set(WindowFrameBoundStatic.kind,expr=>this.visitWindowFrameBoundStatic(expr)),this.handlers.set(WindowFrameBoundaryValue.kind,expr=>this.visitWindowFrameBoundaryValue(expr)),this.handlers.set(PartitionByClause.kind,expr=>this.visitPartitionByClause(expr)),this.handlers.set(OrderByClause.kind,expr=>this.visitOrderByClause(expr)),this.handlers.set(OrderByItem.kind,expr=>this.visitOrderByItem(expr)),this.handlers.set(SelectItem.kind,expr=>this.visitSelectItem(expr)),this.handlers.set(SelectClause.kind,expr=>this.visitSelectClause(expr)),this.handlers.set(Distinct.kind,expr=>this.visitDistinct(expr)),this.handlers.set(DistinctOn.kind,expr=>this.visitDistinctOn(expr)),this.handlers.set(HintClause.kind,expr=>this.visitHintClause(expr)),this.handlers.set(TableSource.kind,expr=>this.visitTableSource(expr)),this.handlers.set(FunctionSource.kind,expr=>this.visitFunctionSource(expr)),this.handlers.set(SourceExpression.kind,expr=>this.visitSourceExpression(expr)),this.handlers.set(SourceAliasExpression.kind,expr=>this.visitSourceAliasExpression(expr)),this.handlers.set(FromClause.kind,expr=>this.visitFromClause(expr)),this.handlers.set(JoinClause.kind,expr=>this.visitJoinClause(expr)),this.handlers.set(JoinOnClause.kind,expr=>this.visitJoinOnClause(expr)),this.handlers.set(JoinUsingClause.kind,expr=>this.visitJoinUsingClause(expr)),this.handlers.set(WhereClause.kind,expr=>this.visitWhereClause(expr)),this.handlers.set(GroupByClause.kind,expr=>this.visitGroupByClause(expr)),this.handlers.set(HavingClause.kind,expr=>this.visitHavingClause(expr)),this.handlers.set(WindowsClause.kind,expr=>this.visitWindowClause(expr)),this.handlers.set(WindowFrameClause.kind,expr=>this.visitWindowFrameClause(expr)),this.handlers.set(LimitClause.kind,expr=>this.visitLimitClause(expr)),this.handlers.set(OffsetClause.kind,expr=>this.visitOffsetClause(expr)),this.handlers.set(FetchClause.kind,expr=>this.visitFetchClause(expr)),this.handlers.set(FetchExpression.kind,expr=>this.visitFetchExpression(expr)),this.handlers.set(ForClause.kind,expr=>this.visitForClause(expr)),this.handlers.set(WithClause.kind,expr=>this.visitWithClause(expr)),this.handlers.set(CommonTable.kind,expr=>this.visitCommonTable(expr)),this.handlers.set(SimpleSelectQuery.kind,expr=>this.visitSimpleQuery(expr)),this.handlers.set(SubQuerySource.kind,expr=>this.visitSubQuerySource(expr)),this.handlers.set(BinarySelectQuery.kind,expr=>this.visitBinarySelectQuery(expr)),this.handlers.set(ValuesQuery.kind,expr=>this.visitValuesQuery(expr)),this.handlers.set(TupleExpression.kind,expr=>this.visitTupleExpression(expr)),this.handlers.set(InsertQuery.kind,expr=>this.visitInsertQuery(expr)),this.handlers.set(InsertClause.kind,expr=>this.visitInsertClause(expr)),this.handlers.set(UpdateQuery.kind,expr=>this.visitUpdateQuery(expr)),this.handlers.set(UpdateClause.kind,expr=>this.visitUpdateClause(expr)),this.handlers.set(DeleteQuery.kind,expr=>this.visitDeleteQuery(expr)),this.handlers.set(DeleteClause.kind,expr=>this.visitDeleteClause(expr)),this.handlers.set(UsingClause.kind,expr=>this.visitUsingClause(expr)),this.handlers.set(SetClause.kind,expr=>this.visitSetClause(expr)),this.handlers.set(SetClauseItem.kind,expr=>this.visitSetClauseItem(expr)),this.handlers.set(ReturningClause.kind,expr=>this.visitReturningClause(expr)),this.handlers.set(CreateTableQuery.kind,expr=>this.visitCreateTableQuery(expr)),this.handlers.set(TableColumnDefinition.kind,expr=>this.visitTableColumnDefinition(expr)),this.handlers.set(ColumnConstraintDefinition.kind,expr=>this.visitColumnConstraintDefinition(expr)),this.handlers.set(TableConstraintDefinition.kind,expr=>this.visitTableConstraintDefinition(expr)),this.handlers.set(ReferenceDefinition.kind,expr=>this.visitReferenceDefinition(expr)),this.handlers.set(CreateIndexStatement.kind,expr=>this.visitCreateIndexStatement(expr)),this.handlers.set(CreateSchemaStatement.kind,expr=>this.visitCreateSchemaStatement(expr)),this.handlers.set(IndexColumnDefinition.kind,expr=>this.visitIndexColumnDefinition(expr)),this.handlers.set(CreateSequenceStatement.kind,expr=>this.visitCreateSequenceStatement(expr)),this.handlers.set(AlterSequenceStatement.kind,expr=>this.visitAlterSequenceStatement(expr)),this.handlers.set(DropTableStatement.kind,expr=>this.visitDropTableStatement(expr)),this.handlers.set(DropIndexStatement.kind,expr=>this.visitDropIndexStatement(expr)),this.handlers.set(DropSchemaStatement.kind,expr=>this.visitDropSchemaStatement(expr)),this.handlers.set(CommentOnStatement.kind,expr=>this.visitCommentOnStatement(expr)),this.handlers.set(AlterTableStatement.kind,expr=>this.visitAlterTableStatement(expr)),this.handlers.set(AlterTableAddConstraint.kind,expr=>this.visitAlterTableAddConstraint(expr)),this.handlers.set(AlterTableDropConstraint.kind,expr=>this.visitAlterTableDropConstraint(expr)),this.handlers.set(AlterTableAddColumn.kind,expr=>this.visitAlterTableAddColumn(expr)),this.handlers.set(AlterTableDropColumn.kind,expr=>this.visitAlterTableDropColumn(expr)),this.handlers.set(AlterTableAlterColumnDefault.kind,expr=>this.visitAlterTableAlterColumnDefault(expr)),this.handlers.set(DropConstraintStatement.kind,expr=>this.visitDropConstraintStatement(expr)),this.handlers.set(ExplainStatement.kind,expr=>this.visitExplainStatement(expr)),this.handlers.set(AnalyzeStatement.kind,expr=>this.visitAnalyzeStatement(expr)),this.handlers.set(MergeQuery.kind,expr=>this.visitMergeQuery(expr)),this.handlers.set(MergeWhenClause.kind,expr=>this.visitMergeWhenClause(expr)),this.handlers.set(MergeUpdateAction.kind,expr=>this.visitMergeUpdateAction(expr)),this.handlers.set(MergeDeleteAction.kind,expr=>this.visitMergeDeleteAction(expr)),this.handlers.set(MergeInsertAction.kind,expr=>this.visitMergeInsertAction(expr)),this.handlers.set(MergeDoNothingAction.kind,expr=>this.visitMergeDoNothingAction(expr))}static{this.SPACE_TOKEN=new SqlPrintToken(10," ")}static{this.COMMA_TOKEN=new SqlPrintToken(3,",")}static{this.ARGUMENT_SPLIT_COMMA_TOKEN=new SqlPrintToken(11,",")}static{this.PAREN_OPEN_TOKEN=new SqlPrintToken(4,"(")}static{this.PAREN_CLOSE_TOKEN=new SqlPrintToken(4,")")}static{this.DOT_TOKEN=new SqlPrintToken(8,".")}static{this._selfHandlingComponentTypes=null}static getSelfHandlingComponentTypes(){return this._selfHandlingComponentTypes||(this._selfHandlingComponentTypes=new Set([SimpleSelectQuery.kind,SelectItem.kind,CaseKeyValuePair.kind,SwitchCaseArgument.kind,ColumnReference.kind,LiteralValue.kind,ParameterExpression.kind,TableSource.kind,SourceAliasExpression.kind,TypeValue.kind,FunctionCall.kind,IdentifierString.kind,QualifiedName.kind])),this._selfHandlingComponentTypes}visitBinarySelectQuery(arg){let token=new SqlPrintToken(0,"");if(arg.positionedComments&&arg.positionedComments.length>0)this.addPositionedCommentsToToken(token,arg),arg.positionedComments=null;else if(arg.headerComments&&arg.headerComments.length>0){if(this.shouldMergeHeaderComments(arg.headerComments)){let mergedHeaderComment=this.createHeaderMultiLineCommentBlock(arg.headerComments);token.innerTokens.push(mergedHeaderComment)}else{let headerCommentBlocks=this.createCommentBlocks(arg.headerComments,!0);token.innerTokens.push(...headerCommentBlocks)}token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN)}return token.innerTokens.push(this.visit(arg.left)),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,arg.operator.value,"BinarySelectQueryOperator")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.right)),token}visitCreateSchemaStatement(arg){let keywordParts=["create","schema"];arg.ifNotExists&&keywordParts.push("if not exists");let token=new SqlPrintToken(1,keywordParts.join(" "),"CreateSchemaStatement");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.schemaName.accept(this)),arg.authorization&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"authorization")),token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(arg.authorization.accept(this))),token}static commaSpaceTokens(){return[_SqlPrintTokenParser.COMMA_TOKEN,_SqlPrintTokenParser.SPACE_TOKEN]}static argumentCommaSpaceTokens(){return[_SqlPrintTokenParser.ARGUMENT_SPLIT_COMMA_TOKEN,_SqlPrintTokenParser.SPACE_TOKEN]}visitQualifiedName(arg){let token=new SqlPrintToken(0,"","QualifiedName");if(arg.namespaces)for(let i=0;i<arg.namespaces.length;i++)token.innerTokens.push(arg.namespaces[i].accept(this)),token.innerTokens.push(_SqlPrintTokenParser.DOT_TOKEN);let originalNameComments=arg.name.positionedComments,originalNameLegacyComments=arg.name.comments;arg.name.positionedComments=null,arg.name.comments=null;let nameToken=arg.name.accept(this);return token.innerTokens.push(nameToken),arg.name.positionedComments=originalNameComments,arg.name.comments=originalNameLegacyComments,(this.hasPositionedComments(arg.name)||this.hasLegacyComments(arg.name))&&this.addComponentComments(token,arg.name),this.addComponentComments(token,arg),token}visitPartitionByClause(arg){let token=new SqlPrintToken(1,"partition by","PartitionByClause");return token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(this.visit(arg.value)),token}visitOrderByClause(arg){let token=new SqlPrintToken(1,"order by","OrderByClause");token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN);for(let i=0;i<arg.order.length;i++)i>0&&token.innerTokens.push(..._SqlPrintTokenParser.commaSpaceTokens()),token.innerTokens.push(this.visit(arg.order[i]));return token}visitOrderByItem(arg){let token=new SqlPrintToken(0,"","OrderByItem");return token.innerTokens.push(this.visit(arg.value)),arg.sortDirection&&arg.sortDirection!=="asc"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"desc"))),arg.nullsPosition&&(arg.nullsPosition==="first"?(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"nulls first"))):arg.nullsPosition==="last"&&(token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(new SqlPrintToken(1,"nulls last")))),token}parse(arg){this.index=1;let token=this.visit(arg),paramsRaw=ParameterCollector.collect(arg).sort((a,b)=>(a.index??0)-(b.index??0)),style=this.parameterDecorator.style;if(style==="named"){let paramsObj={};for(let p of paramsRaw){let key=p.name.value;if(paramsObj.hasOwnProperty(key)){if(paramsObj[key]!==p.value)throw new Error(`Duplicate parameter name '${key}' with different values detected during query composition.`);continue}paramsObj[key]=p.value}return{token,params:paramsObj}}else if(style==="indexed"){let paramsArr=paramsRaw.map(p=>p.value);return{token,params:paramsArr}}else if(style==="anonymous"){let paramsArr=paramsRaw.map(p=>p.value);return{token,params:paramsArr}}return{token,params:[]}}componentHandlesOwnComments(component){return"handlesOwnComments"in component&&typeof component.handlesOwnComments=="function"?component.handlesOwnComments():_SqlPrintTokenParser.getSelfHandlingComponentTypes().has(component.getKind())}visit(arg){let handler=this.handlers.get(arg.getKind());if(handler){let token=handler(arg);return this.componentHandlesOwnComments(arg)||this.addComponentComments(token,arg),token}throw new Error(`[SqlPrintTokenParser] No handler for kind: ${arg.getKind().toString()}`)}hasPositionedComments(component){return(component.positionedComments?.length??0)>0}hasLegacyComments(component){return(component.comments?.length??0)>0}addComponentComments(token,component){this.hasPositionedComments(component)?this.addPositionedCommentsToToken(token,component):this.hasLegacyComments(component)&&this.addCommentsToToken(token,component.comments)}addPositionedCommentsToToken(token,component){if(!this.hasPositionedComments(component))return;let beforeComments=component.getPositionedComments("before");if(beforeComments.length>0){let commentBlocks=this.createCommentBlocks(beforeComments);for(let i=commentBlocks.length-1;i>=0;i--)token.innerTokens.unshift(commentBlocks[i])}let afterComments=component.getPositionedComments("after");if(afterComments.length>0){let commentBlocks=this.createCommentBlocks(afterComments);for(let commentBlock of commentBlocks)token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(commentBlock)}let componentsWithDuplicationIssues=["CaseExpression","SwitchCaseArgument","CaseKeyValuePair","SelectClause","LiteralValue","IdentifierString","DistinctOn","SourceAliasExpression","SimpleSelectQuery","WhereClause"];token.containerType&&componentsWithDuplicationIssues.includes(token.containerType)&&(component.positionedComments=null)}addCommentsToToken(token,comments){if(!comments?.length)return;let commentBlocks=this.createCommentBlocks(comments);this.insertCommentBlocksWithSpacing(token,commentBlocks)}createInlineCommentSequence(comments){let commentTokens=[];for(let i=0;i<comments.length;i++){let comment=comments[i];if(comment.trim()){let commentToken=new SqlPrintToken(6,this.formatComment(comment));if(commentTokens.push(commentToken),i<comments.length-1){let spaceToken=new SqlPrintToken(10," ");commentTokens.push(spaceToken)}}}return commentTokens}createCommentBlocks(comments,isHeaderComment=!1){let commentBlocks=[];for(let comment of comments){let trimmed=comment.trim(),isSeparatorLine=/^[-=_+*#]+$/.test(trimmed);(trimmed||isSeparatorLine||comment==="")&&commentBlocks.push(this.createSingleCommentBlock(comment,isHeaderComment))}return commentBlocks}shouldMergeComment(trimmed){return!(!/^[-=_+*#]+$/.test(trimmed)&&trimmed.startsWith("--")||trimmed.startsWith("/*")&&trimmed.endsWith("*/")&&(!trimmed.slice(2,-2).trim()||trimmed.includes(`
14
14
  `)))}createSingleCommentBlock(comment,isHeaderComment=!1){let commentBlock=new SqlPrintToken(0,"","CommentBlock");isHeaderComment&&commentBlock.markAsHeaderComment();let commentToken=new SqlPrintToken(6,this.formatComment(comment));commentBlock.innerTokens.push(commentToken);let commentNewlineToken=new SqlPrintToken(12,"");commentBlock.innerTokens.push(commentNewlineToken);let spaceToken=new SqlPrintToken(10," ");return commentBlock.innerTokens.push(spaceToken),commentBlock}formatComment(comment){let trimmed=comment.trim();return trimmed?/^[-=_+*#]+$/.test(trimmed)?this.formatBlockComment(trimmed):trimmed.startsWith("--")?this.formatLineComment(trimmed.slice(2)):trimmed.startsWith("/*")&&trimmed.endsWith("*/")?this.formatBlockComment(trimmed):this.formatBlockComment(trimmed):"/* */"}insertCommentBlocksWithSpacing(token,commentBlocks){if(token.containerType==="SelectItem"){token.innerTokens.length>0&&token.innerTokens[token.innerTokens.length-1].type!==10&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(...commentBlocks);return}if(token.containerType==="SelectClause"){token.innerTokens.unshift(_SqlPrintTokenParser.SPACE_TOKEN,...commentBlocks);return}if(token.containerType==="IdentifierString"){token.innerTokens.length>0&&token.innerTokens[token.innerTokens.length-1].type!==10&&token.innerTokens.push(_SqlPrintTokenParser.SPACE_TOKEN),token.innerTokens.push(...commentBlocks);return}if(token.innerTokens.unshift(...commentBlocks),this.shouldAddSeparatorSpace(token.containerType)){let separatorSpace=new SqlPrintToken(10," ");token.innerTokens.splice(commentBlocks.length,0,separatorSpace),token.innerTokens.length>commentBlocks.length+1&&token.innerTokens[commentBlocks.length+1].type===10&&token.innerTokens.splice(commentBlocks.length+1,1)}else token.innerTokens.length>commentBlocks.length&&token.innerTokens[commentBlocks.length].type===10&&token.innerTokens.splice(commentBlocks.length,1)}addPositionedCommentsToParenExpression(token,component){if(!component.positionedComments)return;let beforeComments=component.getPositionedComments("before");if(beforeComments.length>0){let commentBlocks=this.createCommentBlocks(beforeComments),insertIndex=1;for(let commentBlock of commentBlocks)token.innerTokens.splice(insertIndex,0,commentBlock),insertIndex++}let afterComments=component.getPositionedComments("after");if(afterComments.length>0){let commentBlocks=this.createCommentBlocks(afterComments),insertIndex=token.innerTokens.length-1+1;for(let commentBlock of commentBlocks)token.innerTokens.splice(insertIndex,0,_SqlPrintTokenParser.SPACE_TOKEN,commentBlock),insertIndex+=2}}shouldAddSeparatorSpace(containerType){return this.isClauseLevelContainer(containerType)}isClauseLevelContainer(containerType){switch(containerType){case"SelectClause":case"FromClause":case"WhereClause":case"GroupByClause":case"HavingClause":case"OrderByClause":case"LimitClause":case"OffsetClause":case"WithClause":case"SimpleSelectQuery":return!0;default:return!1}}formatBlockComment(comment){let hasDelimiters=comment.startsWith("/*")&&comment.endsWith("*/"),rawContent=hasDelimiters?comment.slice(2,-2):comment,lines=this.escapeCommentDelimiters(rawContent).replace(/\r?\n/g,`
15
15
  `).split(`
16
16
  `).map(line=>line.replace(/\s+/g," ").trim()).filter(line=>line.length>0);if(lines.length===0)return"/* */";let isSeparatorLine=lines.length===1&&/^[-=_+*#]+$/.test(lines[0]);return hasDelimiters?isSeparatorLine||lines.length===1?`/* ${lines[0]} */`:`/*
@@ -46,7 +46,7 @@ ${query}`}addRestorationComments(sql,targetNode,warnings){let comments=[];return
46
46
  `),charIndex=0;for(let i=0;i<position.line-1&&i<lines.length;i++)charIndex+=lines[i].length+1;return charIndex+=position.column-1,Math.min(charIndex,sql.length-1)}isInsideStringLiteral(sql,charPosition){let inString=!1;for(let i=0;i<charPosition&&i<sql.length;i++)sql[i]==="'"&&(inString=!inString);return inString}getIdentifierAtPosition(sql,charPosition){if(charPosition>=sql.length)return null;let start=charPosition;for(;start>0&&this.isIdentifierChar(sql.charCodeAt(start-1));)start--;let end=charPosition;for(;end<sql.length&&this.isIdentifierChar(sql.charCodeAt(end));)end++;return start===end?null:sql.slice(start,end)}determineIdentifierType(sql,charPosition,identifier){let beforePosition=sql.slice(0,charPosition),afterPosition=sql.slice(charPosition),beforeUpper=beforePosition.toUpperCase(),afterUpper=afterPosition.toUpperCase();if(beforeUpper.lastIndexOf("WITH")!==-1){let start=charPosition;for(;start>0&&this.isIdentifierChar(sql.charCodeAt(start-1));)start--;let end=charPosition;for(;end<sql.length&&this.isIdentifierChar(sql.charCodeAt(end));)end++;if(sql.slice(end).toUpperCase().trim().startsWith("AS ("))return"cte"}let beforeLines=beforePosition.split(`
47
47
  `),currentLine=beforeLines[beforeLines.length-1].toUpperCase();if(currentLine.includes("FROM ")||currentLine.includes("JOIN "))return"table_alias";let contextBefore=beforePosition.slice(Math.max(0,charPosition-50)),contextAfter=afterPosition.slice(0,50),fullContext=(contextBefore+identifier+contextAfter).toUpperCase();return fullContext.includes(" AS "+identifier.toUpperCase())||fullContext.includes(" "+identifier.toUpperCase()+" ON")||fullContext.includes(" "+identifier.toUpperCase()+`
48
48
  `),"table_alias"}calculateScopeRange(sql,charPosition,type){if(type==="cte")return{start:0,end:sql.length};let beforePosition=sql.slice(0,charPosition),afterPosition=sql.slice(charPosition),lastSelect=beforePosition.toUpperCase().lastIndexOf("SELECT"),start=lastSelect!==-1?lastSelect:0,nextMajorClause=afterPosition.search(/\b(SELECT|WITH|UNION)\b/i),end=nextMajorClause!==-1?charPosition+nextMajorClause:sql.length;return{start,end}}replaceIdentifierSafely(sql,oldIdentifier,newIdentifier){if(oldIdentifier===newIdentifier||oldIdentifier.length===0)return sql;let result=[],position=0,sqlLength=sql.length,oldIdLength=oldIdentifier.length;for(;position<sqlLength;){let char=sql[position],charCode=char.charCodeAt(0);if(charCode===34||charCode===96||charCode===91){let{content,nextPosition}=this.extractAndReplaceQuotedIdentifier(sql,position,char,oldIdentifier,newIdentifier);result.push(content),position=nextPosition;continue}if(charCode===39){let{content,nextPosition}=this.extractQuotedString(sql,position,char);result.push(content),position=nextPosition;continue}if(charCode===45&&position+1<sqlLength&&sql.charCodeAt(position+1)===45){let{content,nextPosition}=this.extractLineComment(sql,position);result.push(content),position=nextPosition;continue}if(charCode===47&&position+1<sqlLength&&sql.charCodeAt(position+1)===42){let{content,nextPosition}=this.extractBlockComment(sql,position);result.push(content),position=nextPosition;continue}if(this.isIdentifierStartChar(charCode)&&this.matchesIdentifierAt(sql,position,oldIdentifier)){let beforePosition=position-1,afterPosition=position+oldIdLength,beforeChar=beforePosition>=0?sql[beforePosition]:null,afterChar=afterPosition<sqlLength?sql[afterPosition]:null;if(this.hasValidWordBoundaries(beforeChar,afterChar)){result.push(newIdentifier),position+=oldIdLength;continue}}result.push(char),position++}return result.join("")}validateRename(originalSql,modifiedSql,oldIdentifier,newIdentifier){if(originalSql===modifiedSql||!modifiedSql.includes(newIdentifier))return!1;let originalOccurrences=this.countWordOccurrences(originalSql,oldIdentifier);return this.countWordOccurrences(modifiedSql,oldIdentifier)<originalOccurrences}extractAndReplaceQuotedIdentifier(sql,startPosition,quoteChar,oldIdentifier,newIdentifier){if(quoteChar==="[")return this.extractAndReplaceBracketedIdentifier(sql,startPosition,oldIdentifier,newIdentifier);let result=[quoteChar],position=startPosition+1,identifierStart=position;for(;position<sql.length;){let char=sql[position];if(char===quoteChar){if(position+1<sql.length&&sql[position+1]===quoteChar){result.push(char),result.push(sql[position+1]),position+=2;continue}let quotedContent=sql.slice(identifierStart,position);quotedContent.toLowerCase()===oldIdentifier.toLowerCase()?result.push(newIdentifier):result.push(quotedContent),result.push(char);break}position++}return{content:result.join(""),nextPosition:position+1}}extractAndReplaceBracketedIdentifier(sql,startPosition,oldIdentifier,newIdentifier){let result=["["],position=startPosition+1,identifierStart=position;for(;position<sql.length;){let char=sql[position];if(char==="]"){let bracketedContent=sql.slice(identifierStart,position);bracketedContent.toLowerCase()===oldIdentifier.toLowerCase()?result.push(newIdentifier):result.push(bracketedContent),result.push(char);break}position++}return{content:result.join(""),nextPosition:position+1}}extractQuotedString(sql,startPosition,quoteChar){let result=[quoteChar],position=startPosition+1;for(;position<sql.length;){let char=sql[position];if(result.push(char),char===quoteChar){if(position+1<sql.length&&sql[position+1]===quoteChar){result.push(sql[position+1]),position+=2;continue}break}position++}return{content:result.join(""),nextPosition:position+1}}extractLineComment(sql,startPosition){let result=[],position=startPosition;for(;position<sql.length&&sql.charCodeAt(position)!==10&&sql.charCodeAt(position)!==13;)result.push(sql[position]),position++;return position<sql.length&&(sql.charCodeAt(position)===10||sql.charCodeAt(position)===13)&&(result.push(sql[position]),position++),{content:result.join(""),nextPosition:position}}extractBlockComment(sql,startPosition){let result=["/","*"],position=startPosition+2;for(;position<sql.length-1;){let char=sql[position];if(result.push(char),char==="*"&&sql[position+1]==="/"){result.push("/"),position+=2;break}position++}return{content:result.join(""),nextPosition:position}}isIdentifierStartChar(charCode){return charCode>=65&&charCode<=90||charCode>=97&&charCode<=122||charCode===95}isIdentifierChar(charCode){return charCode>=65&&charCode<=90||charCode>=97&&charCode<=122||charCode>=48&&charCode<=57||charCode===95}matchesIdentifierAt(sql,position,identifier){if(position+identifier.length>sql.length)return!1;for(let i=0;i<identifier.length;i++){let sqlChar=sql.charCodeAt(position+i),idChar=identifier.charCodeAt(i),sqlLower=sqlChar>=65&&sqlChar<=90?sqlChar+32:sqlChar,idLower=idChar>=65&&idChar<=90?idChar+32:idChar;if(sqlLower!==idLower)return!1}return!0}hasValidWordBoundaries(beforeChar,afterChar){let isValidBefore=beforeChar===null||!this.isIdentifierChar(beforeChar.charCodeAt(0)),isValidAfter=afterChar===null||!this.isIdentifierChar(afterChar.charCodeAt(0));return isValidBefore&&isValidAfter}countWordOccurrences(sql,identifier){let count=0,position=0,sqlLength=sql.length,idLength=identifier.length;for(;position<=sqlLength-idLength;){if(this.matchesIdentifierAt(sql,position,identifier)){let beforePosition=position-1,afterPosition=position+idLength,beforeChar=beforePosition>=0?sql[beforePosition]:null,afterChar=afterPosition<sqlLength?sql[afterPosition]:null;this.hasValidWordBoundaries(beforeChar,afterChar)&&count++}position++}return count}};var SmartRenamer=class{constructor(){this.cteRenamer=new CTERenamer,this.aliasRenamer=new AliasRenamer,this.identifierRenamer=new SqlIdentifierRenamer}isRenameable(sql,position){try{if(!sql?.trim())return{renameable:!1,renamerType:"none",reason:"Empty SQL"};if(!position||position.line<1||position.column<1)return{renameable:!1,renamerType:"none",reason:"Invalid position"};let lexeme=LexemeCursor.findLexemeAtLineColumn(sql,position);if(!lexeme)return{renameable:!1,renamerType:"none",reason:"No token found"};if(!(lexeme.type&2112))return{renameable:!1,renamerType:"none",tokenName:lexeme.value,reason:`Token '${lexeme.value}' is not an identifier`};let tokenName=lexeme.value,renamerType=this.detectRenamerType(sql,tokenName);return renamerType==="unknown"?{renameable:!1,renamerType:"none",tokenName,reason:`Cannot determine if '${tokenName}' is renameable`}:{renameable:!0,renamerType,tokenName}}catch(error){return{renameable:!1,renamerType:"none",reason:`Error: ${error instanceof Error?error.message:String(error)}`}}}rename(sql,position,newName,options){try{if(!sql?.trim())return this.createErrorResult(sql,newName,"unknown","","SQL cannot be empty");if(!position||position.line<1||position.column<1)return this.createErrorResult(sql,newName,"unknown","","Position must be valid line/column (1-based)");if(!newName?.trim())return this.createErrorResult(sql,newName,"unknown","","New name cannot be empty");let lexeme=LexemeCursor.findLexemeAtLineColumn(sql,position);if(!lexeme)return this.createErrorResult(sql,newName,"unknown","",`No identifier found at line ${position.line}, column ${position.column}`);if(!(lexeme.type&64))return this.createErrorResult(sql,newName,"unknown",lexeme.value,`Token '${lexeme.value}' is not renameable`);let originalName=lexeme.value,preserveFormatting=options?.preserveFormatting??!1,renamerType=this.detectRenamerType(sql,originalName);if(preserveFormatting)try{let formatPreservedResult=this.attemptFormattingPreservationRename(sql,position,newName,originalName,renamerType);if(formatPreservedResult.success)return formatPreservedResult}catch(error){console.warn("Formatting preservation failed, falling back to standard rename:",error)}try{let newSql;if(renamerType==="cte")newSql=this.cteRenamer.renameCTEAtPosition(sql,position,newName);else if(renamerType==="alias"){let result=this.aliasRenamer.renameAlias(sql,position,newName);if(!result.success)return{success:!1,originalSql:sql,renamerType:"alias",originalName,newName,error:result.conflicts?.join(", ")||"Alias rename failed",formattingPreserved:!1,formattingMethod:"smart-renamer-only"};newSql=result.newSql}else return this.createErrorResult(sql,newName,"unknown",originalName,`Cannot determine if '${originalName}' is a CTE name or table alias`);return{success:!0,originalSql:sql,newSql,renamerType,originalName,newName,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}catch(error){return this.createErrorResult(sql,newName,renamerType,originalName,`${renamerType.toUpperCase()} rename failed: ${error instanceof Error?error.message:String(error)}`)}}catch(error){return this.createErrorResult(sql,newName,"unknown","",`Unexpected error: ${error instanceof Error?error.message:String(error)}`)}}detectRenamerType(sql,identifierName){try{let query=SelectQueryParser.parse(sql);return this.isCTEName(query,identifierName)?"cte":"alias"}catch{return"unknown"}}isCTEName(query,name){return query instanceof SimpleSelectQuery&&query.withClause?query.withClause.tables.some(cte=>cte.aliasExpression&&cte.aliasExpression.table&&cte.aliasExpression.table.name===name):query instanceof BinarySelectQuery?this.isCTEName(query.left,name)||this.isCTEName(query.right,name):!1}attemptFormattingPreservationRename(sql,position,newName,originalName,renamerType){let standardResult=this.performStandardRename(sql,position,newName,originalName,renamerType);if(!standardResult.success)return{...standardResult,formattingPreserved:!1,formattingMethod:"smart-renamer-only"};let renameMap=new Map([[originalName,newName]]);try{let formattedSql=this.identifierRenamer.renameIdentifiers(sql,renameMap);if(this.validateRenameResult(sql,formattedSql,originalName,newName))return{success:!0,originalSql:sql,newSql:formattedSql,renamerType,originalName,newName,formattingPreserved:!0,formattingMethod:"sql-identifier-renamer"};throw new Error("Validation failed: rename may not have been applied correctly")}catch{return{...standardResult,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}}performStandardRename(sql,position,newName,originalName,renamerType){try{let newSql;if(renamerType==="cte")newSql=this.cteRenamer.renameCTEAtPosition(sql,position,newName);else if(renamerType==="alias"){let result=this.aliasRenamer.renameAlias(sql,position,newName);if(!result.success)return{success:!1,originalSql:sql,renamerType:"alias",originalName,newName,error:result.conflicts?.join(", ")||"Alias rename failed"};newSql=result.newSql}else return{success:!1,originalSql:sql,renamerType:"unknown",originalName,newName,error:`Cannot determine if '${originalName}' is a CTE name or table alias`};return{success:!0,originalSql:sql,newSql,renamerType,originalName,newName}}catch(error){return{success:!1,originalSql:sql,renamerType,originalName,newName,error:`${renamerType.toUpperCase()} rename failed: ${error instanceof Error?error.message:String(error)}`}}}validateRenameResult(originalSql,newSql,oldName,newName){if(originalSql===newSql||!newSql.includes(newName))return!1;let originalOccurrences=this.countWordOccurrences(originalSql,oldName);return this.countWordOccurrences(newSql,oldName)<originalOccurrences}countWordOccurrences(sql,name){let regex=new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"gi"),matches=sql.match(regex);return matches?matches.length:0}createErrorResult(sql,newName,renamerType,originalName,error){return{success:!1,originalSql:sql,renamerType,originalName,newName,error,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}batchRename(sql,renames,options){if(options?.preserveFormatting??!1)try{let renameMap=new Map(Object.entries(renames)),formattedSql=this.identifierRenamer.renameIdentifiers(sql,renameMap),originalNames=Object.keys(renames),newNames=Object.values(renames);return{success:!0,originalSql:sql,newSql:formattedSql,renamerType:"alias",originalName:originalNames.join(", "),newName:newNames.join(", "),formattingPreserved:!0,formattingMethod:"sql-identifier-renamer"}}catch(error){return{success:!1,originalSql:sql,renamerType:"unknown",originalName:Object.keys(renames).join(", "),newName:Object.values(renames).join(", "),error:`Batch rename failed: ${error instanceof Error?error.message:String(error)}`,formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}else return{success:!1,originalSql:sql,renamerType:"unknown",originalName:Object.keys(renames).join(", "),newName:Object.values(renames).join(", "),error:"Batch rename without formatting preservation not implemented. Use individual renames or enable formatting preservation.",formattingPreserved:!1,formattingMethod:"smart-renamer-only"}}};var OriginalFormatRestorer=class{restore(lexemes){if(lexemes.length===0)return"";let result="";for(let lexeme of lexemes)result+=lexeme.value,lexeme.followingWhitespace&&(result+=lexeme.followingWhitespace);return result}restoreWithComments(lexemes,includeComments=!0){if(lexemes.length===0)return"";let result="";for(let lexeme of lexemes){if(result+=lexeme.value,includeComments&&lexeme.inlineComments&&lexeme.inlineComments.length>0)for(let comment of lexeme.inlineComments)comment.trim().length>0&&(result+=` -- ${comment}`);lexeme.followingWhitespace&&(result+=lexeme.followingWhitespace)}return result}analyzeFormatting(lexemes){let totalWhitespace=0,totalComments=0,spaceCount=0,tabCount=0,indentLines=0,totalIndentSize=0;for(let lexeme of lexemes){if(lexeme.followingWhitespace){totalWhitespace+=lexeme.followingWhitespace.length;let lines=lexeme.followingWhitespace.split(`
49
- `);for(let i=1;i<lines.length;i++){let line=lines[i],leadingSpaces=line.match(/^ */)?.[0].length||0,leadingTabs=line.match(/^\t*/)?.[0].length||0;(leadingSpaces>0||leadingTabs>0)&&(indentLines++,totalIndentSize+=leadingSpaces+leadingTabs*4,spaceCount+=leadingSpaces,tabCount+=leadingTabs)}}lexeme.inlineComments&&(totalComments+=lexeme.inlineComments.length)}let indentationStyle="none";return spaceCount>0&&tabCount>0?indentationStyle="mixed":spaceCount>0?indentationStyle="spaces":tabCount>0&&(indentationStyle="tabs"),{totalWhitespace,totalComments,indentationStyle,averageIndentSize:indentLines>0?totalIndentSize/indentLines:0}}validateFormattingLexemes(lexemes){let issues=[];for(let i=0;i<lexemes.length;i++){let lexeme=lexemes[i];lexeme.position||issues.push(`Lexeme ${i} missing position information`),lexeme.followingWhitespace===void 0&&issues.push(`Lexeme ${i} missing followingWhitespace property`),lexeme.inlineComments===void 0&&issues.push(`Lexeme ${i} missing inlineComments property`),lexeme.position&&lexeme.position.startPosition>=lexeme.position.endPosition&&issues.push(`Lexeme ${i} has invalid position range`)}return{isValid:issues.length===0,issues}}};var SelectResultSelectConverter=class{static toSelectQuery(query,options){let fixtureTables=options?.fixtureTables??[];if(fixtureTables.length===0)return query;let sources=new TableSourceCollector(!1).collect(query),referencedTables=new Set;sources.forEach(s=>referencedTables.add(s.getSourceName().toLowerCase()));let neededFixtures=fixtureTables.filter(f=>referencedTables.has(f.tableName.toLowerCase()));if(neededFixtures.length===0)return query;let fixtureCtes=FixtureCteBuilder.buildFixtures(neededFixtures);return query instanceof SimpleSelectQuery&&(query.withClause?query.withClause.tables=[...fixtureCtes,...query.withClause.tables]:query.appendWith(fixtureCtes)),query}};var SimulatedSelectConverter=class{static convert(ast,options){if(ast instanceof InsertQuery)return InsertResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof UpdateQuery)return UpdateResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof DeleteQuery)return DeleteResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof MergeQuery)return MergeResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof SimpleSelectQuery||ast instanceof BinarySelectQuery||ast instanceof ValuesQuery)return SelectResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof CreateTableQuery){if(ast.isTemporary&&ast.asSelectQuery){let processedSelect=SelectResultSelectConverter.toSelectQuery(ast.asSelectQuery,options);return ast.asSelectQuery=processedSelect,ast}return null}return null}};var DDLGeneralizer=class{static generalize(ast){let result=[];for(let component of ast)if(component instanceof CreateTableQuery){let{createTable,alterTables}=this.splitCreateTable(component);result.push(createTable),result.push(...alterTables)}else result.push(component);return result}static splitCreateTable(query){let newColumns=[],alterTables=[],tableQualifiedName=new QualifiedName(query.namespaces||[],query.tableName.name);for(let col of query.columns){let newConstraints=[];for(let constraint of col.constraints)if(["primary-key","unique","references","check"].includes(constraint.kind)){let tableConstraint=this.columnToTableConstraint(col.name,constraint);alterTables.push(new AlterTableStatement({table:tableQualifiedName,actions:[new AlterTableAddConstraint({constraint:tableConstraint})]}))}else newConstraints.push(constraint);newColumns.push(new TableColumnDefinition({name:col.name,dataType:col.dataType,constraints:newConstraints}))}if(query.tableConstraints)for(let constraint of query.tableConstraints)alterTables.push(new AlterTableStatement({table:tableQualifiedName,actions:[new AlterTableAddConstraint({constraint})]}));return{createTable:new CreateTableQuery({tableName:query.tableName.name,namespaces:query.namespaces,columns:newColumns,ifNotExists:query.ifNotExists,isTemporary:query.isTemporary,tableOptions:query.tableOptions,asSelectQuery:query.asSelectQuery,withDataOption:query.withDataOption,tableConstraints:[]}),alterTables}}static columnToTableConstraint(columnName,constraint){let baseParams={constraintName:constraint.constraintName,deferrable:constraint.reference?.deferrable,initially:constraint.reference?.initially};switch(constraint.kind){case"primary-key":return new TableConstraintDefinition({kind:"primary-key",columns:[columnName],...baseParams});case"unique":return new TableConstraintDefinition({kind:"unique",columns:[columnName],...baseParams});case"references":return new TableConstraintDefinition({kind:"foreign-key",columns:[columnName],reference:constraint.reference,...baseParams});case"check":return new TableConstraintDefinition({kind:"check",checkExpression:constraint.checkExpression,...baseParams});default:throw new Error(`Unsupported constraint kind for generalization: ${constraint.kind}`)}}};var DDLDiffGenerator=class{static generateDiff(currentSql,expectedSql,options={}){let currentAst=this.parseAndGeneralize(currentSql),expectedAst=this.parseAndGeneralize(expectedSql),currentSchema=this.buildSchema(currentAst),expectedSchema=this.buildSchema(expectedAst),diffAsts=[];for(let[tableName,expectedTable]of expectedSchema.tables){let currentTable=currentSchema.tables.get(tableName);if(currentTable)this.compareColumns(currentTable,expectedTable,diffAsts,options),this.compareConstraints(currentTable,expectedTable,diffAsts,options),this.compareIndexes(currentTable,expectedTable,diffAsts,options);else{let columns=Array.from(expectedTable.columns.values()).map(c=>c.definition),tableNameStr=expectedTable.qualifiedName.name instanceof RawString?expectedTable.qualifiedName.name.value:expectedTable.qualifiedName.name.name,namespaces=expectedTable.qualifiedName.namespaces?expectedTable.qualifiedName.namespaces.map(ns=>ns.name):null,createTable=new CreateTableQuery({tableName:tableNameStr,namespaces,columns});diffAsts.push(createTable);for(let constraint of expectedTable.constraints)diffAsts.push(new AlterTableStatement({table:expectedTable.qualifiedName,actions:[new AlterTableAddConstraint({constraint:constraint.definition})]}));for(let index of expectedTable.indexes)diffAsts.push(index.definition)}}if(options.dropTables)for(let[tableName,currentTable]of currentSchema.tables)expectedSchema.tables.has(tableName)||diffAsts.push(new DropTableStatement({tables:[currentTable.qualifiedName],ifExists:!1}));let formatter2=new SqlFormatter(options.formatOptions||{keywordCase:"upper"});return diffAsts.map(ast=>formatter2.format(ast).formattedSql+";")}static parseAndGeneralize(sql){let split=MultiQuerySplitter.split(sql),asts=[];for(let q of split.queries)if(!q.isEmpty)try{let ast=SqlParser.parse(q.sql);asts.push(ast)}catch(e){console.warn("Failed to parse SQL for diff:",q.sql,e)}return DDLGeneralizer.generalize(asts)}static buildSchema(asts){let tables=new Map,formatter2=new SqlFormatter({keywordCase:"none"});for(let ast of asts)if(ast instanceof CreateTableQuery){let qName=new QualifiedName(ast.namespaces||[],ast.tableName),key=this.getQualifiedNameKey(qName),tableModel={name:key,qualifiedName:qName,columns:new Map,constraints:[],indexes:[]};for(let col of ast.columns)tableModel.columns.set(col.name.name,{name:col.name.name,definition:col});tables.set(key,tableModel)}else if(ast instanceof AlterTableStatement){let key=this.getQualifiedNameKey(ast.table),tableModel=tables.get(key);if(tableModel)for(let action of ast.actions)if(action instanceof AlterTableAddConstraint){let formatted=formatter2.format(action.constraint).formattedSql;tableModel.constraints.push({name:action.constraint.constraintName?.name,kind:action.constraint.kind,definition:action.constraint,formatted})}else action instanceof AlterTableAddColumn&&tableModel.columns.set(action.column.name.name,{name:action.column.name.name,definition:action.column})}else if(ast instanceof CreateIndexStatement){let key=this.getQualifiedNameKey(ast.tableName),tableModel=tables.get(key);if(tableModel){let formatted=formatter2.format(ast).formattedSql;tableModel.indexes.push({name:ast.indexName.toString(),definition:ast,formatted})}}return{tables}}static compareColumns(current,expected,diffs,options){for(let[name,col]of expected.columns)current.columns.has(name)||diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableAddColumn({column:col.definition})]}));if(options.dropColumns)for(let[name,col]of current.columns)expected.columns.has(name)||diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableDropColumn({columnName:col.definition.name})]}))}static compareConstraints(current,expected,diffs,options){let formatter2=new SqlFormatter({keywordCase:"none"}),getConstraintSignature=c=>options.checkConstraintNames?c.kind==="primary-key"?c.formatted.replace(/^constraint\s+("[^"]+"|[^\s]+)\s+/i,"").trim():c.name||c.formatted:c.formatted.replace(/^constraint\s+("[^"]+"|[^\s]+)\s+/i,"").trim(),currentSignatures=new Set(current.constraints.map(getConstraintSignature));for(let expectedC of expected.constraints){let sig=getConstraintSignature(expectedC);currentSignatures.has(sig)||diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableAddConstraint({constraint:expectedC.definition})]}))}if(options.dropConstraints){let expectedSignatures=new Set(expected.constraints.map(getConstraintSignature));for(let currentC of current.constraints){let sig=getConstraintSignature(currentC);expectedSignatures.has(sig)||(currentC.name?diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableDropConstraint({constraintName:new IdentifierString(currentC.name)})]})):console.warn("Cannot drop unnamed constraint:",currentC.formatted))}}}static compareIndexes(current,expected,diffs,options){let getIndexSignature=idx=>{if(options.checkConstraintNames)return idx.name;let def=idx.definition,parts=[];parts.push(def.tableName.toString()),def.unique&&parts.push("UNIQUE"),def.usingMethod&&parts.push(`USING:${def.usingMethod.toString()}`);let columnSigs=def.columns.map(col=>{let expr=col.expression.toString(),sort=col.sortOrder||"",nulls=col.nullsOrder||"";return`${expr}${sort}${nulls}`});return parts.push(`COLS:${columnSigs.join(",")}`),def.include&&def.include.length>0&&parts.push(`INCLUDE:${def.include.map(i=>i.toString()).join(",")}`),def.where&&parts.push(`WHERE:${def.where.toString()}`),parts.join("|")},currentSignatures=new Set(current.indexes.map(getIndexSignature));for(let expectedIdx of expected.indexes){let sig=getIndexSignature(expectedIdx);currentSignatures.has(sig)||diffs.push(expectedIdx.definition)}if(options.checkConstraintNames||options.dropIndexes){let expectedSignatures=new Set(expected.indexes.map(getIndexSignature));for(let currentIdx of current.indexes){let sig=getIndexSignature(currentIdx);expectedSignatures.has(sig)||diffs.push(new DropIndexStatement({indexNames:[currentIdx.definition.indexName],ifExists:!1}))}}}static getQualifiedNameKey(qName){return qName.toString()}};var ParameterDetector=class{static extractParameterNames(query){return ParameterCollector.collect(query).map(p=>p.name.value)}static hasParameter(query,parameterName){return this.extractParameterNames(query).includes(parameterName)}static separateFilters(query,filter){let hardcodedParamNames=this.extractParameterNames(query),hardcodedParams={},dynamicFilters={};for(let[key,value]of Object.entries(filter))hardcodedParamNames.includes(key)?hardcodedParams[key]=value:dynamicFilters[key]=value;return{hardcodedParams,dynamicFilters}}};var FilterableItem=class{constructor(name,type,tableName){this.name=name;this.type=type;this.tableName=tableName}},FilterableItemCollector=class{constructor(tableColumnResolver,options){this.tableColumnResolver=tableColumnResolver,this.options={qualified:!1,upstream:!0,...options}}collect(query){let items=[],columnItems=this.collectColumns(query);items.push(...columnItems);let parameterItems=this.collectParameters(query);return items.push(...parameterItems),this.removeDuplicates(items)}collectColumns(query){let items=[];try{let columns=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:this.options.upstream}).collect(query);for(let column of columns){let tableName,realTableName;if(column.value&&typeof column.value.getNamespace=="function"){let namespace=column.value.getNamespace();namespace&&namespace.trim()!==""&&(tableName=namespace,this.options.qualified&&(realTableName=this.getRealTableName(query,namespace)))}tableName||(tableName=this.inferTableNameFromQuery(query),tableName&&this.options.qualified&&(realTableName=tableName));let columnName=column.name;this.options.qualified&&(realTableName||tableName)&&(columnName=`${realTableName||tableName}.${column.name}`),items.push(new FilterableItem(columnName,"column",tableName))}}catch(error){console.warn("Failed to collect columns with SelectableColumnCollector, using fallback:",error);try{let schemas=new SchemaCollector(this.tableColumnResolver,!0).collect(query);for(let schema of schemas)for(let columnName of schema.columns){let finalColumnName=columnName;this.options.qualified&&(finalColumnName=`${schema.name}.${columnName}`),items.push(new FilterableItem(finalColumnName,"column",schema.name))}}catch(fallbackError){console.warn("Failed to collect columns with both approaches:",error,fallbackError)}}return items}inferTableNameFromQuery(query){if(query instanceof SimpleSelectQuery&&query.fromClause&&query.fromClause.source){let datasource=query.fromClause.source.datasource;if(datasource&&typeof datasource.table=="object"){let table=datasource.table;if(table&&typeof table.name=="string")return table.name}}}getRealTableName(query,aliasOrName){try{let simpleQuery=query.type==="WITH"?query.toSimpleQuery():query;if(simpleQuery instanceof SimpleSelectQuery&&simpleQuery.fromClause){if(simpleQuery.fromClause.source?.datasource){let mainSource=simpleQuery.fromClause.source,realName=this.extractRealTableName(mainSource,aliasOrName);if(realName)return realName}let fromClause=simpleQuery.fromClause;if(fromClause.joinClauses&&Array.isArray(fromClause.joinClauses)){for(let joinClause of fromClause.joinClauses)if(joinClause.source?.datasource){let realName=this.extractRealTableName(joinClause.source,aliasOrName);if(realName)return realName}}}}catch(error){console.warn("Error resolving real table name:",error)}return aliasOrName}extractRealTableName(source,aliasOrName){try{let datasource=source.datasource;if(!datasource)return;let alias=source.alias||source.aliasExpression?.table?.name,realTableName=datasource.table?.name;if(alias===aliasOrName&&realTableName||!alias&&realTableName===aliasOrName)return realTableName}catch{}}collectParameters(query){let items=[];try{let parameterNames=ParameterDetector.extractParameterNames(query);for(let paramName of parameterNames)items.push(new FilterableItem(paramName,"parameter"))}catch(error){console.warn("Failed to collect parameters:",error)}return items}removeDuplicates(items){let seen=new Set,result=[];for(let item of items){let key=`${item.type}:${item.name}:${item.tableName||"none"}`;seen.has(key)||(seen.add(key),result.push(item))}return result.sort((a,b)=>{if(a.type!==b.type)return a.type==="column"?-1:1;if(a.type==="column"){let tableA=a.tableName||"",tableB=b.tableName||"";if(tableA!==tableB)return tableA.localeCompare(tableB)}return a.name.localeCompare(b.name)})}};var SqlSortInjector=class{constructor(tableColumnResolver){this.tableColumnResolver=tableColumnResolver}static removeOrderBy(query){if(typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for ORDER BY removal");return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:null,windowClause:query.windowClause,limitClause:query.limitClause,offsetClause:query.offsetClause,fetchClause:query.fetchClause,forClause:query.forClause})}inject(query,sortConditions){if(typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for sorting");let availableColumns=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query);for(let columnName of Object.keys(sortConditions))if(!availableColumns.find(item=>item.name===columnName))throw new Error(`Column or alias '${columnName}' not found in current query`);let newOrderByItems=[];for(let[columnName,condition]of Object.entries(sortConditions)){let columnEntry=availableColumns.find(item=>item.name===columnName);if(!columnEntry)continue;let columnRef=columnEntry.value;this.validateSortCondition(columnName,condition);let sortDirection;condition.desc?sortDirection="desc":sortDirection="asc";let nullsPosition=null;condition.nullsFirst?nullsPosition="first":condition.nullsLast&&(nullsPosition="last");let orderByItem=new OrderByItem(columnRef,sortDirection,nullsPosition);newOrderByItems.push(orderByItem)}let finalOrderByItems=[];query.orderByClause?finalOrderByItems=[...query.orderByClause.order,...newOrderByItems]:finalOrderByItems=newOrderByItems;let newOrderByClause=finalOrderByItems.length>0?new OrderByClause(finalOrderByItems):null;return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:newOrderByClause,windowClause:query.windowClause,limitClause:query.limitClause,offsetClause:query.offsetClause,fetchClause:query.fetchClause,forClause:query.forClause})}validateSortCondition(columnName,condition){if(condition.asc&&condition.desc)throw new Error(`Conflicting sort directions for column '${columnName}': both asc and desc specified`);if(condition.nullsFirst&&condition.nullsLast)throw new Error(`Conflicting nulls positions for column '${columnName}': both nullsFirst and nullsLast specified`);if(!condition.asc&&!condition.desc&&!condition.nullsFirst&&!condition.nullsLast)throw new Error(`Empty sort condition for column '${columnName}': at least one sort option must be specified`)}};var SqlPaginationInjector=class{inject(query,pagination){if(this.validatePaginationOptions(pagination),typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for pagination");if(query.limitClause||query.offsetClause)throw new Error("Query already contains LIMIT or OFFSET clause. Use removePagination() first if you want to override existing pagination.");let offset=(pagination.page-1)*pagination.pageSize,limitClause=new LimitClause(new ParameterExpression("paging_limit",pagination.pageSize)),offsetClause=new OffsetClause(new ParameterExpression("paging_offset",offset));return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:query.orderByClause,windowClause:query.windowClause,limitClause,offsetClause,fetchClause:query.fetchClause,forClause:query.forClause})}static removePagination(query){if(typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for pagination removal");return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:query.orderByClause,windowClause:query.windowClause,limitClause:null,offsetClause:null,fetchClause:query.fetchClause,forClause:query.forClause})}validatePaginationOptions(pagination){if(!pagination)throw new Error("Pagination options are required");if(typeof pagination.page!="number"||pagination.page<1)throw new Error("Page number must be a positive integer (1 or greater)");if(typeof pagination.pageSize!="number"||pagination.pageSize<1)throw new Error("Page size must be a positive integer (1 or greater)");if(pagination.pageSize>1e3)throw new Error("Page size cannot exceed 1000 items")}};var SqlParameterBinder=class{constructor(options={}){this.options={requireAllParameters:!0,...options}}bind(query,parameterValues){let modifiedQuery=query,existingParams=ParameterDetector.extractParameterNames(modifiedQuery);if(this.options.requireAllParameters){let missingParams=existingParams.filter(paramName=>!(paramName in parameterValues)||parameterValues[paramName]===void 0);if(missingParams.length>0)throw new Error(`Missing values for required parameters: ${missingParams.join(", ")}`)}for(let[paramName,value]of Object.entries(parameterValues))if(existingParams.includes(paramName))try{ParameterHelper.set(modifiedQuery,paramName,value)}catch(error){throw new Error(`Failed to bind parameter '${paramName}': ${error instanceof Error?error.message:"Unknown error"}`)}return modifiedQuery}bindToSimpleQuery(query,parameterValues){return this.bind(query,parameterValues)}};var NAMESPACE_SEPARATOR="|",normalizeIdentifier=input=>{let value=input?.trim()??"";return value===""?"":value.toLowerCase()},normalizeColumnSetKey=columns=>columns.map(column=>normalizeIdentifier(column)).filter(Boolean).sort().join(NAMESPACE_SEPARATOR),buildSchemaMap=schemaInfo=>{let map=new Map;for(let table of schemaInfo){let normalizedName=normalizeIdentifier(table.name);if(!normalizedName)continue;let columnSet=new Set(table.columns.map(normalizeIdentifier).filter(Boolean)),uniqueSetKeys=new Set;for(let uniqueKey of table.uniqueKeys){let normalizedKey=normalizeColumnSetKey(uniqueKey);normalizedKey&&uniqueSetKeys.add(normalizedKey)}columnSet.size===0&&uniqueSetKeys.size===0||map.set(normalizedName,{columnSet,uniqueSetKeys})}return map},collectReferenceMetadata=query=>{let collector=new ColumnReferenceCollector,namespaceCounts=new Map,unqualifiedColumns=new Set;for(let ref of collector.collect(query)){let namespace=normalizeIdentifier(ref.getNamespace());if(namespace)namespaceCounts.set(namespace,(namespaceCounts.get(namespace)??0)+1);else{let column=normalizeIdentifier(ref.column.name);column&&unqualifiedColumns.add(column)}}let joinConditionCounts=new Map;if(query.fromClause?.joins)for(let join of query.fromClause.joins){let counts=new Map;if(join.condition&&join.condition instanceof JoinOnClause){let joinCollector=new ColumnReferenceCollector;for(let ref of joinCollector.collect(join.condition.condition)){let namespace=normalizeIdentifier(ref.getNamespace());namespace&&counts.set(namespace,(counts.get(namespace)??0)+1)}}joinConditionCounts.set(join,counts)}return{namespaceCounts,unqualifiedColumns,joinConditionCounts}},isLeftJoin=join=>join.joinType.value.toLowerCase().includes("left"),getJoinIdentifiers=join=>{let identifiers=new Set,alias=normalizeIdentifier(join.source.getAliasName());if(alias&&identifiers.add(alias),join.source.datasource instanceof TableSource){let rawName=join.source.datasource.getSourceName();rawName&&identifiers.add(normalizeIdentifier(rawName));let shortName=normalizeIdentifier(join.source.datasource.table.name);shortName&&identifiers.add(shortName)}return[...identifiers]},hasExternalReferences=(identifiers,metadata,join)=>{let local=metadata.joinConditionCounts.get(join)??new Map;for(let identifier of identifiers){let total=metadata.namespaceCounts.get(identifier)??0,localCount=local.get(identifier)??0;if(total-localCount>0)return!0}return!1},getJoinColumnInfo=(join,identifiers)=>{if(!(join.condition instanceof JoinOnClause))return null;let expression=join.condition.condition;if(!(expression instanceof BinaryExpression)||expression.operator.value.trim().toLowerCase()!=="=")return null;let resolveColumn=component=>component instanceof ColumnReference?component:null,leftRef=resolveColumn(expression.left),rightRef=resolveColumn(expression.right);if(!leftRef||!rightRef)return null;let normalizedLeftNamespace=normalizeIdentifier(leftRef.getNamespace()),normalizedRightNamespace=normalizeIdentifier(rightRef.getNamespace());return identifiers.has(normalizedLeftNamespace)?normalizeIdentifier(leftRef.column.name):identifiers.has(normalizedRightNamespace)?normalizeIdentifier(rightRef.column.name):null},shouldRemoveJoin=(join,schemaMap,metadata)=>{if(!isLeftJoin(join)||join.lateral||!(join.source.datasource instanceof TableSource))return!1;let candidates=[normalizeIdentifier(join.source.datasource.getSourceName()),normalizeIdentifier(join.source.datasource.table.name)].filter(Boolean),tableInfo;for(let candidate of candidates){let info=schemaMap.get(candidate);if(info){tableInfo=info;break}}if(!tableInfo)return!1;let identifiers=new Set(getJoinIdentifiers(join));if(identifiers.size===0||hasExternalReferences([...identifiers],metadata,join))return!1;let joinColumn=getJoinColumnInfo(join,identifiers);if(!joinColumn||metadata.unqualifiedColumns.has(joinColumn)||tableInfo.columnSet.size>0&&!tableInfo.columnSet.has(joinColumn))return!1;let uniqueKey=normalizeColumnSetKey([joinColumn]);return!!tableInfo.uniqueSetKeys.has(uniqueKey)},optimizeSimpleQuery=(query,schemaMap)=>{if(!query.fromClause?.joins?.length)return!1;let metadata=collectReferenceMetadata(query),retainedJoins=[],removed=!1;for(let join of query.fromClause.joins){if(shouldRemoveJoin(join,schemaMap,metadata)){removed=!0;continue}retainedJoins.push(join)}return query.fromClause.joins=retainedJoins.length>0?retainedJoins:null,removed},traverseSelectQuery=(query,schemaMap)=>{if(query instanceof SimpleSelectQuery)return optimizeSimpleQuery(query,schemaMap);if(query instanceof BinarySelectQuery){let leftChanged=traverseSelectQuery(query.left,schemaMap),rightChanged=traverseSelectQuery(query.right,schemaMap);return leftChanged||rightChanged}return!1},optimizeUnusedLeftJoinsOnce=(query,schemaMap)=>schemaMap.size===0?!1:traverseSelectQuery(query,schemaMap),optimizeUnusedLeftJoins=(query,schemaInfo)=>(optimizeUnusedLeftJoinsOnce(query,buildSchemaMap(schemaInfo)),query),optimizeUnusedLeftJoinsToFixedPoint=(query,schemaInfo)=>{let schemaMap=buildSchemaMap(schemaInfo),changed=!0;for(;changed;)changed=optimizeUnusedLeftJoinsOnce(query,schemaMap);return query},collectTableSourceNames=component=>{let collector=new CTETableReferenceCollector,names=new Set;for(let source of collector.collect(component)){let normalizedName=normalizeIdentifier(source.table.name);normalizedName&&names.add(normalizedName)}return names},isReferencedByOthers=(cteName,mainReferences,cteReferenceMap)=>{if(mainReferences.has(cteName))return!0;for(let[otherName,references]of cteReferenceMap)if(otherName!==cteName&&references.has(cteName))return!0;return!1},optimizeSimpleQueryCtes=query=>{let withClause=query.withClause;if(!withClause||withClause.recursive||withClause.tables.length===0)return!1;let mainReferences=collectTableSourceNames(query),cteReferenceMap=new Map;for(let table of withClause.tables){let normalizedName=normalizeIdentifier(table.aliasExpression.table.name);normalizedName&&cteReferenceMap.set(normalizedName,collectTableSourceNames(table.query))}let removableNames=[];for(let table of withClause.tables){let normalizedName=normalizeIdentifier(table.aliasExpression.table.name);if(!normalizedName)continue;let body=table.query;!(body instanceof SimpleSelectQuery)&&!(body instanceof BinarySelectQuery)||isReferencedByOthers(normalizedName,mainReferences,cteReferenceMap)||removableNames.push(normalizedName)}if(removableNames.length===0)return!1;for(let name of removableNames)query.removeCTE(name);return!0},optimizeCtesInSelectQuery=query=>{if(query instanceof SimpleSelectQuery)return optimizeSimpleQueryCtes(query);if(query instanceof BinarySelectQuery){let leftChanged=optimizeCtesInSelectQuery(query.left),rightChanged=optimizeCtesInSelectQuery(query.right);return leftChanged||rightChanged}return!1},optimizeUnusedCtesOnce=query=>optimizeCtesInSelectQuery(query),optimizeUnusedCtes=query=>(optimizeUnusedCtesOnce(query),query),optimizeUnusedCtesToFixedPoint=query=>{let changed=!0;for(;changed;)changed=optimizeUnusedCtesOnce(query);return query};var isBinaryOperator=(expression,operator)=>expression instanceof BinaryExpression&&expression.operator.value.trim().toLowerCase()===operator,unwrapSingleOuterParen=expression=>{let candidate=expression;for(;candidate instanceof ParenExpression;)candidate=candidate.expression;return candidate},collectTopLevelAndTerms=expression=>{let candidate=unwrapSingleOuterParen(expression);return isBinaryOperator(candidate,"and")?[...collectTopLevelAndTerms(candidate.left),...collectTopLevelAndTerms(candidate.right)]:[expression]},collectTopLevelOrTerms=expression=>{let candidate=unwrapSingleOuterParen(expression);return isBinaryOperator(candidate,"or")?[...collectTopLevelOrTerms(candidate.left),...collectTopLevelOrTerms(candidate.right)]:[expression]},isNullLiteral=expression=>expression instanceof LiteralValue&&expression.value===null||expression instanceof RawString&&expression.value.trim().toLowerCase()==="null",isTrueSentinel=expression=>{let candidate=unwrapSingleOuterParen(expression);return candidate instanceof LiteralValue?candidate.value===!0:isBinaryOperator(candidate,"=")?candidate.left instanceof LiteralValue&&candidate.right instanceof LiteralValue&&candidate.left.value===1&&candidate.right.value===1:!1},getGuardedParameterName=expression=>{let candidate=unwrapSingleOuterParen(expression);return!isBinaryOperator(candidate,"is")||!(candidate.left instanceof ParameterExpression)||!isNullLiteral(candidate.right)?null:candidate.left.name.value},getUniqueParameterNames=expression=>new Set(ParameterCollector.collect(expression).map(parameter=>parameter.name.value)),isSupportedMeaningfulBranch=(expression,parameterName)=>{let candidate=unwrapSingleOuterParen(expression);if(candidate instanceof ParameterExpression)return!1;let parameterNames=getUniqueParameterNames(candidate);return parameterNames.size!==1||!parameterNames.has(parameterName)?!1:!(candidate instanceof LiteralValue||candidate instanceof RawString)},isExplicitPruningTarget=(pruningParameters,parameterName)=>Object.prototype.hasOwnProperty.call(pruningParameters,parameterName),isKnownAbsentTarget=(pruningParameters,parameterName)=>{if(!isExplicitPruningTarget(pruningParameters,parameterName))return!1;let parameterValue=pruningParameters[parameterName];return parameterValue==null},shouldPruneOptionalBranch=(expression,pruningParameters)=>{let branch=getSupportedOptionalConditionBranch(expression);return branch!==null&&isKnownAbsentTarget(pruningParameters,branch.parameterName)},rebuildAndCondition=terms=>{if(terms.length===0)return null;let condition=terms[0];for(let index=1;index<terms.length;index+=1)condition=new BinaryExpression(condition,"and",terms[index]);return condition},pruneSimpleQueryWhereClause=(query,pruningParameters)=>{if(!query.whereClause)return!1;let topLevelTerms=collectTopLevelAndTerms(query.whereClause.condition),retainedTerms=[],prunedAnyBranch=!1;for(let term of topLevelTerms){if(shouldPruneOptionalBranch(term,pruningParameters)){prunedAnyBranch=!0;continue}retainedTerms.push(term)}if(!prunedAnyBranch)return!1;let cleanedTerms=retainedTerms.filter(term=>!isTrueSentinel(term)),rebuiltCondition=rebuildAndCondition(cleanedTerms);return query.whereClause=rebuiltCondition?new WhereClause(rebuiltCondition):null,!0},isSelectQueryNode=value=>value instanceof SimpleSelectQuery||value instanceof BinarySelectQuery,traverseNestedSelectQueries=(root,pruningParameters)=>{let changed=!1,visited=new WeakSet,walk=value=>{if(!(!value||typeof value!="object")&&!visited.has(value)){if(visited.add(value),value!==root&&isSelectQueryNode(value)){changed=traverseSelectQuery2(value,pruningParameters)||changed;return}if(Array.isArray(value)){value.forEach(walk);return}for(let child of Object.values(value))walk(child)}};return walk(root),changed},traverseSelectQuery2=(query,pruningParameters)=>{if(query instanceof SimpleSelectQuery){let selfChanged=pruneSimpleQueryWhereClause(query,pruningParameters),nestedChanged=traverseNestedSelectQueries(query,pruningParameters);return selfChanged||nestedChanged}if(query instanceof BinarySelectQuery){let leftChanged=traverseSelectQuery2(query.left,pruningParameters),rightChanged=traverseSelectQuery2(query.right,pruningParameters);return leftChanged||rightChanged}return!1},getSupportedOptionalConditionBranch=expression=>{let orTerms=collectTopLevelOrTerms(expression);if(orTerms.length<2)return null;let guardTerms=orTerms.map(term=>({term,parameterName:getGuardedParameterName(term)})).filter(candidate=>candidate.parameterName!==null);if(guardTerms.length!==1)return null;let[{term:guardTerm,parameterName}]=guardTerms,meaningfulTerms=orTerms.filter(term=>term!==guardTerm);return meaningfulTerms.length===0||!meaningfulTerms.every(term=>isSupportedMeaningfulBranch(term,parameterName))?null:{parameterName,kind:"expression"}},collectSupportedBranchesFromSimpleQuery=(query,branches)=>{if(!query.whereClause)return;let topLevelTerms=collectTopLevelAndTerms(query.whereClause.condition);for(let term of topLevelTerms){let branch=getSupportedOptionalConditionBranch(term);branch&&branches.push({query,parameterName:branch.parameterName,expression:term,kind:branch.kind})}},collectSupportedBranchesFromSelectQuery=(query,branches)=>{if(query instanceof SimpleSelectQuery){collectSupportedBranchesFromSimpleQuery(query,branches),traverseNestedSelectQueriesForCollection(query,branches);return}query instanceof BinarySelectQuery&&(collectSupportedBranchesFromSelectQuery(query.left,branches),collectSupportedBranchesFromSelectQuery(query.right,branches))},traverseNestedSelectQueriesForCollection=(root,branches)=>{let visited=new WeakSet,walk=value=>{if(!(!value||typeof value!="object")&&!visited.has(value)){if(visited.add(value),value!==root&&isSelectQueryNode(value)){collectSupportedBranchesFromSelectQuery(value,branches);return}if(Array.isArray(value)){value.forEach(walk);return}for(let child of Object.values(value))walk(child)}};walk(root)},pruneOptionalConditionBranches=(query,pruningParameters)=>(Object.keys(pruningParameters).length===0||traverseSelectQuery2(query,pruningParameters),query),collectSupportedOptionalConditionBranches=query=>{let branches=[];return collectSupportedBranchesFromSelectQuery(query,branches),branches},collectSupportedOptionalConditionBranchSpans=sql=>{let parsed=SelectQueryParser.parse(sql),supportedBranches=collectSupportedOptionalConditionBranches(parsed);if(supportedBranches.length===0)return[];let candidates=collectOptionalConditionSpanCandidates(sql),remainingSupportedCounts=countSupportedBranchesByKey(supportedBranches);assertUnambiguousCandidateCounts(candidates,remainingSupportedCounts);let spans=[];for(let candidate of candidates){let key=getSupportedBranchKey(candidate),remainingCount=remainingSupportedCounts.get(key)??0;remainingCount<=0||(spans.push(candidate),remainingSupportedCounts.set(key,remainingCount-1))}return assertNoMissingSupportedBranches(remainingSupportedCounts),spans},getSupportedBranchKey=branch=>`${branch.kind}:${branch.parameterName}`,countSupportedBranchesByKey=branches=>{let counts=new Map;for(let branch of branches){let key=getSupportedBranchKey(branch);counts.set(key,(counts.get(key)??0)+1)}return counts},assertUnambiguousCandidateCounts=(candidates,supportedCounts)=>{let candidateCounts=countSupportedBranchesByKey(candidates);for(let[key,supportedCount]of supportedCounts){let candidateCount=candidateCounts.get(key)??0;if(candidateCount<supportedCount)throw new Error(`Could not locate source range for supported optional condition branch '${key}'.`);if(candidateCount>supportedCount)throw new Error(`Ambiguous source ranges for supported optional condition branch '${key}'.`)}},assertNoMissingSupportedBranches=supportedCounts=>{let missingKeys=[...supportedCounts.entries()].filter(([,count])=>count>0).map(([key])=>key);if(missingKeys.length>0)throw new Error(`Could not locate source ranges for supported optional condition branches: ${missingKeys.join(", ")}.`)},collectOptionalConditionSpanCandidates=sql=>{let lexemes=new SqlTokenizer(sql).readLexemes(),candidates=[],stack=[];for(let index=0;index<lexemes.length;index+=1){let lexeme=lexemes[index];if(isOpenParen(lexeme)){stack.push(index);continue}if(!isCloseParen(lexeme))continue;let openParenIndex=stack.pop();if(openParenIndex===void 0)continue;let candidate=buildOptionalConditionSpanCandidate(sql,lexemes,openParenIndex,index);candidate&&candidates.push(candidate)}return candidates.sort((left,right)=>left.sourceRange.start-right.sourceRange.start)},buildOptionalConditionSpanCandidate=(sql,lexemes,openParenIndex,closeParenIndex)=>{let inside=lexemes.slice(openParenIndex+1,closeParenIndex),orTermRanges=splitTopLevelTermsByKeyword(inside,"or");if(orTermRanges.length<2)return null;let guardTerms=orTermRanges.map(range=>({range,parameterName:getGuardedParameterNameFromLexemes(inside.slice(range.start,range.end))})).filter(candidate=>candidate.parameterName!==null);if(guardTerms.length!==1)return null;let[{range:guardRange,parameterName}]=guardTerms,meaningfulTerms=orTermRanges.filter(range=>range!==guardRange);if(meaningfulTerms.length===0||!meaningfulTerms.every(range=>isSupportedMeaningfulBranchFromLexemes(inside.slice(range.start,range.end),parameterName)))return null;let expandedRange=expandWrappingParenRange(lexemes,openParenIndex,closeParenIndex),sourceStart=requiredPosition(lexemes[expandedRange.openParenIndex]).startPosition,sourceEnd=requiredPosition(lexemes[expandedRange.closeParenIndex]).endPosition,removalRange=getRemovalRange(sql,lexemes,expandedRange.openParenIndex,expandedRange.closeParenIndex);return{parameterName,kind:"expression",sourceRange:{start:sourceStart,end:sourceEnd,text:sql.slice(sourceStart,sourceEnd)},removalRange,openParenIndex:expandedRange.openParenIndex,closeParenIndex:expandedRange.closeParenIndex}},expandWrappingParenRange=(lexemes,openParenIndex,closeParenIndex)=>{let expandedOpenParenIndex=openParenIndex,expandedCloseParenIndex=closeParenIndex;for(;isOpenParen(lexemes[expandedOpenParenIndex-1])&&isCloseParen(lexemes[expandedCloseParenIndex+1]);)expandedOpenParenIndex-=1,expandedCloseParenIndex+=1;return{openParenIndex:expandedOpenParenIndex,closeParenIndex:expandedCloseParenIndex}},splitTopLevelTermsByKeyword=(lexemes,keyword)=>{let ranges=[],depth=0,start=0;for(let index=0;index<lexemes.length;index+=1){let lexeme=lexemes[index];if(isOpenParen(lexeme)){depth+=1;continue}if(isCloseParen(lexeme)){depth-=1;continue}depth===0&&isKeyword(lexeme,keyword)&&(ranges.push({start,end:index}),start=index+1)}return ranges.push({start,end:lexemes.length}),ranges},getGuardedParameterNameFromLexemes=lexemes=>{let compact=lexemes.filter(lexeme=>!isWrappingParen(lexeme));return compact.length!==3||!isParameter(compact[0])||!isKeyword(compact[1],"is")||!isKeyword(compact[2],"null")?null:normalizeParameterName(compact[0].value)},isSupportedMeaningfulBranchFromLexemes=(lexemes,parameterName)=>{try{let parsed=ValueParser.parseFromLexeme(lexemes,0);return parsed.newIndex!==lexemes.length?!1:isSupportedMeaningfulBranch(parsed.value,parameterName)}catch{return!1}},getRemovalRange=(sql,lexemes,openParenIndex,closeParenIndex)=>{let previous=lexemes[openParenIndex-1],next=lexemes[closeParenIndex+1],start=requiredPosition(lexemes[openParenIndex]).startPosition,end=requiredPosition(lexemes[closeParenIndex]).endPosition;return previous&&isKeyword(previous,"and")?start=requiredPosition(previous).startPosition:next&&isKeyword(next,"and")?end=requiredPosition(next).endPosition:previous&&isKeyword(previous,"where")&&(start=requiredPosition(previous).startPosition),{start,end,text:sql.slice(start,end)}},isParameter=lexeme=>(lexeme.type&256)!==0,isOpenParen=lexeme=>(lexeme.type&4)!==0,isCloseParen=lexeme=>(lexeme.type&8)!==0,isKeyword=(lexeme,keyword)=>lexeme.value.toLowerCase()===keyword,isWrappingParen=lexeme=>isOpenParen(lexeme)||isCloseParen(lexeme),normalizeParameterName=value=>value.startsWith("${")&&value.endsWith("}")?value.slice(2,-1):value.replace(/^[:@$]/,""),requiredPosition=lexeme=>{if(!lexeme.position)throw new Error(`Lexeme '${lexeme.value}' is missing source position metadata.`);return lexeme.position};var DynamicQueryBuilder=class{constructor(resolverOrOptions){typeof resolverOrOptions=="function"?this.tableColumnResolver=resolverOrOptions:resolverOrOptions&&(this.tableColumnResolver=resolverOrOptions.tableColumnResolver,this.defaultSchemaInfo=resolverOrOptions.schemaInfo)}buildQuery(sqlContent,options={}){let removedOptions=options;if("serialize"in removedOptions||"jsonb"in removedOptions)throw new Error("DynamicQueryBuilder SQL-result JSON shaping has been removed. Keep SQL results as rows and use generated AOT mappers so the executed SQL remains debuggable.");let parsedQuery;try{parsedQuery=SelectQueryParser.parse(sqlContent)}catch(error){throw new Error(`Failed to parse SQL: ${error instanceof Error?error.message:"Unknown error"}`)}let modifiedQuery=parsedQuery;if(options.filter&&Object.keys(options.filter).length>0){let{hardcodedParams,dynamicFilters}=ParameterDetector.separateFilters(modifiedQuery,options.filter);if(Object.keys(hardcodedParams).length>0&&(modifiedQuery=new SqlParameterBinder({requireAllParameters:!1}).bind(modifiedQuery,hardcodedParams)),Object.keys(dynamicFilters).length>0)throw new Error("DynamicQueryBuilder no longer injects runtime filter predicates. Use `ztd query sssql scaffold` to author optional filters, `ztd query sssql refresh` to refresh them, and `optionalConditionParameters` at runtime for pruning only.")}if(options.sort&&Object.keys(options.sort).length>0){let sortInjector=new SqlSortInjector(this.tableColumnResolver),simpleQuery=QueryBuilder.buildSimpleQuery(modifiedQuery);modifiedQuery=sortInjector.inject(simpleQuery,options.sort)}if(options.paging){let{page=1,pageSize}=options.paging;if(pageSize!==void 0){let paginationInjector=new SqlPaginationInjector,paginationOptions={page,pageSize},simpleQuery=QueryBuilder.buildSimpleQuery(modifiedQuery);modifiedQuery=paginationInjector.inject(simpleQuery,paginationOptions)}}modifiedQuery=this.applyColumnFilters(modifiedQuery,options);let optionalConditionParameters=this.resolveOptionalConditionPruningParameters(options);Object.keys(optionalConditionParameters).length>0&&(modifiedQuery=pruneOptionalConditionBranches(modifiedQuery,optionalConditionParameters));let effectiveSchemaInfo=options.schemaInfo??this.defaultSchemaInfo;return options.removeUnusedLeftJoins&&effectiveSchemaInfo?.length&&(modifiedQuery=optimizeUnusedLeftJoinsToFixedPoint(modifiedQuery,effectiveSchemaInfo)),options.removeUnusedCtes&&(modifiedQuery=optimizeUnusedCtesToFixedPoint(modifiedQuery)),modifiedQuery}resolveOptionalConditionPruningParameters(options){if(options.optionalConditionParameters)return options.optionalConditionParameters;if(!options.optionalConditionParameterStates)return{};let legacyParameters={};for(let[parameterName,state]of Object.entries(options.optionalConditionParameterStates))legacyParameters[parameterName]=state==="absent"?null:"__RAWSQL_OPTIONAL_CONDITION_PRESENT__";return legacyParameters}applyColumnFilters(query,options){let hasIncludeFilters=Array.isArray(options.includeColumns)&&options.includeColumns.length>0,hasExcludeFilters=Array.isArray(options.excludeColumns)&&options.excludeColumns.length>0;if(!hasIncludeFilters&&!hasExcludeFilters)return query;if(hasIncludeFilters&&hasExcludeFilters)throw new Error("includeColumns and excludeColumns cannot be used together.");let simpleQuery=QueryBuilder.buildSimpleQuery(query),metadata=simpleQuery.selectClause.items.map(item=>{let name=this.getSelectItemName(item);return{item,normalized:name?this.normalizeColumnIdentifier(name):null}}),availableColumns=new Set(metadata.map(entry=>entry.normalized).filter(name=>name!==null)),includeFilters=hasIncludeFilters?this.normalizeColumnList(options.includeColumns):null,excludeFilters=hasExcludeFilters?this.normalizeColumnList(options.excludeColumns):null,includeSet=includeFilters?new Set(includeFilters.map(entry=>entry.normalized)):null,excludeSet=excludeFilters?new Set(excludeFilters.map(entry=>entry.normalized)):null;if(includeFilters){let missing=includeFilters.filter(entry=>!availableColumns.has(entry.normalized));if(missing.length>0)throw new Error(`Column${missing.length===1?"":"s"} not found in SELECT clause: ${missing.map(entry=>`'${entry.original}'`).join(", ")}.`)}if(excludeFilters){let missing=excludeFilters.filter(entry=>!availableColumns.has(entry.normalized));if(missing.length>0)throw new Error(`Column${missing.length===1?"":"s"} not found in SELECT clause: ${missing.map(entry=>`'${entry.original}'`).join(", ")}.`)}let filteredItems=metadata.filter(entry=>entry.normalized?includeSet?includeSet.has(entry.normalized):excludeSet?!excludeSet.has(entry.normalized):!0:!0).map(entry=>entry.item);if(filteredItems.length===0)throw new Error("Column filtering removed every SELECT item.");return simpleQuery.selectClause.items=filteredItems,simpleQuery}normalizeColumnList(columns){return columns.map(column=>{if(typeof column!="string")throw new Error("Column filters must be strings.");let trimmed=column.trim();if(trimmed==="")throw new Error("Column filters must not be empty.");return{normalized:this.normalizeColumnIdentifier(trimmed),original:trimmed}})}normalizeColumnIdentifier(value){return value.trim().toLowerCase()}getSelectItemName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}buildFilteredQuery(sqlContent,filter){return this.buildQuery(sqlContent,{filter})}buildSortedQuery(sqlContent,sort){return this.buildQuery(sqlContent,{sort})}buildPaginatedQuery(sqlContent,paging){return this.buildQuery(sqlContent,{paging})}validateSql(sqlContent){try{return SelectQueryParser.parse(sqlContent),!0}catch(error){throw new Error(`Invalid SQL: ${error instanceof Error?error.message:"Unknown error"}`)}}};var SUPPORTED_SCALAR_OPERATORS=new Set(["=","<>","<","<=",">",">=","like","ilike"]),formatter=null,normalizeIdentifier2=value=>value.trim().toLowerCase(),normalizeSql=value=>value.replace(/\s+/g," ").trim().toLowerCase(),normalizeRewriteTokenType=lexeme=>(lexeme.type&128)!==0?128:(lexeme.type&64)!==0?64:lexeme.type,normalizeRewriteTokenValue=lexeme=>(lexeme.type&128)!==0?lexeme.value.toLowerCase():lexeme.value,tokenizeForRewritePlan=sql=>new SqlTokenizer(sql).tokenize().map(lexeme=>({type:normalizeRewriteTokenType(lexeme),value:normalizeRewriteTokenValue(lexeme)})),tokenSequencesEqual=(left,right)=>left.length!==right.length?!1:left.every((token,index)=>{let other=right[index];return other!==void 0&&token.type===other.type&&token.value===other.value}),collectCommentFragments=sql=>new SqlTokenizer(sql).tokenize().flatMap(lexeme=>lexeme.positionedComments?lexeme.positionedComments.flatMap(positioned=>positioned.comments):lexeme.comments?[...lexeme.comments]:[]),commentsPreservedInOrder=(before,after)=>{let cursor=0;for(let comment of before){let foundAt=after.indexOf(comment,cursor);if(foundAt<0)return!1;cursor=foundAt+1}return!0},countCommandToken=(tokens,value)=>tokens.filter(token=>token.type===128&&token.value===value).length,applyRewriteEdits=(sql,edits)=>[...edits].sort((left,right)=>right.start-left.start).reduce((current,edit)=>current.slice(0,edit.start)+edit.after+current.slice(edit.end),sql),getStatementEndPosition=sql=>{let end=sql.length;for(;end>0&&/\s/.test(sql[end-1]);)end--;if(end>0&&sql[end-1]===";")for(end--;end>0&&/\s/.test(sql[end-1]);)end--;return end},clauseBoundaryCommands=new Set(["group by","having","order by","limit","offset","fetch","for"]),isClauseBoundary=lexeme=>(lexeme.type&128)!==0&&clauseBoundaryCommands.has(lexeme.value.toLowerCase()),findMinimalWhereInsertPosition=sql=>{let lexemes=new SqlTokenizer(sql).tokenize(),whereIndex=lexemes.findIndex(lexeme=>(lexeme.type&128)!==0&&lexeme.value.toLowerCase()==="where"),statementEnd=getStatementEndPosition(sql);return whereIndex>=0?{position:lexemes.slice(whereIndex+1).find(isClauseBoundary)?.position?.startPosition??statementEnd,hasWhere:!0}:{position:lexemes.find(isClauseBoundary)?.position?.startPosition??statementEnd,hasWhere:!1}},findMatchingParenEnd=(sql,start)=>{let depth=0,quote=null;for(let index=start;index<sql.length;index++){let char=sql[index];if(quote){if(char===quote){if(quote==="'"&&sql[index+1]==="'"){index++;continue}quote=null}continue}if(char==="'"||char==='"'){quote=char;continue}if(char==="("&&depth++,char===")"&&(depth--,depth===0))return index+1}return-1},findOptionalBranchSpans=(sql,parameterName)=>{let spans=[],parameterNeedle=`:${parameterName.toLowerCase()}`,lowerSql=sql.toLowerCase();for(let index=0;index<sql.length;index++){if(sql[index]!=="(")continue;let end=findMatchingParenEnd(sql,index);if(end<0)break;let text=sql.slice(index,end),normalized=lowerSql.slice(index,end);normalized.includes(parameterNeedle)&&normalized.includes(" is null")&&normalized.includes(" or ")&&spans.push({start:index,end,text}),index=end-1}return spans},findBooleanOperatorBefore=(sql,start)=>{let prefix=sql.slice(0,start),match=/(\s+)(and|or)(\s*)$/i.exec(prefix);return!match||match.index===void 0?null:{start:match.index,end:start,value:match[2].toLowerCase()}},findBooleanOperatorAfter=(sql,end)=>{let suffix=sql.slice(end),match=/^(\s*)(and|or)(\s+)/i.exec(suffix);return match?{start:end,end:end+match[0].length,value:match[2].toLowerCase()}:null},findWhereBefore=(sql,position)=>{let lexemes=new SqlTokenizer(sql).tokenize(),found=null;for(let lexeme of lexemes){if((lexeme.position?.startPosition??0)>=position)break;(lexeme.type&128)!==0&&lexeme.value.toLowerCase()==="where"&&(found=lexeme)}return found?.position?{start:found.position.startPosition,end:found.position.endPosition}:null},findSourceColumnReferenceText=(sql,reference)=>{let namespace=normalizeIdentifier2(reference.getNamespace()),column=normalizeIdentifier2(reference.column.name),lexemes=new SqlTokenizer(sql).tokenize();for(let index=0;index<lexemes.length-2;index++){let first=lexemes[index],dot=lexemes[index+1],last=lexemes[index+2];if(!((first.type&64)===0||dot.value!=="."||(last.type&64)===0)&&!(normalizeIdentifier2(first.value)!==namespace||normalizeIdentifier2(last.value)!==column)&&!(!first.position||!last.position))return sql.slice(first.position.startPosition,last.position.endPosition)}return normalizeColumnReferenceText(reference)},normalizeColumnReferenceKey=reference=>`${normalizeIdentifier2(reference.getNamespace())}.${normalizeIdentifier2(reference.column.name)}`,normalizeColumnReferenceText=reference=>{let namespace=reference.getNamespace();return namespace?`${namespace}.${reference.column.name}`:reference.column.name},normalizeScalarOperator=value=>{if(!value)return"=";let normalized=value.trim().toLowerCase();if(normalized==="!=")return"<>";if(SUPPORTED_SCALAR_OPERATORS.has(normalized))return normalized;throw new Error(`Unsupported SSSQL operator '${value}'.`)},isExplicitEqualityScaffoldValue=value=>{if(value==null)return!0;if(Array.isArray(value))return!1;if(typeof value!="object")return!0;let entries=Object.entries(value).filter(([,entry])=>entry!==void 0);return entries.length===1&&entries[0]?.[0]==="="},parseQualifiedFilterName=filterName=>{let segments=filterName.split(".");if(segments.length!==2)return null;let[table,column]=segments.map(segment=>segment.trim());return!table||!column?null:{table,column}},makeParameterName=filterName=>filterName.trim().replace(/\./g,"_").replace(/[^a-zA-Z0-9_]/g,"_"),unwrapParens=expression=>{let candidate=expression;for(;candidate instanceof ParenExpression;)candidate=candidate.expression;return candidate},isBinaryOperator2=(expression,operator)=>expression instanceof BinaryExpression&&expression.operator.value.trim().toLowerCase()===operator,collectTopLevelAndTerms2=expression=>{let candidate=unwrapParens(expression);return isBinaryOperator2(candidate,"and")?[...collectTopLevelAndTerms2(candidate.left),...collectTopLevelAndTerms2(candidate.right)]:[expression]},collectTopLevelOrTerms2=expression=>{let candidate=unwrapParens(expression);return isBinaryOperator2(candidate,"or")?[...collectTopLevelOrTerms2(candidate.left),...collectTopLevelOrTerms2(candidate.right)]:[expression]},getGuardedParameterName2=expression=>{let candidate=unwrapParens(expression);if(!isBinaryOperator2(candidate,"is")||!(candidate.left instanceof ParameterExpression))return null;let right=unwrapParens(candidate.right);return right instanceof LiteralValue&&right.value===null||right instanceof RawString&&right.value.trim().toLowerCase()==="null"?candidate.left.name.value:null},buildOptionalScalarBranch=(column,parameterName,operator)=>{let guard=new BinaryExpression(new ParameterExpression(parameterName),"is",new LiteralValue(null)),predicate=new BinaryExpression(new ColumnReference(column.getNamespace()||null,column.column.name),operator,new ParameterExpression(parameterName));return new ParenExpression(new BinaryExpression(guard,"or",predicate))},buildOptionalExistsBranch=(parameterName,subquery,kind)=>{let guard=new BinaryExpression(new ParameterExpression(parameterName),"is",new LiteralValue(null)),existsExpression=new UnaryExpression("exists",new InlineQuery(subquery)),predicate=kind==="exists"?existsExpression:new UnaryExpression("not",existsExpression);return new ParenExpression(new BinaryExpression(guard,"or",predicate))},rebuildWhereWithoutTerm=(query,termToRemove)=>{if(!query.whereClause)return;let terms=collectTopLevelAndTerms2(query.whereClause.condition).filter(term=>term!==termToRemove);if(terms.length===0){query.whereClause=null;return}let rebuilt=terms[0];for(let index=1;index<terms.length;index+=1)rebuilt=new BinaryExpression(rebuilt,"and",terms[index]);query.whereClause=new WhereClause(rebuilt)},formatSqlComponent=component=>(formatter??=new SqlFormatter,formatter.format(component).formattedSql),enforceSubqueryConstraints=sql=>{if(!sql.trim())throw new Error("SSSQL EXISTS/NOT EXISTS scaffold query must not be empty.");if(sql.includes(";"))throw new Error("SSSQL EXISTS/NOT EXISTS scaffold query must not contain semicolons or multiple statements.");if(/\blateral\b/i.test(sql))throw new Error("LATERAL is not supported in SSSQL EXISTS/NOT EXISTS scaffold.")},substituteAnchorPlaceholders=(sql,formattedColumns)=>{let usedIndexes=new Set,replaced=sql.replace(/\$c(\d+)/g,(_,indexDigits)=>{let index=Number(indexDigits);if(!Number.isInteger(index))throw new Error(`Invalid placeholder '$c${indexDigits}' in SSSQL scaffold query.`);if(index<0||index>=formattedColumns.length)throw new Error(`Placeholder '$c${index}' references a missing SSSQL scaffold anchor column.`);return usedIndexes.add(index),formattedColumns[index]});if(formattedColumns.length===0)return replaced;for(let index=0;index<formattedColumns.length;index+=1)if(!usedIndexes.has(index))throw new Error(`Missing placeholder '$c${index}' for SSSQL scaffold anchor column.`);return replaced},getScalarBranchDetails=(expression,parameterName)=>{let meaningfulTerms=collectTopLevelOrTerms2(expression).filter(term=>getGuardedParameterName2(term)!==parameterName);if(meaningfulTerms.length!==1)return null;let predicate=unwrapParens(meaningfulTerms[0]);if(!(predicate instanceof BinaryExpression))return null;let left=unwrapParens(predicate.left),right=unwrapParens(predicate.right);if(left instanceof ColumnReference&&right instanceof ParameterExpression&&right.name.value===parameterName)try{return{operator:normalizeScalarOperator(predicate.operator.value),target:normalizeColumnReferenceText(left)}}catch{return null}if(right instanceof ColumnReference&&left instanceof ParameterExpression&&left.name.value===parameterName)try{return{operator:normalizeScalarOperator(predicate.operator.value),target:normalizeColumnReferenceText(right)}}catch{return null}return null},hasSelectQuery=value=>typeof value=="object"&&value!==null&&"selectQuery"in value,collectColumnReferencesDeep=value=>{let references=[],visited=new WeakSet,walk=candidate=>{if(!(!candidate||typeof candidate!="object")){if(candidate instanceof ColumnReference){references.push(candidate);return}if(!visited.has(candidate)){if(visited.add(candidate),Array.isArray(candidate)){for(let item of candidate)walk(item);return}for(let child of Object.values(candidate))walk(child)}}};return walk(value),references},getExistsBranchKind=(expression,parameterName)=>{let meaningfulTerms=collectTopLevelOrTerms2(expression).filter(term=>getGuardedParameterName2(term)!==parameterName);if(meaningfulTerms.length!==1)return null;let predicate=unwrapParens(meaningfulTerms[0]),isInlineQueryValue=value=>value instanceof InlineQuery||hasSelectQuery(value);if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="exists")return isInlineQueryValue(unwrapParens(predicate.expression))?"exists":null;if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not exists")return isInlineQueryValue(unwrapParens(predicate.expression))?"not-exists":null;if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not"&&unwrapParens(predicate.expression)instanceof UnaryExpression){let nested=unwrapParens(predicate.expression);if(nested.operator.value.trim().toLowerCase()==="exists"&&isInlineQueryValue(unwrapParens(nested.expression)))return"not-exists"}return null},getExistsPredicateDetails=(expression,parameterName)=>{let meaningfulTerms=collectTopLevelOrTerms2(expression).filter(term=>getGuardedParameterName2(term)!==parameterName);if(meaningfulTerms.length!==1)return null;let predicate=unwrapParens(meaningfulTerms[0]),isInlineQueryValue=value=>value instanceof InlineQuery||hasSelectQuery(value);if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="exists"){let candidate=unwrapParens(predicate.expression);return isInlineQueryValue(candidate)?{kind:"exists",subquery:candidate.selectQuery}:null}if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not exists"){let candidate=unwrapParens(predicate.expression);return isInlineQueryValue(candidate)?{kind:"not-exists",subquery:candidate.selectQuery}:null}if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not"&&unwrapParens(predicate.expression)instanceof UnaryExpression){let nested=unwrapParens(predicate.expression),candidate=unwrapParens(nested.expression);if(nested.operator.value.trim().toLowerCase()==="exists"&&isInlineQueryValue(candidate))return{kind:"not-exists",subquery:candidate.selectQuery}}return null},getBranchInfo=branch=>{let scalar=getScalarBranchDetails(branch.expression,branch.parameterName);if(scalar)return{parameterName:branch.parameterName,kind:"scalar",operator:scalar.operator,target:scalar.target,query:branch.query,expression:branch.expression,sql:formatSqlComponent(branch.expression)};let existsKind=getExistsBranchKind(branch.expression,branch.parameterName);return existsKind?{parameterName:branch.parameterName,kind:existsKind,query:branch.query,expression:branch.expression,sql:formatSqlComponent(branch.expression)}:{parameterName:branch.parameterName,kind:"expression",query:branch.query,expression:branch.expression,sql:formatSqlComponent(branch.expression)}},SSSQLFilterBuilder=class{constructor(tableColumnResolver){this.tableColumnResolver=tableColumnResolver;this.finder=new UpstreamSelectQueryFinder(this.tableColumnResolver)}list(query){let parsed=this.parseQuery(query);return collectSupportedOptionalConditionBranches(parsed).map(getBranchInfo)}planScaffold(query,filters){if(typeof query=="string"){let entries=Object.entries(filters);if(entries.length===1){let[filterName,filterValue]=entries[0];if(isExplicitEqualityScaffoldValue(filterValue))try{return this.planScalarInsert(query,{target:filterName,parameterName:makeParameterName(filterName),operator:"="})}catch{}}}return this.planRewrite(query,parsed=>this.scaffold(parsed,filters))}dryRunScaffold(query,filters){return this.planScaffold(query,filters)}planScaffoldBranch(query,spec){if(typeof query=="string"&&(spec.kind==="exists"||spec.kind==="not-exists"))try{return this.planExistsInsert(query,spec)}catch{}if(typeof query=="string"&&spec.kind!=="exists"&&spec.kind!=="not-exists")try{return this.planScalarInsert(query,spec)}catch{}return this.planRewrite(query,parsed=>this.scaffoldBranch(parsed,spec))}dryRunScaffoldBranch(query,spec){return this.planScaffoldBranch(query,spec)}planRefresh(query,filters){return this.planRewrite(query,parsed=>this.refresh(parsed,filters))}dryRunRefresh(query,filters){return this.planRefresh(query,filters)}planRemove(query,spec){if(typeof query=="string")try{return this.planBranchRemoval(query,spec)}catch{}return this.planRewrite(query,parsed=>this.remove(parsed,spec))}dryRunRemove(query,spec){return this.planRemove(query,spec)}planRemoveAll(query){return this.planRewrite(query,parsed=>this.removeAll(parsed))}dryRunRemoveAll(query){return this.planRemoveAll(query)}scaffold(query,filters){let parsed=this.parseQuery(query);for(let[filterName,filterValue]of Object.entries(filters)){if(!isExplicitEqualityScaffoldValue(filterValue))throw new Error(`SSSQL scaffold only supports equality filters in v1. Use structured scaffold or refresh for pre-authored branches: '${filterName}'.`);this.scaffoldBranch(parsed,{target:filterName,parameterName:makeParameterName(filterName),operator:"="})}return parsed}scaffoldBranch(query,spec){let parsed=this.parseQuery(query);return spec.kind==="exists"||spec.kind==="not-exists"?(this.scaffoldExistsBranch(parsed,spec),parsed):(this.scaffoldScalarBranch(parsed,spec),parsed)}refresh(query,filters){let parsed=this.parseQuery(query);for(let[filterName,filterValue]of Object.entries(filters)){let parameterName=filterName,target=null,matches=collectSupportedOptionalConditionBranches(parsed).filter(branch=>branch.parameterName===parameterName);if(matches.length===0&&(target=this.resolveTarget(parsed,filterName),parameterName=target.parameterName,matches=collectSupportedOptionalConditionBranches(parsed).filter(branch=>branch.parameterName===parameterName)),matches.length===0){if(target||(target=this.resolveTarget(parsed,filterName),parameterName=target.parameterName),!isExplicitEqualityScaffoldValue(filterValue))throw new Error(`No existing SSSQL branch was found for '${filterName}', and v1 scaffold only supports equality filters.`);this.scaffoldScalarBranch(parsed,{target:filterName,parameterName:target.parameterName,operator:"="});continue}if(matches.length>1)throw new Error(`Multiple SSSQL branches matched parameter ':${parameterName}'. Refresh is ambiguous.`);let[match]=matches;if(!match)continue;let correlatedPlan=this.buildCorrelatedRefreshPlan(parsed,match);if(correlatedPlan){if(correlatedPlan.target.query===match.query)continue;this.rebaseMovedBranchByAlias(match.expression,correlatedPlan.sourceAlias,correlatedPlan.target.column),rebuildWhereWithoutTerm(match.query,match.expression),correlatedPlan.target.query.appendWhere(match.expression);continue}target||(target=this.resolveTarget(parsed,filterName)),match.query!==target.query&&(this.rebaseMovedBranch(match.expression,match.query,target.column),rebuildWhereWithoutTerm(match.query,match.expression),target.query.appendWhere(match.expression))}return parsed}remove(query,spec){let parsed=this.parseQuery(query),matches=this.findMatchingBranchInfos(parsed,spec);if(matches.length===0)return parsed;if(matches.length>1)throw new Error(`Multiple SSSQL branches matched parameter ':${spec.parameterName}'. Remove is ambiguous.`);let[match]=matches;return match&&rebuildWhereWithoutTerm(match.query,match.expression),parsed}removeAll(query){let parsed=this.parseQuery(query),matches=this.list(parsed);for(let match of matches)rebuildWhereWithoutTerm(match.query,match.expression);return parsed}parseQuery(query){return typeof query=="string"?SelectQueryParser.parse(query):query}planScalarInsert(sourceSql,spec){let parsed=SelectQueryParser.parse(sourceSql),target=this.resolveTarget(parsed,spec.target);if(target.query!==parsed)return this.planRewrite(sourceSql,query=>this.scaffoldBranch(query,spec));let parameterName=spec.parameterName?.trim()||target.parameterName,operator=normalizeScalarOperator(spec.operator),targetColumnText=findSourceColumnReferenceText(sourceSql,target.column),branchSql=`(:${parameterName} is null or ${targetColumnText} ${operator} :${parameterName})`,normalizedBranch=normalizeSql(branchSql);return this.list(parsed).find(existing=>existing.query===target.query&&normalizeSql(existing.sql)===normalizedBranch)?this.buildPlanFromEdits(sourceSql,[],[],[]):this.buildMinimalInsertPlan(sourceSql,branchSql,{branchKind:"scalar",parameterName,column:targetColumnText})}planExistsInsert(sourceSql,spec){let parameterName=spec.parameterName.trim();if(!parameterName)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires parameterName.");if(spec.anchorColumns.length===0)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires at least one anchorColumn.");let parsed=SelectQueryParser.parse(sourceSql),anchorTargets=spec.anchorColumns.map(anchorColumn=>this.resolveTarget(parsed,anchorColumn)),targetQueries=[...new Set(anchorTargets.map(target=>target.query))];if(targetQueries.length!==1)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold anchor columns must resolve within one query scope.");let targetQuery=targetQueries[0];if(targetQuery!==parsed)return this.planRewrite(sourceSql,query=>this.scaffoldBranch(query,spec));let sourceColumns=anchorTargets.map(target=>findSourceColumnReferenceText(sourceSql,target.column)),substitutedSql=substituteAnchorPlaceholders(spec.query,sourceColumns).trim();enforceSubqueryConstraints(substitutedSql);let subquery=SelectQueryParser.parse(substitutedSql),parameterNames=new Set(ParameterCollector.collect(subquery).map(parameter=>parameter.name.value));if(parameterNames.size!==1||!parameterNames.has(parameterName))throw new Error(`SSSQL ${spec.kind.toUpperCase()} scaffold query must reference only parameter ':${parameterName}'.`);let branchSql=`(:${parameterName} is null or ${spec.kind==="not-exists"?"not exists":"exists"} (${substitutedSql}))`;return this.list(parsed).find(existing=>existing.query===targetQuery&&normalizeSql(existing.sql)===normalizeSql(branchSql))?this.buildPlanFromEdits(sourceSql,[],[],[]):this.buildMinimalInsertPlan(sourceSql,branchSql,{branchKind:spec.kind,parameterName,column:sourceColumns.join(", ")})}buildMinimalInsertPlan(sourceSql,branchSql,target){let insertPosition=findMinimalWhereInsertPosition(sourceSql),prefix=`${insertPosition.position===0||!/\s/.test(sourceSql[insertPosition.position-1])?" ":""}${insertPosition.hasWhere?"and":"where"} `,suffix=insertPosition.position<getStatementEndPosition(sourceSql)?" ":"",branchLabel=target.branchKind==="scalar"?"scalar":target.branchKind,edit={start:insertPosition.position,end:insertPosition.position,before:"",after:`${prefix}${branchSql}${suffix}`,kind:"insert",reason:insertPosition.hasWhere?`Append SSSQL ${branchLabel} branch to the existing WHERE clause.`:`Create a WHERE clause for the SSSQL ${branchLabel} branch.`,target},changedRegions=[{kind:"target-branch",start:edit.start+prefix.length,end:edit.start+edit.after.length-suffix.length,message:`Inserted SSSQL ${branchLabel} optional branch.`}];return insertPosition.hasWhere?changedRegions.unshift({kind:"boolean-operator",start:edit.start,end:edit.start+prefix.length,message:`Inserted AND before the SSSQL ${branchLabel} branch.`}):changedRegions.unshift({kind:"where-keyword",start:edit.start,end:edit.start+prefix.length,message:`Inserted WHERE before the SSSQL ${branchLabel} branch.`}),this.buildPlanFromEdits(sourceSql,[edit],changedRegions,[])}planBranchRemoval(sourceSql,spec){let parsed=SelectQueryParser.parse(sourceSql),matches=this.findMatchingBranchInfos(parsed,spec);if(matches.length>1)return this.buildPlanFromEdits(sourceSql,[],[],[],[{code:"REWRITE_FAILED",message:"SSSQL remove planning found multiple matching branches.",detail:`Multiple SSSQL branches matched parameter ':${spec.parameterName}'. Remove is ambiguous.`}]);if(matches.length===0)return this.buildPlanFromEdits(sourceSql,[],[],[]);let branchSpans=findOptionalBranchSpans(sourceSql,spec.parameterName);if(branchSpans.length>1)return this.planRewrite(sourceSql,query=>this.remove(query,spec));let span=branchSpans[0];if(!span)return this.planRewrite(sourceSql,query=>this.remove(query,spec));let beforeOperator=findBooleanOperatorBefore(sourceSql,span.start),afterOperator=findBooleanOperatorAfter(sourceSql,span.end),where=findWhereBefore(sourceSql,span.start),start=span.start,end=span.end,changedRegions=[{kind:"target-branch",start:span.start,end:span.end,message:"Removed SSSQL optional branch."}];if(beforeOperator)start=beforeOperator.start,changedRegions.unshift({kind:"boolean-operator",start:beforeOperator.start,end:beforeOperator.end,message:`Removed adjacent ${beforeOperator.value.toUpperCase()} before the SSSQL branch.`});else if(afterOperator)end=afterOperator.end,changedRegions.push({kind:"boolean-operator",start:afterOperator.start,end:afterOperator.end,message:`Removed adjacent ${afterOperator.value.toUpperCase()} after the SSSQL branch.`});else if(where){for(start=where.start;end<sourceSql.length&&/\s/.test(sourceSql[end]);)end++;changedRegions.unshift({kind:"where-keyword",start:where.start,end:where.end,message:"Removed WHERE because the SSSQL branch was the only condition."})}let edit={start,end,before:sourceSql.slice(start,end),after:"",kind:"delete",reason:"Remove the targeted SSSQL optional branch from the source SQL.",target:{branchKind:matches[0].kind,parameterName:matches[0].parameterName,column:matches[0].target}};return this.buildPlanFromEdits(sourceSql,[edit],changedRegions,[])}buildPlanFromEdits(sourceSql,edits,changedRegions,warnings,errors=[]){let plannedSql=errors.length===0?applyRewriteEdits(sourceSql,edits):void 0,beforeTokens=tokenizeForRewritePlan(sourceSql),beforeComments=collectCommentFragments(sourceSql),afterTokens=plannedSql!==void 0?tokenizeForRewritePlan(plannedSql):[],afterComments=plannedSql!==void 0?collectCommentFragments(plannedSql):[],commentsPreserved=plannedSql!==void 0?commentsPreservedInOrder(beforeComments,afterComments):!1,changedOnlyTargetBranches=errors.length===0&&changedRegions.every(region=>region.kind==="target-branch"||region.kind==="where-keyword"||region.kind==="boolean-operator"||region.kind==="parentheses")&&commentsPreserved,planWarnings=[...warnings];if(plannedSql!==void 0&&applyRewriteEdits(sourceSql,edits)!==plannedSql&&(errors=[...errors,{code:"APPLY_PLAN_MISMATCH",message:"Applying SSSQL rewrite plan edits did not reproduce the planned SQL."}]),plannedSql!==void 0)try{SelectQueryParser.parse(plannedSql)}catch(error){errors=[...errors,{code:"PARSE_AFTER_FAILED",message:"The SQL produced by SSSQL rewrite planning could not be parsed.",detail:error instanceof Error?error.message:error}]}return plannedSql!==void 0&&!commentsPreserved&&planWarnings.push({code:"COMMENTS_NOT_PRESERVED",message:"One or more input SQL comments are missing or reordered after the SSSQL rewrite."}),{ok:errors.length===0,requiresFullReformat:!1,edits,sql:plannedSql,safety:{tokenCountBefore:beforeTokens.length,tokenCountAfter:afterTokens.length,tokenSequencePreserved:plannedSql!==void 0?tokenSequencesEqual(beforeTokens,afterTokens):!1,commentsPreserved,changedOnlyTargetBranches,changedRegions},warnings:planWarnings,errors}}planRewrite(query,rewrite){let warnings=[],errors=[],sourceSql=typeof query=="string"?query:formatSqlComponent(query);typeof query!="string"&&warnings.push({code:"SOURCE_SQL_UNAVAILABLE",message:"SSSQL rewrite planning received an AST, so the source SQL had to be formatter-generated before analysis."});let beforeTokens=[],beforeComments=[];try{beforeTokens=tokenizeForRewritePlan(sourceSql),beforeComments=collectCommentFragments(sourceSql)}catch(error){errors.push({code:"TOKENIZE_BEFORE_FAILED",message:"Could not tokenize the input SQL before SSSQL rewrite planning.",detail:error instanceof Error?error.message:error})}let plannedSql,afterTokens=[],afterComments=[];if(errors.length===0)try{let parsed=SelectQueryParser.parse(sourceSql),rewritten=rewrite(parsed);plannedSql=formatSqlComponent(rewritten)}catch(error){errors.push({code:"REWRITE_FAILED",message:"SSSQL rewrite planning could not produce a rewritten query.",detail:error instanceof Error?error.message:error})}if(plannedSql!==void 0){try{SelectQueryParser.parse(plannedSql)}catch(error){errors.push({code:"PARSE_AFTER_FAILED",message:"The SQL produced by SSSQL rewrite planning could not be parsed.",detail:error instanceof Error?error.message:error})}try{afterTokens=tokenizeForRewritePlan(plannedSql),afterComments=collectCommentFragments(plannedSql)}catch(error){errors.push({code:"TOKENIZE_AFTER_FAILED",message:"Could not tokenize the SQL produced by SSSQL rewrite planning.",detail:error instanceof Error?error.message:error})}}let edits=plannedSql!==void 0&&plannedSql!==sourceSql?[{start:0,end:sourceSql.length,before:sourceSql,after:plannedSql,kind:"replace",reason:"Current SSSQL rewrite planning is backed by AST rewrite plus formatter output."}]:[],changedRegions=edits.length>0?[{kind:"formatter-rewrite",start:0,end:sourceSql.length,message:"The conservative SSSQL rewrite plan requires replacing formatter output for the full SQL text."}]:[],requiresFullReformat=edits.length>0,tokenSequencePreserved=plannedSql!==void 0?tokenSequencesEqual(beforeTokens,afterTokens):!1,commentsPreserved=plannedSql!==void 0?commentsPreservedInOrder(beforeComments,afterComments):!1,changedOnlyTargetBranches=edits.length===0;return requiresFullReformat&&warnings.push({code:"FULL_REFORMAT_REQUIRED",message:"The current SSSQL rewrite plan can only represent the change as a full SQL replacement."}),plannedSql!==void 0&&!tokenSequencePreserved&&warnings.push({code:"TOKEN_SEQUENCE_CHANGED",message:"The SQL token sequence changes after the SSSQL rewrite. The conservative planner cannot prove that only target branches changed.",detail:{tokenCountBefore:beforeTokens.length,tokenCountAfter:afterTokens.length}}),plannedSql!==void 0&&!commentsPreserved&&warnings.push({code:"COMMENTS_NOT_PRESERVED",message:"One or more input SQL comments are missing or reordered after the SSSQL rewrite."}),plannedSql!==void 0&&countCommandToken(afterTokens,"as")>countCommandToken(beforeTokens,"as")&&warnings.push({code:"OPTIONAL_ALIAS_AS_ADDED",message:"The rewrite output contains more AS tokens than the input, which may indicate formatter-added aliases."}),plannedSql!==void 0&&!sourceSql.includes('"')&&plannedSql.includes('"')&&warnings.push({code:"IDENTIFIER_QUOTES_ADDED",message:"The rewrite output contains double-quoted identifiers that were not present in the input SQL."}),{ok:errors.length===0,requiresFullReformat,edits,sql:plannedSql,safety:{tokenCountBefore:beforeTokens.length,tokenCountAfter:afterTokens.length,tokenSequencePreserved,commentsPreserved,changedOnlyTargetBranches,changedRegions},warnings,errors}}findMatchingBranchInfos(root,spec){let normalizedOperator=spec.operator?normalizeScalarOperator(spec.operator):void 0,normalizedTarget=spec.target?normalizeIdentifier2(spec.target):void 0;return this.list(root).filter(branch=>!(branch.parameterName!==spec.parameterName||spec.kind&&branch.kind!==spec.kind||normalizedOperator&&branch.operator!==normalizedOperator||normalizedTarget&&(!branch.target||normalizeIdentifier2(branch.target)!==normalizedTarget)))}scaffoldScalarBranch(root,spec){let target=this.resolveTarget(root,spec.target),parameterName=spec.parameterName?.trim()||target.parameterName,operator=normalizeScalarOperator(spec.operator),branch=buildOptionalScalarBranch(target.column,parameterName,operator),branchSql=normalizeSql(formatSqlComponent(branch));this.list(root).find(existing=>existing.query===target.query&&normalizeSql(existing.sql)===branchSql)||target.query.appendWhere(branch)}scaffoldExistsBranch(root,spec){let parameterName=spec.parameterName.trim();if(!parameterName)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires parameterName.");if(spec.anchorColumns.length===0)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires at least one anchorColumn.");let anchorTargets=spec.anchorColumns.map(anchorColumn=>this.resolveTarget(root,anchorColumn)),targetQueries=[...new Set(anchorTargets.map(target=>target.query))];if(targetQueries.length!==1)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold anchor columns must resolve within one query scope.");let targetQuery=targetQueries[0],formattedColumns=anchorTargets.map(target=>formatSqlComponent(target.column)),substitutedSql=substituteAnchorPlaceholders(spec.query,formattedColumns).trim();enforceSubqueryConstraints(substitutedSql);let subquery=SelectQueryParser.parse(substitutedSql),parameterNames=new Set(ParameterCollector.collect(subquery).map(parameter=>parameter.name.value));if(parameterNames.size!==1||!parameterNames.has(parameterName))throw new Error(`SSSQL ${spec.kind.toUpperCase()} scaffold query must reference only parameter ':${parameterName}'.`);let branch=buildOptionalExistsBranch(parameterName,subquery,spec.kind),branchSql=normalizeSql(formatSqlComponent(branch));this.list(root).find(existing=>existing.query===targetQuery&&normalizeSql(existing.sql)===branchSql)||targetQuery.appendWhere(branch)}resolveTarget(root,filterName){let qualified=parseQualifiedFilterName(filterName),lookupColumn=qualified?.column??filterName.trim(),matches=[...new Set(this.finder.find(root,lookupColumn))].map(query=>this.resolveTargetInQuery(query,filterName,qualified)).filter(target=>target!==null);if(matches.length===0)throw new Error(`Could not resolve SSSQL filter target '${filterName}' in the current query graph.`);if(matches.length>1)throw new Error(`SSSQL filter target '${filterName}' is ambiguous across multiple query scopes.`);return matches[0]}resolveTargetInQuery(query,filterName,qualified){return qualified?this.resolveQualifiedTarget(query,qualified):this.resolveUnqualifiedTarget(query,filterName)}resolveQualifiedTarget(query,filterName){let alias=this.findAliasForTable(query,filterName.table);if(!alias)return null;let matches=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query).filter(entry=>entry.value instanceof ColumnReference).filter(entry=>normalizeColumnReferenceKey(entry.value)===`${normalizeIdentifier2(alias)}.${normalizeIdentifier2(filterName.column)}`);if(matches.length===0)return null;if(matches.length>1)throw new Error(`SSSQL scaffold target '${filterName.table}.${filterName.column}' resolved to multiple columns.`);return{query,column:matches[0].value,parameterName:makeParameterName(`${filterName.table}.${filterName.column}`)}}resolveUnqualifiedTarget(query,filterName){let matches=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query).filter(entry=>entry.value instanceof ColumnReference).filter(entry=>normalizeIdentifier2(entry.name)===normalizeIdentifier2(filterName));if(matches.length===0)return null;if(matches.length>1)throw new Error(`SSSQL scaffold target '${filterName}' is ambiguous. Use a qualified table.column reference.`);return{query,column:matches[0].value,parameterName:makeParameterName(filterName)}}findAliasForTable(query,tableName){let normalizedTable=normalizeIdentifier2(tableName),matchingAliases=(query.fromClause?.getSources()??[]).map(source=>this.resolveAliasForSource(source,normalizedTable)).filter(alias=>alias!==null);if(matchingAliases.length===0)return null;if(matchingAliases.length>1)throw new Error(`SSSQL scaffold target table '${tableName}' is ambiguous in the selected query scope.`);return matchingAliases[0]}resolveAliasForSource(source,normalizedTable){if(!(source.datasource instanceof TableSource))return null;let sourceName=normalizeIdentifier2(source.datasource.getSourceName()),shortName=normalizeIdentifier2(source.datasource.table.name);return sourceName!==normalizedTable&&shortName!==normalizedTable?null:source.getAliasName()??source.datasource.table.name}buildCorrelatedRefreshPlan(root,branch){let details=getExistsPredicateDetails(branch.expression,branch.parameterName);if(!details)return null;let sourceAliases=this.collectSourceAliases(branch.query),candidatesByKey=new Map;for(let reference of new ColumnReferenceCollector().collect(details.subquery)){let namespace=normalizeIdentifier2(reference.getNamespace());if(!namespace||!sourceAliases.has(namespace))continue;let column=normalizeIdentifier2(reference.column.name),key=`${namespace}.${column}`;candidatesByKey.has(key)||candidatesByKey.set(key,{namespace,column})}let candidates=[...candidatesByKey.values()];if(candidates.length===0)throw new Error(`SSSQL refresh could not infer a correlated anchor for ':${branch.parameterName}'.`);if(candidates.length>1){let listed=candidates.map(candidate=>`${candidate.namespace}.${candidate.column}`).join(", ");throw new Error(`SSSQL refresh found multiple correlated anchor candidates for ':${branch.parameterName}' (${listed}).`)}let[anchor]=candidates;if(!anchor)throw new Error(`SSSQL refresh could not infer a correlated anchor for ':${branch.parameterName}'.`);return{target:this.resolveCorrelatedAnchorTarget(root,branch.query,anchor,branch.parameterName),sourceAlias:anchor.namespace}}collectSourceAliases(query){let aliases=new Set;for(let source of query.fromClause?.getSources()??[]){let sourceAlias=this.getSourceAlias(source);sourceAlias&&aliases.add(sourceAlias)}return aliases}resolveCorrelatedAnchorTarget(root,sourceQuery,anchor,parameterName){let sourceExpression=this.findSourceExpressionByAlias(sourceQuery,anchor.namespace,parameterName),upstreamQuery=this.resolveSourceExpressionToUpstreamQuery(root,sourceExpression,parameterName);return upstreamQuery?this.resolveAnchorTargetInQuery(upstreamQuery,anchor,parameterName):{query:sourceQuery,column:new ColumnReference(anchor.namespace,anchor.column),parameterName}}findSourceExpressionByAlias(query,alias,parameterName){let matches=(query.fromClause?.getSources()??[]).filter(source=>this.getSourceAlias(source)===alias);if(matches.length===0)throw new Error(`SSSQL refresh could not resolve correlated alias '${alias}' for ':${parameterName}'.`);if(matches.length>1)throw new Error(`SSSQL refresh found multiple correlated sources for alias '${alias}' and ':${parameterName}'.`);return matches[0]}resolveSourceExpressionToUpstreamQuery(root,source,parameterName){if(source.datasource instanceof SubQuerySource){if(source.datasource.query instanceof SimpleSelectQuery)return source.datasource.query;throw new Error(`SSSQL refresh requires a simple query anchor for ':${parameterName}'.`)}if(!(source.datasource instanceof TableSource))return null;let cteName=normalizeIdentifier2(source.datasource.table.name),cteMatches=new CTECollector().collect(root).filter(cte2=>normalizeIdentifier2(cte2.getSourceAliasName())===cteName);if(cteMatches.length===0)return null;if(cteMatches.length>1)throw new Error(`SSSQL refresh found multiple CTE anchors for ':${parameterName}' (${source.datasource.table.name}).`);let[cte]=cteMatches;if(!cte)return null;let cteQuery=cte.query;if(!(cteQuery instanceof SimpleSelectQuery))throw new Error(`SSSQL refresh requires a simple CTE anchor for ':${parameterName}'.`);return cteQuery}resolveAnchorTargetInQuery(query,anchor,parameterName){let matches=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query).filter(entry=>entry.value instanceof ColumnReference).filter(entry=>normalizeIdentifier2(entry.name)===anchor.column);if(matches.length===0)throw new Error(`SSSQL refresh could not resolve correlated anchor column '${anchor.column}' for ':${parameterName}'.`);if(matches.length>1)throw new Error(`SSSQL refresh found multiple correlated anchor columns '${anchor.column}' for ':${parameterName}'.`);return{query,column:matches[0].value,parameterName}}getSourceAlias(source){let explicitAlias=source.getAliasName();return explicitAlias?normalizeIdentifier2(explicitAlias):source.datasource instanceof TableSource?normalizeIdentifier2(source.datasource.table.name):null}rebaseMovedBranch(expression,sourceQuery,targetColumn){let targetNamespace=targetColumn.qualifiedName.namespaces?targetColumn.qualifiedName.namespaces.map(namespace=>namespace.name):null,targetColumnName=normalizeIdentifier2(targetColumn.column.name),sourceAliases=new Set(collectColumnReferencesDeep(expression).filter(reference=>normalizeIdentifier2(reference.column.name)===targetColumnName).map(reference=>normalizeIdentifier2(reference.getNamespace())).filter(namespace=>namespace.length>0));if(sourceAliases.size===0)return;if(sourceAliases.size>1){let aliases=[...sourceAliases].join(", ");throw new Error(`SSSQL refresh cannot safely rebase '${targetColumn.column.name}' across multiple aliases (${aliases}).`)}let[sourceAlias]=[...sourceAliases];if(new Set((sourceQuery.fromClause?.getSources()??[]).map(source=>source.getAliasName()).filter(alias=>typeof alias=="string").map(alias=>normalizeIdentifier2(alias))).has(sourceAlias))for(let reference of collectColumnReferencesDeep(expression))normalizeIdentifier2(reference.getNamespace())===sourceAlias&&(reference.qualifiedName.namespaces=targetNamespace?.map(namespace=>new IdentifierString(namespace))??null)}rebaseMovedBranchByAlias(expression,sourceAlias,targetColumn){let normalizedSourceAlias=normalizeIdentifier2(sourceAlias);if(!normalizedSourceAlias)return;let targetNamespace=targetColumn.qualifiedName.namespaces?targetColumn.qualifiedName.namespaces.map(namespace=>namespace.name):null;for(let reference of collectColumnReferencesDeep(expression))normalizeIdentifier2(reference.getNamespace())===normalizedSourceAlias&&(reference.qualifiedName.namespaces=targetNamespace?.map(namespace=>new IdentifierString(namespace))??null)}},scaffoldSssqlQuery=(sqlContent,filters)=>({query:new SSSQLFilterBuilder().scaffold(sqlContent,filters)}),refreshSssqlQuery=(sqlContent,filters)=>({query:new SSSQLFilterBuilder().refresh(sqlContent,filters)});var BaseDataFlowNode=class{constructor(id,label,type,shape,details){this.id=id;this.label=label;this.type=type;this.shape=shape;this.details=details}},DataSourceNode=class _DataSourceNode extends BaseDataFlowNode{constructor(id,label,type){super(id,label,type,type==="subquery"?"hexagon":"cylinder");this.annotations=new Set}addAnnotation(annotation){this.annotations.add(annotation)}hasAnnotation(annotation){return this.annotations.has(annotation)}getMermaidRepresentation(){return this.shape==="hexagon"?`${this.id}{{${this.label}}}`:`${this.id}[(${this.label})]`}static createTable(tableName){return new _DataSourceNode(`table_${tableName}`,tableName,"table")}static createCTE(cteName){return new _DataSourceNode(`cte_${cteName}`,`CTE:${cteName}`,"cte")}static createSubquery(alias){return new _DataSourceNode(`subquery_${alias}`,`SubQuery:${alias}`,"subquery")}},ProcessNode=class _ProcessNode extends BaseDataFlowNode{constructor(id,operation,context=""){let nodeId=context?`${context}_${operation.toLowerCase().replace(/\s+/g,"_")}`:operation.toLowerCase().replace(/\s+/g,"_");super(nodeId,operation,"process","hexagon")}getMermaidRepresentation(){return`${this.id}{{${this.label}}}`}static createWhere(context){return new _ProcessNode(`${context}_where`,"WHERE",context)}static createGroupBy(context){return new _ProcessNode(`${context}_group_by`,"GROUP BY",context)}static createHaving(context){return new _ProcessNode(`${context}_having`,"HAVING",context)}static createSelect(context){return new _ProcessNode(`${context}_select`,"SELECT",context)}static createOrderBy(context){return new _ProcessNode(`${context}_order_by`,"ORDER BY",context)}static createLimit(context,hasOffset=!1){let label=hasOffset?"LIMIT/OFFSET":"LIMIT";return new _ProcessNode(`${context}_limit`,label,context)}},OperationNode=class _OperationNode extends BaseDataFlowNode{constructor(id,operation,shape="diamond"){super(id,operation,"operation",shape)}getMermaidRepresentation(){switch(this.shape){case"rounded":return`${this.id}(${this.label})`;case"rectangle":return`${this.id}[${this.label}]`;case"hexagon":return`${this.id}{{${this.label}}}`;case"stadium":return`${this.id}([${this.label}])`;case"diamond":default:return`${this.id}{${this.label}}`}}static createJoin(joinId,joinType){let label,normalizedType=joinType.trim().toLowerCase();return normalizedType==="join"?label="INNER JOIN":normalizedType.endsWith(" join")?label=normalizedType.toUpperCase():label=normalizedType.toUpperCase()+" JOIN",new _OperationNode(`join_${joinId}`,label,"rectangle")}static createUnion(unionId,unionType="UNION ALL"){return new _OperationNode(`${unionType.toLowerCase().replace(/\s+/g,"_")}_${unionId}`,unionType.toUpperCase(),"rectangle")}static createSetOperation(operationId,operation){let normalizedOp=operation.toUpperCase(),id=`${normalizedOp.toLowerCase().replace(/\s+/g,"_")}_${operationId}`;return new _OperationNode(id,normalizedOp,"rectangle")}},OutputNode=class extends BaseDataFlowNode{constructor(context="main"){let label=context==="main"?"Final Result":`${context} Result`;super(`${context}_output`,label,"output","stadium")}getMermaidRepresentation(){return`${this.id}([${this.label}])`}};var DataFlowConnection=class _DataFlowConnection{constructor(from,to,label){this.from=from;this.to=to;this.label=label}getMermaidRepresentation(){let arrow=this.label?` -->|${this.label}| `:" --> ";return`${this.from}${arrow}${this.to}`}static create(from,to,label){return new _DataFlowConnection(from,to,label)}static createWithNullability(from,to,isNullable){let label=isNullable?"NULLABLE":"NOT NULL";return new _DataFlowConnection(from,to,label)}},DataFlowEdgeCollection=class{constructor(){this.edges=[];this.connectionSet=new Set}add(edge){let key=`${edge.from}->${edge.to}`;this.connectionSet.has(key)||(this.edges.push(edge),this.connectionSet.add(key))}addConnection(from,to,label){this.add(DataFlowConnection.create(from,to,label))}addJoinConnection(from,to,isNullable){this.add(DataFlowConnection.createWithNullability(from,to,isNullable))}hasConnection(from,to){return this.connectionSet.has(`${from}->${to}`)}getAll(){return[...this.edges]}getMermaidRepresentation(){return this.edges.map(edge=>edge.getMermaidRepresentation()).join(`
49
+ `);for(let i=1;i<lines.length;i++){let line=lines[i],leadingSpaces=line.match(/^ */)?.[0].length||0,leadingTabs=line.match(/^\t*/)?.[0].length||0;(leadingSpaces>0||leadingTabs>0)&&(indentLines++,totalIndentSize+=leadingSpaces+leadingTabs*4,spaceCount+=leadingSpaces,tabCount+=leadingTabs)}}lexeme.inlineComments&&(totalComments+=lexeme.inlineComments.length)}let indentationStyle="none";return spaceCount>0&&tabCount>0?indentationStyle="mixed":spaceCount>0?indentationStyle="spaces":tabCount>0&&(indentationStyle="tabs"),{totalWhitespace,totalComments,indentationStyle,averageIndentSize:indentLines>0?totalIndentSize/indentLines:0}}validateFormattingLexemes(lexemes){let issues=[];for(let i=0;i<lexemes.length;i++){let lexeme=lexemes[i];lexeme.position||issues.push(`Lexeme ${i} missing position information`),lexeme.followingWhitespace===void 0&&issues.push(`Lexeme ${i} missing followingWhitespace property`),lexeme.inlineComments===void 0&&issues.push(`Lexeme ${i} missing inlineComments property`),lexeme.position&&lexeme.position.startPosition>=lexeme.position.endPosition&&issues.push(`Lexeme ${i} has invalid position range`)}return{isValid:issues.length===0,issues}}};var SelectResultSelectConverter=class{static toSelectQuery(query,options){let fixtureTables=options?.fixtureTables??[];if(fixtureTables.length===0)return query;let sources=new TableSourceCollector(!1).collect(query),referencedTables=new Set;sources.forEach(s=>referencedTables.add(s.getSourceName().toLowerCase()));let neededFixtures=fixtureTables.filter(f=>referencedTables.has(f.tableName.toLowerCase()));if(neededFixtures.length===0)return query;let fixtureCtes=FixtureCteBuilder.buildFixtures(neededFixtures);return query instanceof SimpleSelectQuery&&(query.withClause?query.withClause.tables=[...fixtureCtes,...query.withClause.tables]:query.appendWith(fixtureCtes)),query}};var SimulatedSelectConverter=class{static convert(ast,options){if(ast instanceof InsertQuery)return InsertResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof UpdateQuery)return UpdateResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof DeleteQuery)return DeleteResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof MergeQuery)return MergeResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof SimpleSelectQuery||ast instanceof BinarySelectQuery||ast instanceof ValuesQuery)return SelectResultSelectConverter.toSelectQuery(ast,options);if(ast instanceof CreateTableQuery){if(ast.isTemporary&&ast.asSelectQuery){let processedSelect=SelectResultSelectConverter.toSelectQuery(ast.asSelectQuery,options);return ast.asSelectQuery=processedSelect,ast}return null}return null}};var DDLGeneralizer=class{static generalize(ast){let result=[];for(let component of ast)if(component instanceof CreateTableQuery){let{createTable,alterTables}=this.splitCreateTable(component);result.push(createTable),result.push(...alterTables)}else result.push(component);return result}static splitCreateTable(query){let newColumns=[],alterTables=[],tableQualifiedName=new QualifiedName(query.namespaces||[],query.tableName.name);for(let col of query.columns){let newConstraints=[];for(let constraint of col.constraints)if(["primary-key","unique","references","check"].includes(constraint.kind)){let tableConstraint=this.columnToTableConstraint(col.name,constraint);alterTables.push(new AlterTableStatement({table:tableQualifiedName,actions:[new AlterTableAddConstraint({constraint:tableConstraint})]}))}else newConstraints.push(constraint);newColumns.push(new TableColumnDefinition({name:col.name,dataType:col.dataType,constraints:newConstraints}))}if(query.tableConstraints)for(let constraint of query.tableConstraints)alterTables.push(new AlterTableStatement({table:tableQualifiedName,actions:[new AlterTableAddConstraint({constraint})]}));return{createTable:new CreateTableQuery({tableName:query.tableName.name,namespaces:query.namespaces,columns:newColumns,ifNotExists:query.ifNotExists,isTemporary:query.isTemporary,tableOptions:query.tableOptions,asSelectQuery:query.asSelectQuery,withDataOption:query.withDataOption,tableConstraints:[]}),alterTables}}static columnToTableConstraint(columnName,constraint){let baseParams={constraintName:constraint.constraintName,deferrable:constraint.reference?.deferrable,initially:constraint.reference?.initially};switch(constraint.kind){case"primary-key":return new TableConstraintDefinition({kind:"primary-key",columns:[columnName],...baseParams});case"unique":return new TableConstraintDefinition({kind:"unique",columns:[columnName],...baseParams});case"references":return new TableConstraintDefinition({kind:"foreign-key",columns:[columnName],reference:constraint.reference,...baseParams});case"check":return new TableConstraintDefinition({kind:"check",checkExpression:constraint.checkExpression,...baseParams});default:throw new Error(`Unsupported constraint kind for generalization: ${constraint.kind}`)}}};var DDLDiffGenerator=class{static generateDiff(currentSql,expectedSql,options={}){let currentAst=this.parseAndGeneralize(currentSql),expectedAst=this.parseAndGeneralize(expectedSql),currentSchema=this.buildSchema(currentAst),expectedSchema=this.buildSchema(expectedAst),diffAsts=[];for(let[tableName,expectedTable]of expectedSchema.tables){let currentTable=currentSchema.tables.get(tableName);if(currentTable)this.compareColumns(currentTable,expectedTable,diffAsts,options),this.compareConstraints(currentTable,expectedTable,diffAsts,options),this.compareIndexes(currentTable,expectedTable,diffAsts,options);else{let columns=Array.from(expectedTable.columns.values()).map(c=>c.definition),tableNameStr=expectedTable.qualifiedName.name instanceof RawString?expectedTable.qualifiedName.name.value:expectedTable.qualifiedName.name.name,namespaces=expectedTable.qualifiedName.namespaces?expectedTable.qualifiedName.namespaces.map(ns=>ns.name):null,createTable=new CreateTableQuery({tableName:tableNameStr,namespaces,columns});diffAsts.push(createTable);for(let constraint of expectedTable.constraints)diffAsts.push(new AlterTableStatement({table:expectedTable.qualifiedName,actions:[new AlterTableAddConstraint({constraint:constraint.definition})]}));for(let index of expectedTable.indexes)diffAsts.push(index.definition)}}if(options.dropTables)for(let[tableName,currentTable]of currentSchema.tables)expectedSchema.tables.has(tableName)||diffAsts.push(new DropTableStatement({tables:[currentTable.qualifiedName],ifExists:!1}));let formatter2=new SqlFormatter(options.formatOptions||{keywordCase:"upper"});return diffAsts.map(ast=>formatter2.format(ast).formattedSql+";")}static parseAndGeneralize(sql){let split=MultiQuerySplitter.split(sql),asts=[];for(let q of split.queries)if(!q.isEmpty)try{let ast=SqlParser.parse(q.sql);asts.push(ast)}catch(e){console.warn("Failed to parse SQL for diff:",q.sql,e)}return DDLGeneralizer.generalize(asts)}static buildSchema(asts){let tables=new Map,formatter2=new SqlFormatter({keywordCase:"none"});for(let ast of asts)if(ast instanceof CreateTableQuery){let qName=new QualifiedName(ast.namespaces||[],ast.tableName),key=this.getQualifiedNameKey(qName),tableModel={name:key,qualifiedName:qName,columns:new Map,constraints:[],indexes:[]};for(let col of ast.columns)tableModel.columns.set(col.name.name,{name:col.name.name,definition:col});tables.set(key,tableModel)}else if(ast instanceof AlterTableStatement){let key=this.getQualifiedNameKey(ast.table),tableModel=tables.get(key);if(tableModel)for(let action of ast.actions)if(action instanceof AlterTableAddConstraint){let formatted=formatter2.format(action.constraint).formattedSql;tableModel.constraints.push({name:action.constraint.constraintName?.name,kind:action.constraint.kind,definition:action.constraint,formatted})}else action instanceof AlterTableAddColumn&&tableModel.columns.set(action.column.name.name,{name:action.column.name.name,definition:action.column})}else if(ast instanceof CreateIndexStatement){let key=this.getQualifiedNameKey(ast.tableName),tableModel=tables.get(key);if(tableModel){let formatted=formatter2.format(ast).formattedSql;tableModel.indexes.push({name:ast.indexName.toString(),definition:ast,formatted})}}return{tables}}static compareColumns(current,expected,diffs,options){for(let[name,col]of expected.columns)current.columns.has(name)||diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableAddColumn({column:col.definition})]}));if(options.dropColumns)for(let[name,col]of current.columns)expected.columns.has(name)||diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableDropColumn({columnName:col.definition.name})]}))}static compareConstraints(current,expected,diffs,options){let formatter2=new SqlFormatter({keywordCase:"none"}),getConstraintSignature=c=>options.checkConstraintNames?c.kind==="primary-key"?c.formatted.replace(/^constraint\s+("[^"]+"|[^\s]+)\s+/i,"").trim():c.name||c.formatted:c.formatted.replace(/^constraint\s+("[^"]+"|[^\s]+)\s+/i,"").trim(),currentSignatures=new Set(current.constraints.map(getConstraintSignature));for(let expectedC of expected.constraints){let sig=getConstraintSignature(expectedC);currentSignatures.has(sig)||diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableAddConstraint({constraint:expectedC.definition})]}))}if(options.dropConstraints){let expectedSignatures=new Set(expected.constraints.map(getConstraintSignature));for(let currentC of current.constraints){let sig=getConstraintSignature(currentC);expectedSignatures.has(sig)||(currentC.name?diffs.push(new AlterTableStatement({table:expected.qualifiedName,actions:[new AlterTableDropConstraint({constraintName:new IdentifierString(currentC.name)})]})):console.warn("Cannot drop unnamed constraint:",currentC.formatted))}}}static compareIndexes(current,expected,diffs,options){let getIndexSignature=idx=>{if(options.checkConstraintNames)return idx.name;let def=idx.definition,parts=[];parts.push(def.tableName.toString()),def.unique&&parts.push("UNIQUE"),def.usingMethod&&parts.push(`USING:${def.usingMethod.toString()}`);let columnSigs=def.columns.map(col=>{let expr=col.expression.toString(),sort=col.sortOrder||"",nulls=col.nullsOrder||"";return`${expr}${sort}${nulls}`});return parts.push(`COLS:${columnSigs.join(",")}`),def.include&&def.include.length>0&&parts.push(`INCLUDE:${def.include.map(i=>i.toString()).join(",")}`),def.where&&parts.push(`WHERE:${def.where.toString()}`),parts.join("|")},currentSignatures=new Set(current.indexes.map(getIndexSignature));for(let expectedIdx of expected.indexes){let sig=getIndexSignature(expectedIdx);currentSignatures.has(sig)||diffs.push(expectedIdx.definition)}if(options.checkConstraintNames||options.dropIndexes){let expectedSignatures=new Set(expected.indexes.map(getIndexSignature));for(let currentIdx of current.indexes){let sig=getIndexSignature(currentIdx);expectedSignatures.has(sig)||diffs.push(new DropIndexStatement({indexNames:[currentIdx.definition.indexName],ifExists:!1}))}}}static getQualifiedNameKey(qName){return qName.toString()}};var ParameterDetector=class{static extractParameterNames(query){return ParameterCollector.collect(query).map(p=>p.name.value)}static hasParameter(query,parameterName){return this.extractParameterNames(query).includes(parameterName)}static separateFilters(query,filter){let hardcodedParamNames=this.extractParameterNames(query),hardcodedParams={},dynamicFilters={};for(let[key,value]of Object.entries(filter))hardcodedParamNames.includes(key)?hardcodedParams[key]=value:dynamicFilters[key]=value;return{hardcodedParams,dynamicFilters}}};var FilterableItem=class{constructor(name,type,tableName){this.name=name;this.type=type;this.tableName=tableName}},FilterableItemCollector=class{constructor(tableColumnResolver,options){this.tableColumnResolver=tableColumnResolver,this.options={qualified:!1,upstream:!0,...options}}collect(query){let items=[],columnItems=this.collectColumns(query);items.push(...columnItems);let parameterItems=this.collectParameters(query);return items.push(...parameterItems),this.removeDuplicates(items)}collectColumns(query){let items=[];try{let columns=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:this.options.upstream}).collect(query);for(let column of columns){let tableName,realTableName;if(column.value&&typeof column.value.getNamespace=="function"){let namespace=column.value.getNamespace();namespace&&namespace.trim()!==""&&(tableName=namespace,this.options.qualified&&(realTableName=this.getRealTableName(query,namespace)))}tableName||(tableName=this.inferTableNameFromQuery(query),tableName&&this.options.qualified&&(realTableName=tableName));let columnName=column.name;this.options.qualified&&(realTableName||tableName)&&(columnName=`${realTableName||tableName}.${column.name}`),items.push(new FilterableItem(columnName,"column",tableName))}}catch(error){console.warn("Failed to collect columns with SelectableColumnCollector, using fallback:",error);try{let schemas=new SchemaCollector(this.tableColumnResolver,!0).collect(query);for(let schema of schemas)for(let columnName of schema.columns){let finalColumnName=columnName;this.options.qualified&&(finalColumnName=`${schema.name}.${columnName}`),items.push(new FilterableItem(finalColumnName,"column",schema.name))}}catch(fallbackError){console.warn("Failed to collect columns with both approaches:",error,fallbackError)}}return items}inferTableNameFromQuery(query){if(query instanceof SimpleSelectQuery&&query.fromClause&&query.fromClause.source){let datasource=query.fromClause.source.datasource;if(datasource&&typeof datasource.table=="object"){let table=datasource.table;if(table&&typeof table.name=="string")return table.name}}}getRealTableName(query,aliasOrName){try{let simpleQuery=query.type==="WITH"?query.toSimpleQuery():query;if(simpleQuery instanceof SimpleSelectQuery&&simpleQuery.fromClause){if(simpleQuery.fromClause.source?.datasource){let mainSource=simpleQuery.fromClause.source,realName=this.extractRealTableName(mainSource,aliasOrName);if(realName)return realName}let fromClause=simpleQuery.fromClause;if(fromClause.joinClauses&&Array.isArray(fromClause.joinClauses)){for(let joinClause of fromClause.joinClauses)if(joinClause.source?.datasource){let realName=this.extractRealTableName(joinClause.source,aliasOrName);if(realName)return realName}}}}catch(error){console.warn("Error resolving real table name:",error)}return aliasOrName}extractRealTableName(source,aliasOrName){try{let datasource=source.datasource;if(!datasource)return;let alias=source.alias||source.aliasExpression?.table?.name,realTableName=datasource.table?.name;if(alias===aliasOrName&&realTableName||!alias&&realTableName===aliasOrName)return realTableName}catch{}}collectParameters(query){let items=[];try{let parameterNames=ParameterDetector.extractParameterNames(query);for(let paramName of parameterNames)items.push(new FilterableItem(paramName,"parameter"))}catch(error){console.warn("Failed to collect parameters:",error)}return items}removeDuplicates(items){let seen=new Set,result=[];for(let item of items){let key=`${item.type}:${item.name}:${item.tableName||"none"}`;seen.has(key)||(seen.add(key),result.push(item))}return result.sort((a,b)=>{if(a.type!==b.type)return a.type==="column"?-1:1;if(a.type==="column"){let tableA=a.tableName||"",tableB=b.tableName||"";if(tableA!==tableB)return tableA.localeCompare(tableB)}return a.name.localeCompare(b.name)})}};var SqlSortInjector=class{constructor(tableColumnResolver){this.tableColumnResolver=tableColumnResolver}static removeOrderBy(query){if(typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for ORDER BY removal");return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:null,windowClause:query.windowClause,limitClause:query.limitClause,offsetClause:query.offsetClause,fetchClause:query.fetchClause,forClause:query.forClause})}inject(query,sortConditions){if(typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for sorting");let availableColumns=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query);for(let columnName of Object.keys(sortConditions))if(!availableColumns.find(item=>item.name===columnName))throw new Error(`Column or alias '${columnName}' not found in current query`);let newOrderByItems=[];for(let[columnName,condition]of Object.entries(sortConditions)){let columnEntry=availableColumns.find(item=>item.name===columnName);if(!columnEntry)continue;let columnRef=columnEntry.value;this.validateSortCondition(columnName,condition);let sortDirection;condition.desc?sortDirection="desc":sortDirection="asc";let nullsPosition=null;condition.nullsFirst?nullsPosition="first":condition.nullsLast&&(nullsPosition="last");let orderByItem=new OrderByItem(columnRef,sortDirection,nullsPosition);newOrderByItems.push(orderByItem)}let finalOrderByItems=[];query.orderByClause?finalOrderByItems=[...query.orderByClause.order,...newOrderByItems]:finalOrderByItems=newOrderByItems;let newOrderByClause=finalOrderByItems.length>0?new OrderByClause(finalOrderByItems):null;return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:newOrderByClause,windowClause:query.windowClause,limitClause:query.limitClause,offsetClause:query.offsetClause,fetchClause:query.fetchClause,forClause:query.forClause})}validateSortCondition(columnName,condition){if(condition.asc&&condition.desc)throw new Error(`Conflicting sort directions for column '${columnName}': both asc and desc specified`);if(condition.nullsFirst&&condition.nullsLast)throw new Error(`Conflicting nulls positions for column '${columnName}': both nullsFirst and nullsLast specified`);if(!condition.asc&&!condition.desc&&!condition.nullsFirst&&!condition.nullsLast)throw new Error(`Empty sort condition for column '${columnName}': at least one sort option must be specified`)}};var SqlPaginationInjector=class{inject(query,pagination){if(this.validatePaginationOptions(pagination),typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for pagination");if(query.limitClause||query.offsetClause)throw new Error("Query already contains LIMIT or OFFSET clause. Use removePagination() first if you want to override existing pagination.");let offset=(pagination.page-1)*pagination.pageSize,limitClause=new LimitClause(new ParameterExpression("paging_limit",pagination.pageSize)),offsetClause=new OffsetClause(new ParameterExpression("paging_offset",offset));return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:query.orderByClause,windowClause:query.windowClause,limitClause,offsetClause,fetchClause:query.fetchClause,forClause:query.forClause})}static removePagination(query){if(typeof query=="string"&&(query=SelectQueryParser.parse(query)),!(query instanceof SimpleSelectQuery))throw new Error("Complex queries are not supported for pagination removal");return new SimpleSelectQuery({withClause:query.withClause,selectClause:query.selectClause,fromClause:query.fromClause,whereClause:query.whereClause,groupByClause:query.groupByClause,havingClause:query.havingClause,orderByClause:query.orderByClause,windowClause:query.windowClause,limitClause:null,offsetClause:null,fetchClause:query.fetchClause,forClause:query.forClause})}validatePaginationOptions(pagination){if(!pagination)throw new Error("Pagination options are required");if(typeof pagination.page!="number"||pagination.page<1)throw new Error("Page number must be a positive integer (1 or greater)");if(typeof pagination.pageSize!="number"||pagination.pageSize<1)throw new Error("Page size must be a positive integer (1 or greater)");if(pagination.pageSize>1e3)throw new Error("Page size cannot exceed 1000 items")}};var SqlParameterBinder=class{constructor(options={}){this.options={requireAllParameters:!0,...options}}bind(query,parameterValues){let modifiedQuery=query,existingParams=ParameterDetector.extractParameterNames(modifiedQuery);if(this.options.requireAllParameters){let missingParams=existingParams.filter(paramName=>!(paramName in parameterValues)||parameterValues[paramName]===void 0);if(missingParams.length>0)throw new Error(`Missing values for required parameters: ${missingParams.join(", ")}`)}for(let[paramName,value]of Object.entries(parameterValues))if(existingParams.includes(paramName))try{ParameterHelper.set(modifiedQuery,paramName,value)}catch(error){throw new Error(`Failed to bind parameter '${paramName}': ${error instanceof Error?error.message:"Unknown error"}`)}return modifiedQuery}bindToSimpleQuery(query,parameterValues){return this.bind(query,parameterValues)}};var NAMESPACE_SEPARATOR="|",normalizeIdentifier=input=>{let value=input?.trim()??"";return value===""?"":value.toLowerCase()},normalizeColumnSetKey=columns=>columns.map(column=>normalizeIdentifier(column)).filter(Boolean).sort().join(NAMESPACE_SEPARATOR),buildSchemaMap=schemaInfo=>{let map=new Map;for(let table of schemaInfo){let normalizedName=normalizeIdentifier(table.name);if(!normalizedName)continue;let columnSet=new Set(table.columns.map(normalizeIdentifier).filter(Boolean)),uniqueSetKeys=new Set;for(let uniqueKey of table.uniqueKeys){let normalizedKey=normalizeColumnSetKey(uniqueKey);normalizedKey&&uniqueSetKeys.add(normalizedKey)}columnSet.size===0&&uniqueSetKeys.size===0||map.set(normalizedName,{columnSet,uniqueSetKeys})}return map},collectReferenceMetadata=query=>{let collector=new ColumnReferenceCollector,namespaceCounts=new Map,unqualifiedColumns=new Set;for(let ref of collector.collect(query)){let namespace=normalizeIdentifier(ref.getNamespace());if(namespace)namespaceCounts.set(namespace,(namespaceCounts.get(namespace)??0)+1);else{let column=normalizeIdentifier(ref.column.name);column&&unqualifiedColumns.add(column)}}let joinConditionCounts=new Map;if(query.fromClause?.joins)for(let join of query.fromClause.joins){let counts=new Map;if(join.condition&&join.condition instanceof JoinOnClause){let joinCollector=new ColumnReferenceCollector;for(let ref of joinCollector.collect(join.condition.condition)){let namespace=normalizeIdentifier(ref.getNamespace());namespace&&counts.set(namespace,(counts.get(namespace)??0)+1)}}joinConditionCounts.set(join,counts)}return{namespaceCounts,unqualifiedColumns,joinConditionCounts}},isLeftJoin=join=>join.joinType.value.toLowerCase().includes("left"),getJoinIdentifiers=join=>{let identifiers=new Set,alias=normalizeIdentifier(join.source.getAliasName());if(alias&&identifiers.add(alias),join.source.datasource instanceof TableSource){let rawName=join.source.datasource.getSourceName();rawName&&identifiers.add(normalizeIdentifier(rawName));let shortName=normalizeIdentifier(join.source.datasource.table.name);shortName&&identifiers.add(shortName)}return[...identifiers]},hasExternalReferences=(identifiers,metadata,join)=>{let local=metadata.joinConditionCounts.get(join)??new Map;for(let identifier of identifiers){let total=metadata.namespaceCounts.get(identifier)??0,localCount=local.get(identifier)??0;if(total-localCount>0)return!0}return!1},getJoinColumnInfo=(join,identifiers)=>{if(!(join.condition instanceof JoinOnClause))return null;let expression=join.condition.condition;if(!(expression instanceof BinaryExpression)||expression.operator.value.trim().toLowerCase()!=="=")return null;let resolveColumn=component=>component instanceof ColumnReference?component:null,leftRef=resolveColumn(expression.left),rightRef=resolveColumn(expression.right);if(!leftRef||!rightRef)return null;let normalizedLeftNamespace=normalizeIdentifier(leftRef.getNamespace()),normalizedRightNamespace=normalizeIdentifier(rightRef.getNamespace());return identifiers.has(normalizedLeftNamespace)?normalizeIdentifier(leftRef.column.name):identifiers.has(normalizedRightNamespace)?normalizeIdentifier(rightRef.column.name):null},shouldRemoveJoin=(join,schemaMap,metadata)=>{if(!isLeftJoin(join)||join.lateral||!(join.source.datasource instanceof TableSource))return!1;let candidates=[normalizeIdentifier(join.source.datasource.getSourceName()),normalizeIdentifier(join.source.datasource.table.name)].filter(Boolean),tableInfo;for(let candidate of candidates){let info=schemaMap.get(candidate);if(info){tableInfo=info;break}}if(!tableInfo)return!1;let identifiers=new Set(getJoinIdentifiers(join));if(identifiers.size===0||hasExternalReferences([...identifiers],metadata,join))return!1;let joinColumn=getJoinColumnInfo(join,identifiers);if(!joinColumn||metadata.unqualifiedColumns.has(joinColumn)||tableInfo.columnSet.size>0&&!tableInfo.columnSet.has(joinColumn))return!1;let uniqueKey=normalizeColumnSetKey([joinColumn]);return!!tableInfo.uniqueSetKeys.has(uniqueKey)},optimizeSimpleQuery=(query,schemaMap)=>{if(!query.fromClause?.joins?.length)return!1;let metadata=collectReferenceMetadata(query),retainedJoins=[],removed=!1;for(let join of query.fromClause.joins){if(shouldRemoveJoin(join,schemaMap,metadata)){removed=!0;continue}retainedJoins.push(join)}return query.fromClause.joins=retainedJoins.length>0?retainedJoins:null,removed},traverseSelectQuery=(query,schemaMap)=>{if(query instanceof SimpleSelectQuery)return optimizeSimpleQuery(query,schemaMap);if(query instanceof BinarySelectQuery){let leftChanged=traverseSelectQuery(query.left,schemaMap),rightChanged=traverseSelectQuery(query.right,schemaMap);return leftChanged||rightChanged}return!1},optimizeUnusedLeftJoinsOnce=(query,schemaMap)=>schemaMap.size===0?!1:traverseSelectQuery(query,schemaMap),optimizeUnusedLeftJoins=(query,schemaInfo)=>(optimizeUnusedLeftJoinsOnce(query,buildSchemaMap(schemaInfo)),query),optimizeUnusedLeftJoinsToFixedPoint=(query,schemaInfo)=>{let schemaMap=buildSchemaMap(schemaInfo),changed=!0;for(;changed;)changed=optimizeUnusedLeftJoinsOnce(query,schemaMap);return query},collectTableSourceNames=component=>{let collector=new CTETableReferenceCollector,names=new Set;for(let source of collector.collect(component)){let normalizedName=normalizeIdentifier(source.table.name);normalizedName&&names.add(normalizedName)}return names},isReferencedByOthers=(cteName,mainReferences,cteReferenceMap)=>{if(mainReferences.has(cteName))return!0;for(let[otherName,references]of cteReferenceMap)if(otherName!==cteName&&references.has(cteName))return!0;return!1},optimizeSimpleQueryCtes=query=>{let withClause=query.withClause;if(!withClause||withClause.recursive||withClause.tables.length===0)return!1;let mainReferences=collectTableSourceNames(query),cteReferenceMap=new Map;for(let table of withClause.tables){let normalizedName=normalizeIdentifier(table.aliasExpression.table.name);normalizedName&&cteReferenceMap.set(normalizedName,collectTableSourceNames(table.query))}let removableNames=[];for(let table of withClause.tables){let normalizedName=normalizeIdentifier(table.aliasExpression.table.name);if(!normalizedName)continue;let body=table.query;!(body instanceof SimpleSelectQuery)&&!(body instanceof BinarySelectQuery)||isReferencedByOthers(normalizedName,mainReferences,cteReferenceMap)||removableNames.push(normalizedName)}if(removableNames.length===0)return!1;for(let name of removableNames)query.removeCTE(name);return!0},optimizeCtesInSelectQuery=query=>{if(query instanceof SimpleSelectQuery)return optimizeSimpleQueryCtes(query);if(query instanceof BinarySelectQuery){let leftChanged=optimizeCtesInSelectQuery(query.left),rightChanged=optimizeCtesInSelectQuery(query.right);return leftChanged||rightChanged}return!1},optimizeUnusedCtesOnce=query=>optimizeCtesInSelectQuery(query),optimizeUnusedCtes=query=>(optimizeUnusedCtesOnce(query),query),optimizeUnusedCtesToFixedPoint=query=>{let changed=!0;for(;changed;)changed=optimizeUnusedCtesOnce(query);return query};var isBinaryOperator=(expression,operator)=>expression instanceof BinaryExpression&&expression.operator.value.trim().toLowerCase()===operator,unwrapSingleOuterParen=expression=>{let candidate=expression;for(;candidate instanceof ParenExpression;)candidate=candidate.expression;return candidate},unwrapOptionalGuardParameter=expression=>{let candidate=unwrapSingleOuterParen(expression);for(;candidate instanceof CastExpression;)candidate=unwrapSingleOuterParen(candidate.input);if(candidate instanceof FunctionCall&&getFunctionCallName(candidate)==="cast"&&candidate.argument){let argument=unwrapSingleOuterParen(candidate.argument);if(isBinaryOperator(argument,"as"))return unwrapOptionalGuardParameter(argument.left)}return candidate},getFunctionCallName=expression=>{let name=expression.qualifiedName.name;return"value"in name?name.value.toLowerCase():name.name.toLowerCase()},collectTopLevelAndTerms=expression=>{let candidate=unwrapSingleOuterParen(expression);return isBinaryOperator(candidate,"and")?[...collectTopLevelAndTerms(candidate.left),...collectTopLevelAndTerms(candidate.right)]:[expression]},collectTopLevelOrTerms=expression=>{let candidate=unwrapSingleOuterParen(expression);return isBinaryOperator(candidate,"or")?[...collectTopLevelOrTerms(candidate.left),...collectTopLevelOrTerms(candidate.right)]:[expression]},isNullLiteral=expression=>expression instanceof LiteralValue&&expression.value===null||expression instanceof RawString&&expression.value.trim().toLowerCase()==="null",isTrueSentinel=expression=>{let candidate=unwrapSingleOuterParen(expression);return candidate instanceof LiteralValue?candidate.value===!0:isBinaryOperator(candidate,"=")?candidate.left instanceof LiteralValue&&candidate.right instanceof LiteralValue&&candidate.left.value===1&&candidate.right.value===1:!1},getGuardedParameterName=expression=>{let candidate=unwrapSingleOuterParen(expression);if(!isBinaryOperator(candidate,"is"))return null;let left=unwrapOptionalGuardParameter(candidate.left);return!(left instanceof ParameterExpression)||!isNullLiteral(candidate.right)?null:left.name.value},getUniqueParameterNames=expression=>new Set(ParameterCollector.collect(expression).map(parameter=>parameter.name.value)),isSupportedMeaningfulBranch=(expression,parameterName)=>{let candidate=unwrapSingleOuterParen(expression);if(candidate instanceof ParameterExpression)return!1;let parameterNames=getUniqueParameterNames(candidate);return parameterNames.size!==1||!parameterNames.has(parameterName)?!1:!(candidate instanceof LiteralValue||candidate instanceof RawString)},isExplicitPruningTarget=(pruningParameters,parameterName)=>Object.prototype.hasOwnProperty.call(pruningParameters,parameterName),isKnownAbsentTarget=(pruningParameters,parameterName)=>{if(!isExplicitPruningTarget(pruningParameters,parameterName))return!1;let parameterValue=pruningParameters[parameterName];return parameterValue==null},shouldPruneOptionalBranch=(expression,pruningParameters)=>{let branch=getSupportedOptionalConditionBranch(expression);return branch!==null&&isKnownAbsentTarget(pruningParameters,branch.parameterName)},rebuildAndCondition=terms=>{if(terms.length===0)return null;let condition=terms[0];for(let index=1;index<terms.length;index+=1)condition=new BinaryExpression(condition,"and",terms[index]);return condition},pruneSimpleQueryWhereClause=(query,pruningParameters)=>{if(!query.whereClause)return!1;let topLevelTerms=collectTopLevelAndTerms(query.whereClause.condition),retainedTerms=[],prunedAnyBranch=!1;for(let term of topLevelTerms){if(shouldPruneOptionalBranch(term,pruningParameters)){prunedAnyBranch=!0;continue}retainedTerms.push(term)}if(!prunedAnyBranch)return!1;let cleanedTerms=retainedTerms.filter(term=>!isTrueSentinel(term)),rebuiltCondition=rebuildAndCondition(cleanedTerms);return query.whereClause=rebuiltCondition?new WhereClause(rebuiltCondition):null,!0},isSelectQueryNode=value=>value instanceof SimpleSelectQuery||value instanceof BinarySelectQuery,traverseNestedSelectQueries=(root,pruningParameters)=>{let changed=!1,visited=new WeakSet,walk=value=>{if(!(!value||typeof value!="object")&&!visited.has(value)){if(visited.add(value),value!==root&&isSelectQueryNode(value)){changed=traverseSelectQuery2(value,pruningParameters)||changed;return}if(Array.isArray(value)){value.forEach(walk);return}for(let child of Object.values(value))walk(child)}};return walk(root),changed},traverseSelectQuery2=(query,pruningParameters)=>{if(query instanceof SimpleSelectQuery){let selfChanged=pruneSimpleQueryWhereClause(query,pruningParameters),nestedChanged=traverseNestedSelectQueries(query,pruningParameters);return selfChanged||nestedChanged}if(query instanceof BinarySelectQuery){let leftChanged=traverseSelectQuery2(query.left,pruningParameters),rightChanged=traverseSelectQuery2(query.right,pruningParameters);return leftChanged||rightChanged}return!1},getSupportedOptionalConditionBranch=expression=>{let orTerms=collectTopLevelOrTerms(expression);if(orTerms.length<2)return null;let guardTerms=orTerms.map(term=>({term,parameterName:getGuardedParameterName(term)})).filter(candidate=>candidate.parameterName!==null);if(guardTerms.length!==1)return null;let[{term:guardTerm,parameterName}]=guardTerms,meaningfulTerms=orTerms.filter(term=>term!==guardTerm);return meaningfulTerms.length===0||!meaningfulTerms.every(term=>isSupportedMeaningfulBranch(term,parameterName))?null:{parameterName,kind:"expression"}},collectSupportedBranchesFromSimpleQuery=(query,branches)=>{if(!query.whereClause)return;let topLevelTerms=collectTopLevelAndTerms(query.whereClause.condition);for(let term of topLevelTerms){let branch=getSupportedOptionalConditionBranch(term);branch&&branches.push({query,parameterName:branch.parameterName,expression:term,kind:branch.kind})}},collectSupportedBranchesFromSelectQuery=(query,branches)=>{if(query instanceof SimpleSelectQuery){collectSupportedBranchesFromSimpleQuery(query,branches),traverseNestedSelectQueriesForCollection(query,branches);return}query instanceof BinarySelectQuery&&(collectSupportedBranchesFromSelectQuery(query.left,branches),collectSupportedBranchesFromSelectQuery(query.right,branches))},traverseNestedSelectQueriesForCollection=(root,branches)=>{let visited=new WeakSet,walk=value=>{if(!(!value||typeof value!="object")&&!visited.has(value)){if(visited.add(value),value!==root&&isSelectQueryNode(value)){collectSupportedBranchesFromSelectQuery(value,branches);return}if(Array.isArray(value)){value.forEach(walk);return}for(let child of Object.values(value))walk(child)}};walk(root)},pruneOptionalConditionBranches=(query,pruningParameters)=>(Object.keys(pruningParameters).length===0||traverseSelectQuery2(query,pruningParameters),query),collectSupportedOptionalConditionBranches=query=>{let branches=[];return collectSupportedBranchesFromSelectQuery(query,branches),branches},collectSupportedOptionalConditionBranchSpans=sql=>{let parsed=SelectQueryParser.parse(sql),supportedBranches=collectSupportedOptionalConditionBranches(parsed);if(supportedBranches.length===0)return[];let candidates=collectOptionalConditionSpanCandidates(sql),remainingSupportedCounts=countSupportedBranchesByKey(supportedBranches);assertUnambiguousCandidateCounts(candidates,remainingSupportedCounts);let spans=[];for(let candidate of candidates){let key=getSupportedBranchKey(candidate),remainingCount=remainingSupportedCounts.get(key)??0;remainingCount<=0||(spans.push(candidate),remainingSupportedCounts.set(key,remainingCount-1))}return assertNoMissingSupportedBranches(remainingSupportedCounts),spans},getSupportedBranchKey=branch=>`${branch.kind}:${branch.parameterName}`,countSupportedBranchesByKey=branches=>{let counts=new Map;for(let branch of branches){let key=getSupportedBranchKey(branch);counts.set(key,(counts.get(key)??0)+1)}return counts},assertUnambiguousCandidateCounts=(candidates,supportedCounts)=>{let candidateCounts=countSupportedBranchesByKey(candidates);for(let[key,supportedCount]of supportedCounts){let candidateCount=candidateCounts.get(key)??0;if(candidateCount<supportedCount)throw new Error(`Could not locate source range for supported optional condition branch '${key}'.`);if(candidateCount>supportedCount)throw new Error(`Ambiguous source ranges for supported optional condition branch '${key}'.`)}},assertNoMissingSupportedBranches=supportedCounts=>{let missingKeys=[...supportedCounts.entries()].filter(([,count])=>count>0).map(([key])=>key);if(missingKeys.length>0)throw new Error(`Could not locate source ranges for supported optional condition branches: ${missingKeys.join(", ")}.`)},collectOptionalConditionSpanCandidates=sql=>{let lexemes=new SqlTokenizer(sql).readLexemes(),candidates=[],stack=[];for(let index=0;index<lexemes.length;index+=1){let lexeme=lexemes[index];if(isOpenParen(lexeme)){stack.push(index);continue}if(!isCloseParen(lexeme))continue;let openParenIndex=stack.pop();if(openParenIndex===void 0)continue;let candidate=buildOptionalConditionSpanCandidate(sql,lexemes,openParenIndex,index);candidate&&candidates.push(candidate)}return candidates.sort((left,right)=>left.sourceRange.start-right.sourceRange.start)},buildOptionalConditionSpanCandidate=(sql,lexemes,openParenIndex,closeParenIndex)=>{let inside=lexemes.slice(openParenIndex+1,closeParenIndex),orTermRanges=splitTopLevelTermsByKeyword(inside,"or");if(orTermRanges.length<2)return null;let guardTerms=orTermRanges.map(range=>({range,parameterName:getGuardedParameterNameFromLexemes(inside.slice(range.start,range.end))})).filter(candidate=>candidate.parameterName!==null);if(guardTerms.length!==1)return null;let[{range:guardRange,parameterName}]=guardTerms,meaningfulTerms=orTermRanges.filter(range=>range!==guardRange);if(meaningfulTerms.length===0||!meaningfulTerms.every(range=>isSupportedMeaningfulBranchFromLexemes(inside.slice(range.start,range.end),parameterName)))return null;let expandedRange=expandWrappingParenRange(lexemes,openParenIndex,closeParenIndex),sourceStart=requiredPosition(lexemes[expandedRange.openParenIndex]).startPosition,sourceEnd=requiredPosition(lexemes[expandedRange.closeParenIndex]).endPosition,removalRange=getRemovalRange(sql,lexemes,expandedRange.openParenIndex,expandedRange.closeParenIndex);return{parameterName,kind:"expression",sourceRange:{start:sourceStart,end:sourceEnd,text:sql.slice(sourceStart,sourceEnd)},removalRange,openParenIndex:expandedRange.openParenIndex,closeParenIndex:expandedRange.closeParenIndex}},expandWrappingParenRange=(lexemes,openParenIndex,closeParenIndex)=>{let expandedOpenParenIndex=openParenIndex,expandedCloseParenIndex=closeParenIndex;for(;isOpenParen(lexemes[expandedOpenParenIndex-1])&&isCloseParen(lexemes[expandedCloseParenIndex+1]);)expandedOpenParenIndex-=1,expandedCloseParenIndex+=1;return{openParenIndex:expandedOpenParenIndex,closeParenIndex:expandedCloseParenIndex}},splitTopLevelTermsByKeyword=(lexemes,keyword)=>{let ranges=[],depth=0,start=0;for(let index=0;index<lexemes.length;index+=1){let lexeme=lexemes[index];if(isOpenParen(lexeme)){depth+=1;continue}if(isCloseParen(lexeme)){depth-=1;continue}depth===0&&isKeyword(lexeme,keyword)&&(ranges.push({start,end:index}),start=index+1)}return ranges.push({start,end:lexemes.length}),ranges},getGuardedParameterNameFromLexemes=lexemes=>{let compact=lexemes.filter(lexeme=>!isWrappingParen(lexeme)),isIndexKeyword=(index,keyword)=>{let lexeme=compact[index];return lexeme!==void 0&&isKeyword(lexeme,keyword)};if(compact.length===3)return!isParameter(compact[0])||!isIndexKeyword(1,"is")||!isIndexKeyword(2,"null")?null:normalizeParameterName(compact[0].value);if(compact.length===5&&isParameter(compact[0])&&compact[1]?.value==="::"&&isIndexKeyword(3,"is")&&isIndexKeyword(4,"null"))return normalizeParameterName(compact[0].value);if(compact.length>=6&&isIndexKeyword(0,"cast")&&isParameter(compact[1])&&isIndexKeyword(2,"as")){let isIndex=compact.findIndex((lexeme,index)=>index>2&&isKeyword(lexeme,"is"));if(isIndex>=0&&isIndexKeyword(isIndex+1,"null"))return normalizeParameterName(compact[1].value)}return null},isSupportedMeaningfulBranchFromLexemes=(lexemes,parameterName)=>{try{let parsed=ValueParser.parseFromLexeme(lexemes,0);return parsed.newIndex!==lexemes.length?!1:isSupportedMeaningfulBranch(parsed.value,parameterName)}catch{return!1}},getRemovalRange=(sql,lexemes,openParenIndex,closeParenIndex)=>{let previous=lexemes[openParenIndex-1],next=lexemes[closeParenIndex+1],start=requiredPosition(lexemes[openParenIndex]).startPosition,end=requiredPosition(lexemes[closeParenIndex]).endPosition;return previous&&isKeyword(previous,"and")?start=requiredPosition(previous).startPosition:next&&isKeyword(next,"and")?end=requiredPosition(next).endPosition:previous&&isKeyword(previous,"where")&&(start=requiredPosition(previous).startPosition),{start,end,text:sql.slice(start,end)}},isParameter=lexeme=>(lexeme.type&256)!==0,isOpenParen=lexeme=>(lexeme.type&4)!==0,isCloseParen=lexeme=>(lexeme.type&8)!==0,isKeyword=(lexeme,keyword)=>lexeme.value.toLowerCase()===keyword,isWrappingParen=lexeme=>isOpenParen(lexeme)||isCloseParen(lexeme),normalizeParameterName=value=>value.startsWith("${")&&value.endsWith("}")?value.slice(2,-1):value.replace(/^[:@$]/,""),requiredPosition=lexeme=>{if(!lexeme.position)throw new Error(`Lexeme '${lexeme.value}' is missing source position metadata.`);return lexeme.position};var DynamicQueryBuilder=class{constructor(resolverOrOptions){typeof resolverOrOptions=="function"?this.tableColumnResolver=resolverOrOptions:resolverOrOptions&&(this.tableColumnResolver=resolverOrOptions.tableColumnResolver,this.defaultSchemaInfo=resolverOrOptions.schemaInfo)}buildQuery(sqlContent,options={}){let removedOptions=options;if("serialize"in removedOptions||"jsonb"in removedOptions)throw new Error("DynamicQueryBuilder SQL-result JSON shaping has been removed. Keep SQL results as rows and use generated AOT mappers so the executed SQL remains debuggable.");let parsedQuery;try{parsedQuery=SelectQueryParser.parse(sqlContent)}catch(error){throw new Error(`Failed to parse SQL: ${error instanceof Error?error.message:"Unknown error"}`)}let modifiedQuery=parsedQuery;if(options.filter&&Object.keys(options.filter).length>0){let{hardcodedParams,dynamicFilters}=ParameterDetector.separateFilters(modifiedQuery,options.filter);if(Object.keys(hardcodedParams).length>0&&(modifiedQuery=new SqlParameterBinder({requireAllParameters:!1}).bind(modifiedQuery,hardcodedParams)),Object.keys(dynamicFilters).length>0)throw new Error("DynamicQueryBuilder no longer injects runtime filter predicates. Use `ashiba query optional add` to author optional filters, `ashiba query optional refresh` to refresh them, and `optionalConditionParameters` at runtime for pruning only.")}if(options.sort&&Object.keys(options.sort).length>0){let sortInjector=new SqlSortInjector(this.tableColumnResolver),simpleQuery=QueryBuilder.buildSimpleQuery(modifiedQuery);modifiedQuery=sortInjector.inject(simpleQuery,options.sort)}if(options.paging){let{page=1,pageSize}=options.paging;if(pageSize!==void 0){let paginationInjector=new SqlPaginationInjector,paginationOptions={page,pageSize},simpleQuery=QueryBuilder.buildSimpleQuery(modifiedQuery);modifiedQuery=paginationInjector.inject(simpleQuery,paginationOptions)}}modifiedQuery=this.applyColumnFilters(modifiedQuery,options);let optionalConditionParameters=this.resolveOptionalConditionPruningParameters(options);Object.keys(optionalConditionParameters).length>0&&(modifiedQuery=pruneOptionalConditionBranches(modifiedQuery,optionalConditionParameters));let effectiveSchemaInfo=options.schemaInfo??this.defaultSchemaInfo;return options.removeUnusedLeftJoins&&effectiveSchemaInfo?.length&&(modifiedQuery=optimizeUnusedLeftJoinsToFixedPoint(modifiedQuery,effectiveSchemaInfo)),options.removeUnusedCtes&&(modifiedQuery=optimizeUnusedCtesToFixedPoint(modifiedQuery)),modifiedQuery}resolveOptionalConditionPruningParameters(options){if(options.optionalConditionParameters)return options.optionalConditionParameters;if(!options.optionalConditionParameterStates)return{};let legacyParameters={};for(let[parameterName,state]of Object.entries(options.optionalConditionParameterStates))legacyParameters[parameterName]=state==="absent"?null:"__RAWSQL_OPTIONAL_CONDITION_PRESENT__";return legacyParameters}applyColumnFilters(query,options){let hasIncludeFilters=Array.isArray(options.includeColumns)&&options.includeColumns.length>0,hasExcludeFilters=Array.isArray(options.excludeColumns)&&options.excludeColumns.length>0;if(!hasIncludeFilters&&!hasExcludeFilters)return query;if(hasIncludeFilters&&hasExcludeFilters)throw new Error("includeColumns and excludeColumns cannot be used together.");let simpleQuery=QueryBuilder.buildSimpleQuery(query),metadata=simpleQuery.selectClause.items.map(item=>{let name=this.getSelectItemName(item);return{item,normalized:name?this.normalizeColumnIdentifier(name):null}}),availableColumns=new Set(metadata.map(entry=>entry.normalized).filter(name=>name!==null)),includeFilters=hasIncludeFilters?this.normalizeColumnList(options.includeColumns):null,excludeFilters=hasExcludeFilters?this.normalizeColumnList(options.excludeColumns):null,includeSet=includeFilters?new Set(includeFilters.map(entry=>entry.normalized)):null,excludeSet=excludeFilters?new Set(excludeFilters.map(entry=>entry.normalized)):null;if(includeFilters){let missing=includeFilters.filter(entry=>!availableColumns.has(entry.normalized));if(missing.length>0)throw new Error(`Column${missing.length===1?"":"s"} not found in SELECT clause: ${missing.map(entry=>`'${entry.original}'`).join(", ")}.`)}if(excludeFilters){let missing=excludeFilters.filter(entry=>!availableColumns.has(entry.normalized));if(missing.length>0)throw new Error(`Column${missing.length===1?"":"s"} not found in SELECT clause: ${missing.map(entry=>`'${entry.original}'`).join(", ")}.`)}let filteredItems=metadata.filter(entry=>entry.normalized?includeSet?includeSet.has(entry.normalized):excludeSet?!excludeSet.has(entry.normalized):!0:!0).map(entry=>entry.item);if(filteredItems.length===0)throw new Error("Column filtering removed every SELECT item.");return simpleQuery.selectClause.items=filteredItems,simpleQuery}normalizeColumnList(columns){return columns.map(column=>{if(typeof column!="string")throw new Error("Column filters must be strings.");let trimmed=column.trim();if(trimmed==="")throw new Error("Column filters must not be empty.");return{normalized:this.normalizeColumnIdentifier(trimmed),original:trimmed}})}normalizeColumnIdentifier(value){return value.trim().toLowerCase()}getSelectItemName(item){return item.identifier?item.identifier.name:item.value instanceof ColumnReference?item.value.column.name:null}buildFilteredQuery(sqlContent,filter){return this.buildQuery(sqlContent,{filter})}buildSortedQuery(sqlContent,sort){return this.buildQuery(sqlContent,{sort})}buildPaginatedQuery(sqlContent,paging){return this.buildQuery(sqlContent,{paging})}validateSql(sqlContent){try{return SelectQueryParser.parse(sqlContent),!0}catch(error){throw new Error(`Invalid SQL: ${error instanceof Error?error.message:"Unknown error"}`)}}};var SUPPORTED_SCALAR_OPERATORS=new Set(["=","<>","<","<=",">",">=","like","ilike"]),formatter=null,normalizeIdentifier2=value=>value.trim().toLowerCase(),normalizeSql=value=>value.replace(/\s+/g," ").trim().toLowerCase(),normalizeRewriteTokenType=lexeme=>(lexeme.type&128)!==0?128:(lexeme.type&64)!==0?64:lexeme.type,normalizeRewriteTokenValue=lexeme=>(lexeme.type&128)!==0?lexeme.value.toLowerCase():lexeme.value,tokenizeForRewritePlan=sql=>new SqlTokenizer(sql).tokenize().map(lexeme=>({type:normalizeRewriteTokenType(lexeme),value:normalizeRewriteTokenValue(lexeme)})),tokenSequencesEqual=(left,right)=>left.length!==right.length?!1:left.every((token,index)=>{let other=right[index];return other!==void 0&&token.type===other.type&&token.value===other.value}),collectCommentFragments=sql=>new SqlTokenizer(sql).tokenize().flatMap(lexeme=>lexeme.positionedComments?lexeme.positionedComments.flatMap(positioned=>positioned.comments):lexeme.comments?[...lexeme.comments]:[]),commentsPreservedInOrder=(before,after)=>{let cursor=0;for(let comment of before){let foundAt=after.indexOf(comment,cursor);if(foundAt<0)return!1;cursor=foundAt+1}return!0},countCommandToken=(tokens,value)=>tokens.filter(token=>token.type===128&&token.value===value).length,applyRewriteEdits=(sql,edits)=>[...edits].sort((left,right)=>right.start-left.start).reduce((current,edit)=>current.slice(0,edit.start)+edit.after+current.slice(edit.end),sql),getStatementEndPosition=sql=>{let end=sql.length;for(;end>0&&/\s/.test(sql[end-1]);)end--;if(end>0&&sql[end-1]===";")for(end--;end>0&&/\s/.test(sql[end-1]);)end--;return end},clauseBoundaryCommands=new Set(["group by","having","order by","limit","offset","fetch","for"]),isClauseBoundary=lexeme=>(lexeme.type&128)!==0&&clauseBoundaryCommands.has(lexeme.value.toLowerCase()),findMinimalWhereInsertPosition=sql=>{let lexemes=new SqlTokenizer(sql).tokenize(),statementEnd=getStatementEndPosition(sql),topLevelLexemes=[],depth=0;for(let index=0;index<lexemes.length;index+=1){let lexeme=lexemes[index];(lexeme.type&8)!==0&&(depth=Math.max(0,depth-1)),depth===0&&topLevelLexemes.push({lexeme,index}),(lexeme.type&4)!==0&&(depth+=1)}let where=topLevelLexemes.find(entry=>(entry.lexeme.type&128)!==0&&entry.lexeme.value.toLowerCase()==="where");return where?{position:topLevelLexemes.filter(entry=>entry.index>where.index).map(entry=>entry.lexeme).find(isClauseBoundary)?.position?.startPosition??statementEnd,hasWhere:!0}:{position:topLevelLexemes.map(entry=>entry.lexeme).find(isClauseBoundary)?.position?.startPosition??statementEnd,hasWhere:!1}},findMatchingParenEnd=(sql,start)=>{let depth=0,quote=null;for(let index=start;index<sql.length;index++){let char=sql[index];if(quote){if(char===quote){if(quote==="'"&&sql[index+1]==="'"){index++;continue}quote=null}continue}if(char==="'"||char==='"'){quote=char;continue}if(char==="("&&depth++,char===")"&&(depth--,depth===0))return index+1}return-1},findOptionalBranchSpans=(sql,parameterName)=>{let spans=[],parameterNeedle=`:${parameterName.toLowerCase()}`,lowerSql=sql.toLowerCase();for(let index=0;index<sql.length;index++){if(sql[index]!=="(")continue;let end=findMatchingParenEnd(sql,index);if(end<0)break;let text=sql.slice(index,end),normalized=lowerSql.slice(index,end);normalized.includes(parameterNeedle)&&normalized.includes(" is null")&&normalized.includes(" or ")&&spans.push({start:index,end,text}),index=end-1}return spans},findBooleanOperatorBefore=(sql,start)=>{let prefix=sql.slice(0,start),match=/(\s+)(and|or)(\s*)$/i.exec(prefix);return!match||match.index===void 0?null:{start:match.index,end:start,value:match[2].toLowerCase()}},findBooleanOperatorAfter=(sql,end)=>{let suffix=sql.slice(end),match=/^(\s*)(and|or)(\s+)/i.exec(suffix);return match?{start:end,end:end+match[0].length,value:match[2].toLowerCase()}:null},findWhereBefore=(sql,position)=>{let lexemes=new SqlTokenizer(sql).tokenize(),found=null;for(let lexeme of lexemes){if((lexeme.position?.startPosition??0)>=position)break;(lexeme.type&128)!==0&&lexeme.value.toLowerCase()==="where"&&(found=lexeme)}return found?.position?{start:found.position.startPosition,end:found.position.endPosition}:null},findSourceColumnReferenceText=(sql,reference)=>{let namespace=normalizeIdentifier2(reference.getNamespace()),column=normalizeIdentifier2(reference.column.name),lexemes=new SqlTokenizer(sql).tokenize();for(let index=0;index<lexemes.length-2;index++){let first=lexemes[index],dot=lexemes[index+1],last=lexemes[index+2];if(!((first.type&64)===0||dot.value!=="."||(last.type&64)===0)&&!(normalizeIdentifier2(first.value)!==namespace||normalizeIdentifier2(last.value)!==column)&&!(!first.position||!last.position))return sql.slice(first.position.startPosition,last.position.endPosition)}return normalizeColumnReferenceText(reference)},normalizeColumnReferenceKey=reference=>`${normalizeIdentifier2(reference.getNamespace())}.${normalizeIdentifier2(reference.column.name)}`,normalizeColumnReferenceText=reference=>{let namespace=reference.getNamespace();return namespace?`${namespace}.${reference.column.name}`:reference.column.name},normalizeScalarOperator=value=>{if(!value)return"=";let normalized=value.trim().toLowerCase();if(normalized==="!=")return"<>";if(SUPPORTED_SCALAR_OPERATORS.has(normalized))return normalized;throw new Error(`Unsupported SSSQL operator '${value}'.`)},isExplicitEqualityScaffoldValue=value=>{if(value==null)return!0;if(Array.isArray(value))return!1;if(typeof value!="object")return!0;let entries=Object.entries(value).filter(([,entry])=>entry!==void 0);return entries.length===1&&entries[0]?.[0]==="="},parseQualifiedFilterName=filterName=>{let segments=filterName.split(".");if(segments.length!==2)return null;let[table,column]=segments.map(segment=>segment.trim());return!table||!column?null:{table,column}},makeParameterName=filterName=>filterName.trim().replace(/\./g,"_").replace(/[^a-zA-Z0-9_]/g,"_"),unwrapParens=expression=>{let candidate=expression;for(;candidate instanceof ParenExpression;)candidate=candidate.expression;return candidate},isBinaryOperator2=(expression,operator)=>expression instanceof BinaryExpression&&expression.operator.value.trim().toLowerCase()===operator,collectTopLevelAndTerms2=expression=>{let candidate=unwrapParens(expression);return isBinaryOperator2(candidate,"and")?[...collectTopLevelAndTerms2(candidate.left),...collectTopLevelAndTerms2(candidate.right)]:[expression]},collectTopLevelOrTerms2=expression=>{let candidate=unwrapParens(expression);return isBinaryOperator2(candidate,"or")?[...collectTopLevelOrTerms2(candidate.left),...collectTopLevelOrTerms2(candidate.right)]:[expression]},getGuardedParameterName2=expression=>{let candidate=unwrapParens(expression);if(!isBinaryOperator2(candidate,"is"))return null;let left=unwrapOptionalGuardParameter2(candidate.left);if(!(left instanceof ParameterExpression))return null;let right=unwrapParens(candidate.right);return right instanceof LiteralValue&&right.value===null||right instanceof RawString&&right.value.trim().toLowerCase()==="null"?left.name.value:null},unwrapOptionalGuardParameter2=expression=>{let candidate=unwrapParens(expression);for(;candidate instanceof CastExpression;)candidate=unwrapParens(candidate.input);if(candidate instanceof FunctionCall&&getFunctionCallName2(candidate)==="cast"&&candidate.argument){let argument=unwrapParens(candidate.argument);if(isBinaryOperator2(argument,"as"))return unwrapOptionalGuardParameter2(argument.left)}return candidate},getFunctionCallName2=expression=>{let name=expression.qualifiedName.name;return"value"in name?name.value.toLowerCase():name.name.toLowerCase()},buildOptionalScalarBranch=(column,parameterName,operator)=>{let guard=new BinaryExpression(new ParameterExpression(parameterName),"is",new LiteralValue(null)),predicate=new BinaryExpression(new ColumnReference(column.getNamespace()||null,column.column.name),operator,new ParameterExpression(parameterName));return new ParenExpression(new BinaryExpression(guard,"or",predicate))},buildOptionalExistsBranch=(parameterName,subquery,kind)=>{let guard=new BinaryExpression(new ParameterExpression(parameterName),"is",new LiteralValue(null)),existsExpression=new UnaryExpression("exists",new InlineQuery(subquery)),predicate=kind==="exists"?existsExpression:new UnaryExpression("not",existsExpression);return new ParenExpression(new BinaryExpression(guard,"or",predicate))},rebuildWhereWithoutTerm=(query,termToRemove)=>{if(!query.whereClause)return;let terms=collectTopLevelAndTerms2(query.whereClause.condition).filter(term=>term!==termToRemove);if(terms.length===0){query.whereClause=null;return}let rebuilt=terms[0];for(let index=1;index<terms.length;index+=1)rebuilt=new BinaryExpression(rebuilt,"and",terms[index]);query.whereClause=new WhereClause(rebuilt)},formatSqlComponent=component=>(formatter??=new SqlFormatter,formatter.format(component).formattedSql),enforceSubqueryConstraints=sql=>{if(!sql.trim())throw new Error("SSSQL EXISTS/NOT EXISTS scaffold query must not be empty.");if(sql.includes(";"))throw new Error("SSSQL EXISTS/NOT EXISTS scaffold query must not contain semicolons or multiple statements.");if(/\blateral\b/i.test(sql))throw new Error("LATERAL is not supported in SSSQL EXISTS/NOT EXISTS scaffold.")},substituteAnchorPlaceholders=(sql,formattedColumns)=>{let usedIndexes=new Set,replaced=sql.replace(/\$c(\d+)/g,(_,indexDigits)=>{let index=Number(indexDigits);if(!Number.isInteger(index))throw new Error(`Invalid placeholder '$c${indexDigits}' in SSSQL scaffold query.`);if(index<0||index>=formattedColumns.length)throw new Error(`Placeholder '$c${index}' references a missing SSSQL scaffold anchor column.`);return usedIndexes.add(index),formattedColumns[index]});if(formattedColumns.length===0)return replaced;for(let index=0;index<formattedColumns.length;index+=1)if(!usedIndexes.has(index))throw new Error(`Missing placeholder '$c${index}' for SSSQL scaffold anchor column.`);return replaced},getScalarBranchDetails=(expression,parameterName)=>{let meaningfulTerms=collectTopLevelOrTerms2(expression).filter(term=>getGuardedParameterName2(term)!==parameterName);if(meaningfulTerms.length!==1)return null;let predicate=unwrapParens(meaningfulTerms[0]);if(!(predicate instanceof BinaryExpression))return null;let left=unwrapParens(predicate.left),right=unwrapParens(predicate.right);if(left instanceof ColumnReference&&right instanceof ParameterExpression&&right.name.value===parameterName)try{return{operator:normalizeScalarOperator(predicate.operator.value),target:normalizeColumnReferenceText(left)}}catch{return null}if(right instanceof ColumnReference&&left instanceof ParameterExpression&&left.name.value===parameterName)try{return{operator:normalizeScalarOperator(predicate.operator.value),target:normalizeColumnReferenceText(right)}}catch{return null}return null},hasSelectQuery=value=>typeof value=="object"&&value!==null&&"selectQuery"in value,collectColumnReferencesDeep=value=>{let references=[],visited=new WeakSet,walk=candidate=>{if(!(!candidate||typeof candidate!="object")){if(candidate instanceof ColumnReference){references.push(candidate);return}if(!visited.has(candidate)){if(visited.add(candidate),Array.isArray(candidate)){for(let item of candidate)walk(item);return}for(let child of Object.values(candidate))walk(child)}}};return walk(value),references},getExistsBranchKind=(expression,parameterName)=>{let meaningfulTerms=collectTopLevelOrTerms2(expression).filter(term=>getGuardedParameterName2(term)!==parameterName);if(meaningfulTerms.length!==1)return null;let predicate=unwrapParens(meaningfulTerms[0]),isInlineQueryValue=value=>value instanceof InlineQuery||hasSelectQuery(value);if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="exists")return isInlineQueryValue(unwrapParens(predicate.expression))?"exists":null;if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not exists")return isInlineQueryValue(unwrapParens(predicate.expression))?"not-exists":null;if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not"&&unwrapParens(predicate.expression)instanceof UnaryExpression){let nested=unwrapParens(predicate.expression);if(nested.operator.value.trim().toLowerCase()==="exists"&&isInlineQueryValue(unwrapParens(nested.expression)))return"not-exists"}return null},getExistsPredicateDetails=(expression,parameterName)=>{let meaningfulTerms=collectTopLevelOrTerms2(expression).filter(term=>getGuardedParameterName2(term)!==parameterName);if(meaningfulTerms.length!==1)return null;let predicate=unwrapParens(meaningfulTerms[0]),isInlineQueryValue=value=>value instanceof InlineQuery||hasSelectQuery(value);if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="exists"){let candidate=unwrapParens(predicate.expression);return isInlineQueryValue(candidate)?{kind:"exists",subquery:candidate.selectQuery}:null}if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not exists"){let candidate=unwrapParens(predicate.expression);return isInlineQueryValue(candidate)?{kind:"not-exists",subquery:candidate.selectQuery}:null}if(predicate instanceof UnaryExpression&&predicate.operator.value.trim().toLowerCase()==="not"&&unwrapParens(predicate.expression)instanceof UnaryExpression){let nested=unwrapParens(predicate.expression),candidate=unwrapParens(nested.expression);if(nested.operator.value.trim().toLowerCase()==="exists"&&isInlineQueryValue(candidate))return{kind:"not-exists",subquery:candidate.selectQuery}}return null},getBranchInfo=branch=>{let scalar=getScalarBranchDetails(branch.expression,branch.parameterName);if(scalar)return{parameterName:branch.parameterName,kind:"scalar",operator:scalar.operator,target:scalar.target,query:branch.query,expression:branch.expression,sql:formatSqlComponent(branch.expression)};let existsKind=getExistsBranchKind(branch.expression,branch.parameterName);return existsKind?{parameterName:branch.parameterName,kind:existsKind,query:branch.query,expression:branch.expression,sql:formatSqlComponent(branch.expression)}:{parameterName:branch.parameterName,kind:"expression",query:branch.query,expression:branch.expression,sql:formatSqlComponent(branch.expression)}},isEquivalentScalarBranch=(branch,query,parameterName,operator,targetColumnText)=>branch.query===query&&branch.kind==="scalar"&&branch.parameterName===parameterName&&branch.operator===operator&&branch.target!==void 0&&normalizeIdentifier2(branch.target)===normalizeIdentifier2(targetColumnText),SSSQLFilterBuilder=class{constructor(tableColumnResolver){this.tableColumnResolver=tableColumnResolver;this.finder=new UpstreamSelectQueryFinder(this.tableColumnResolver)}list(query){let parsed=this.parseQuery(query);return collectSupportedOptionalConditionBranches(parsed).map(getBranchInfo)}planScaffold(query,filters){if(typeof query=="string"){let entries=Object.entries(filters);if(entries.length===1){let[filterName,filterValue]=entries[0];if(isExplicitEqualityScaffoldValue(filterValue))try{return this.planScalarInsert(query,{target:filterName,parameterName:makeParameterName(filterName),operator:"="})}catch{}}}return this.planRewrite(query,parsed=>this.scaffold(parsed,filters))}dryRunScaffold(query,filters){return this.planScaffold(query,filters)}planScaffoldBranch(query,spec){if(typeof query=="string"&&(spec.kind==="exists"||spec.kind==="not-exists"))try{return this.planExistsInsert(query,spec)}catch{}if(typeof query=="string"&&spec.kind!=="exists"&&spec.kind!=="not-exists")try{return this.planScalarInsert(query,spec)}catch{}return this.planRewrite(query,parsed=>this.scaffoldBranch(parsed,spec))}dryRunScaffoldBranch(query,spec){return this.planScaffoldBranch(query,spec)}planRefresh(query,filters){if(typeof query=="string")try{let parsed=SelectQueryParser.parse(query);if(!this.refreshParsed(parsed,filters).changed)return this.buildPlanFromEdits(query,[],[],[])}catch{}return this.planRewrite(query,parsed=>this.refresh(parsed,filters))}dryRunRefresh(query,filters){return this.planRefresh(query,filters)}planRemove(query,spec){if(typeof query=="string")try{return this.planBranchRemoval(query,spec)}catch{}return this.planRewrite(query,parsed=>this.remove(parsed,spec))}dryRunRemove(query,spec){return this.planRemove(query,spec)}planRemoveAll(query){return this.planRewrite(query,parsed=>this.removeAll(parsed))}dryRunRemoveAll(query){return this.planRemoveAll(query)}scaffold(query,filters){let parsed=this.parseQuery(query);for(let[filterName,filterValue]of Object.entries(filters)){if(!isExplicitEqualityScaffoldValue(filterValue))throw new Error(`SSSQL scaffold only supports equality filters in v1. Use structured scaffold or refresh for pre-authored branches: '${filterName}'.`);this.scaffoldBranch(parsed,{target:filterName,parameterName:makeParameterName(filterName),operator:"="})}return parsed}scaffoldBranch(query,spec){let parsed=this.parseQuery(query);return spec.kind==="exists"||spec.kind==="not-exists"?(this.scaffoldExistsBranch(parsed,spec),parsed):(this.scaffoldScalarBranch(parsed,spec),parsed)}refresh(query,filters){let parsed=this.parseQuery(query);return this.refreshParsed(parsed,filters),parsed}refreshParsed(parsed,filters){let changed=!1;for(let[filterName,filterValue]of Object.entries(filters)){let parameterName=filterName,target=null,matches=collectSupportedOptionalConditionBranches(parsed).filter(branch=>branch.parameterName===parameterName);if(matches.length===0&&(target=this.resolveTarget(parsed,filterName),parameterName=target.parameterName,matches=collectSupportedOptionalConditionBranches(parsed).filter(branch=>branch.parameterName===parameterName)),matches.length===0){if(target||(target=this.resolveTarget(parsed,filterName),parameterName=target.parameterName),!isExplicitEqualityScaffoldValue(filterValue))throw new Error(`No existing SSSQL branch was found for '${filterName}', and v1 scaffold only supports equality filters.`);this.scaffoldScalarBranch(parsed,{target:filterName,parameterName:target.parameterName,operator:"="}),changed=!0;continue}if(matches.length>1)throw new Error(`Multiple SSSQL branches matched parameter ':${parameterName}'. Refresh is ambiguous.`);let[match]=matches;if(!match)continue;let correlatedPlan=this.buildCorrelatedRefreshPlan(parsed,match);if(correlatedPlan){if(correlatedPlan.target.query===match.query)continue;this.rebaseMovedBranchByAlias(match.expression,correlatedPlan.sourceAlias,correlatedPlan.target.column),rebuildWhereWithoutTerm(match.query,match.expression),correlatedPlan.target.query.appendWhere(match.expression),changed=!0;continue}!target&&(target=this.tryResolveTarget(parsed,filterName),!target)||match.query!==target.query&&(this.rebaseMovedBranch(match.expression,match.query,target.column),rebuildWhereWithoutTerm(match.query,match.expression),target.query.appendWhere(match.expression),changed=!0)}return{query:parsed,changed}}remove(query,spec){let parsed=this.parseQuery(query),matches=this.findMatchingBranchInfos(parsed,spec);if(matches.length===0)return parsed;if(matches.length>1)throw new Error(`Multiple SSSQL branches matched parameter ':${spec.parameterName}'. Remove is ambiguous.`);let[match]=matches;return match&&rebuildWhereWithoutTerm(match.query,match.expression),parsed}removeAll(query){let parsed=this.parseQuery(query),matches=this.list(parsed);for(let match of matches)rebuildWhereWithoutTerm(match.query,match.expression);return parsed}parseQuery(query){return typeof query=="string"?SelectQueryParser.parse(query):query}planScalarInsert(sourceSql,spec){let parsed=SelectQueryParser.parse(sourceSql),target=this.resolveTarget(parsed,spec.target);if(target.query!==parsed)return this.planRewrite(sourceSql,query=>this.scaffoldBranch(query,spec));let parameterName=spec.parameterName?.trim()||target.parameterName,operator=normalizeScalarOperator(spec.operator),targetColumnText=findSourceColumnReferenceText(sourceSql,target.column),branchSql=`(:${parameterName} is null or ${targetColumnText} ${operator} :${parameterName})`,normalizedBranch=normalizeSql(branchSql);return this.list(parsed).find(existing=>existing.query===target.query&&normalizeSql(existing.sql)===normalizedBranch||isEquivalentScalarBranch(existing,target.query,parameterName,operator,targetColumnText))?this.buildPlanFromEdits(sourceSql,[],[],[]):this.buildMinimalInsertPlan(sourceSql,branchSql,{branchKind:"scalar",parameterName,column:targetColumnText})}planExistsInsert(sourceSql,spec){let parameterName=spec.parameterName.trim();if(!parameterName)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires parameterName.");if(spec.anchorColumns.length===0)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires at least one anchorColumn.");let parsed=SelectQueryParser.parse(sourceSql),anchorTargets=spec.anchorColumns.map(anchorColumn=>this.resolveTarget(parsed,anchorColumn)),targetQueries=[...new Set(anchorTargets.map(target=>target.query))];if(targetQueries.length!==1)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold anchor columns must resolve within one query scope.");let targetQuery=targetQueries[0];if(targetQuery!==parsed)return this.planRewrite(sourceSql,query=>this.scaffoldBranch(query,spec));let sourceColumns=anchorTargets.map(target=>findSourceColumnReferenceText(sourceSql,target.column)),substitutedSql=substituteAnchorPlaceholders(spec.query,sourceColumns).trim();enforceSubqueryConstraints(substitutedSql);let subquery=SelectQueryParser.parse(substitutedSql),parameterNames=new Set(ParameterCollector.collect(subquery).map(parameter=>parameter.name.value));if(parameterNames.size!==1||!parameterNames.has(parameterName))throw new Error(`SSSQL ${spec.kind.toUpperCase()} scaffold query must reference only parameter ':${parameterName}'.`);let branchSql=`(:${parameterName} is null or ${spec.kind==="not-exists"?"not exists":"exists"} (${substitutedSql}))`;return this.list(parsed).find(existing=>existing.query===targetQuery&&normalizeSql(existing.sql)===normalizeSql(branchSql))?this.buildPlanFromEdits(sourceSql,[],[],[]):this.buildMinimalInsertPlan(sourceSql,branchSql,{branchKind:spec.kind,parameterName,column:sourceColumns.join(", ")})}buildMinimalInsertPlan(sourceSql,branchSql,target){let insertPosition=findMinimalWhereInsertPosition(sourceSql),prefix=`${insertPosition.position===0||!/\s/.test(sourceSql[insertPosition.position-1])?" ":""}${insertPosition.hasWhere?"and":"where"} `,suffix=insertPosition.position<getStatementEndPosition(sourceSql)?" ":"",branchLabel=target.branchKind==="scalar"?"scalar":target.branchKind,edit={start:insertPosition.position,end:insertPosition.position,before:"",after:`${prefix}${branchSql}${suffix}`,kind:"insert",reason:insertPosition.hasWhere?`Append SSSQL ${branchLabel} branch to the existing WHERE clause.`:`Create a WHERE clause for the SSSQL ${branchLabel} branch.`,target},changedRegions=[{kind:"target-branch",start:edit.start+prefix.length,end:edit.start+edit.after.length-suffix.length,message:`Inserted SSSQL ${branchLabel} optional branch.`}];return insertPosition.hasWhere?changedRegions.unshift({kind:"boolean-operator",start:edit.start,end:edit.start+prefix.length,message:`Inserted AND before the SSSQL ${branchLabel} branch.`}):changedRegions.unshift({kind:"where-keyword",start:edit.start,end:edit.start+prefix.length,message:`Inserted WHERE before the SSSQL ${branchLabel} branch.`}),this.buildPlanFromEdits(sourceSql,[edit],changedRegions,[])}planBranchRemoval(sourceSql,spec){let parsed=SelectQueryParser.parse(sourceSql),matches=this.findMatchingBranchInfos(parsed,spec);if(matches.length>1)return this.buildPlanFromEdits(sourceSql,[],[],[],[{code:"REWRITE_FAILED",message:"SSSQL remove planning found multiple matching branches.",detail:`Multiple SSSQL branches matched parameter ':${spec.parameterName}'. Remove is ambiguous.`}]);if(matches.length===0)return this.buildPlanFromEdits(sourceSql,[],[],[]);let branchSpans=findOptionalBranchSpans(sourceSql,spec.parameterName);if(branchSpans.length>1)return this.planRewrite(sourceSql,query=>this.remove(query,spec));let span=branchSpans[0];if(!span)return this.planRewrite(sourceSql,query=>this.remove(query,spec));let beforeOperator=findBooleanOperatorBefore(sourceSql,span.start),afterOperator=findBooleanOperatorAfter(sourceSql,span.end),where=findWhereBefore(sourceSql,span.start),start=span.start,end=span.end,changedRegions=[{kind:"target-branch",start:span.start,end:span.end,message:"Removed SSSQL optional branch."}];if(beforeOperator)start=beforeOperator.start,changedRegions.unshift({kind:"boolean-operator",start:beforeOperator.start,end:beforeOperator.end,message:`Removed adjacent ${beforeOperator.value.toUpperCase()} before the SSSQL branch.`});else if(afterOperator)end=afterOperator.end,changedRegions.push({kind:"boolean-operator",start:afterOperator.start,end:afterOperator.end,message:`Removed adjacent ${afterOperator.value.toUpperCase()} after the SSSQL branch.`});else if(where){for(start=where.start;end<sourceSql.length&&/\s/.test(sourceSql[end]);)end++;changedRegions.unshift({kind:"where-keyword",start:where.start,end:where.end,message:"Removed WHERE because the SSSQL branch was the only condition."})}let edit={start,end,before:sourceSql.slice(start,end),after:"",kind:"delete",reason:"Remove the targeted SSSQL optional branch from the source SQL.",target:{branchKind:matches[0].kind,parameterName:matches[0].parameterName,column:matches[0].target}};return this.buildPlanFromEdits(sourceSql,[edit],changedRegions,[])}buildPlanFromEdits(sourceSql,edits,changedRegions,warnings,errors=[]){let plannedSql=errors.length===0?applyRewriteEdits(sourceSql,edits):void 0,beforeTokens=tokenizeForRewritePlan(sourceSql),beforeComments=collectCommentFragments(sourceSql),afterTokens=plannedSql!==void 0?tokenizeForRewritePlan(plannedSql):[],afterComments=plannedSql!==void 0?collectCommentFragments(plannedSql):[],commentsPreserved=plannedSql!==void 0?commentsPreservedInOrder(beforeComments,afterComments):!1,changedOnlyTargetBranches=errors.length===0&&changedRegions.every(region=>region.kind==="target-branch"||region.kind==="where-keyword"||region.kind==="boolean-operator"||region.kind==="parentheses")&&commentsPreserved,planWarnings=[...warnings];if(plannedSql!==void 0&&applyRewriteEdits(sourceSql,edits)!==plannedSql&&(errors=[...errors,{code:"APPLY_PLAN_MISMATCH",message:"Applying SSSQL rewrite plan edits did not reproduce the planned SQL."}]),plannedSql!==void 0)try{SelectQueryParser.parse(plannedSql)}catch(error){errors=[...errors,{code:"PARSE_AFTER_FAILED",message:"The SQL produced by SSSQL rewrite planning could not be parsed.",detail:error instanceof Error?error.message:error}]}return plannedSql!==void 0&&!commentsPreserved&&planWarnings.push({code:"COMMENTS_NOT_PRESERVED",message:"One or more input SQL comments are missing or reordered after the SSSQL rewrite."}),{ok:errors.length===0,requiresFullReformat:!1,edits,sql:plannedSql,safety:{tokenCountBefore:beforeTokens.length,tokenCountAfter:afterTokens.length,tokenSequencePreserved:plannedSql!==void 0?tokenSequencesEqual(beforeTokens,afterTokens):!1,commentsPreserved,changedOnlyTargetBranches,changedRegions},warnings:planWarnings,errors}}planRewrite(query,rewrite){let warnings=[],errors=[],sourceSql=typeof query=="string"?query:formatSqlComponent(query);typeof query!="string"&&warnings.push({code:"SOURCE_SQL_UNAVAILABLE",message:"SSSQL rewrite planning received an AST, so the source SQL had to be formatter-generated before analysis."});let beforeTokens=[],beforeComments=[];try{beforeTokens=tokenizeForRewritePlan(sourceSql),beforeComments=collectCommentFragments(sourceSql)}catch(error){errors.push({code:"TOKENIZE_BEFORE_FAILED",message:"Could not tokenize the input SQL before SSSQL rewrite planning.",detail:error instanceof Error?error.message:error})}let plannedSql,afterTokens=[],afterComments=[];if(errors.length===0)try{let parsed=SelectQueryParser.parse(sourceSql),rewritten=rewrite(parsed);plannedSql=formatSqlComponent(rewritten)}catch(error){errors.push({code:"REWRITE_FAILED",message:"SSSQL rewrite planning could not produce a rewritten query.",detail:error instanceof Error?error.message:error})}if(plannedSql!==void 0){try{SelectQueryParser.parse(plannedSql)}catch(error){errors.push({code:"PARSE_AFTER_FAILED",message:"The SQL produced by SSSQL rewrite planning could not be parsed.",detail:error instanceof Error?error.message:error})}try{afterTokens=tokenizeForRewritePlan(plannedSql),afterComments=collectCommentFragments(plannedSql)}catch(error){errors.push({code:"TOKENIZE_AFTER_FAILED",message:"Could not tokenize the SQL produced by SSSQL rewrite planning.",detail:error instanceof Error?error.message:error})}}let edits=plannedSql!==void 0&&plannedSql!==sourceSql?[{start:0,end:sourceSql.length,before:sourceSql,after:plannedSql,kind:"replace",reason:"Current SSSQL rewrite planning is backed by AST rewrite plus formatter output."}]:[],changedRegions=edits.length>0?[{kind:"formatter-rewrite",start:0,end:sourceSql.length,message:"The conservative SSSQL rewrite plan requires replacing formatter output for the full SQL text."}]:[],requiresFullReformat=edits.length>0,tokenSequencePreserved=plannedSql!==void 0?tokenSequencesEqual(beforeTokens,afterTokens):!1,commentsPreserved=plannedSql!==void 0?commentsPreservedInOrder(beforeComments,afterComments):!1,changedOnlyTargetBranches=edits.length===0;return requiresFullReformat&&warnings.push({code:"FULL_REFORMAT_REQUIRED",message:"The current SSSQL rewrite plan can only represent the change as a full SQL replacement."}),plannedSql!==void 0&&!tokenSequencePreserved&&warnings.push({code:"TOKEN_SEQUENCE_CHANGED",message:"The SQL token sequence changes after the SSSQL rewrite. The conservative planner cannot prove that only target branches changed.",detail:{tokenCountBefore:beforeTokens.length,tokenCountAfter:afterTokens.length}}),plannedSql!==void 0&&!commentsPreserved&&warnings.push({code:"COMMENTS_NOT_PRESERVED",message:"One or more input SQL comments are missing or reordered after the SSSQL rewrite."}),plannedSql!==void 0&&countCommandToken(afterTokens,"as")>countCommandToken(beforeTokens,"as")&&warnings.push({code:"OPTIONAL_ALIAS_AS_ADDED",message:"The rewrite output contains more AS tokens than the input, which may indicate formatter-added aliases."}),plannedSql!==void 0&&!sourceSql.includes('"')&&plannedSql.includes('"')&&warnings.push({code:"IDENTIFIER_QUOTES_ADDED",message:"The rewrite output contains double-quoted identifiers that were not present in the input SQL."}),{ok:errors.length===0,requiresFullReformat,edits,sql:plannedSql,safety:{tokenCountBefore:beforeTokens.length,tokenCountAfter:afterTokens.length,tokenSequencePreserved,commentsPreserved,changedOnlyTargetBranches,changedRegions},warnings,errors}}findMatchingBranchInfos(root,spec){let normalizedOperator=spec.operator?normalizeScalarOperator(spec.operator):void 0,normalizedTarget=spec.target?normalizeIdentifier2(spec.target):void 0;return this.list(root).filter(branch=>!(branch.parameterName!==spec.parameterName||spec.kind&&branch.kind!==spec.kind||normalizedOperator&&branch.operator!==normalizedOperator||normalizedTarget&&(!branch.target||normalizeIdentifier2(branch.target)!==normalizedTarget)))}scaffoldScalarBranch(root,spec){let target=this.resolveTarget(root,spec.target),parameterName=spec.parameterName?.trim()||target.parameterName,operator=normalizeScalarOperator(spec.operator),branch=buildOptionalScalarBranch(target.column,parameterName,operator),branchSql=normalizeSql(formatSqlComponent(branch));this.list(root).find(existing=>existing.query===target.query&&normalizeSql(existing.sql)===branchSql)||target.query.appendWhere(branch)}scaffoldExistsBranch(root,spec){let parameterName=spec.parameterName.trim();if(!parameterName)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires parameterName.");if(spec.anchorColumns.length===0)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold requires at least one anchorColumn.");let anchorTargets=spec.anchorColumns.map(anchorColumn=>this.resolveTarget(root,anchorColumn)),targetQueries=[...new Set(anchorTargets.map(target=>target.query))];if(targetQueries.length!==1)throw new Error("SSSQL EXISTS/NOT EXISTS scaffold anchor columns must resolve within one query scope.");let targetQuery=targetQueries[0],formattedColumns=anchorTargets.map(target=>formatSqlComponent(target.column)),substitutedSql=substituteAnchorPlaceholders(spec.query,formattedColumns).trim();enforceSubqueryConstraints(substitutedSql);let subquery=SelectQueryParser.parse(substitutedSql),parameterNames=new Set(ParameterCollector.collect(subquery).map(parameter=>parameter.name.value));if(parameterNames.size!==1||!parameterNames.has(parameterName))throw new Error(`SSSQL ${spec.kind.toUpperCase()} scaffold query must reference only parameter ':${parameterName}'.`);let branch=buildOptionalExistsBranch(parameterName,subquery,spec.kind),branchSql=normalizeSql(formatSqlComponent(branch));this.list(root).find(existing=>existing.query===targetQuery&&normalizeSql(existing.sql)===branchSql)||targetQuery.appendWhere(branch)}resolveTarget(root,filterName){let qualified=parseQualifiedFilterName(filterName),lookupColumn=qualified?.column??filterName.trim(),matches=[...new Set(this.finder.find(root,lookupColumn))].map(query=>this.resolveTargetInQuery(query,filterName,qualified)).filter(target=>target!==null);if(matches.length===0)throw new Error(`Could not resolve SSSQL filter target '${filterName}' in the current query graph.`);if(matches.length>1)throw new Error(`SSSQL filter target '${filterName}' is ambiguous across multiple query scopes.`);return matches[0]}resolveTargetInQuery(query,filterName,qualified){return qualified?this.resolveQualifiedTarget(query,qualified):this.resolveUnqualifiedTarget(query,filterName)}resolveQualifiedTarget(query,filterName){let alias=this.findAliasForTable(query,filterName.table);if(!alias)return null;let matches=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query).filter(entry=>entry.value instanceof ColumnReference).filter(entry=>normalizeColumnReferenceKey(entry.value)===`${normalizeIdentifier2(alias)}.${normalizeIdentifier2(filterName.column)}`);if(matches.length===0)return null;if(matches.length>1)throw new Error(`SSSQL scaffold target '${filterName.table}.${filterName.column}' resolved to multiple columns.`);return{query,column:matches[0].value,parameterName:makeParameterName(`${filterName.table}.${filterName.column}`)}}resolveUnqualifiedTarget(query,filterName){let matches=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query).filter(entry=>entry.value instanceof ColumnReference).filter(entry=>normalizeIdentifier2(entry.name)===normalizeIdentifier2(filterName));if(matches.length===0)return null;if(matches.length>1)throw new Error(`SSSQL scaffold target '${filterName}' is ambiguous. Use a qualified table.column reference.`);return{query,column:matches[0].value,parameterName:makeParameterName(filterName)}}tryResolveTarget(root,filterName){try{return this.resolveTarget(root,filterName)}catch{return null}}findAliasForTable(query,tableName){let normalizedTable=normalizeIdentifier2(tableName),matchingAliases=(query.fromClause?.getSources()??[]).map(source=>this.resolveAliasForSource(source,normalizedTable)).filter(alias=>alias!==null);if(matchingAliases.length===0)return null;if(matchingAliases.length>1)throw new Error(`SSSQL scaffold target table '${tableName}' is ambiguous in the selected query scope.`);return matchingAliases[0]}resolveAliasForSource(source,normalizedTable){if(!(source.datasource instanceof TableSource))return null;let sourceName=normalizeIdentifier2(source.datasource.getSourceName()),shortName=normalizeIdentifier2(source.datasource.table.name);return sourceName!==normalizedTable&&shortName!==normalizedTable?null:source.getAliasName()??source.datasource.table.name}buildCorrelatedRefreshPlan(root,branch){let details=getExistsPredicateDetails(branch.expression,branch.parameterName);if(!details)return null;let sourceAliases=this.collectSourceAliases(branch.query),candidatesByKey=new Map;for(let reference of new ColumnReferenceCollector().collect(details.subquery)){let namespace=normalizeIdentifier2(reference.getNamespace());if(!namespace||!sourceAliases.has(namespace))continue;let column=normalizeIdentifier2(reference.column.name),key=`${namespace}.${column}`;candidatesByKey.has(key)||candidatesByKey.set(key,{namespace,column})}let candidates=[...candidatesByKey.values()];if(candidates.length===0)throw new Error(`SSSQL refresh could not infer a correlated anchor for ':${branch.parameterName}'.`);if(candidates.length>1){let listed=candidates.map(candidate=>`${candidate.namespace}.${candidate.column}`).join(", ");throw new Error(`SSSQL refresh found multiple correlated anchor candidates for ':${branch.parameterName}' (${listed}).`)}let[anchor]=candidates;if(!anchor)throw new Error(`SSSQL refresh could not infer a correlated anchor for ':${branch.parameterName}'.`);return{target:this.resolveCorrelatedAnchorTarget(root,branch.query,anchor,branch.parameterName),sourceAlias:anchor.namespace}}collectSourceAliases(query){let aliases=new Set;for(let source of query.fromClause?.getSources()??[]){let sourceAlias=this.getSourceAlias(source);sourceAlias&&aliases.add(sourceAlias)}return aliases}resolveCorrelatedAnchorTarget(root,sourceQuery,anchor,parameterName){let sourceExpression=this.findSourceExpressionByAlias(sourceQuery,anchor.namespace,parameterName),upstreamQuery=this.resolveSourceExpressionToUpstreamQuery(root,sourceExpression,parameterName);return upstreamQuery?this.resolveAnchorTargetInQuery(upstreamQuery,anchor,parameterName):{query:sourceQuery,column:new ColumnReference(anchor.namespace,anchor.column),parameterName}}findSourceExpressionByAlias(query,alias,parameterName){let matches=(query.fromClause?.getSources()??[]).filter(source=>this.getSourceAlias(source)===alias);if(matches.length===0)throw new Error(`SSSQL refresh could not resolve correlated alias '${alias}' for ':${parameterName}'.`);if(matches.length>1)throw new Error(`SSSQL refresh found multiple correlated sources for alias '${alias}' and ':${parameterName}'.`);return matches[0]}resolveSourceExpressionToUpstreamQuery(root,source,parameterName){if(source.datasource instanceof SubQuerySource){if(source.datasource.query instanceof SimpleSelectQuery)return source.datasource.query;throw new Error(`SSSQL refresh requires a simple query anchor for ':${parameterName}'.`)}if(!(source.datasource instanceof TableSource))return null;let cteName=normalizeIdentifier2(source.datasource.table.name),cteMatches=new CTECollector().collect(root).filter(cte2=>normalizeIdentifier2(cte2.getSourceAliasName())===cteName);if(cteMatches.length===0)return null;if(cteMatches.length>1)throw new Error(`SSSQL refresh found multiple CTE anchors for ':${parameterName}' (${source.datasource.table.name}).`);let[cte]=cteMatches;if(!cte)return null;let cteQuery=cte.query;if(!(cteQuery instanceof SimpleSelectQuery))throw new Error(`SSSQL refresh requires a simple CTE anchor for ':${parameterName}'.`);return cteQuery}resolveAnchorTargetInQuery(query,anchor,parameterName){let matches=new SelectableColumnCollector(this.tableColumnResolver,!1,"fullName",{upstream:!0}).collect(query).filter(entry=>entry.value instanceof ColumnReference).filter(entry=>normalizeIdentifier2(entry.name)===anchor.column);if(matches.length===0)throw new Error(`SSSQL refresh could not resolve correlated anchor column '${anchor.column}' for ':${parameterName}'.`);if(matches.length>1)throw new Error(`SSSQL refresh found multiple correlated anchor columns '${anchor.column}' for ':${parameterName}'.`);return{query,column:matches[0].value,parameterName}}getSourceAlias(source){let explicitAlias=source.getAliasName();return explicitAlias?normalizeIdentifier2(explicitAlias):source.datasource instanceof TableSource?normalizeIdentifier2(source.datasource.table.name):null}rebaseMovedBranch(expression,sourceQuery,targetColumn){let targetNamespace=targetColumn.qualifiedName.namespaces?targetColumn.qualifiedName.namespaces.map(namespace=>namespace.name):null,targetColumnName=normalizeIdentifier2(targetColumn.column.name),sourceAliases=new Set(collectColumnReferencesDeep(expression).filter(reference=>normalizeIdentifier2(reference.column.name)===targetColumnName).map(reference=>normalizeIdentifier2(reference.getNamespace())).filter(namespace=>namespace.length>0));if(sourceAliases.size===0)return;if(sourceAliases.size>1){let aliases=[...sourceAliases].join(", ");throw new Error(`SSSQL refresh cannot safely rebase '${targetColumn.column.name}' across multiple aliases (${aliases}).`)}let[sourceAlias]=[...sourceAliases];if(new Set((sourceQuery.fromClause?.getSources()??[]).map(source=>source.getAliasName()).filter(alias=>typeof alias=="string").map(alias=>normalizeIdentifier2(alias))).has(sourceAlias))for(let reference of collectColumnReferencesDeep(expression))normalizeIdentifier2(reference.getNamespace())===sourceAlias&&(reference.qualifiedName.namespaces=targetNamespace?.map(namespace=>new IdentifierString(namespace))??null)}rebaseMovedBranchByAlias(expression,sourceAlias,targetColumn){let normalizedSourceAlias=normalizeIdentifier2(sourceAlias);if(!normalizedSourceAlias)return;let targetNamespace=targetColumn.qualifiedName.namespaces?targetColumn.qualifiedName.namespaces.map(namespace=>namespace.name):null;for(let reference of collectColumnReferencesDeep(expression))normalizeIdentifier2(reference.getNamespace())===normalizedSourceAlias&&(reference.qualifiedName.namespaces=targetNamespace?.map(namespace=>new IdentifierString(namespace))??null)}},scaffoldSssqlQuery=(sqlContent,filters)=>({query:new SSSQLFilterBuilder().scaffold(sqlContent,filters)}),refreshSssqlQuery=(sqlContent,filters)=>({query:new SSSQLFilterBuilder().refresh(sqlContent,filters)});var BaseDataFlowNode=class{constructor(id,label,type,shape,details){this.id=id;this.label=label;this.type=type;this.shape=shape;this.details=details}},DataSourceNode=class _DataSourceNode extends BaseDataFlowNode{constructor(id,label,type){super(id,label,type,type==="subquery"?"hexagon":"cylinder");this.annotations=new Set}addAnnotation(annotation){this.annotations.add(annotation)}hasAnnotation(annotation){return this.annotations.has(annotation)}getMermaidRepresentation(){return this.shape==="hexagon"?`${this.id}{{${this.label}}}`:`${this.id}[(${this.label})]`}static createTable(tableName){return new _DataSourceNode(`table_${tableName}`,tableName,"table")}static createCTE(cteName){return new _DataSourceNode(`cte_${cteName}`,`CTE:${cteName}`,"cte")}static createSubquery(alias){return new _DataSourceNode(`subquery_${alias}`,`SubQuery:${alias}`,"subquery")}},ProcessNode=class _ProcessNode extends BaseDataFlowNode{constructor(id,operation,context=""){let nodeId=context?`${context}_${operation.toLowerCase().replace(/\s+/g,"_")}`:operation.toLowerCase().replace(/\s+/g,"_");super(nodeId,operation,"process","hexagon")}getMermaidRepresentation(){return`${this.id}{{${this.label}}}`}static createWhere(context){return new _ProcessNode(`${context}_where`,"WHERE",context)}static createGroupBy(context){return new _ProcessNode(`${context}_group_by`,"GROUP BY",context)}static createHaving(context){return new _ProcessNode(`${context}_having`,"HAVING",context)}static createSelect(context){return new _ProcessNode(`${context}_select`,"SELECT",context)}static createOrderBy(context){return new _ProcessNode(`${context}_order_by`,"ORDER BY",context)}static createLimit(context,hasOffset=!1){let label=hasOffset?"LIMIT/OFFSET":"LIMIT";return new _ProcessNode(`${context}_limit`,label,context)}},OperationNode=class _OperationNode extends BaseDataFlowNode{constructor(id,operation,shape="diamond"){super(id,operation,"operation",shape)}getMermaidRepresentation(){switch(this.shape){case"rounded":return`${this.id}(${this.label})`;case"rectangle":return`${this.id}[${this.label}]`;case"hexagon":return`${this.id}{{${this.label}}}`;case"stadium":return`${this.id}([${this.label}])`;case"diamond":default:return`${this.id}{${this.label}}`}}static createJoin(joinId,joinType){let label,normalizedType=joinType.trim().toLowerCase();return normalizedType==="join"?label="INNER JOIN":normalizedType.endsWith(" join")?label=normalizedType.toUpperCase():label=normalizedType.toUpperCase()+" JOIN",new _OperationNode(`join_${joinId}`,label,"rectangle")}static createUnion(unionId,unionType="UNION ALL"){return new _OperationNode(`${unionType.toLowerCase().replace(/\s+/g,"_")}_${unionId}`,unionType.toUpperCase(),"rectangle")}static createSetOperation(operationId,operation){let normalizedOp=operation.toUpperCase(),id=`${normalizedOp.toLowerCase().replace(/\s+/g,"_")}_${operationId}`;return new _OperationNode(id,normalizedOp,"rectangle")}},OutputNode=class extends BaseDataFlowNode{constructor(context="main"){let label=context==="main"?"Final Result":`${context} Result`;super(`${context}_output`,label,"output","stadium")}getMermaidRepresentation(){return`${this.id}([${this.label}])`}};var DataFlowConnection=class _DataFlowConnection{constructor(from,to,label){this.from=from;this.to=to;this.label=label}getMermaidRepresentation(){let arrow=this.label?` -->|${this.label}| `:" --> ";return`${this.from}${arrow}${this.to}`}static create(from,to,label){return new _DataFlowConnection(from,to,label)}static createWithNullability(from,to,isNullable){let label=isNullable?"NULLABLE":"NOT NULL";return new _DataFlowConnection(from,to,label)}},DataFlowEdgeCollection=class{constructor(){this.edges=[];this.connectionSet=new Set}add(edge){let key=`${edge.from}->${edge.to}`;this.connectionSet.has(key)||(this.edges.push(edge),this.connectionSet.add(key))}addConnection(from,to,label){this.add(DataFlowConnection.create(from,to,label))}addJoinConnection(from,to,isNullable){this.add(DataFlowConnection.createWithNullability(from,to,isNullable))}hasConnection(from,to){return this.connectionSet.has(`${from}->${to}`)}getAll(){return[...this.edges]}getMermaidRepresentation(){return this.edges.map(edge=>edge.getMermaidRepresentation()).join(`
50
50
  `)}};var DataFlowGraph=class{constructor(){this.nodes=new Map;this.edges=new DataFlowEdgeCollection}addNode(node){this.nodes.set(node.id,node)}addEdge(edge){this.edges.add(edge)}addConnection(from,to,label){this.edges.addConnection(from,to,label)}hasNode(nodeId){return this.nodes.has(nodeId)}hasConnection(from,to){return this.edges.hasConnection(from,to)}getNode(nodeId){return this.nodes.get(nodeId)}getAllNodes(){return Array.from(this.nodes.values())}getAllEdges(){return this.edges.getAll()}generateMermaid(direction="TD",title){let mermaid=`flowchart ${direction}
51
51
  `;title&&(mermaid+=` %% ${title}
52
52
  `);let nodeLines=Array.from(this.nodes.values()).map(node=>` ${node.getMermaidRepresentation()}`).join(`