rawsql-ts
Version:
[beta]High-performance SQL parser and AST analyzer written in TypeScript. Provides fast parsing and advanced transformation capabilities.
11 lines • 325 kB
JavaScript
"use strict";var gr=Object.defineProperty;var ri=Object.getOwnPropertyDescriptor;var ii=Object.getOwnPropertyNames;var si=Object.prototype.hasOwnProperty;var oi=(a,e)=>{for(var t in e)gr(a,t,{get:e[t],enumerable:!0})},ai=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ii(e))!si.call(a,r)&&r!==t&&gr(a,r,{get:()=>e[r],enumerable:!(n=ri(e,r))||n.enumerable});return a};var li=a=>ai(gr({},"__esModule",{value:!0}),a);var Ri={};oi(Ri,{AliasRenamer:()=>an,ArrayExpression:()=>ye,ArrayIndexExpression:()=>Ze,ArrayQueryExpression:()=>ve,ArraySliceExpression:()=>Ye,BetweenExpression:()=>we,BinaryExpression:()=>w,BinarySelectQuery:()=>Q,CTECollector:()=>X,CTEComposer:()=>sn,CTEDependencyAnalyzer:()=>pt,CTEDisabler:()=>bt,CTENormalizer:()=>Xe,CTENotFoundError:()=>jt,CTEQueryDecomposer:()=>Tr,CTERegionDetector:()=>ct,CTERenamer:()=>on,CTETableReferenceCollector:()=>tn,CaseExpression:()=>ne,CaseKeyValuePair:()=>Te,CastExpression:()=>ae,ColumnReference:()=>b,ColumnReferenceCollector:()=>At,CommentEditor:()=>nn,CursorContextAnalyzer:()=>Qt,DuplicateCTEError:()=>Wt,DuplicateDetectionMode:()=>Ct,DynamicQueryBuilder:()=>Ar,FilterableItem:()=>Lt,FilterableItemCollector:()=>Pr,Formatter:()=>ut,FunctionCall:()=>J,IdentifierString:()=>P,InlineQuery:()=>me,InsertQuery:()=>rt,InsertQueryParser:()=>xr,InvalidCTENameError:()=>xt,JsonMappingConverter:()=>Ut,JsonSchemaValidator:()=>$r,LexemeCursor:()=>Pe,LiteralValue:()=>Z,MultiQuerySplitter:()=>Ot,MultiQueryUtils:()=>Mr,OriginalFormatRestorer:()=>Ir,ParameterExpression:()=>N,ParenExpression:()=>Y,PositionAwareParser:()=>Sn,PostgresJsonQueryBuilder:()=>un,QualifiedName:()=>Ue,QueryBuilder:()=>$e,QueryFlowDiagramGenerator:()=>Vr,RawString:()=>B,SchemaCollector:()=>Pt,SchemaManager:()=>_t,ScopeResolver:()=>qt,SelectQueryParser:()=>A,SelectValueCollector:()=>De,SelectableColumnCollector:()=>Ee,SimpleSelectQuery:()=>C,SmartRenamer:()=>kr,SqlComponent:()=>v,SqlDialectConfiguration:()=>yr,SqlFormatter:()=>Qe,SqlIdentifierRenamer:()=>ln,SqlPaginationInjector:()=>mn,SqlParamInjector:()=>cn,SqlSchemaValidator:()=>rn,SqlSortInjector:()=>pn,StringSpecifierExpression:()=>Me,SwitchCaseArgument:()=>xe,TableSchema:()=>at,TableSourceCollector:()=>He,TokenType:()=>$,TupleExpression:()=>ke,TypeTransformationPostProcessor:()=>hn,TypeTransformers:()=>Ai,TypeValue:()=>Be,UnaryExpression:()=>ee,UpstreamSelectQueryFinder:()=>Tt,VALID_PRESETS:()=>Ti,ValueList:()=>U,ValuesQuery:()=>pe,WindowFrameBound:()=>wr,WindowFrameBoundStatic:()=>yt,WindowFrameBoundaryValue:()=>vt,WindowFrameExpression:()=>Fe,WindowFrameSpec:()=>qe,WindowFrameType:()=>vr,WithClauseParser:()=>It,convertColumnsToLegacy:()=>dn,convertModelDrivenMapping:()=>pr,convertToLegacyJsonMapping:()=>ki,createJsonMappingFromSchema:()=>Qi,createSchemaManager:()=>Ni,createTableColumnResolver:()=>Li,extractTypeProtection:()=>Lr,getCompletionSuggestions:()=>ei,getCursorContext:()=>jr,getIntelliSenseInfo:()=>Xr,isLegacyFormat:()=>Zr,isModelDrivenFormat:()=>Hr,isUnifiedFormat:()=>Yr,parseToPosition:()=>Wr,processJsonMapping:()=>qr,resolveScope:()=>Cr,splitQueries:()=>Dr,toLegacyMapping:()=>Nr,transformDatabaseResult:()=>Pi,unifyJsonMapping:()=>Gr,validateModelDrivenMapping:()=>zr});module.exports=li(Ri);var v=class{constructor(){this.comments=null}getKind(){return this.constructor.kind}accept(e){return e.visit(this)}toSqlString(e){return this.accept(e)}},yr=class{constructor(){this.parameterSymbol=":";this.identifierEscape={start:'"',end:'"'};this.exportComment=!0}};var rt=class extends v{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var me=class extends v{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},U=class extends v{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},b=class extends v{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof P?this.qualifiedName.name:new P(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(e,t){super();let n=typeof t=="string"?new P(t):t;this.qualifiedName=new Ue(Ur(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},J=class extends v{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,r,i=null,s=!1,o=null){super(),this.qualifiedName=new Ue(e,t),this.argument=n,this.over=r,this.withinGroup=i,this.withOrdinality=s,this.internalOrderBy=o}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},vr=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(vr||{}),wr=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(wr||{}),yt=class extends v{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},vt=class extends v{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},qe=class extends v{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Fe=class extends v{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},ee=class extends v{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new B(e),this.expression=t}},w=class extends v{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new B(t),this.right=n}},Z=class extends v{static{this.kind=Symbol("LiteralExpression")}constructor(e,t,n){super(),this.value=e,this.isStringLiteral=n}},N=class extends v{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new B(e),this.value=t,this.index=null}},xe=class extends v{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},Te=class extends v{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},B=class extends v{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},P=class extends v{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},Y=class extends v{static{this.kind=Symbol("ParenExpression")}constructor(e){super(),this.expression=e}},ae=class extends v{static{this.kind=Symbol("CastExpression")}constructor(e,t){super(),this.input=e,this.castType=t}},ne=class extends v{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},ye=class extends v{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},ve=class extends v{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},we=class extends v{static{this.kind=Symbol("BetweenExpression")}constructor(e,t,n,r){super(),this.expression=e,this.lower=t,this.upper=n,this.negated=r}},Me=class extends v{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new B(e),this.value=new Z(t)}},Be=class extends v{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new Ue(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof B?this.qualifiedName.name.value:this.qualifiedName.name.name;return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(t=>t.name).join(".")+"."+e:e}},ke=class extends v{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}},Ye=class extends v{static{this.kind=Symbol("ArraySliceExpression")}constructor(e,t,n){super(),this.array=e,this.startIndex=t,this.endIndex=n}},Ze=class extends v{static{this.kind=Symbol("ArrayIndexExpression")}constructor(e,t){super(),this.array=e,this.index=t}};function Ur(a){if(a==null)return null;if(typeof a=="string")return a.trim()===""?null:[new P(a)];if(Array.isArray(a)){if(a.length===0)return null;if(typeof a[0]=="string"){let e=a.filter(t=>t.trim()!=="");return e.length===0?null:e.map(t=>new P(t))}else{let e=a.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var Ue=class extends v{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=Ur(e),typeof t=="string"?this.name=new B(t):this.name=t}toString(){let e=this.name instanceof B?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(t=>t.name).join(".")+"."+e:e}};var z=class extends v{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new P(t):null}},_=class extends v{static{this.kind=Symbol("SelectClause")}constructor(e,t=null,n=[]){super(),this.items=e,this.distinct=t,this.hints=n}},Rt=class extends v{static{this.kind=Symbol("Distinct")}constructor(){super()}},Ft=class extends v{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},se=class extends v{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},Je=class extends v{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},Ae=class extends v{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new P(e),this.expression=t}},it=class extends v{static{this.kind=Symbol("WindowsClause")}constructor(e){super(),this.windows=e}};var de=class extends v{static{this.kind=Symbol("OrderByClause")}constructor(e){super(),this.order=e}},Ne=class extends v{static{this.kind=Symbol("OrderByItem")}constructor(e,t,n){super(),this.value=e,this.sortDirection=t===null?"asc":t,this.nullsPosition=n}},he=class extends v{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},fe=class extends v{static{this.kind=Symbol("HavingClause")}constructor(e){super(),this.condition=e}},O=class extends v{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof P?this.qualifiedName.name:new P(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(e,t){super();let n=typeof t=="string"?new P(t):t;this.qualifiedName=new Ue(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof B?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof B?this.qualifiedName.name.value:this.qualifiedName.name.name}},Ge=class extends v{static{this.kind=Symbol("FunctionSource")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"name"in e){let n=e;this.qualifiedName=new Ue(n.namespaces,n.name)}else this.qualifiedName=new Ue(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},We=class extends v{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},j=class extends v{static{this.kind=Symbol("SubQuerySource")}constructor(e){super(),this.query=e}},V=class extends v{static{this.kind=Symbol("SourceExpression")}constructor(e,t){super(),this.datasource=e,this.aliasExpression=t}getAliasName(){return this.aliasExpression?this.aliasExpression.table.name:this.datasource instanceof O?this.datasource.getSourceName():null}},Ce=class extends v{static{this.kind=Symbol("JoinOnClause")}constructor(e){super(),this.condition=e}},Se=class extends v{static{this.kind=Symbol("JoinUsingClause")}constructor(e){super(),this.condition=e}},ge=class extends v{static{this.kind=Symbol("JoinItem")}constructor(e,t,n,r){super(),this.joinType=new B(e),this.source=t,this.condition=n,this.lateral=r}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof O?this.source.table.name:null}},K=class extends v{static{this.kind=Symbol("FromClause")}constructor(e,t){super(),this.source=e,this.joins=t}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof O?this.source.datasource.table.name:null}getSources(){let e=[this.source];if(this.joins)for(let t of this.joins)e.push(t.source);return e}},re=class extends v{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new ie(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},le=class extends v{constructor(t,n){super();this.trailingComments=null;this.globalComments=null;this.recursive=t,this.tables=n}static{this.kind=Symbol("WithClause")}},oe=class extends v{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var Ve=class extends v{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},Ke=class extends v{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},wt=class extends v{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var Le=class extends v{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},ie=class extends v{static{this.kind=Symbol("SourceAliasExpression")}constructor(e,t){super(),this.table=new P(e),this.columns=t!==null?t.map(n=>new P(n)):null}},bn=class extends v{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new P(t):t)}},lt=class extends v{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof mt?t:new mt(t.column,t.value))}},mt=class extends v{static{this.kind=Symbol("SetClauseItem")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"column"in e){let n=e,r=typeof n.column=="string"?new P(n.column):n.column;this.qualifiedName=new Ue(n.namespaces,r)}else{let n=typeof e=="string"?new P(e):e;this.qualifiedName=new Ue(null,n)}this.value=t}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof P?this.qualifiedName.name:new P(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},Bt=class extends v{static{this.kind=Symbol("UpdateClause")}constructor(e){super(),this.source=e}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source.datasource instanceof O?this.source.datasource.table.name:null}},dt=class extends v{constructor(e,t){super(),this.source=e,this.columns=t.map(n=>new P(n))}};var $=(h=>(h[h.None=0]="None",h[h.Literal=1]="Literal",h[h.Operator=2]="Operator",h[h.OpenParen=4]="OpenParen",h[h.CloseParen=8]="CloseParen",h[h.Comma=16]="Comma",h[h.Dot=32]="Dot",h[h.Identifier=64]="Identifier",h[h.Command=128]="Command",h[h.Parameter=256]="Parameter",h[h.OpenBracket=512]="OpenBracket",h[h.CloseBracket=1024]="CloseBracket",h[h.Function=2048]="Function",h[h.StringSpecifier=4096]="StringSpecifier",h[h.Type=8192]="Type",h))($||{});var te=class{static isWhitespace(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===32||t===9||t===10||t===13}static isDigit(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57}static isHexChar(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=97&&t<=102||t>=65&&t<=70}static isOperatorSymbol(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===43||t===45||t===42||t===47||t===37||t===126||t===64||t===35||t===94||t===38||t===58||t===33||t===60||t===62||t===61||t===124||t===63}static isDelimiter(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===46||t===44||t===40||t===41||t===91||t===93||t===123||t===125||t===59||t===32||t===9||t===10||t===13?!0:t===43||t===45||t===42||t===47||t===37||t===126||t===64||t===35||t===94||t===38||t===58||t===33||t===60||t===62||t===61||t===124||t===63}static isNamedParameterPrefix(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===64||t===58||t===36}};var ue=class a{static getDebugPositionInfo(e,t){let n=Math.max(0,t-5),r=Math.min(e.length,t+5),i=e.slice(n,r),s=" ".repeat(t-n)+"^";return`${i}
${s}`}static skipWhiteSpace(e,t){let n=e.length;for(;t+4<=n&&e.slice(t,t+4)===" ";)t+=4;for(;t<n;){let r=e.charCodeAt(t);if(r!==32&&r!==9&&r!==10&&r!==13)break;t++}return t}static readLineComment(e,t){if(t+1>=e.length)return{newPosition:t,comment:null};if(e.charCodeAt(t)===45&&e.charCodeAt(t+1)===45){let n=t;for(t+=2;t<e.length&&e.charCodeAt(t)!==10;)t++;let r=e.slice(n+2,t).trim();return{newPosition:t,comment:r}}return{newPosition:t,comment:null}}static readBlockComment(e,t){if(t+3>=e.length)return{newPosition:t,comments:null};if(e.charCodeAt(t)===47&&e.charCodeAt(t+1)===42&&e.charCodeAt(t+2)!==43){let n=t;for(t+=2;t+1<e.length;){if(e.charCodeAt(t)===42&&e.charCodeAt(t+1)===47){t+=2;let r=e.slice(n+2,t-2).replace(/\r/g,"").split(`
`);for(let i=0;i<r.length;i++)r[i]=r[i].trim();for(;r.length>0&&r[0]==="";)r.shift();for(;r.length>0&&r[r.length-1]==="";)r.pop();return{newPosition:t,comments:r}}t++}throw new Error(`Block comment is not closed. position: ${t}`)}return{newPosition:t,comments:null}}static readWhiteSpaceAndComment(e,t){let n=[],r=e.length;for(;t<r;){let i=t;if(t=a.skipWhiteSpace(e,t),t!==i)continue;let s=e.charCodeAt(t);if(s===45){let o=a.readLineComment(e,t);if(o.newPosition!==t){t=o.newPosition,o.comment&&n.push(o.comment.trim());continue}}else if(s===47){let o=a.readBlockComment(e,t);if(o.newPosition!==t){t=o.newPosition,o.comments&&n.push(...o.comments);continue}}break}return{position:t,lines:n}}static readRegularIdentifier(e,t){let n=this.tryReadRegularIdentifier(e,t);if(!n)throw new Error(`Unexpected character. position: ${t}
${a.getDebugPositionInfo(e,t)}`);return n}static tryReadRegularIdentifier(e,t){let n=t;for(;t<e.length&&!te.isDelimiter(e[t]);)t++;if(n===t)return null;for(;t+1<e.length&&e[t]==="["&&e[t+1]==="]";){let r=e.slice(0,n).trim();if(r===""||/[)]$/.test(r)||/\b(select|from|where|and|or|set|values|insert|update|delete)\s*$/i.test(r))break;t+=2}return{identifier:e.slice(n,t),newPosition:t}}};var ce=class{constructor(e,t=0){this.input=e,this.position=t}getPosition(){return this.position}setPosition(e){this.position=e}isEndOfInput(e=0){return this.position+e>=this.input.length}canRead(e=0){return!this.isEndOfInput(e)}read(e){if(this.isEndOfInput())throw new Error(`Unexpected character. expect: ${e}, actual: EndOfInput, position: ${this.position}`);let t=this.input[this.position];if(t!==e)throw new Error(`Unexpected character. expect: ${e}, actual: ${t}, position: ${this.position}`);return this.position++,t}createLexeme(e,t,n=null,r,i){let s={type:e,value:e===128||e===2||e===2048?t.toLowerCase():t,comments:n};return r!==void 0&&i!==void 0&&(s.position={startPosition:r,endPosition:i}),s}createLexemeWithPosition(e,t,n,r=null){return this.createLexeme(e,t,r,n,n+t.length)}getDebugPositionInfo(e){return ue.getDebugPositionInfo(this.input,e)}};var En=class extends ce{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="*")return this.position++,this.createLexeme(64,t);let n=ue.readRegularIdentifier(this.input,this.position);return this.position=n.newPosition,this.createLexeme(64,n.identifier)}};var Ie=class{constructor(e){this.trie=e}isEndOfInput(e,t,n=0){return t+n>=e.length}canParse(e,t,n=0){return!this.isEndOfInput(e,t,n)}parse(e,t){if(this.isEndOfInput(e,t))return null;this.trie.reset();let n=ue.tryReadRegularIdentifier(e,t);if(n===null)return null;let r=this.trie.pushLexeme(n.identifier.toLowerCase());if(r===0)return null;if(r===3)return{keyword:n.identifier,newPosition:n.newPosition};let i=n.identifier,s=ue.readWhiteSpaceAndComment(e,n.newPosition);t=s.position;let o=[...s.lines];if(this.isEndOfInput(e,t))return r===2?{keyword:i,newPosition:t,comments:o.length>0?o:void 0}:null;for(;this.canParse(e,t);){let l=r,u=ue.tryReadRegularIdentifier(e,t);if(u!==null){if(r=this.trie.pushLexeme(u.identifier.toLowerCase()),r===0){if(l===2)break;return null}i+=" "+u.identifier;let c=ue.readWhiteSpaceAndComment(e,u.newPosition);if(t=c.position,o.push(...c.lines),r===3)break}else{if(l===2)break;return null}}return{keyword:i,newPosition:t,comments:o.length>0?o:void 0}}};var _e=class{constructor(e){this.root=new Map;this.hasEndProperty=!1;this.hasMoreProperties=!1;for(let t of e)this.addKeyword(t);this.currentNode=this.root}addKeyword(e){let t=this.root;for(let n of e)t.has(n)||t.set(n,new Map),t=t.get(n);t.set("__end__",!0)}reset(){this.currentNode=this.root,this.hasEndProperty=!1,this.hasMoreProperties=!1}pushLexeme(e){return this.currentNode.has(e)?(this.currentNode=this.currentNode.get(e),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 ui=[["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"]],ci=new _e(ui),Sr=new Ie(ci),xn=class extends ce{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="'"){let r=this.readSingleQuotedString();return this.createLexeme(1,r)}let n=this.tryReadKeyword();if(n)return n;if(t==="."&&this.canRead(1)&&te.isDigit(this.input[this.position+1]))return this.createLexeme(1,this.readDigit());if(te.isDigit(t))return this.createLexeme(1,this.readDigit());if(t==="$"&&this.isDollarQuotedString())return this.createLexeme(1,this.readDollarQuotedString());if(t==="$"&&this.canRead(1)&&te.isDigit(this.input[this.position+1])){let r=this.position+1,i=!1;for(;r<this.input.length&&(te.isDigit(this.input[r])||this.input[r]===","||this.input[r]===".");){if(this.input[r]==="."||this.input[r]===","){i=!0;break}r++}if(i){this.position++;let s=this.readMoneyDigit();return this.createLexeme(1,"$"+s)}}if((t==="+"||t==="-")&&this.determineSignOrOperator(e)==="sign"){let r=t;this.position++;let i=this.position;for(;this.canRead()&&te.isWhitespace(this.input[this.position]);)this.position++;if(this.canRead()&&(te.isDigit(this.input[this.position])||this.input[this.position]==="."&&this.canRead(1)&&te.isDigit(this.input[this.position+1])))return this.createLexeme(1,r==="-"?r+this.readDigit():this.readDigit());this.position=i-1}return null}tryReadKeyword(){let e=Sr.parse(this.input,this.position);return e?(this.position=e.newPosition,this.createLexeme(1,e.keyword)):null}determineSignOrOperator(e){return e===null?"sign":e.type&1||e.type&64||e.type&256||e.type&8?"operator":"sign"}readDigit(){let e=this.position,t=!1,n=!1;if(this.canRead(1)&&this.input[this.position]==="0"&&"xbo".includes(this.input[this.position+1].toLowerCase())){let r=this.input[this.position+1].toLowerCase();this.position+=2;let i=r==="x";for(;this.canRead();){let s=this.input[this.position];if(te.isDigit(s)||i&&te.isHexChar(s))this.position++;else break}return this.input.slice(e,this.position)}for(this.input[e]==="."&&(t=!0,this.position++);this.canRead();){let r=this.input[this.position];if(r==="."&&!t)t=!0;else if((r==="e"||r==="E")&&!n)n=!0,this.canRead(1)&&(this.input[this.position+1]==="+"||this.input[this.position+1]==="-")&&this.position++;else if(!te.isDigit(r))break;this.position++}if(e===this.position)throw new Error(`Unexpected character. position: ${e}
${this.getDebugPositionInfo(e)}`);return this.input[e]==="."?"0"+this.input.slice(e,this.position):this.input.slice(e,this.position)}readMoneyDigit(){let e=this.position,t=!1;for(;this.canRead();){let n=this.input[this.position];if(n==="."&&!t)t=!0;else if(!(n===","&&!t)){if(!te.isDigit(n))break}this.position++}if(e===this.position)throw new Error(`Unexpected character. position: ${e}
${this.getDebugPositionInfo(e)}`);return this.input.slice(e,this.position)}readSingleQuotedString(){let e=this.position,t=!1;for(this.read("'");this.canRead();){let n=this.input[this.position];if(this.position++,n==="\\"&&this.canRead(1)){this.position++;continue}else if(n==="'"){t=!0;break}}if(t===!1)throw new Error(`Single quote is not closed. position: ${e}
${this.getDebugPositionInfo(e)}`);return this.input.slice(e,this.position)}isDollarQuotedString(){if(!this.canRead(1))return!1;if(this.input[this.position+1]==="$")return!0;let e=this.position+1;for(;e<this.input.length;){let t=this.input[e];if(t==="$")return!0;if(!this.isAlphanumeric(t)&&t!=="_")return!1;e++}return!1}readDollarQuotedString(){let e=this.position;this.position++;let t="";for(;this.canRead()&&this.input[this.position]!=="$";)t+=this.input[this.position],this.position++;if(!this.canRead())throw new Error(`Unexpected end of input while reading dollar-quoted string tag at position ${e}`);this.position++;let n="$"+t+"$",r=n,i="";for(;this.canRead();){if(this.input.substring(this.position,this.position+r.length)===r)return this.position+=r.length,n+i+r;i+=this.input[this.position],this.position++}throw new Error(`Unclosed dollar-quoted string starting at position ${e}. Expected closing tag: ${r}`)}isAlphanumeric(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}};var Tn=class extends ce{constructor(e){super(e)}tryRead(e){if(this.isEndOfInput())return null;if(this.canRead(1)&&this.input[this.position]==="$"&&this.input[this.position+1]==="{"){this.position+=2;let n=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 ${n}`);let r=this.input.slice(n,this.position);if(r.length===0)throw new Error("Empty parameter name is not allowed: found ${} at position "+(n-2));return this.position++,this.createLexeme(256,"${"+r+"}")}let t=this.input[this.position];if(te.isNamedParameterPrefix(t)){if(this.canRead(1)&&te.isOperatorSymbol(this.input[this.position+1])||t===":"&&this.isInArraySliceContext()||t==="$"&&this.isDollarQuotedString())return null;if(t==="$"&&this.canRead(1)&&te.isDigit(this.input[this.position+1])){let i=this.position+1,s=!1;for(;i<this.input.length&&(te.isDigit(this.input[i])||this.input[i]===","||this.input[i]===".");){if(this.input[i]==="."||this.input[i]===","){s=!0;break}i++}if(s)return null}this.position++;let n=this.position;for(;this.canRead()&&!te.isDelimiter(this.input[this.position]);)this.position++;let r=this.input.slice(n,this.position);return this.createLexeme(256,t+r)}if(t==="?"){if(this.canRead(1)){let n=this.input[this.position+1];if(n==="|"||n==="&")return null}return e&&(e.type&64||e.type&1)?null:(this.position++,this.createLexeme(256,t))}return null}isInArraySliceContext(){let e=this.position-1,t=0,n=0;for(;e>=0;){let r=this.input[e];if(r==="]")t++;else if(r==="["){if(t--,t<0){if(e>0){let i=this.input[e-1];if(/[a-zA-Z0-9_)\]]/.test(i))return!0}if(e===0)return!1;break}}else r===")"?n++:r==="("&&n--;e--}return!1}isDollarQuotedString(){if(!this.canRead(1))return!1;if(this.input[this.position+1]==="$")return!0;let e=this.position+1;for(;e<this.input.length;){let t=this.input[e];if(t==="$")return!0;if(!this.isAlphanumeric(t)&&t!=="_")return!1;e++}return!1}isAlphanumeric(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}};var kn=class a extends ce{static{this.SPECIAL_SYMBOL_TOKENS={".":32,",":16,"(":4,")":8,"[":512,"]":1024}}tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];return t in a.SPECIAL_SYMBOL_TOKENS?(this.position++,this.createLexeme(a.SPECIAL_SYMBOL_TOKENS[t],t)):null}};var In=class{constructor(e,t=0){this.cacheHits=0;this.cacheMisses=0;this.input=e,this.position=t,this.readers=[],this.tokenCache=new Map}register(e){return this.readers.push(e),this}registerAll(e){return e.forEach(t=>this.register(t)),this}setPosition(e){this.position=e;for(let t of this.readers)t.setPosition(e)}tryRead(e,t){if(this.tokenCache.has(e))return this.cacheHits++,this.tokenCache.get(e)||null;this.cacheMisses++,this.setPosition(e);let n=null;for(let r of this.readers)if(n=r.tryRead(t),n){this.position=r.getPosition();break}for(let r of this.readers)r.setPosition(this.position);return this.tokenCache.set(e,n),n}getMaxPosition(){let e=this.position;for(let t of this.readers){let n=t.getPosition();n>e&&(e=n)}return e}getInput(){return this.input}getCacheStats(){let e=this.cacheHits+this.cacheMisses,t=e>0?this.cacheHits/e:0;return{hits:this.cacheHits,misses:this.cacheMisses,ratio:t}}};var pi=new _e([["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"]]),mi=new _e([["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"]]),di=new Ie(pi),hi=new Ie(mi);var Pn=class extends ce{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(te.isOperatorSymbol(t)){let r=this.position;for(;this.canRead()&&te.isOperatorSymbol(this.input[this.position]);){if(this.canRead(1)){let s=this.input[this.position];if(s==="-"&&this.input[this.position+1]==="-")break;if(s==="/"&&this.input[this.position+1]==="*")break}this.position++}let i=this.input.slice(r,this.position);return this.createLexeme(2,i)}let n=hi.parse(this.input,this.position);return n!==null?(this.position=n.newPosition,this.createLexeme(8258,n.keyword)):(n=di.parse(this.input,this.position),n!==null?(this.position=n.newPosition,this.createLexeme(2,n.keyword)):null)}};var fi=new _e([["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"]]),Gt=new _e([["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"]]),Ci=new Ie(Gt),Ht=new Ie(fi);var An=class extends ce{tryRead(e){if(this.isEndOfInput())return null;let t=Ht.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(128,t.keyword);let n=Ci.parse(this.input,this.position);if(n!==null)return this.position=n.newPosition,this.createLexeme(128,n.keyword,n.comments);if(this.canRead(2)&&this.input[this.position]==="/"&&this.input[this.position+1]==="*"&&this.input[this.position+2]==="+"){this.position+=3;let r=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(r,this.position-2).trim()+" */");this.position++}throw new Error(`Block comment is not closed. position: ${this.position}`)}return null}};var gi=new Set(["e'","E'","x'","X'","b'","B'"]),yi=new Set(["u&'","U&'"]),Nn=class extends ce{tryRead(e){let t=this.position;return this.canRead(1)&&gi.has(this.input.slice(t,t+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(t,this.position))):this.canRead(2)&&yi.has(this.input.slice(t,t+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(t,this.position))):null}};var vi=new _e([["grouping","sets"],["array"]]),wi=new Ie(vi),Ln=class extends ce{tryRead(e){if(this.isEndOfInput())return null;let t=wi.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(2048,t.keyword);let n=ue.tryReadRegularIdentifier(this.input,this.position);if(!n)return null;this.position=n.newPosition;var r=ue.readWhiteSpaceAndComment(this.input,this.position).position-this.position;return this.canRead(r)&&this.input[this.position+r]==="("?this.createLexeme(2048,n.identifier):null}};var Si=new _e([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),bi=new Ie(Si),Qn=class extends ce{tryRead(e){if(this.isEndOfInput())return null;let t=bi.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(8192,t.keyword);if(e===null)return null;let n=ue.tryReadRegularIdentifier(this.input,this.position);return n?(this.position=n.newPosition,e.type&128&&e.value==="as"?this.createLexeme(8256,n.identifier):e.type&2&&e.value==="::"?this.createLexeme(8192,n.identifier):null):null}};var On=class extends ce{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="`"){let n=this.readEscapedIdentifier("`");return this.createLexeme(64,n)}if(t==='"'){let n=this.readEscapedIdentifier('"');return this.createLexeme(64,n)}if(t==="["&&this.isSqlServerBracketIdentifier(e)){let n=this.readEscapedIdentifier("]");return this.createLexeme(64,n)}return null}isSqlServerBracketIdentifier(e){if(e?.value==="array")return!1;let t=this.position+1,n=t;for(;n<this.input.length&&this.input[n]!=="]";){let i=this.input[n];if(i===":"||i===","||i==="+"||i==="-"||i==="*"||i==="/"||i==="("||i===")")return!1;n++}if(n>=this.input.length)return!1;let r=this.input.slice(t,n).trim();return r===""?!1:/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$/.test(r)}readEscapedIdentifier(e){let t=this.position;for(this.position++;this.canRead()&&this.input[this.position]!==e;)this.position++;if(t===this.position)throw new Error(`Closing delimiter is not found. position: ${t}, delimiter: ${e}
${this.getDebugPositionInfo(t)}`);return this.position++,this.input.slice(t+1,this.position-1)}};var R=class a{constructor(e){this.input=e,this.position=0,this.readerManager=new In(e).register(new On(e)).register(new Tn(e)).register(new Nn(e)).register(new xn(e)).register(new kn(e)).register(new An(e)).register(new Pn(e)).register(new Qn(e)).register(new Ln(e)).register(new En(e))}isEndOfInput(e=0){return this.position+e>=this.input.length}canRead(e=0){return!this.isEndOfInput(e)}tokenize(e){return e?.preserveFormatting?this.tokenizeWithFormatting():new a(this.input).readLexmes()}readLexmes(){return this.tokenizeBasic()}tokenizeBasic(){this.position=0;let e=Math.ceil(this.input.length/8),t=new Array(e),n=0,r=this.readComment(),i=r.lines;this.position=r.position;let s=null;for(;this.canRead()&&this.input[this.position]!==";";){let o=this.readerManager.tryRead(this.position,s);if(o===null)throw new Error(`Unexpected character. actual: ${this.input[this.position]}, position: ${this.position}
${this.getDebugPositionInfo(this.position)}`);this.position=this.readerManager.getMaxPosition();let l=this.readComment();this.position=l.position,o.type&16||o.type&2?l.lines.length>0&&i.push(...l.lines):((i.length>0||l.lines.length>0)&&this.addCommentsToToken(o,i,l.lines),i=[]),t[n++]=o,s=o}if(i.length>0&&n>0){let o=t[n-1];o.comments===null&&(o.comments=[]),o.comments.push(...i)}return n===e?t:t.slice(0,n)}addCommentsToToken(e,t,n){(t.length>0||n.length>0)&&(e.comments===null&&(e.comments=[]),t.length>0&&e.comments.unshift(...t),n.length>0&&e.comments.push(...n))}readComment(){return ue.readWhiteSpaceAndComment(this.input,this.position)}getDebugPositionInfo(e){return ue.getDebugPositionInfo(this.input,e)}tokenizeWithFormatting(){let e=this.tokenizeBasic();return this.mapToFormattingLexemes(e)}mapToFormattingLexemes(e){if(e.length===0)return[];let t=[],n=0;for(let i of e){n=this.skipWhitespaceAndComments(n);let s=this.findLexemeAtPosition(i,n);if(s)t.push(s),n=s.endPosition;else{let o={startPosition:n,endPosition:n+i.value.length};t.push(o),n=o.endPosition}}let r=[];for(let i=0;i<e.length;i++){let s=e[i],o=t[i],l=i<e.length-1?t[i+1].startPosition:this.input.length,u=this.input.slice(o.endPosition,l),c=this.extractCommentsFromWhitespace(u),p={...s,followingWhitespace:u,inlineComments:c,position:{startPosition:o.startPosition,endPosition:o.endPosition,...this.getLineColumnInfo(o.startPosition,o.endPosition)}};r.push(p)}return r}findLexemeAtPosition(e,t){if(t>=this.input.length)return null;let n=[e.value,e.value.toUpperCase(),e.value.toLowerCase()];for(let r of n)if(t+r.length<=this.input.length&&this.input.substring(t,t+r.length)===r&&this.isValidLexemeMatch(r,t))return{startPosition:t,endPosition:t+r.length};return null}isValidLexemeMatch(e,t){if(t>0){let r=this.input[t-1];if(this.isAlphanumericUnderscore(r))return!1}let n=t+e.length;if(n<this.input.length){let r=this.input[n];if(this.isAlphanumericUnderscore(r))return!1}return!0}isAlphanumericUnderscore(e){let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95}isWhitespace(e){let t=e.charCodeAt(0);return t===32||t===9||t===10||t===13}extractCommentsFromWhitespace(e){let t=[],n=0;for(;n<e.length;){let r=n,i=ue.readWhiteSpaceAndComment(e,n);i.lines.length>0&&t.push(...i.lines),n=i.position,n===r&&n++}return t}skipWhitespaceAndComments(e){let t=e;for(;t<this.input.length;){let n=this.input[t];if(this.isWhitespace(n)){t++;continue}if(t<this.input.length-1&&this.input[t]==="-"&&this.input[t+1]==="-"){for(;t<this.input.length&&this.input[t]!==`
`&&this.input[t]!=="\r";)t++;continue}if(t<this.input.length-1&&this.input[t]==="/"&&this.input[t+1]==="*"){for(t+=2;t<this.input.length-1;){if(this.input[t]==="*"&&this.input[t+1]==="/"){t+=2;break}t++}continue}break}return t}getLineColumnInfo(e,t){let n=this.getLineColumn(e),r=this.getLineColumn(t);return{startLine:n.line,startColumn:n.column,endLine:r.line,endColumn:r.column}}getLineColumn(e){let t=1,n=1;for(let r=0;r<Math.min(e,this.input.length);r++)this.input[r]===`
`?(t++,n=1):n++;return{line:t,column:n}}};var je=class a{static parseFromLexeme(e,t){let{identifiers:n,newIndex:r}=a.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:i,name:s}=a.extractNamespacesAndName(n),o=0;return r>t&&(o=e[r-1].type),{namespaces:i,name:new P(s),newIndex:r,lastTokenType:o}}static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The name is complete but additional tokens were found.`);return{namespaces:r.namespaces,name:r.name}}static parseEscapedOrDotSeparatedIdentifiers(e,t){let n=t,r=[];for(;n<e.length;){if(e[n].type&512){if(n++,n>=e.length||!(e[n].type&64||e[n].type&128))throw new Error(`Expected identifier after '[' at position ${n}`);if(r.push(e[n].value),n++,n>=e.length||e[n].value!=="]")throw new Error(`Expected closing ']' after identifier at position ${n}`);n++}else if(e[n].type&64)r.push(e[n].value),n++;else if(e[n].type&2048)r.push(e[n].value),n++;else if(e[n].type&8192)r.push(e[n].value),n++;else if(e[n].value==="*"){r.push(e[n].value),n++;break}if(n<e.length&&e[n].type&32)n++;else break}return{identifiers:r,newIndex:n}}static extractNamespacesAndName(e){if(!e||e.length===0)throw new Error("Identifier list is empty");return e.length===1?{namespaces:null,name:e[0]}:{namespaces:e.slice(0,-1),name:e[e.length-1]}}};var Rn=class{static parseFromLexeme(e,t){let{namespaces:n,name:r,newIndex:i}=je.parseFromLexeme(e,t);return{value:new b(n,r),newIndex:i}}};var Yt=class{static parseFromLexeme(e,t){let n=t,r=e[n].value,i,s=Sr.parse(r.toLowerCase(),0);if(s){let o=new B(s.keyword);return n++,{value:o,newIndex:n}}if(/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(r))return i=Number(r),n++,{value:new Z(i),newIndex:n};{/^\$[^$]*\$[\s\S]*\$[^$]*\$$/.test(r)?i=r:r.startsWith("'")&&r.endsWith("'")?i=r.slice(1,-1):i=r;let o=r.startsWith("'")&&r.endsWith("'");return n++,{value:new Z(i,void 0,o),newIndex:n}}}};var Fn=class{static parseFromLexeme(e,t){let n=t;if(n+1<e.length&&e[n].type&4&&(e[n+1].value==="select"||e[n+1].value==="values"||e[n+1].value==="with")){n+=1;let r=A.parseFromLexeme(e,n);if(n=r.newIndex,n>=e.length||e[n].type!==8)throw new Error(`Expected ')' at index ${n}, but found ${e[n].value}`);let i=e[n].comments;n++;let s=new me(r.value);return i&&i.length>0&&(s.comments=i),{value:s,newIndex:n}}else{let r=I.parseArgument(4,8,e,t);return n=r.newIndex,{value:new Y(r.value),newIndex:n}}}};var Bn=class{static parseFromLexeme(e,t){let n=t;if(n<e.length&&e[n].type&2){let r=e[n].value;if(n++,r==="*")return{value:new b(null,"*"),newIndex:n};let i=I.parseFromLexeme(e,n);return n=i.newIndex,{value:new ee(r,i.value),newIndex:n}}throw new Error(`Invalid unary expression at index ${t}: ${e[t].value}`)}};var Vn=class{static parseFromLexeme(e,t){let n=t,r=e[n].value;r.startsWith("${")&&r.endsWith("}")?r=r.slice(2,-1):r=r.slice(1);let i=new N(r);return n++,{value:i,newIndex:n}}};var $n=class{static parseFromLexeme(e,t){let n=t,r=e[n].value;if(n++,n>=e.length||e[n].type!==1)throw new Error(`Expected string literal after string specifier at index ${n}`);let i=e[n].value;return n++,{value:new Me(r,i),newIndex:n}}};var Mn=class{static parseFromLexeme(e,t){let n=t,r=e[n];return r.value==="case"?(n++,this.parseCaseExpression(e,n)):r.value==="case when"?(n++,this.parseCaseWhenExpression(e,n)):this.parseModifierUnaryExpression(e,n)}static parseModifierUnaryExpression(e,t){let n=t;if(n<e.length&&e[n].type&128){let r=e[n].value;n++;let i=I.parseFromLexeme(e,n);return{value:new ee(r,i.value),newIndex:i.newIndex}}throw new Error(`Invalid modifier unary expression at index ${n}, Lexeme: ${e[n].value}`)}static parseCaseExpression(e,t){let n=t,r=I.parseFromLexeme(e,n);n=r.newIndex;let i=this.parseSwitchCaseArgument(e,n,[]);return n=i.newIndex,{value:new ne(r.value,i.value),newIndex:n}}static parseCaseWhenExpression(e,t){let n=t,r=this.parseCaseConditionValuePair(e,n);n=r.newIndex;let i=[r.value],s=this.parseSwitchCaseArgument(e,n,i);return n=s.newIndex,{value:new ne(null,s.value),newIndex:n}}static parseSwitchCaseArgument(e,t,n){let r=t,i=[...n],s=null;for(;r<e.length&&this.isCommandWithValue(e[r],"when");){r++;let l=this.parseCaseConditionValuePair(e,r);r=l.newIndex,i.push(l.value)}if(r<e.length&&this.isCommandWithValue(e[r],"else")){r++;let l=I.parseFromLexeme(e,r);s=l.value,r=l.newIndex}if(r<e.length&&this.isCommandWithValue(e[r],"end"))r++;else throw new Error(`The CASE expression requires 'end' keyword at the end (index ${r})`);if(i.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${r})`);return{value:new xe(i,s),newIndex:r}}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,r=I.parseFromLexeme(e,n);if(n=r.newIndex,n>=e.length||!(e[n].type&128)||e[n].value!=="then")throw new Error(`Expected 'then' after WHEN condition at index ${n}`);n++;let i=I.parseFromLexeme(e,n);return n=i.newIndex,{value:new Te(r.value,i.value),newIndex:n}}};var st=class{static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The ORDER BY clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="order by")throw new Error(`Syntax error at position ${n}: Expected 'ORDER BY' keyword but found "${e[n].value}". ORDER BY clauses must start with the ORDER BY keywords.`);n++;let r=[],i=this.parseItem(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=this.parseItem(e,n);r.push(s.value),n=s.newIndex}if(r.length===0)throw new Error(`Syntax error at position ${t}: No ordering expressions found. The ORDER BY clause requires at least one expression to order by.`);return{value:new de(r),newIndex:n}}static parseItem(e,t){let n=t,r=I.parseFromLexeme(e,n),i=r.value;if(n=r.newIndex,n>=e.length)return{value:i,newIndex:n};let s=n>=e.length?null:e[n].value==="asc"?(n++,"asc"):e[n].value==="desc"?(n++,"desc"):null,o=n>=e.length?null:e[n].value==="nulls first"?(n++,"first"):e[n].value==="nulls last"?(n++,"last"):null;return s===null&&o===null?{value:i,newIndex:n}:{value:new Ne(i,s,o),newIndex:n}}};var Wn=class{static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The PARTITION BY clause is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="partition by")throw new Error(`Syntax error at position ${n}: Expected 'PARTITION BY' keyword but found "${e[n].value}". PARTITION BY clauses must start with the PARTITION BY keywords.`);n++;let r=[],i=I.parseFromLexeme(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let s=I.parseFromLexeme(e,n);r.push(s.value),n=s.newIndex}if(r.length===0)throw new Error(`Syntax error at position ${t}: No partition expressions found. The PARTITION BY clause requires at least one expression to partition by.`);return r.length===1?{value:new Je(r[0]),newIndex:n}:{value:new Je(new U(r)),newIndex:n}}};var Vt=class{static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The window frame expression is complete but there are additional tokens.`);return r.value}static parseFromLexeme(e,t){let n=t;if(e[n].type!==4)throw new Error(`Syntax error at position ${n}: Expected opening parenthesis '(' but found "${e[n].value}".`);n++;let r=null,i=null,s=null;if(n<e.length&&e[n].value==="partition by"){let o=Wn.parseFromLexeme(e,n);r=o.value,n=o.newIndex}if(n<e.length&&e[n].value==="order by"){let o=st.parseFromLexeme(e,n);i=o.value,n=o.newIndex}if(n<e.length&&this.isFrameTypeKeyword(e[n].value)){let o=this.parseFrameSpec(e,n);s=o.value,n=o.newIndex}if(n>=e.length||e[n].type!==8)throw new Error(`Syntax error at position ${n}: Missing closing parenthesis ')' for window frame. Each opening parenthesis must have a matching closing parenthesis.`);return n++,{value:new Fe(r,i,s),newIndex:n}}static isFrameTypeKeyword(e){let t=e;return t==="rows"||t==="range"||t==="groups"}static parseFrameSpec(e,t){let n=t,r=e[n].value,i;switch(r){case"rows":i="rows";break;case"range":i="range";break;case"groups":i="groups";break;default:throw new Error(`Syntax error at position ${n}: Invalid frame type "${e[n].value}". Expected one of: ROWS, RANGE, GROUPS.`)}if(n++,n<e.length&&e[n].value==="between"){n++;let s=this.parseFrameBoundary(e,n),o=s.value;if(n=s.newIndex,n>=e.length||e[n].value!=="and")throw new Error(`Syntax error at position ${n}: Expected 'AND' keyword in BETWEEN clause.`);n++;let l=this.parseFrameBoundary(e,n),u=l.value;return n=l.newIndex,{value:new qe(i,o,u),newIndex:n}}else{let s=this.parseFrameBoundary(e,n),o=s.value;return n=s.newIndex,{value:new qe(i,o,null),newIndex:n}}}static parseFrameBoundary(e,t){let n=t;if(n<e.length&&e[n].type&128){let r=e[n].value,i;switch(r){case"current row":i="current row";break;case"unbounded preceding":i="unbounded preceding";break;case"unbounded following":i="unbounded following";break;default:throw new Error(`Syntax error at position ${n}: Invalid frame type "${e[n].value}". Expected one of: ROWS, RANGE, GROUPS.`)}return{value:new yt(i),newIndex:n+1}}else if(n<e.length&&e[n].type&1){let r=I.parseFromLexeme(e,n);if(n=r.newIndex,n<e.length&&e[n].type&128){let i=e[n].value,s;if(i==="preceding")s=!1;else if(i==="following")s=!0;else throw new Error(`Syntax error at position ${n}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`);return n++,{value:new vt(r.value,s),newIndex:n}}else throw new Error(`Syntax error at position ${n}: Expected 'preceding' or 'following' after numeric value in window frame boundary.`)}throw new Error(`Syntax error at position ${n}: Expected a valid frame boundary component.`)}};var Zt=class{static parse(e){let n=new R(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[r.newIndex].value}" at position ${r.newIndex}. The OVER expression is complete but there are additional tokens.`);return r.va