rawsql-ts
Version:
[beta]High-performance SQL parser and AST analyzer written in TypeScript. Provides fast parsing and advanced transformation capabilities.
9 lines • 524 kB
JavaScript
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var index_exports={};__export(index_exports,{AliasRenamer:()=>AliasRenamer,ArrayExpression:()=>ArrayExpression,ArrayIndexExpression:()=>ArrayIndexExpression,ArrayQueryExpression:()=>ArrayQueryExpression,ArraySliceExpression:()=>ArraySliceExpression,BetweenExpression:()=>BetweenExpression,BinaryExpression:()=>BinaryExpression,BinarySelectQuery:()=>BinarySelectQuery,CTECollector:()=>CTECollector,CTEComposer:()=>CTEComposer,CTEDependencyAnalyzer:()=>CTEDependencyAnalyzer,CTEDisabler:()=>CTEDisabler,CTENormalizer:()=>CTENormalizer,CTENotFoundError:()=>CTENotFoundError,CTEQueryDecomposer:()=>CTEQueryDecomposer,CTERegionDetector:()=>CTERegionDetector,CTERenamer:()=>CTERenamer,CTETableReferenceCollector:()=>CTETableReferenceCollector,CaseExpression:()=>CaseExpression,CaseKeyValuePair:()=>CaseKeyValuePair,CastExpression:()=>CastExpression,ColumnReference:()=>ColumnReference,ColumnReferenceCollector:()=>ColumnReferenceCollector,CommentEditor:()=>CommentEditor,CursorContextAnalyzer:()=>CursorContextAnalyzer,DuplicateCTEError:()=>DuplicateCTEError,DuplicateDetectionMode:()=>DuplicateDetectionMode,DynamicQueryBuilder:()=>DynamicQueryBuilder,FilterableItem:()=>FilterableItem,FilterableItemCollector:()=>FilterableItemCollector,Formatter:()=>Formatter,FunctionCall:()=>FunctionCall,IdentifierString:()=>IdentifierString,InlineQuery:()=>InlineQuery,InsertQuery:()=>InsertQuery,InsertQueryParser:()=>InsertQueryParser,InvalidCTENameError:()=>InvalidCTENameError,JsonMappingConverter:()=>JsonMappingConverter,JsonSchemaValidator:()=>JsonSchemaValidator,LexemeCursor:()=>LexemeCursor,LiteralValue:()=>LiteralValue,MultiQuerySplitter:()=>MultiQuerySplitter,MultiQueryUtils:()=>MultiQueryUtils,OriginalFormatRestorer:()=>OriginalFormatRestorer,ParameterExpression:()=>ParameterExpression,ParenExpression:()=>ParenExpression,PositionAwareParser:()=>PositionAwareParser,PostgresJsonQueryBuilder:()=>PostgresJsonQueryBuilder,QualifiedName:()=>QualifiedName,QueryBuilder:()=>QueryBuilder,QueryFlowDiagramGenerator:()=>QueryFlowDiagramGenerator,RawString:()=>RawString,SchemaCollector:()=>SchemaCollector,SchemaManager:()=>SchemaManager,ScopeResolver:()=>ScopeResolver,SelectQueryParser:()=>SelectQueryParser,SelectValueCollector:()=>SelectValueCollector,SelectableColumnCollector:()=>SelectableColumnCollector,SimpleSelectQuery:()=>SimpleSelectQuery,SmartRenamer:()=>SmartRenamer,SqlComponent:()=>SqlComponent,SqlDialectConfiguration:()=>SqlDialectConfiguration,SqlFormatter:()=>SqlFormatter,SqlIdentifierRenamer:()=>SqlIdentifierRenamer,SqlPaginationInjector:()=>SqlPaginationInjector,SqlParamInjector:()=>SqlParamInjector,SqlSchemaValidator:()=>SqlSchemaValidator,SqlSortInjector:()=>SqlSortInjector,StringSpecifierExpression:()=>StringSpecifierExpression,SwitchCaseArgument:()=>SwitchCaseArgument,TableSchema:()=>TableSchema,TableSourceCollector:()=>TableSourceCollector,TokenType:()=>TokenType,TupleExpression:()=>TupleExpression,TypeTransformationPostProcessor:()=>TypeTransformationPostProcessor,TypeTransformers:()=>TypeTransformers,TypeValue:()=>TypeValue,UnaryExpression:()=>UnaryExpression,UpstreamSelectQueryFinder:()=>UpstreamSelectQueryFinder,VALID_PRESETS:()=>VALID_PRESETS,ValueList:()=>ValueList,ValuesQuery:()=>ValuesQuery,WindowFrameBound:()=>WindowFrameBound,WindowFrameBoundStatic:()=>WindowFrameBoundStatic,WindowFrameBoundaryValue:()=>WindowFrameBoundaryValue,WindowFrameExpression:()=>WindowFrameExpression,WindowFrameSpec:()=>WindowFrameSpec,WindowFrameType:()=>WindowFrameType,WithClauseParser:()=>WithClauseParser,convertColumnsToLegacy:()=>convertColumnsToLegacy,convertModelDrivenMapping:()=>convertModelDrivenMapping,convertToLegacyJsonMapping:()=>convertToLegacyJsonMapping,createJsonMappingFromSchema:()=>createJsonMappingFromSchema,createSchemaManager:()=>createSchemaManager,createTableColumnResolver:()=>createTableColumnResolver,extractTypeProtection:()=>extractTypeProtection,getCompletionSuggestions:()=>getCompletionSuggestions,getCursorContext:()=>getCursorContext,getIntelliSenseInfo:()=>getIntelliSenseInfo,isLegacyFormat:()=>isLegacyFormat,isModelDrivenFormat:()=>isModelDrivenFormat,isUnifiedFormat:()=>isUnifiedFormat,parseToPosition:()=>parseToPosition,processJsonMapping:()=>processJsonMapping,resolveScope:()=>resolveScope,splitQueries:()=>splitQueries,toLegacyMapping:()=>toLegacyMapping,transformDatabaseResult:()=>transformDatabaseResult,unifyJsonMapping:()=>unifyJsonMapping,validateModelDrivenMapping:()=>validateModelDrivenMapping});module.exports=__toCommonJS(index_exports);var SqlComponent=class{constructor(){this.comments=null;this.positionedComments=null}getKind(){return this.constructor.kind}accept(visitor){return visitor.visit(this)}toSqlString(formatter){return this.accept(formatter)}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=!0}};var InsertQuery=class extends SqlComponent{static{this.kind=Symbol("InsertQuery")}constructor(params){super(),this.insertClause=params.insertClause,this.selectQuery=params.selectQuery??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){super(),this.qualifiedName=new QualifiedName(namespaces,name),this.argument=argument,this.over=over,this.withinGroup=withinGroup,this.withOrdinality=withOrdinality,this.internalOrderBy=internalOrderBy}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}};var 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){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}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}},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}};var 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}};var 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(columns){super(),this.columns=columns.map(col=>typeof col=="string"?new IdentifierString(col):col)}},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}},InsertClause=class extends SqlComponent{constructor(source,columns){super(),this.source=source,this.columns=columns.map(col=>new IdentifierString(col))}};var TokenType=(TokenType2=>(TokenType2[TokenType2.None=0]="None",TokenType2[TokenType2.Literal=1]="Literal",TokenType2[TokenType2.Operator=2]="Operator",TokenType2[TokenType2.OpenParen=4]="OpenParen",TokenType2[TokenType2.CloseParen=8]="CloseParen",TokenType2[TokenType2.Comma=16]="Comma",TokenType2[TokenType2.Dot=32]="Dot",TokenType2[TokenType2.Identifier=64]="Identifier",TokenType2[TokenType2.Command=128]="Command",TokenType2[TokenType2.Parameter=256]="Parameter",TokenType2[TokenType2.OpenBracket=512]="OpenBracket",TokenType2[TokenType2.CloseBracket=1024]="CloseBracket",TokenType2[TokenType2.Function=2048]="Function",TokenType2[TokenType2.StringSpecifier=4096]="StringSpecifier",TokenType2[TokenType2.Type=8192]="Type",TokenType2))(TokenType||{});var CharLookupTable=class{static isWhitespace(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code===32||code===9||code===10||code===13}static isDigit(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code>=48&&code<=57}static isHexChar(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code>=48&&code<=57||code>=97&&code<=102||code>=65&&code<=70}static isOperatorSymbol(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code===43||code===45||code===42||code===47||code===37||code===126||code===64||code===35||code===94||code===38||code===58||code===33||code===60||code===62||code===61||code===124||code===63}static isDelimiter(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code===46||code===44||code===40||code===41||code===91||code===93||code===123||code===125||code===59||code===32||code===9||code===10||code===13?!0:code===43||code===45||code===42||code===47||code===37||code===126||code===64||code===35||code===94||code===38||code===58||code===33||code===60||code===62||code===61||code===124||code===63}static isNamedParameterPrefix(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code===64||code===58||code===36}};var StringUtils=class _StringUtils{static getDebugPositionInfo(input,errPosition){let start=Math.max(0,errPosition-5),end=Math.min(input.length,errPosition+5),debugInfo=input.slice(start,end),caret=" ".repeat(errPosition-start)+"^";return`${debugInfo}
${caret}`}static skipWhiteSpace(input,position){let length=input.length;for(;position+4<=length&&input.slice(position,position+4)===" ";)position+=4;for(;position<length;){let charCode=input.charCodeAt(position);if(charCode!==32&&charCode!==9&&charCode!==10&&charCode!==13)break;position++}return position}static readLineComment(input,position){if(position+1>=input.length)return{newPosition:position,comment:null};if(input.charCodeAt(position)===45&&input.charCodeAt(position+1)===45){let start=position;for(position+=2;position<input.length&&input.charCodeAt(position)!==10;)position++;let comment=input.slice(start+2,position).trim();return{newPosition:position,comment}}return{newPosition:position,comment:null}}static readBlockComment(input,position){if(position+1>=input.length)return{newPosition:position,comments:null};if(input.charCodeAt(position)!==47||input.charCodeAt(position+1)!==42)return{newPosition:position,comments:null};if(position+2<input.length&&input.charCodeAt(position+2)===43)return{newPosition:position,comments:null};let start=position;for(position+=2;position+1<input.length;){if(input.charCodeAt(position)===42&&input.charCodeAt(position+1)===47){position+=2;let processedLines=this.processBlockCommentContent(input.slice(start+2,position-2));return{newPosition:position,comments:processedLines}}position++}let processedLinesUnterminated=this.processBlockCommentContent(input.slice(start+2));return{newPosition:input.length,comments:processedLinesUnterminated}}static processBlockCommentContent(rawContent){let rawLines=rawContent.replace(/\r/g,"").split(`
`),processedLines=[];for(let rawLine of rawLines){let trimmedLine=rawLine.trim(),isSeparatorLine=/^\s*[-=_+*#]+\s*$/.test(rawLine);trimmedLine!==""||isSeparatorLine?processedLines.push(isSeparatorLine?rawLine.trim():trimmedLine):processedLines.push("")}for(;processedLines.length>0&&processedLines[0]==="";)processedLines.shift();for(;processedLines.length>0&&processedLines[processedLines.length-1]==="";)processedLines.pop();return processedLines}static readWhiteSpaceAndComment(input,position){let lines=null,length=input.length;for(;position<length;){let oldPosition=position;if(position=_StringUtils.skipWhiteSpace(input,position),position!==oldPosition)continue;let charCode=input.charCodeAt(position);if(charCode===45){let lineCommentResult=_StringUtils.readLineComment(input,position);if(lineCommentResult.newPosition!==position){position=lineCommentResult.newPosition,lineCommentResult.comment&&(lines===null&&(lines=[]),lines.push(lineCommentResult.comment.trim()));continue}}else if(charCode===47){let blockCommentResult=_StringUtils.readBlockComment(input,position);if(blockCommentResult.newPosition!==position){position=blockCommentResult.newPosition,blockCommentResult.comments&&(lines===null&&(lines=[]),lines.push(...blockCommentResult.comments));continue}}break}return{position,lines}}static readRegularIdentifier(input,position){let result=this.tryReadRegularIdentifier(input,position);if(!result)throw new Error(`Unexpected character. position: ${position}
${_StringUtils.getDebugPositionInfo(input,position)}`);return result}static tryReadRegularIdentifier(input,position){let start=position;for(;position<input.length&&!CharLookupTable.isDelimiter(input[position]);)position++;if(start===position)return null;for(;position+1<input.length&&input[position]==="["&&input[position+1]==="]";){let beforeIdentifier=input.slice(0,start).trim();if(beforeIdentifier===""||/[)]$/.test(beforeIdentifier)||/\b(select|from|where|and|or|set|values|insert|update|delete)\s*$/i.test(beforeIdentifier))break;position+=2}return{identifier:input.slice(start,position),newPosition:position}}};var BaseTokenReader=class{constructor(input,position=0){this.input=input,this.position=position}getPosition(){return this.position}setPosition(position){this.position=position}isEndOfInput(shift=0){return this.position+shift>=this.input.length}canRead(shift=0){return!this.isEndOfInput(shift)}read(expectChar){if(this.isEndOfInput())throw new Error(`Unexpected character. expect: ${expectChar}, actual: EndOfInput, position: ${this.position}`);let char=this.input[this.position];if(char!==expectChar)throw new Error(`Unexpected character. expect: ${expectChar}, actual: ${char}, position: ${this.position}`);return this.position++,char}createLexeme(type,value,comments=null,startPosition,endPosition){let lexeme={type,value:type===128||type===2||type===2048?value.toLowerCase():value,comments};return startPosition!==void 0&&endPosition!==void 0&&(lexeme.position={startPosition,endPosition}),lexeme}createLexemeWithPosition(type,value,startPos,comments=null){return this.createLexeme(type,value,comments,startPos,startPos+value.length)}getDebugPositionInfo(errPosition){return StringUtils.getDebugPositionInfo(this.input,errPosition)}};var IdentifierTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(char==="*")return this.position++,this.createLexeme(64,char);let result=StringUtils.readRegularIdentifier(this.input,this.position);return this.position=result.newPosition,this.createLexeme(64,result.identifier)}};var KeywordParser=class{constructor(trie5){this.trie=trie5}isEndOfInput(input,position,shift=0){return position+shift>=input.length}canParse(input,position,shift=0){return!this.isEndOfInput(input,position,shift)}parse(input,position){if(this.isEndOfInput(input,position))return null;this.trie.reset();let result=StringUtils.tryReadRegularIdentifier(input,position);if(result===null)return null;let matchResult=this.trie.pushLexeme(result.identifier.toLowerCase());if(matchResult===0)return null;if(matchResult===3)return{keyword:result.identifier,newPosition:result.newPosition};let lexeme=result.identifier,commentResult=StringUtils.readWhiteSpaceAndComment(input,result.newPosition);position=commentResult.position;let collectedComments=commentResult.lines?[...commentResult.lines]:[];if(this.isEndOfInput(input,position))return matchResult===2?{keyword:lexeme,newPosition:position,comments:collectedComments.length>0?collectedComments:void 0}:null;for(;this.canParse(input,position);){let previousMatchResult=matchResult,result2=StringUtils.tryReadRegularIdentifier(input,position);if(result2!==null){if(matchResult=this.trie.pushLexeme(result2.identifier.toLowerCase()),matchResult===0){if(previousMatchResult===2)break;return null}lexeme+=" "+result2.identifier;let nextCommentResult=StringUtils.readWhiteSpaceAndComment(input,result2.newPosition);if(position=nextCommentResult.position,nextCommentResult.lines&&nextCommentResult.lines.length>0&&collectedComments.push(...nextCommentResult.lines),matchResult===3)break}else{if(previousMatchResult===2)break;return null}}return{keyword:lexeme,newPosition:position,comments:collectedComments.length>0?collectedComments:void 0}}};var KeywordTrie=class{constructor(keywords2){this.root=new Map;this.hasEndProperty=!1;this.hasMoreProperties=!1;for(let keyword of keywords2)this.addKeyword(keyword);this.currentNode=this.root}addKeyword(keyword){let node=this.root;for(let word of keyword)node.has(word)||node.set(word,new Map),node=node.get(word);node.set("__end__",!0)}reset(){this.currentNode=this.root,this.hasEndProperty=!1,this.hasMoreProperties=!1}pushLexeme(lexeme){return this.currentNode.has(lexeme)?(this.currentNode=this.currentNode.get(lexeme),this.hasEndProperty=this.currentNode.has("__end__"),this.hasMoreProperties=this.currentNode.size>(this.hasEndProperty?1:0),this.hasEndProperty&&!this.hasMoreProperties?3:this.hasEndProperty&&this.hasMoreProperties?2:1):0}};var keywords=[["null"],["true"],["false"],["current_date"],["current_time"],["current_timestamp"],["localtime"],["localtimestamp"],["unbounded"],["normalized"],["nfc","normalized"],["nfd","normalized"],["nfkc","normalized"],["nfkd","normalized"],["nfc"],["nfd"],["nfkc"],["nfkd"]],trie=new KeywordTrie(keywords),literalKeywordParser=new KeywordParser(trie),LiteralTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(char==="'"){let value=this.readSingleQuotedString();return this.createLexeme(1,value)}let keyword=this.tryReadKeyword();if(keyword)return keyword;if(char==="."&&this.canRead(1)&&CharLookupTable.isDigit(this.input[this.position+1]))return this.createLexeme(1,this.readDigit());if(CharLookupTable.isDigit(char))return this.createLexeme(1,this.readDigit());if(char==="$"&&this.isDollarQuotedString())return this.createLexeme(1,this.readDollarQuotedString());if(char==="$"&&this.canRead(1)&&CharLookupTable.isDigit(this.input[this.position+1])){let pos=this.position+1,hasDecimalOrComma=!1;for(;pos<this.input.length&&(CharLookupTable.isDigit(this.input[pos])||this.input[pos]===","||this.input[pos]===".");){if(this.input[pos]==="."||this.input[pos]===","){hasDecimalOrComma=!0;break}pos++}if(hasDecimalOrComma){this.position++;let numberPart=this.readMoneyDigit();return this.createLexeme(1,"$"+numberPart)}}if((char==="+"||char==="-")&&this.determineSignOrOperator(previous)==="sign"){let sign=char;this.position++;let pos=this.position;for(;this.canRead()&&CharLookupTable.isWhitespace(this.input[this.position]);)this.position++;if(this.canRead()&&(CharLookupTable.isDigit(this.input[this.position])||this.input[this.position]==="."&&this.canRead(1)&&CharLookupTable.isDigit(this.input[this.position+1])))return this.createLexeme(1,sign==="-"?sign+this.readDigit():this.readDigit());this.position=pos-1}return null}tryReadKeyword(){let result=literalKeywordParser.parse(this.input,this.position);return result?(this.position=result.newPosition,this.createLexeme(1,result.keyword)):null}determineSignOrOperator(previous){return previous===null?"sign":previous.type&1||previous.type&64||previous.type&256||previous.type&8?"operator":"sign"}readDigit(){let start=this.position,hasDot=!1,hasExponent=!1;if(this.canRead(1)&&this.input[this.position]==="0"&&"xbo".includes(this.input[this.position+1].toLowerCase())){let prefixType=this.input[this.position+1].toLowerCase();this.position+=2;let isHex=prefixType==="x";for(;this.canRead();){let c=this.input[this.position];if(CharLookupTable.isDigit(c)||isHex&&CharLookupTable.isHexChar(c))this.position++;else break}return this.input.slice(start,this.position)}for(this.input[start]==="."&&(hasDot=!0,this.position++);this.canRead();){let char=this.input[this.position];if(char==="."&&!hasDot)hasDot=!0;else if((char==="e"||char==="E")&&!hasExponent)hasExponent=!0,this.canRead(1)&&(this.input[this.position+1]==="+"||this.input[this.position+1]==="-")&&this.position++;else if(!CharLookupTable.isDigit(char))break;this.position++}if(start===this.position)throw new Error(`Unexpected character. position: ${start}
${this.getDebugPositionInfo(start)}`);return this.input[start]==="."?"0"+this.input.slice(start,this.position):this.input.slice(start,this.position)}readMoneyDigit(){let start=this.position,hasDot=!1;for(;this.canRead();){let char=this.input[this.position];if(char==="."&&!hasDot)hasDot=!0;else if(!(char===","&&!hasDot)){if(!CharLookupTable.isDigit(char))break}this.position++}if(start===this.position)throw new Error(`Unexpected character. position: ${start}
${this.getDebugPositionInfo(start)}`);return this.input.slice(start,this.position)}readSingleQuotedString(){let start=this.position,closed=!1;for(this.read("'");this.canRead();){let char=this.input[this.position];if(this.position++,char==="\\"&&this.canRead(1)){this.position++;continue}else if(char==="'"){closed=!0;break}}if(closed===!1)throw new Error(`Single quote is not closed. position: ${start}
${this.getDebugPositionInfo(start)}`);return this.input.slice(start,this.position)}isDollarQuotedString(){if(!this.canRead(1))return!1;if(this.input[this.position+1]==="$")return!0;let pos=this.position+1;for(;pos<this.input.length;){let char=this.input[pos];if(char==="$")return!0;if(!this.isAlphanumeric(char)&&char!=="_")return!1;pos++}return!1}readDollarQuotedString(){let start=this.position;this.position++;let tag="";for(;this.canRead()&&this.input[this.position]!=="$";)tag+=this.input[this.position],this.position++;if(!this.canRead())throw new Error(`Unexpected end of input while reading dollar-quoted string tag at position ${start}`);this.position++;let openingTag="$"+tag+"$",closingTag=openingTag,content="";for(;this.canRead();){if(this.input.substring(this.position,this.position+closingTag.length)===closingTag)return this.position+=closingTag.length,openingTag+content+closingTag;content+=this.input[this.position],this.position++}throw new Error(`Unclosed dollar-quoted string starting at position ${start}. Expected closing tag: ${closingTag}`)}isAlphanumeric(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122}};var ParameterTokenReader=class extends BaseTokenReader{constructor(input){super(input)}tryRead(previous){if(this.isEndOfInput())return null;if(this.canRead(1)&&this.input[this.position]==="$"&&this.input[this.position+1]==="{"){this.position+=2;let start=this.position;for(;this.canRead()&&this.input[this.position]!=="}";)this.position++;if(this.isEndOfInput())throw new Error(`Unexpected end of input. Expected closing '}' for parameter at position ${start}`);let identifier=this.input.slice(start,this.position);if(identifier.length===0)throw new Error("Empty parameter name is not allowed: found ${} at position "+(start-2));return this.position++,this.createLexeme(256,"${"+identifier+"}")}let char=this.input[this.position];if(CharLookupTable.isNamedParameterPrefix(char)){if(this.canRead(1)&&CharLookupTable.isOperatorSymbol(this.input[this.position+1])||char===":"&&this.isInArraySliceContext()||char==="$"&&this.isDollarQuotedString())return null;if(char==="$"&&this.canRead(1)&&CharLookupTable.isDigit(this.input[this.position+1])){let pos=this.position+1,hasDecimalOrComma=!1;for(;pos<this.input.length&&(CharLookupTable.isDigit(this.input[pos])||this.input[pos]===","||this.input[pos]===".");){if(this.input[pos]==="."||this.input[pos]===","){hasDecimalOrComma=!0;break}pos++}if(hasDecimalOrComma)return null}this.position++;let start=this.position;for(;this.canRead()&&!CharLookupTable.isDelimiter(this.input[this.position]);)this.position++;let identifier=this.input.slice(start,this.position);return this.createLexeme(256,char+identifier)}if(char==="?"){if(this.canRead(1)){let nextChar=this.input[this.position+1];if(nextChar==="|"||nextChar==="&")return null}return previous&&(previous.type&64||previous.type&1)?null:(this.position++,this.createLexeme(256,char))}return null}isInArraySliceContext(){let pos=this.position-1,bracketDepth=0,parenDepth=0;for(;pos>=0;){let char=this.input[pos];if(char==="]")bracketDepth++;else if(char==="["){if(bracketDepth--,bracketDepth<0){if(pos>0){let prevChar=this.input[pos-1];if(/[a-zA-Z0-9_)\]]/.test(prevChar))return!0}if(pos===0)return!1;break}}else char===")"?parenDepth++:char==="("&&parenDepth--;pos--}return!1}isDollarQuotedString(){if(!this.canRead(1))return!1;if(this.input[this.position+1]==="$")return!0;let pos=this.position+1;for(;pos<this.input.length;){let char=this.input[pos];if(char==="$")return!0;if(!this.isAlphanumeric(char)&&char!=="_")return!1;pos++}return!1}isAlphanumeric(char){if(char.length!==1)return!1;let code=char.charCodeAt(0);return code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122}};var SpecialSymbolTokenReader=class _SpecialSymbolTokenReader extends BaseTokenReader{static{this.SPECIAL_SYMBOL_TOKENS={".":32,",":16,"(":4,")":8,"[":512,"]":1024}}tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];return char in _SpecialSymbolTokenReader.SPECIAL_SYMBOL_TOKENS?(this.position++,this.createLexeme(_SpecialSymbolTokenReader.SPECIAL_SYMBOL_TOKENS[char],char)):null}};var TokenReaderManager=class{constructor(input,position=0){this.cacheHits=0;this.cacheMisses=0;this.input=input,this.position=position,this.readers=[],this.tokenCache=new Map}register(reader){return this.readers.push(reader),this}registerAll(readers){return readers.forEach(reader=>this.register(reader)),this}setPosition(position){this.position=position;for(let reader of this.readers)reader.setPosition(position)}tryRead(position,previous){if(this.tokenCache.has(position))return this.cacheHits++,this.tokenCache.get(position)||null;this.cacheMisses++,this.setPosition(position);let lexeme=null;for(let reader of this.readers)if(lexeme=reader.tryRead(previous),lexeme){this.position=reader.getPosition();break}for(let reader of this.readers)reader.setPosition(this.position);return this.tokenCache.set(position,lexeme),lexeme}getMaxPosition(){let maxPosition=this.position;for(let reader of this.readers){let position=reader.getPosition();position>maxPosition&&(maxPosition=position)}return maxPosition}getInput(){return this.input}getCacheStats(){let total=this.cacheHits+this.cacheMisses,ratio=total>0?this.cacheHits/total:0;return{hits:this.cacheHits,misses:this.cacheMisses,ratio}}};var trie2=new KeywordTrie([["and"],["or"],["is"],["is","not"],["is","distinct","from"],["is","not","distinct","from"],["like"],["ilike"],["in"],["exists"],["between"],["not","like"],["not","ilike"],["not","in"],["not","exists"],["not","between"],["escape"],["uescape"],["similar","to"],["not","similar","to"],["similar"],["placing"],["rlike"],["regexp"],["mod"],["xor"],["not"],["both"],["leading"],["trailing"],["both","from"],["leading","from"],["trailing","from"],["year","from"],["month","from"],["day","from"],["hour","from"],["minute","from"],["second","from"],["dow","from"],["doy","from"],["isodow","from"],["quarter","from"],["week","from"],["epoch","from"],["at","time","zone"]]),operatorOrTypeTrie=new KeywordTrie([["date"],["time"],["timestamp"],["timestamptz"],["timetz"],["interval"],["boolean"],["integer"],["bigint"],["smallint"],["numeric"],["decimal"],["real"],["double","precision"],["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),keywordParser=new KeywordParser(trie2),operatorOrTypeParser=new KeywordParser(operatorOrTypeTrie);var OperatorTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(CharLookupTable.isOperatorSymbol(char)){let start=this.position;for(;this.canRead()&&CharLookupTable.isOperatorSymbol(this.input[this.position])&&(this.position++,!!this.canRead());){let previous2=this.input[this.position-1],next=this.input[this.position];if(previous2==="-"&&next==="-"||previous2==="/"&&next==="*")break}this.position===start&&this.position++;let resut=this.input.slice(start,this.position);return this.createLexeme(2,resut)}let result=operatorOrTypeParser.parse(this.input,this.position);return result!==null?(this.position=result.newPosition,this.createLexeme(8258,result.keyword)):(result=keywordParser.parse(this.input,this.position),result!==null?(this.position=result.newPosition,this.createLexeme(2,result.keyword)):null)}};var joinTrie=new KeywordTrie([["join"],["inner","join"],["cross","join"],["left","join"],["left","outer","join"],["right","join"],["right","outer","join"],["full","join"],["full","outer","join"],["natural","join"],["natural","inner","join"],["natural","left","join"],["natural","left","outer","join"],["natural","right","join"],["natural","right","outer","join"],["natural","full","join"],["natural","full","outer","join"],["lateral","join"],["lateral","inner","join"],["lateral","left","join"],["lateral","left","outer","join"]]),keywordTrie=new KeywordTrie([["with"],["recursive"],["materialized"],["not","materialized"],["select"],["from"],["distinct"],["distinct","on"],["where"],["group","by"],["having"],["order","by"],["limit"],["offset"],["fetch"],["first"],["next"],["row"],["row","only"],["rows","only"],["percent"],["percent","with","ties"],["for"],["update"],["share"],["key","share"],["no","key","update"],["union"],["union","all"],["intersect"],["intersect","all"],["except"],["except","all"],["beteen"],["window"],["over"],["partition","by"],["range"],["rows"],["groups"],["within","group"],["with","ordinality"],["current","row"],["unbounded","preceding"],["unbounded","following"],["preceding"],["following"],["on"],["using"],["lateral"],["case"],["case","when"],["when"],["then"],["else"],["end"],["insert","into"],["update"],["delete","from"],["merge","into"],["matched"],["not","matched"],["update","set"],["do","nothing"],["values"],["set"],["returning"],["create","table"],["create","temporary","table"],["tablesample"],["as"],["asc"],["desc"],["nulls","first"],["nulls","last"]]),keywordParser2=new KeywordParser(keywordTrie),joinkeywordParser=new KeywordParser(joinTrie);var CommandTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let keywordJoin=joinkeywordParser.parse(this.input,this.position);if(keywordJoin!==null)return this.position=keywordJoin.newPosition,this.createLexeme(128,keywordJoin.keyword);let keyword=keywordParser2.parse(this.input,this.position);if(keyword!==null){this.position=keyword.newPosition;let lexeme=this.createLexeme(128,keyword.keyword,keyword.comments);return keyword.comments&&keyword.comments.length>0&&(lexeme.positionedComments=[{position:"after",comments:keyword.comments}]),lexeme}if(this.canRead(2)&&this.input[this.position]==="/"&&this.input[this.position+1]==="*"&&this.input[this.position+2]==="+"){this.position+=3;let start=this.position;for(;this.position+1<this.input.length;){if(this.input[this.position]==="*"&&this.input[this.position+1]==="/")return this.position+=2,this.createLexeme(128,"/*+ "+this.input.slice(start,this.position-2).trim()+" */");this.position++}throw new Error(`Block comment is not closed. position: ${this.position}`)}return null}};var STRING_SPECIFIERS=new Set(["e'","E'","x'","X'","b'","B'"]),UNICODE_STRING_SPECIFIERS=new Set(["u&'","U&'"]),StringSpecifierTokenReader=class extends BaseTokenReader{tryRead(previous){let start=this.position;return this.canRead(1)&&STRING_SPECIFIERS.has(this.input.slice(start,start+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(start,this.position))):this.canRead(2)&&UNICODE_STRING_SPECIFIERS.has(this.input.slice(start,start+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(start,this.position))):null}};var trie3=new KeywordTrie([["grouping","sets"],["array"]]),keywordParser3=new KeywordParser(trie3),FunctionTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let keyword=keywordParser3.parse(this.input,this.position);if(keyword!==null)return this.position=keyword.newPosition,this.createLexeme(2048,keyword.keyword);let result=StringUtils.tryReadRegularIdentifier(this.input,this.position);if(!result)return null;this.position=result.newPosition;var shift=StringUtils.readWhiteSpaceAndComment(this.input,this.position).position-this.position;return this.canRead(shift)&&this.input[this.position+shift]==="("?this.createLexeme(2048,result.identifier):null}};var trie4=new KeywordTrie([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),typeParser=new KeywordParser(trie4),TypeTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let keyword=typeParser.parse(this.input,this.position);if(keyword!==null)return this.position=keyword.newPosition,this.createLexeme(8192,keyword.keyword);if(previous===null)return null;let result=StringUtils.tryReadRegularIdentifier(this.input,this.position);return result?(this.position=result.newPosition,previous.type&128&&previous.value==="as"?this.createLexeme(8256,result.identifier):previous.type&2&&previous.value==="::"?this.createLexeme(8192,result.identifier):null):null}};var EscapedIdentifierTokenReader=class extends BaseTokenReader{tryRead(previous){if(this.isEndOfInput())return null;let char=this.input[this.position];if(char==="`"){let identifier=this.readEscapedIdentifier("`");return this.createLexeme(64,identifier)}if(char==='"'){let identifier=this.readEscapedIdentifier('"');return this.createLexeme(64,identifier)}if(char==="["&&this.isSqlServerBracketIdentifier(previous)){let identifier=this.readEscapedIdentifier("]");return this.createLexeme(64,identifier)}return null}isSqlServerBracketIdentifier(previous){if(previous?.value==="array")return!1;let start=this.position+1,pos=start;for(;pos<this.input.length&&this.input[pos]!=="]";){let char=this.input[pos];if(char===":"||char===","||char==="+"||char==="-"||char==="*"||char==="/"||char==="("||char===")")return!1;pos++}if(pos>=this.input.length)return!1;let content=this.input.slice(start,pos).trim();return content===""?!1:/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$/.test(content)}readEscapedIdentifier(delimiter){let start=this.position;this.position++;let foundClosing=!1;for(;this.canRead();){if(this.input[this.position]===delimiter){foundClosing=!0;break}this.position++}if(!foundClosing)throw new Error(`Closing delimiter is not found. position: ${start}, delimiter: ${delimiter}
${this.getDebugPositionInfo(start)}`);if(start===this.position)throw new Error(`Closing delimiter is not found. position: ${start}, delimiter: ${delimiter}
${this.getDebugPositionInfo(start)}`);return this.position++,this.input.slice(start+1,this.position-1)}};var SqlTokenizer=class _SqlTokenizer{constructor(input){this.input=input,this.position=0,this.readerManager=new TokenReaderManager(input).register(new EscapedIdentifierTokenReader(input)).register(new ParameterTokenReader(input)).register(new StringSpecifierTokenReader(input)).register(new LiteralTokenReader(input)).register(new SpecialSymbolTokenReader(input)).register(new CommandTokenReader(input)).register(new OperatorTokenReader(input)).register(new Type