UNPKG

rawsql-ts

Version:

[beta]High-performance SQL parser and AST analyzer written in TypeScript. Provides fast parsing and advanced transformation capabilities.

11 lines 160 kB
"use strict";var rn=Object.defineProperty;var Sn=Object.getOwnPropertyDescriptor;var xn=Object.getOwnPropertyNames;var En=Object.prototype.hasOwnProperty;var bn=(r,e)=>{for(var t in e)rn(r,t,{get:e[t],enumerable:!0})},gn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of xn(e))!En.call(r,i)&&i!==t&&rn(r,i,{get:()=>e[i],enumerable:!(n=Sn(e,i))||n.enumerable});return r};var kn=r=>gn(rn({},"__esModule",{value:!0}),r);var Hn={};bn(Hn,{ArrayExpression:()=>se,ArrayQueryExpression:()=>re,BetweenExpression:()=>oe,BinaryExpression:()=>b,BinarySelectQuery:()=>R,CTECollector:()=>K,CTENormalizer:()=>ke,CaseExpression:()=>M,CaseKeyValuePair:()=>ne,CastExpression:()=>ie,ColumnReference:()=>d,DuplicateDetectionMode:()=>pn,Formatter:()=>Ae,FunctionCall:()=>L,IdentifierString:()=>C,InlineQuery:()=>me,InsertQuery:()=>Pe,InsertQueryParser:()=>hn,LiteralValue:()=>V,ParameterExpression:()=>N,ParenExpression:()=>H,PostgresJsonQueryBuilder:()=>dn,QualifiedName:()=>de,QueryBuilder:()=>_e,RawString:()=>g,SchemaCollector:()=>ht,SchemaManager:()=>ot,SelectQueryParser:()=>B,SelectValueCollector:()=>pe,SelectableColumnCollector:()=>xe,SimpleSelectQuery:()=>E,SqlFormatter:()=>De,SqlParamInjector:()=>fn,SqlSchemaValidator:()=>wn,StringSpecifierExpression:()=>je,SwitchCaseArgument:()=>te,TableSchema:()=>mt,TableSourceCollector:()=>ut,TupleExpression:()=>ae,TypeValue:()=>ve,UnaryExpression:()=>U,UpstreamSelectQueryFinder:()=>Me,VALID_PRESETS:()=>Jn,ValueList:()=>Q,ValuesQuery:()=>J,WindowFrameBound:()=>an,WindowFrameBoundStatic:()=>Ke,WindowFrameBoundaryValue:()=>Ue,WindowFrameExpression:()=>he,WindowFrameSpec:()=>Ee,WindowFrameType:()=>on,createJsonMappingFromSchema:()=>_n,createSchemaManager:()=>Mn,createTableColumnResolver:()=>zn});module.exports=kn(Hn);var h=class{constructor(){this.comments=null}getKind(){return this.constructor.kind}accept(e){return e.visit(this)}toSqlString(e){return this.accept(e)}};var Pe=class extends h{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var me=class extends h{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},Q=class extends h{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},d=class extends h{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof C?this.qualifiedName.name:new C(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(e,t){super();let n=typeof t=="string"?new C(t):t;this.qualifiedName=new de(Cn(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},L=class extends h{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,i){super(),this.qualifiedName=new de(e,t),this.argument=n,this.over=i}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},on=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(on||{}),an=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(an||{}),Ke=class extends h{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},Ue=class extends h{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},Ee=class extends h{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},he=class extends h{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},U=class extends h{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new g(e),this.expression=t}},b=class extends h{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new g(t),this.right=n}},V=class extends h{static{this.kind=Symbol("LiteralExpression")}constructor(e){super(),this.value=e}},N=class extends h{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new g(e),this.value=t,this.index=null}},te=class extends h{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},ne=class extends h{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},g=class extends h{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},C=class extends h{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},H=class extends h{static{this.kind=Symbol("ParenExpression")}constructor(e){super(),this.expression=e}},ie=class extends h{static{this.kind=Symbol("CastExpression")}constructor(e,t){super(),this.input=e,this.castType=t}},M=class extends h{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},se=class extends h{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},re=class extends h{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},oe=class extends h{static{this.kind=Symbol("BetweenExpression")}constructor(e,t,n,i){super(),this.expression=e,this.lower=t,this.upper=n,this.negated=i}},je=class extends h{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new g(e),this.value=new V(t)}},ve=class extends h{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new de(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof g?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}},ae=class extends h{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}};function Cn(r){if(r==null)return null;if(typeof r=="string")return r.trim()===""?null:[new C(r)];if(Array.isArray(r)){if(r.length===0)return null;if(typeof r[0]=="string"){let e=r.filter(t=>t.trim()!=="");return e.length===0?null:e.map(t=>new C(t))}else{let e=r.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var de=class extends h{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=Cn(e),typeof t=="string"?this.name=new g(t):this.name=t}toString(){let e=this.name instanceof g?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(t=>t.name).join(".")+"."+e:e}};var F=class extends h{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new C(t):null}},O=class extends h{static{this.kind=Symbol("SelectClause")}constructor(e,t=null){super(),this.items=e,this.distinct=t}},He=class extends h{static{this.kind=Symbol("Distinct")}constructor(){super()}},Ge=class extends h{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},z=class extends h{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},be=class extends h{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},le=class extends h{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new C(e),this.expression=t}},Ve=class extends h{static{this.kind=Symbol("WindowsClause")}constructor(e){super(),this.windows=e}};var ue=class extends h{static{this.kind=Symbol("OrderByClause")}constructor(e){super(),this.order=e}},ye=class extends h{static{this.kind=Symbol("OrderByItem")}constructor(e,t,n){super(),this.value=e,this.sortDirection=t===null?"asc":t,this.nullsPosition=n}},G=class extends h{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},Y=class extends h{static{this.kind=Symbol("HavingClause")}constructor(e){super(),this.condition=e}},I=class extends h{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof C?this.qualifiedName.name:new C(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(e,t){super();let n=typeof t=="string"?new C(t):t;this.qualifiedName=new de(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof g?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof g?this.qualifiedName.name.value:this.qualifiedName.name.name}},Fe=class extends h{static{this.kind=Symbol("FunctionSource")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"name"in e){let n=e;this.qualifiedName=new de(n.namespaces,n.name)}else this.qualifiedName=new de(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},ge=class extends h{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},A=class extends h{static{this.kind=Symbol("SubQuerySource")}constructor(e){super(),this.query=e}},k=class extends h{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 I?this.datasource.getSourceName():null}},X=class extends h{static{this.kind=Symbol("JoinOnClause")}constructor(e){super(),this.condition=e}},ce=class extends h{static{this.kind=Symbol("JoinUsingClause")}constructor(e){super(),this.condition=e}},Z=class extends h{static{this.kind=Symbol("JoinItem")}constructor(e,t,n,i){super(),this.joinType=new g(e),this.source=t,this.condition=n,this.lateral=i}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof I?this.source.table.name:null}},P=class extends h{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 I?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}},j=class extends h{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new W(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},q=class extends h{static{this.kind=Symbol("WithClause")}constructor(e,t){super(),this.recursive=e,this.tables=t}},ee=class extends h{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var Oe=class extends h{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},Le=class extends h{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},qe=class extends h{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var Se=class extends h{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},W=class extends h{static{this.kind=Symbol("SourceAliasExpression")}constructor(e,t){super(),this.table=new C(e),this.columns=t!==null?t.map(n=>new C(n)):null}},ft=class extends h{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new C(t):t)}},Ne=class extends h{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof Be?t:new Be(t.column,t.value))}},Be=class extends h{static{this.kind=Symbol("SetClauseItem")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"column"in e){let n=e,i=typeof n.column=="string"?new C(n.column):n.column;this.qualifiedName=new de(n.namespaces,i)}else{let n=typeof e=="string"?new C(e):e;this.qualifiedName=new de(null,n)}this.value=t}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof C?this.qualifiedName.name:new C(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},Ye=class extends h{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 I?this.source.datasource.table.name:null}},Re=class extends h{constructor(e,t){super(),this.source=e,this.columns=t.map(n=>new C(n))}};var T=(S=>(S[S.None=0]="None",S[S.Literal=1]="Literal",S[S.Operator=2]="Operator",S[S.OpenParen=4]="OpenParen",S[S.CloseParen=8]="CloseParen",S[S.Comma=16]="Comma",S[S.Dot=32]="Dot",S[S.Identifier=64]="Identifier",S[S.Command=128]="Command",S[S.Parameter=256]="Parameter",S[S.OpenBracket=512]="OpenBracket",S[S.CloseBracket=1024]="CloseBracket",S[S.Function=2048]="Function",S[S.StringSpecifier=4096]="StringSpecifier",S[S.Type=8192]="Type",S))(T||{});var D=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}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}static isNamedParameterPrefix(e){if(e.length!==1)return!1;let t=e.charCodeAt(0);return t===64||t===58||t===36}};var _=class r{static getDebugPositionInfo(e,t){let n=Math.max(0,t-5),i=Math.min(e.length,t+5),s=e.slice(n,i),o=" ".repeat(t-n)+"^";return`${s} ${o}`}static skipWhiteSpace(e,t){let n=e.length;for(;t+4<=n&&e.slice(t,t+4)===" ";)t+=4;for(;t<n;){let i=e.charCodeAt(t);if(i!==32&&i!==9&&i!==10&&i!==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 i=e.slice(n+2,t).trim();return{newPosition:t,comment:i}}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 i=e.slice(n+2,t-2).replace(/\r/g,"").split(` `);for(let s=0;s<i.length;s++)i[s]=i[s].trim();for(;i.length>0&&i[0]==="";)i.shift();for(;i.length>0&&i[i.length-1]==="";)i.pop();return{newPosition:t,comments:i}}t++}throw new Error(`Block comment is not closed. position: ${t}`)}return{newPosition:t,comments:null}}static readWhiteSpaceAndComment(e,t){let n=[],i=e.length;for(;t<i;){let s=t;if(t=r.skipWhiteSpace(e,t),t!==s)continue;let o=e.charCodeAt(t);if(o===45){let a=r.readLineComment(e,t);if(a.newPosition!==t){t=a.newPosition,a.comment&&n.push(a.comment.trim());continue}}else if(o===47){let a=r.readBlockComment(e,t);if(a.newPosition!==t){t=a.newPosition,a.comments&&n.push(...a.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} ${r.getDebugPositionInfo(e,t)}`);return n}static tryReadRegularIdentifier(e,t){let n=t;for(;t<e.length&&!D.isDelimiter(e[t]);)t++;if(n===t)return null;for(;t+1<e.length&&e[t]==="["&&e[t+1]==="]";)t+=2;return{identifier:e.slice(n,t),newPosition:t}}};var $=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){return e===128||e===2||e===2048?{type:e,value:t.toLowerCase(),comments:n}:{type:e,value:t,comments:n}}getDebugPositionInfo(e){return _.getDebugPositionInfo(this.input,e)}};var wt=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="*")return this.position++,this.createLexeme(64,t);let n=_.readRegularIdentifier(this.input,this.position);return this.position=n.newPosition,this.createLexeme(64,n.identifier)}};var fe=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=_.tryReadRegularIdentifier(e,t);if(n===null)return null;let i=this.trie.pushLexeme(n.identifier.toLowerCase());if(i===0)return null;if(i===3)return{keyword:n.identifier,newPosition:n.newPosition};let s=n.identifier;if(t=_.readWhiteSpaceAndComment(e,n.newPosition).position,this.isEndOfInput(e,t))return i===2?{keyword:s,newPosition:t}:null;for(;this.canParse(e,t);){let o=i,a=_.tryReadRegularIdentifier(e,t);if(a!==null){if(i=this.trie.pushLexeme(a.identifier.toLowerCase()),i===0){if(o===2)break;return null}if(s+=" "+a.identifier,t=_.readWhiteSpaceAndComment(e,a.newPosition).position,i===3)break}else{if(o===2)break;return null}}return{keyword:s,newPosition:t}}};var we=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 Tn=[["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"]],In=new we(Tn),ln=new fe(In),Ct=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position],n=this.tryReadKeyword();if(n)return n;if(t==="."&&this.canRead(1)&&D.isDigit(this.input[this.position+1]))return this.createLexeme(1,this.readDigit());if(t==="'"){let i=this.readSingleQuotedString(!1);return this.createLexeme(1,i)}if(D.isDigit(t))return this.createLexeme(1,this.readDigit());if((t==="+"||t==="-")&&this.determineSignOrOperator(e)==="sign"){let i=t;this.position++;let s=this.position;for(;this.canRead()&&D.isWhitespace(this.input[this.position]);)this.position++;if(this.canRead()&&(D.isDigit(this.input[this.position])||this.input[this.position]==="."&&this.canRead(1)&&D.isDigit(this.input[this.position+1])))return this.createLexeme(1,i==="-"?i+this.readDigit():this.readDigit());this.position=s-1}return null}tryReadKeyword(){let e=ln.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===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 i=this.input[this.position+1].toLowerCase();this.position+=2;let s=i==="x";for(;this.canRead();){let o=this.input[this.position];if(D.isDigit(o)||s&&D.isHexChar(o))this.position++;else break}return this.input.slice(e,this.position)}for(this.input[e]==="."&&(t=!0,this.position++);this.canRead();){let i=this.input[this.position];if(i==="."&&!t)t=!0;else if((i==="e"||i==="E")&&!n)n=!0,this.canRead(1)&&(this.input[this.position+1]==="+"||this.input[this.position+1]==="-")&&this.position++;else if(!D.isDigit(i))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)}readSingleQuotedString(e){let t=this.position,n=!1;for(this.read("'");this.canRead();){let i=this.input[this.position];if(this.position++,i==="\\"&&this.canRead(1)){this.position++;continue}else if(i==="'"){n=!0;break}}if(n===!1)throw new Error(`Single quote is not closed. position: ${t} ${this.getDebugPositionInfo(t)}`);return e?this.input.slice(t,this.position):this.input.slice(t+1,this.position-1)}};var vt=class extends ${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 i=this.input.slice(n,this.position);if(i.length===0)throw new Error("Empty parameter name is not allowed: found ${} at position "+(n-2));return this.position++,this.createLexeme(256,"${"+i+"}")}let t=this.input[this.position];if(D.isNamedParameterPrefix(t)){if(this.canRead(1)&&D.isOperatorSymbol(this.input[this.position+1]))return null;this.position++;let n=this.position;for(;this.canRead()&&!D.isDelimiter(this.input[this.position]);)this.position++;let i=this.input.slice(n,this.position);return this.createLexeme(256,t+i)}return t==="?"?(this.position++,this.createLexeme(256,t)):null}};var yt=class r extends ${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 r.SPECIAL_SYMBOL_TOKENS?(this.position++,this.createLexeme(r.SPECIAL_SYMBOL_TOKENS[t],t)):null}};var St=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 i of this.readers)if(n=i.tryRead(t),n){this.position=i.getPosition();break}for(let i of this.readers)i.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 Pn=new we([["and"],["or"],["is"],["is","not"],["is","distinct","from"],["is","not","distinct","from"],["like"],["in"],["exists"],["between"],["not","like"],["not","in"],["not","exists"],["not","between"],["escape"],["uescape"],["similar"],["placing"],["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"]]),Fn=new we([["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"]]),On=new fe(Pn),Ln=new fe(Fn);var xt=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(D.isOperatorSymbol(t)){let i=this.position;for(;this.canRead()&&D.isOperatorSymbol(this.input[this.position]);){if(this.canRead(1)){let o=this.input[this.position];if(o==="-"&&this.input[this.position+1]==="-")break;if(o==="/"&&this.input[this.position+1]==="*")break}this.position++}let s=this.input.slice(i,this.position);return this.createLexeme(2,s)}let n=Ln.parse(this.input,this.position);return n!==null?(this.position=n.newPosition,this.createLexeme(8258,n.keyword)):(n=On.parse(this.input,this.position),n!==null?(this.position=n.newPosition,this.createLexeme(2,n.keyword)):null)}};var Nn=new we([["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"]]),An=new we([["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"],["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"]]),Qn=new fe(An),un=new fe(Nn),Et=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=un.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(128,t.keyword);let n=Qn.parse(this.input,this.position);if(n!==null)return this.position=n.newPosition,this.createLexeme(128,n.keyword);if(this.canRead(2)&&this.input[this.position]==="/"&&this.input[this.position+1]==="*"&&this.input[this.position+2]==="+"){this.position+=3;let i=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(i,this.position-2).trim()+" */");this.position++}throw new Error(`Block comment is not closed. position: ${this.position}`)}return null}};var Vn=new Set(["e'","E'","x'","X'","b'","B'"]),Bn=new Set(["u&'","U&'"]),bt=class extends ${tryRead(e){let t=this.position;return this.canRead(1)&&Vn.has(this.input.slice(t,t+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(t,this.position))):this.canRead(2)&&Bn.has(this.input.slice(t,t+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(t,this.position))):null}};var Rn=new we([["grouping","sets"],["array"]]),Wn=new fe(Rn),gt=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=Wn.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(2048,t.keyword);let n=_.tryReadRegularIdentifier(this.input,this.position);if(!n)return null;this.position=n.newPosition;var i=_.readWhiteSpaceAndComment(this.input,this.position).position-this.position;return this.canRead(i)&&this.input[this.position+i]==="("?this.createLexeme(2048,n.identifier):null}};var $n=new we([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),Kn=new fe($n),kt=class extends ${tryRead(e){if(this.isEndOfInput())return null;let t=Kn.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=_.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 Tt=class extends ${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==="["&&(e===null||e.value!=="array")){let n=this.readEscapedIdentifier("]");return this.createLexeme(64,n)}return null}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 x=class{constructor(e){this.input=e,this.position=0,this.readerManager=new St(e).register(new Tt(e)).register(new vt(e)).register(new bt(e)).register(new Ct(e)).register(new yt(e)).register(new Et(e)).register(new xt(e)).register(new kt(e)).register(new gt(e)).register(new wt(e))}isEndOfInput(e=0){return this.position+e>=this.input.length}canRead(e=0){return!this.isEndOfInput(e)}readLexmes(){let e=Math.ceil(this.input.length/8),t=new Array(e),n=0,i=this.readComment(),s=i.lines;this.position=i.position;let o=null;for(;this.canRead()&&this.input[this.position]!==";";){let a=this.readerManager.tryRead(this.position,o);if(a===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,a.type&16||a.type&2?l.lines.length>0&&s.push(...l.lines):((s.length>0||l.lines.length>0)&&this.addCommentsToToken(a,s,l.lines),s=[]),t[n++]=a,o=a}if(s.length>0&&n>0){let a=t[n-1];a.comments===null&&(a.comments=[]),a.comments.push(...s)}return n===e?t:t.slice(0,n)}addPendingCommentsToLastToken(e,t){if(t.length>0&&e.length>0){let n=e[e.length-1];n.comments===null&&(n.comments=[]),n.comments.push(...t)}}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 _.readWhiteSpaceAndComment(this.input,this.position)}getDebugPositionInfo(e){return _.getDebugPositionInfo(this.input,e)}};var Ce=class r{static parseFromLexeme(e,t){let{identifiers:n,newIndex:i}=r.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:s,name:o}=r.extractNamespacesAndName(n),a=0;return i>t&&(a=e[i-1].type),{namespaces:s,name:new C(o),newIndex:i,lastTokenType:a}}static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The name is complete but additional tokens were found.`);return{namespaces:i.namespaces,name:i.name}}static parseEscapedOrDotSeparatedIdentifiers(e,t){let n=t,i=[];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(i.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)i.push(e[n].value),n++;else if(e[n].type&2048)i.push(e[n].value),n++;else if(e[n].type&8192)i.push(e[n].value),n++;else if(e[n].value==="*"){i.push(e[n].value),n++;break}if(n<e.length&&e[n].type&32)n++;else break}return{identifiers:i,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 It=class{static parseFromLexeme(e,t){let{namespaces:n,name:i,newIndex:s}=Ce.parseFromLexeme(e,t);return{value:new d(n,i),newIndex:s}}};var at=class{static parseFromLexeme(e,t){let n=t,i=e[n].value,s,o=ln.parse(i.toLowerCase(),0);if(o){let l=new g(o.keyword);return n++,{value:l,newIndex:n}}return/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(i)?s=Number(i):i.startsWith("'")&&i.endsWith("'")?s=i.slice(1,-1):s=i,n++,{value:new V(s),newIndex:n}}};var Pt=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 i=B.parseFromLexeme(e,n);if(n=i.newIndex,n>=e.length||e[n].type!==8)throw new Error(`Expected ')' at index ${n}, but found ${e[n].value}`);return n++,{value:new me(i.value),newIndex:n}}else{let i=v.parseArgument(4,8,e,t);return n=i.newIndex,{value:new H(i.value),newIndex:n}}}};var Ft=class{static parseFromLexeme(e,t){let n=t;if(n<e.length&&e[n].type&2){let i=e[n].value;if(n++,i==="*")return{value:new d(null,"*"),newIndex:n};let s=v.parseFromLexeme(e,n);return n=s.newIndex,{value:new U(i,s.value),newIndex:n}}throw new Error(`Invalid unary expression at index ${t}: ${e[t].value}`)}};var Ot=class{static parseFromLexeme(e,t){let n=t,i=e[n].value;i.startsWith("${")&&i.endsWith("}")?i=i.slice(2,-1):i=i.slice(1);let s=new N(i);return n++,{value:s,newIndex:n}}};var Lt=class{static parseFromLexeme(e,t){let n=t,i=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 s=e[n].value;return n++,{value:new je(i,s),newIndex:n}}};var Nt=class{static parseFromLexeme(e,t){let n=t,i=e[n];return i.value==="case"?(n++,this.parseCaseExpression(e,n)):i.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 i=e[n].value;n++;let s=v.parseFromLexeme(e,n);return{value:new U(i,s.value),newIndex:s.newIndex}}throw new Error(`Invalid modifier unary expression at index ${n}, Lexeme: ${e[n].value}`)}static parseCaseExpression(e,t){let n=t,i=v.parseFromLexeme(e,n);n=i.newIndex;let s=this.parseSwitchCaseArgument(e,n,[]);return n=s.newIndex,{value:new M(i.value,s.value),newIndex:n}}static parseCaseWhenExpression(e,t){let n=t,i=this.parseCaseConditionValuePair(e,n);n=i.newIndex;let s=[i.value],o=this.parseSwitchCaseArgument(e,n,s);return n=o.newIndex,{value:new M(null,o.value),newIndex:n}}static parseSwitchCaseArgument(e,t,n){let i=t,s=[...n],o=null;for(;i<e.length&&this.isCommandWithValue(e[i],"when");){i++;let l=this.parseCaseConditionValuePair(e,i);i=l.newIndex,s.push(l.value)}if(i<e.length&&this.isCommandWithValue(e[i],"else")){i++;let l=v.parseFromLexeme(e,i);o=l.value,i=l.newIndex}if(i<e.length&&this.isCommandWithValue(e[i],"end"))i++;else throw new Error(`The CASE expression requires 'end' keyword at the end (index ${i})`);if(s.length===0)throw new Error(`The CASE expression requires at least one WHEN clause (index ${i})`);return{value:new te(s,o),newIndex:i}}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,i=v.parseFromLexeme(e,n);if(n=i.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 s=v.parseFromLexeme(e,n);return n=s.newIndex,{value:new ne(i.value,s.value),newIndex:n}}};var Xe=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The ORDER BY clause is complete but there are additional tokens.`);return i.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 i=[],s=this.parseItem(e,n);for(i.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let o=this.parseItem(e,n);i.push(o.value),n=o.newIndex}if(i.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 ue(i),newIndex:n}}static parseItem(e,t){let n=t,i=v.parseFromLexeme(e,n),s=i.value;if(n=i.newIndex,n>=e.length)return{value:s,newIndex:n};let o=n>=e.length?null:e[n].value==="asc"?(n++,"asc"):e[n].value==="desc"?(n++,"desc"):null,a=n>=e.length?null:e[n].value==="nulls first"?(n++,"first"):e[n].value==="nulls last"?(n++,"last"):null;return o===null&&a===null?{value:s,newIndex:n}:{value:new ye(s,o,a),newIndex:n}}};var At=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The PARTITION BY clause is complete but there are additional tokens.`);return i.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 i=[],s=v.parseFromLexeme(e,n);for(i.push(s.value),n=s.newIndex;n<e.length&&e[n].type&16;){n++;let o=v.parseFromLexeme(e,n);i.push(o.value),n=o.newIndex}if(i.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 i.length===1?{value:new be(i[0]),newIndex:n}:{value:new be(new Q(i)),newIndex:n}}};var Ze=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The window frame expression is complete but there are additional tokens.`);return i.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 i=null,s=null,o=null;if(n<e.length&&e[n].value==="partition by"){let a=At.parseFromLexeme(e,n);i=a.value,n=a.newIndex}if(n<e.length&&e[n].value==="order by"){let a=Xe.parseFromLexeme(e,n);s=a.value,n=a.newIndex}if(n<e.length&&this.isFrameTypeKeyword(e[n].value)){let a=this.parseFrameSpec(e,n);o=a.value,n=a.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 he(i,s,o),newIndex:n}}static isFrameTypeKeyword(e){let t=e;return t==="rows"||t==="range"||t==="groups"}static parseFrameSpec(e,t){let n=t,i=e[n].value,s;switch(i){case"rows":s="rows";break;case"range":s="range";break;case"groups":s="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 o=this.parseFrameBoundary(e,n),a=o.value;if(n=o.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 Ee(s,a,u),newIndex:n}}else{let o=this.parseFrameBoundary(e,n),a=o.value;return n=o.newIndex,{value:new Ee(s,a,null),newIndex:n}}}static parseFrameBoundary(e,t){let n=t;if(n<e.length&&e[n].type&128){let i=e[n].value,s;switch(i){case"current row":s="current row";break;case"unbounded preceding":s="unbounded preceding";break;case"unbounded following":s="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 Ke(s),newIndex:n+1}}else if(n<e.length&&e[n].type&1){let i=v.parseFromLexeme(e,n);if(n=i.newIndex,n<e.length&&e[n].type&128){let s=e[n].value,o;if(s==="preceding")o=!1;else if(s==="following")o=!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 Ue(i.value,o),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 lt=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw new Error(`Syntax error: Unexpected token "${n[i.newIndex].value}" at position ${i.newIndex}. The OVER expression is complete but there are additional tokens.`);return i.value}static parseFromLexeme(e,t){let n=t;if(e[n].value!=="over")throw new Error(`Syntax error at position ${n}: Expected 'OVER' keyword but found "${e[n].value}". OVER expressions must start with the OVER keyword.`);if(n++,n>=e.length)throw new Error("Syntax error: Unexpected end of input after 'OVER' keyword. Expected either a window name or an opening parenthesis '('.");if(e[n].type&64){let i=e[n].value;return n++,{value:new C(i),newIndex:n}}if(e[n].type&4)return Ze.parseFromLexeme(e,n);throw new Error(`Syntax error at position ${n}: Expected a window name or opening parenthesis '(' after OVER keyword, but found "${e[n].value}".`)}};var et=class{static parseArrayExpression(e,t){let n=t;if(n+1<e.length&&e[n+1].type&512){n++;let i=v.parseArgument(512,1024,e,n);return n=i.newIndex,{value:new se(i.value),newIndex:n}}else if(n+1<e.length&&e[n+1].type&4){n++,n++;let i=B.parseFromLexeme(e,n);return n=i.newIndex,n++,{value:new re(i.value),newIndex:n}}throw new Error(`Invalid ARRAY syntax at index ${n}, expected ARRAY[... or ARRAY(...)`)}static parseFromLexeme(e,t){let n=t,i=e[n];return i.value==="array"?this.parseArrayExpression(e,n):i.value==="substring"||i.value==="overlay"?this.parseKeywordFunction(e,n,[{key:"from",required:!1},{key:"for",required:!1}]):i.value==="cast"?this.parseKeywordFunction(e,n,[{key:"as",required:!0}]):i.value==="trim"?this.parseKeywordFunction(e,n,[{key:"from",required:!1}]):this.parseFunctionCall(e,n)}static tryParseBinaryExpression(e,t,n,i=!0){let s=t;if(s<e.length&&e[s].type&2){if(!i&&e[s].value==="and")return null;let o=e[s].value;if(s++,o==="between")return this.parseBetweenExpression(e,s,n,!1);if(o==="not between")return this.parseBetweenExpression(e,s,n,!0);if(o==="::"){let u=this.parseTypeValue(e,s);return s=u.newIndex,{value:new ie(n,u.value),newIndex:s}}let a=v.parseFromLexeme(e,s);return s=a.newIndex,{value:new b(n,o,a.value),newIndex:s}}return null}static parseBetweenExpression(e,t,n,i){let s=t,o=v.parseFromLexeme(e,s,!1);if(s=o.newIndex,s<e.length&&e[s].type&2&&e[s].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${s}`);s++;let a=v.parseFromLexeme(e,s);return s=a.newIndex,{value:new oe(n,o.value,a.value,i),newIndex:s}}static parseFunctionCall(e,t){let n=t,i=Ce.parseFromLexeme(e,n),s=i.namespaces,o=i.name;if(n=i.newIndex,n<e.length&&e[n].type&4){let a=v.parseArgument(4,8,e,n);if(n=a.newIndex,n<e.length&&e[n].value==="over"){let l=lt.parseFromLexeme(e,n);return n=l.newIndex,{value:new L(s,o.name,a.value,l.value),newIndex:n}}else return{value:new L(s,o.name,a.value,null),newIndex:n}}else throw new Error(`Expected opening parenthesis after function name '${o.name}' at index ${n}`)}static parseKeywordFunction(e,t,n){let i=t,s=Ce.parseFromLexeme(e,i),o=s.namespaces,a=s.name;if(i=s.newIndex,i<e.length&&e[i].type&4){i++;let l=v.parseFromLexeme(e,i),u=l.value;if(i=l.newIndex,i<e.length&&e[i].type&16)return this.parseFunctionCall(e,t);for(let{key:c,required:m}of n)if(i<e.length&&e[i].type&128&&e[i].value===c)if(i++,i<e.length&&e[i].type&8192){let f=this.parseTypeValue(e,i);u=new b(u,c,f.value),i=f.newIndex}else{let f=v.parseFromLexeme(e,i);u=new b(u,c,f.value),i=f.newIndex}else if(m)throw new Error(`Keyword '${c}' is required at index ${i}`);if(i<e.length&&e[i].type&8)if(i++,i<e.length&&e[i].value==="over"){i++;let c=lt.parseFromLexeme(e,i);return i=c.newIndex,{value:new L(o,a.name,u,c.value),newIndex:i}}else return{value:new L(o,a.name,u,null),newIndex:i};else throw new Error(`Missing closing parenthesis for function '${a.name}' at index ${i}`)}else throw new Error(`Missing opening parenthesis for function '${a.name}' at index ${i}`)}static parseTypeValue(e,t){let n=t,{namespaces:i,name:s,newIndex:o}=Ce.parseFromLexeme(e,n);if(n=o,n<e.length&&e[n].type&4){let a=v.parseArgument(4,8,e,n);return n=a.newIndex,{value:new ve(i,new g(s.name),a.value),newIndex:n}}else return{value:new ve(i,new g(s.name)),newIndex:n}}};var Qt=class r extends Error{constructor(t,n,i){super(t);this.index=n;this.context=i;this.name="ParseError"}static fromUnparsedLexemes(t,n,i){let s=Math.max(0,n-2),o=Math.min(t.length,n+3),a=t.slice(s,o).map((u,c)=>{let m=c+s===n?">":" ",f=T[u.type]||u.type;return`${m} ${c+s}:${u.value} [${f}]`}).join(` `),l=`${i} Unparsed lexeme remains at index ${n}: ${t[n].value} Context: ${a}`;return new r(l,n,a)}};var v=class{static parse(e){let n=new x(e).readLexmes(),i=this.parseFromLexeme(n,0);if(i.newIndex<n.length)throw Qt.fromUnparsedLexemes(n,i.newIndex,"[ValueParser]");return i.value}static parseFromLexeme(e,t,n=!0){let i=t,s=e[i].comments,o=this.parseItem(e,i);for(o.value.comments=s,i=o.newIndex;i<e.length&&e[i].type&2;){let a=et.tryParseBinaryExpression(e,i,o.value,n);if(a)o.value=a.value,i=a.newIndex;else break}return{value:o.value,newIndex:i}}static parseItem(e,t){let n=t;if(n>=e.length)throw new Error(`Unexpected end of lexemes at index ${t}`);let i=e[n];if(i.type&64&&i.type&2&&i.type&8192){let s=It.parseFromLexeme(e,n);if(s.newIndex>=e.length)return s;if(e[s.newIndex].type&1){let a=at.parseFromLexeme(e,s.newIndex);return{value:new U(e[n].value,a.value),newIndex:a.newIndex}}return s}else if(i.type&64){let{namespaces:s,name:o,newIndex:a}=Ce.parseFromLexeme(e,n);return e[a-1].type&10240?et.parseFromLexeme(e,n):{value:new d(s,o),newIndex:a}}else{if(i.type&1)return at.parseFromLexeme(e,n);if(i.type&4)return Pt.parseFromLexeme(e,n);if(i.type&2048)return et.parseFromLexeme(e,n);if(i.type&2)return Ft.parseFromLexeme(e,n);if(i.type&256)return Ot.parseFromLexeme(e,n);if(i.type&4096)return Lt.parseFromLexeme(e,n);if(i.type&128)return Nt.parseFromLexeme(e,n);if(i.type&512){let{namespaces:s,name:o,newIndex:a}=Ce.parseFromLexeme(e,n);return{value:new d(s,o),newIndex:a}}}throw new Error(`[ValueParser] Invalid lexeme. index: ${n}, type: ${e[n].type}, value: ${e[n].value}`)}static parseArgument(e,t,n,i){let s=i,o=[];if(s<n.length&&n[s].type===e){if(s++,s<n.length&&n[s].type===t)return s++,{value:new Q([]),newIndex:s};if(s<n.length&&n[s].value==="*"){let l=new d(null,"*");if(s++,s<n.length&&n[s].type===t)return s++,{value:l,newIndex:s};throw new Error(`Expected closing parenthesis at index ${s}`)}let a=this.parseFromLexeme(n,s);for(s=a.newIndex,o.push(a.value);s<n.length&&n[s].type&16;){s++;let l=this.parseFromLexeme(n,s);s=l.newIndex,o.push(l.value)}if(s<n.length&&n[s].type===t)return s++,o.length===1?{value:o[0],newIndex:s}:{value:new Q(o),newIndex:s};throw new Error(`Missing closing parenthesis at index ${s}`)}throw new Error(`Expected opening parenthesis at index ${i}`)}};var K=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(E.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(R.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(J.kind,e=>this.visitValuesQuery(e)),this.handlers.set(q.kind,e=>this.visitWithClause(e)),this.handlers.set(j.kind,e=>this.visitCommonTable(e)),this.handlers.set(F.kind,e=>this.visitSelectItem(e)),this.handlers.set(C.kind,e=>this.visitIdentifierString(e)),this.handlers.set(g.kind,e=>this.visitRawString(e)),this.handlers.set(d.kind,e=>this.visitColumnReference(e)),this.handlers.set(N.kind,e=>this.visitParameterExpression(e)),this.handlers.set(V.kind,e=>this.visitLiteralValue(e)),this.handlers.set(k.kind,e=>this.visitSourceExpression(e)),this.handlers.set(I.kind,e=>this.visitTableSource(e)),this.handlers.set(Fe.kind,e=>this.visitFunctionSource(e)),this.handlers.set(ge.kind,e=>this.visitParenSource(e)),this.handlers.set(A.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(me.kind,e=>this.visitInlineQuery(e)),this.handlers.set(P.kind,e=>this.visitFromClause(e)),this.handlers.set(Z.kind,e=>this.visitJoinClause(e)),this.handlers.set(X.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(ce.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(z.kind,e=>this.visitWhereClause(e)),this.handlers.set(H.kind,e=>this.visitParenExpression(e)),this.handlers.set(b.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(U.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(M.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ne.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(te.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(oe.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(L.kind,e=>this.visitFunctionCall(e)),this.handlers.set(se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(re.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(ae.kind,e=