rawsql-ts
Version:
[beta]High-performance SQL parser and AST analyzer written in TypeScript. Provides fast parsing and advanced transformation capabilities.
11 lines • 184 kB
JavaScript
var w=class{constructor(){this.comments=null}getKind(){return this.constructor.kind}accept(e){return e.visit(this)}toSqlString(e){return this.accept(e)}};var qe=class extends w{static{this.kind=Symbol("InsertQuery")}constructor(e){super(),this.insertClause=e.insertClause,this.selectQuery=e.selectQuery??null}};var Le=class extends w{static{this.kind=Symbol("InlineQuery")}constructor(e){super(),this.selectQuery=e}},q=class extends w{static{this.kind=Symbol("ValueList")}constructor(e){super(),this.values=e}},x=class extends w{get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof E?this.qualifiedName.name:new E(this.qualifiedName.name.value)}static{this.kind=Symbol("ColumnReference")}constructor(e,t){super();let n=typeof t=="string"?new E(t):t;this.qualifiedName=new Ae(On(e),n)}toString(){return this.qualifiedName.toString()}getNamespace(){return this.qualifiedName.namespaces?this.qualifiedName.namespaces.map(e=>e.name).join("."):""}},U=class extends w{static{this.kind=Symbol("FunctionCall")}constructor(e,t,n,r){super(),this.qualifiedName=new Ae(e,t),this.argument=n,this.over=r}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},In=(n=>(n.Rows="rows",n.Range="range",n.Groups="groups",n))(In||{}),Pn=(n=>(n.UnboundedPreceding="unbounded preceding",n.UnboundedFollowing="unbounded following",n.CurrentRow="current row",n))(Pn||{}),rt=class extends w{static{this.kind=Symbol("WindowFrameStaticBound")}constructor(e){super(),this.bound=e}},it=class extends w{static{this.kind=Symbol("WindowFrameBoundary")}constructor(e,t){super(),this.value=e,this.isFollowing=t}},$e=class extends w{static{this.kind=Symbol("WindowFrameSpec")}constructor(e,t,n){super(),this.frameType=e,this.startBound=t,this.endBound=n}},Qe=class extends w{static{this.kind=Symbol("WindowFrameExpression")}constructor(e,t,n=null){super(),this.partition=e,this.order=t,this.frameSpec=n}},ie=class extends w{static{this.kind=Symbol("UnaryExpression")}constructor(e,t){super(),this.operator=new Q(e),this.expression=t}},C=class extends w{static{this.kind=Symbol("BinaryExpression")}constructor(e,t,n){super(),this.left=e,this.operator=new Q(t),this.right=n}},z=class extends w{static{this.kind=Symbol("LiteralExpression")}constructor(e){super(),this.value=e}},b=class extends w{static{this.kind=Symbol("ParameterExpression")}constructor(e,t=null){super(),this.name=new Q(e),this.value=t,this.index=null}},ye=class extends w{static{this.kind=Symbol("SwitchCaseArgument")}constructor(e,t=null){super(),this.cases=e,this.elseValue=t}},ve=class extends w{static{this.kind=Symbol("CaseKeyValuePair")}constructor(e,t){super(),this.key=e,this.value=t}},Q=class extends w{static{this.kind=Symbol("RawString")}constructor(e){super(),this.value=e}},E=class extends w{static{this.kind=Symbol("IdentifierString")}constructor(e){super(),this.name=e}},Y=class extends w{static{this.kind=Symbol("ParenExpression")}constructor(e){super(),this.expression=e}},ce=class extends w{static{this.kind=Symbol("CastExpression")}constructor(e,t){super(),this.input=e,this.castType=t}},ue=class extends w{static{this.kind=Symbol("CaseExpression")}constructor(e,t){super(),this.condition=e,this.switchCase=t}},Se=class extends w{static{this.kind=Symbol("ArrayExpression")}constructor(e){super(),this.expression=e}},ge=class extends w{static{this.kind=Symbol("ArrayQueryExpression")}constructor(e){super(),this.query=e}},xe=class extends w{static{this.kind=Symbol("BetweenExpression")}constructor(e,t,n,r){super(),this.expression=e,this.lower=t,this.upper=n,this.negated=r}},Ue=class extends w{static{this.kind=Symbol("StringSpecifierExpression")}constructor(e,t){super(),this.specifier=new Q(e),this.value=new z(t)}},Ie=class extends w{static{this.kind=Symbol("TypeValue")}constructor(e,t,n=null){super(),this.qualifiedName=new Ae(e,t),this.argument=n}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}getTypeName(){let e=this.qualifiedName.name instanceof Q?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}},Ee=class extends w{static{this.kind=Symbol("TupleExpression")}constructor(e){super(),this.values=e}};function On(s){if(s==null)return null;if(typeof s=="string")return s.trim()===""?null:[new E(s)];if(Array.isArray(s)){if(s.length===0)return null;if(typeof s[0]=="string"){let e=s.filter(t=>t.trim()!=="");return e.length===0?null:e.map(t=>new E(t))}else{let e=s.filter(t=>t.name.trim()!=="");return e.length===0?null:e}}return null}var Ae=class extends w{static{this.kind=Symbol("QualifiedName")}constructor(e,t){super(),this.namespaces=On(e),typeof t=="string"?this.name=new Q(t):this.name=t}toString(){let e=this.name instanceof Q?this.name.value:this.name.name;return this.namespaces&&this.namespaces.length>0?this.namespaces.map(t=>t.name).join(".")+"."+e:e}};var j=class extends w{static{this.kind=Symbol("SelectItem")}constructor(e,t=null){super(),this.value=e,this.identifier=t?new E(t):null}},D=class extends w{static{this.kind=Symbol("SelectClause")}constructor(e,t=null){super(),this.items=e,this.distinct=t}},st=class extends w{static{this.kind=Symbol("Distinct")}constructor(){super()}},ot=class extends w{static{this.kind=Symbol("DistinctOn")}constructor(e){super(),this.value=e}},se=class extends w{static{this.kind=Symbol("WhereClause")}constructor(e){super(),this.condition=e}},We=class extends w{static{this.kind=Symbol("PartitionByClause")}constructor(e){super(),this.value=e}},we=class extends w{static{this.kind=Symbol("WindowFrameClause")}constructor(e,t){super(),this.name=new E(e),this.expression=t}},ze=class extends w{static{this.kind=Symbol("WindowsClause")}constructor(e){super(),this.windows=e}};var pe=class extends w{static{this.kind=Symbol("OrderByClause")}constructor(e){super(),this.order=e}},be=class extends w{static{this.kind=Symbol("OrderByItem")}constructor(e,t,n){super(),this.value=e,this.sortDirection=t===null?"asc":t,this.nullsPosition=n}},me=class extends w{static{this.kind=Symbol("GroupByClause")}constructor(e){super(),this.grouping=e}},de=class extends w{static{this.kind=Symbol("HavingClause")}constructor(e){super(),this.condition=e}},R=class extends w{static{this.kind=Symbol("TableSource")}get namespaces(){return this.qualifiedName.namespaces}get table(){return this.qualifiedName.name instanceof E?this.qualifiedName.name:new E(this.qualifiedName.name.value)}get identifier(){return this.table}constructor(e,t){super();let n=typeof t=="string"?new E(t):t;this.qualifiedName=new Ae(e,n)}getSourceName(){return this.qualifiedName.namespaces&&this.qualifiedName.namespaces.length>0?this.qualifiedName.namespaces.map(e=>e.name).join(".")+"."+(this.qualifiedName.name instanceof Q?this.qualifiedName.name.value:this.qualifiedName.name.name):this.qualifiedName.name instanceof Q?this.qualifiedName.name.value:this.qualifiedName.name.name}},De=class extends w{static{this.kind=Symbol("FunctionSource")}constructor(e,t){if(super(),typeof e=="object"&&e!==null&&"name"in e){let n=e;this.qualifiedName=new Ae(n.namespaces,n.name)}else this.qualifiedName=new Ae(null,e);this.argument=t}get namespaces(){return this.qualifiedName.namespaces}get name(){return this.qualifiedName.name}},Me=class extends w{static{this.kind=Symbol("ParenSource")}constructor(e){super(),this.source=e}},_=class extends w{static{this.kind=Symbol("SubQuerySource")}constructor(e){super(),this.query=e}},B=class extends w{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 R?this.datasource.getSourceName():null}},he=class extends w{static{this.kind=Symbol("JoinOnClause")}constructor(e){super(),this.condition=e}},ke=class extends w{static{this.kind=Symbol("JoinUsingClause")}constructor(e){super(),this.condition=e}},fe=class extends w{static{this.kind=Symbol("JoinItem")}constructor(e,t,n,r){super(),this.joinType=new Q(e),this.source=t,this.condition=n,this.lateral=r}getSourceAliasName(){return this.source.aliasExpression?this.source.aliasExpression.table.name:this.source instanceof R?this.source.table.name:null}},$=class extends w{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 R?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}},Z=class extends w{static{this.kind=Symbol("CommonTable")}constructor(e,t,n){super(),this.query=e,this.materialized=n,typeof t=="string"?this.aliasExpression=new H(t,null):this.aliasExpression=t}getSourceAliasName(){return this.aliasExpression.table.name}},ee=class extends w{static{this.kind=Symbol("WithClause")}constructor(e,t){super(),this.recursive=e,this.tables=t}},oe=class extends w{static{this.kind=Symbol("LimitClause")}constructor(e){super(),this.value=e}};var Re=class extends w{static{this.kind=Symbol("OffsetClause")}constructor(e){super(),this.value=e}},Ke=class extends w{static{this.kind=Symbol("FetchClause")}constructor(e){super(),this.expression=e}},Ze=class extends w{static{this.kind=Symbol("FetchExpression")}constructor(e,t,n){super(),this.type=e,this.count=t,this.unit=n}};var Be=class extends w{static{this.kind=Symbol("ForClause")}constructor(e){super(),this.lockMode=e}},H=class extends w{static{this.kind=Symbol("SourceAliasExpression")}constructor(e,t){super(),this.table=new E(e),this.columns=t!==null?t.map(n=>new E(n)):null}},Et=class extends w{static{this.kind=Symbol("ReturningClause")}constructor(e){super(),this.columns=e.map(t=>typeof t=="string"?new E(t):t)}},_e=class extends w{static{this.kind=Symbol("SetClause")}constructor(e){super(),this.items=e.map(t=>t instanceof Ge?t:new Ge(t.column,t.value))}},Ge=class extends w{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 E(n.column):n.column;this.qualifiedName=new Ae(n.namespaces,r)}else{let n=typeof e=="string"?new E(e):e;this.qualifiedName=new Ae(null,n)}this.value=t}get namespaces(){return this.qualifiedName.namespaces}get column(){return this.qualifiedName.name instanceof E?this.qualifiedName.name:new E(this.qualifiedName.name.value)}getFullName(){return this.qualifiedName.toString()}},at=class extends w{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 R?this.source.datasource.table.name:null}},He=class extends w{constructor(e,t){super(),this.source=e,this.columns=t.map(n=>new E(n))}};var V=(d=>(d[d.None=0]="None",d[d.Literal=1]="Literal",d[d.Operator=2]="Operator",d[d.OpenParen=4]="OpenParen",d[d.CloseParen=8]="CloseParen",d[d.Comma=16]="Comma",d[d.Dot=32]="Dot",d[d.Identifier=64]="Identifier",d[d.Command=128]="Command",d[d.Parameter=256]="Parameter",d[d.OpenBracket=512]="OpenBracket",d[d.CloseBracket=1024]="CloseBracket",d[d.Function=2048]="Function",d[d.StringSpecifier=4096]="StringSpecifier",d[d.Type=8192]="Type",d))(V||{});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}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 ae=class s{static getDebugPositionInfo(e,t){let n=Math.max(0,t-5),r=Math.min(e.length,t+5),i=e.slice(n,r),o=" ".repeat(t-n)+"^";return`${i}
${o}`}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=s.skipWhiteSpace(e,t),t!==i)continue;let o=e.charCodeAt(t);if(o===45){let a=s.readLineComment(e,t);if(a.newPosition!==t){t=a.newPosition,a.comment&&n.push(a.comment.trim());continue}}else if(o===47){let a=s.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}
${s.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]==="]";)t+=2;return{identifier:e.slice(n,t),newPosition:t}}};var X=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 ae.getDebugPositionInfo(this.input,e)}};var bt=class extends X{tryRead(e){if(this.isEndOfInput())return null;let t=this.input[this.position];if(t==="*")return this.position++,this.createLexeme(64,t);let n=ae.readRegularIdentifier(this.input,this.position);return this.position=n.newPosition,this.createLexeme(64,n.identifier)}};var Pe=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=ae.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;if(t=ae.readWhiteSpaceAndComment(e,n.newPosition).position,this.isEndOfInput(e,t))return r===2?{keyword:i,newPosition:t}:null;for(;this.canParse(e,t);){let o=r,a=ae.tryReadRegularIdentifier(e,t);if(a!==null){if(r=this.trie.pushLexeme(a.identifier.toLowerCase()),r===0){if(o===2)break;return null}if(i+=" "+a.identifier,t=ae.readWhiteSpaceAndComment(e,a.newPosition).position,r===3)break}else{if(o===2)break;return null}}return{keyword:i,newPosition:t}}};var Oe=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 jn=[["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"]],Un=new Oe(jn),xn=new Pe(Un),kt=class extends X{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)&&te.isDigit(this.input[this.position+1]))return this.createLexeme(1,this.readDigit());if(t==="'"){let r=this.readSingleQuotedString(!1);return this.createLexeme(1,r)}if(te.isDigit(t))return this.createLexeme(1,this.readDigit());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=xn.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 o=this.input[this.position];if(te.isDigit(o)||i&&te.isHexChar(o))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)}readSingleQuotedString(e){let t=this.position,n=!1;for(this.read("'");this.canRead();){let r=this.input[this.position];if(this.position++,r==="\\"&&this.canRead(1)){this.position++;continue}else if(r==="'"){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 Tt=class extends X{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]))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)}return t==="?"?(this.position++,this.createLexeme(256,t)):null}};var It=class s extends X{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 s.SPECIAL_SYMBOL_TOKENS?(this.position++,this.createLexeme(s.SPECIAL_SYMBOL_TOKENS[t],t)):null}};var Pt=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 Dn=new Oe([["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"],["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"]]),Kn=new Oe([["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"]]),Jn=new Pe(Dn),qn=new Pe(Kn);var Ot=class extends X{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 o=this.input[this.position];if(o==="-"&&this.input[this.position+1]==="-")break;if(o==="/"&&this.input[this.position+1]==="*")break}this.position++}let i=this.input.slice(r,this.position);return this.createLexeme(2,i)}let n=qn.parse(this.input,this.position);return n!==null?(this.position=n.newPosition,this.createLexeme(8258,n.keyword)):(n=Jn.parse(this.input,this.position),n!==null?(this.position=n.newPosition,this.createLexeme(2,n.keyword)):null)}};var _n=new Oe([["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"]]),zn=new Oe([["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"]]),Gn=new Pe(zn),En=new Pe(_n),Nt=class extends X{tryRead(e){if(this.isEndOfInput())return null;let t=En.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(128,t.keyword);let n=Gn.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 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 Hn=new Set(["e'","E'","x'","X'","b'","B'"]),Yn=new Set(["u&'","U&'"]),Ft=class extends X{tryRead(e){let t=this.position;return this.canRead(1)&&Hn.has(this.input.slice(t,t+2))?(this.position+=1,this.createLexeme(4096,this.input.slice(t,this.position))):this.canRead(2)&&Yn.has(this.input.slice(t,t+3))?(this.position+=2,this.createLexeme(4096,this.input.slice(t,this.position))):null}};var Xn=new Oe([["grouping","sets"],["array"]]),Zn=new Pe(Xn),Lt=class extends X{tryRead(e){if(this.isEndOfInput())return null;let t=Zn.parse(this.input,this.position);if(t!==null)return this.position=t.newPosition,this.createLexeme(2048,t.keyword);let n=ae.tryReadRegularIdentifier(this.input,this.position);if(!n)return null;this.position=n.newPosition;var r=ae.readWhiteSpaceAndComment(this.input,this.position).position-this.position;return this.canRead(r)&&this.input[this.position+r]==="("?this.createLexeme(2048,n.identifier):null}};var er=new Oe([["double","precision"],["character","varying"],["time","without","time","zone"],["time","with","time","zone"],["timestamp","without","time","zone"],["timestamp","with","time","zone"]]),tr=new Pe(er),Qt=class extends X{tryRead(e){if(this.isEndOfInput())return null;let t=tr.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=ae.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 At=class extends X{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 P=class{constructor(e){this.input=e,this.position=0,this.readerManager=new Pt(e).register(new At(e)).register(new Tt(e)).register(new Ft(e)).register(new kt(e)).register(new It(e)).register(new Nt(e)).register(new Ot(e)).register(new Qt(e)).register(new Lt(e)).register(new bt(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,r=this.readComment(),i=r.lines;this.position=r.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&&i.push(...l.lines):((i.length>0||l.lines.length>0)&&this.addCommentsToToken(a,i,l.lines),i=[]),t[n++]=a,o=a}if(i.length>0&&n>0){let a=t[n-1];a.comments===null&&(a.comments=[]),a.comments.push(...i)}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 ae.readWhiteSpaceAndComment(this.input,this.position)}getDebugPositionInfo(e){return ae.getDebugPositionInfo(this.input,e)}};var Te=class s{static parseFromLexeme(e,t){let{identifiers:n,newIndex:r}=s.parseEscapedOrDotSeparatedIdentifiers(e,t),{namespaces:i,name:o}=s.extractNamespacesAndName(n),a=0;return r>t&&(a=e[r-1].type),{namespaces:i,name:new E(o),newIndex:r,lastTokenType:a}}static parse(e){let n=new P(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 Bt=class{static parseFromLexeme(e,t){let{namespaces:n,name:r,newIndex:i}=Te.parseFromLexeme(e,t);return{value:new x(n,r),newIndex:i}}};var Ct=class{static parseFromLexeme(e,t){let n=t,r=e[n].value,i,o=xn.parse(r.toLowerCase(),0);if(o){let l=new Q(o.keyword);return n++,{value:l,newIndex:n}}return/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(r)?i=Number(r):r.startsWith("'")&&r.endsWith("'")?i=r.slice(1,-1):i=r,n++,{value:new z(i),newIndex:n}}};var Vt=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=W.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}`);return n++,{value:new Le(r.value),newIndex:n}}else{let r=k.parseArgument(4,8,e,t);return n=r.newIndex,{value:new Y(r.value),newIndex:n}}}};var Rt=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 x(null,"*"),newIndex:n};let i=k.parseFromLexeme(e,n);return n=i.newIndex,{value:new ie(r,i.value),newIndex:n}}throw new Error(`Invalid unary expression at index ${t}: ${e[t].value}`)}};var $t=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 b(r);return n++,{value:i,newIndex:n}}};var Wt=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 Ue(r,i),newIndex:n}}};var Mt=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=k.parseFromLexeme(e,n);return{value:new ie(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=k.parseFromLexeme(e,n);n=r.newIndex;let i=this.parseSwitchCaseArgument(e,n,[]);return n=i.newIndex,{value:new ue(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],o=this.parseSwitchCaseArgument(e,n,i);return n=o.newIndex,{value:new ue(null,o.value),newIndex:n}}static parseSwitchCaseArgument(e,t,n){let r=t,i=[...n],o=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=k.parseFromLexeme(e,r);o=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 ye(i,o),newIndex:r}}static isCommandWithValue(e,t){return(e.type&128)!==0&&e.value===t}static parseCaseConditionValuePair(e,t){let n=t,r=k.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=k.parseFromLexeme(e,n);return n=i.newIndex,{value:new ve(r.value,i.value),newIndex:n}}};var lt=class{static parse(e){let n=new P(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 o=this.parseItem(e,n);r.push(o.value),n=o.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 pe(r),newIndex:n}}static parseItem(e,t){let n=t,r=k.parseFromLexeme(e,n),i=r.value;if(n=r.newIndex,n>=e.length)return{value:i,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:i,newIndex:n}:{value:new be(i,o,a),newIndex:n}}};var jt=class{static parse(e){let n=new P(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=k.parseFromLexeme(e,n);for(r.push(i.value),n=i.newIndex;n<e.length&&e[n].type&16;){n++;let o=k.parseFromLexeme(e,n);r.push(o.value),n=o.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 We(r[0]),newIndex:n}:{value:new We(new q(r)),newIndex:n}}};var ut=class{static parse(e){let n=new P(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,o=null;if(n<e.length&&e[n].value==="partition by"){let a=jt.parseFromLexeme(e,n);r=a.value,n=a.newIndex}if(n<e.length&&e[n].value==="order by"){let a=lt.parseFromLexeme(e,n);i=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 Qe(r,i,o),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 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 $e(i,a,u),newIndex:n}}else{let o=this.parseFrameBoundary(e,n),a=o.value;return n=o.newIndex,{value:new $e(i,a,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 rt(i),newIndex:n+1}}else if(n<e.length&&e[n].type&1){let r=k.parseFromLexeme(e,n);if(n=r.newIndex,n<e.length&&e[n].type&128){let i=e[n].value,o;if(i==="preceding")o=!1;else if(i==="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 it(r.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 yt=class{static parse(e){let n=new P(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.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 r=e[n].value;return n++,{value:new E(r),newIndex:n}}if(e[n].type&4)return ut.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 r=k.parseArgument(512,1024,e,n);return n=r.newIndex,{value:new Se(r.value),newIndex:n}}else if(n+1<e.length&&e[n+1].type&4){n++,n++;let r=W.parseFromLexeme(e,n);return n=r.newIndex,n++,{value:new ge(r.value),newIndex:n}}throw new Error(`Invalid ARRAY syntax at index ${n}, expected ARRAY[... or ARRAY(...)`)}static parseFromLexeme(e,t){let n=t,r=e[n];return r.value==="array"?this.parseArrayExpression(e,n):r.value==="substring"||r.value==="overlay"?this.parseKeywordFunction(e,n,[{key:"from",required:!1},{key:"for",required:!1}]):r.value==="cast"?this.parseKeywordFunction(e,n,[{key:"as",required:!0}]):r.value==="trim"?this.parseKeywordFunction(e,n,[{key:"from",required:!1}]):this.parseFunctionCall(e,n)}static tryParseBinaryExpression(e,t,n,r=!0,i=!0){let o=t;if(o<e.length&&e[o].type&2){let a=e[o].value.toLowerCase();if(!r&&a==="and"||!i&&a==="or")return null;if(o++,a==="between")return this.parseBetweenExpression(e,o,n,!1);if(a==="not between")return this.parseBetweenExpression(e,o,n,!0);if(a==="::"){let p=this.parseTypeValue(e,o);return o=p.newIndex,{value:new ce(n,p.value),newIndex:o}}let l=k.parseFromLexeme(e,o);return o=l.newIndex,{value:new C(n,a,l.value),newIndex:o}}return null}static parseBetweenExpression(e,t,n,r){let i=t,o=k.parseFromLexeme(e,i,!1);if(i=o.newIndex,i<e.length&&e[i].type&2&&e[i].value!=="and")throw new Error(`Expected 'and' after 'between' at index ${i}`);i++;let a=this.parseBetweenUpperBound(e,i);return i=a.newIndex,{value:new xe(n,o.value,a.value,r),newIndex:i}}static parseBetweenUpperBound(e,t){return k.parseFromLexeme(e,t,!1,!1)}static parseFunctionCall(e,t){let n=t,r=Te.parseFromLexeme(e,n),i=r.namespaces,o=r.name;if(n=r.newIndex,n<e.length&&e[n].type&4){let a=k.parseArgument(4,8,e,n);if(n=a.newIndex,n<e.length&&e[n].value==="over"){let l=yt.parseFromLexeme(e,n);return n=l.newIndex,{value:new U(i,o.name,a.value,l.value),newIndex:n}}else return{value:new U(i,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 r=t,i=Te.parseFromLexeme(e,r),o=i.namespaces,a=i.name;if(r=i.newIndex,r<e.length&&e[r].type&4){r++;let l=k.parseFromLexeme(e,r),u=l.value;if(r=l.newIndex,r<e.length&&e[r].type&16)return this.parseFunctionCall(e,t);for(let{key:p,required:h}of n)if(r<e.length&&e[r].type&128&&e[r].value===p)if(r++,r<e.length&&e[r].type&8192){let y=this.parseTypeValue(e,r);u=new C(u,p,y.value),r=y.newIndex}else{let y=k.parseFromLexeme(e,r);u=new C(u,p,y.value),r=y.newIndex}else if(h)throw new Error(`Keyword '${p}' is required at index ${r}`);if(r<e.length&&e[r].type&8)if(r++,r<e.length&&e[r].value==="over"){r++;let p=yt.parseFromLexeme(e,r);return r=p.newIndex,{value:new U(o,a.name,u,p.value),newIndex:r}}else return{value:new U(o,a.name,u,null),newIndex:r};else throw new Error(`Missing closing parenthesis for function '${a.name}' at index ${r}`)}else throw new Error(`Missing opening parenthesis for function '${a.name}' at index ${r}`)}static parseTypeValue(e,t){let n=t,{namespaces:r,name:i,newIndex:o}=Te.parseFromLexeme(e,n);if(n=o,n<e.length&&e[n].type&4){let a=k.parseArgument(4,8,e,n);return n=a.newIndex,{value:new Ie(r,new Q(i.name),a.value),newIndex:n}}else return{value:new Ie(r,new Q(i.name)),newIndex:n}}};var Ut=class s extends Error{constructor(t,n,r){super(t);this.index=n;this.context=r;this.name="ParseError"}static fromUnparsedLexemes(t,n,r){let i=Math.max(0,n-2),o=Math.min(t.length,n+3),a=t.slice(i,o).map((u,p)=>{let h=p+i===n?">":" ",y=V[u.type]||u.type;return`${h} ${p+i}:${u.value} [${y}]`}).join(`
`),l=`${r} Unparsed lexeme remains at index ${n}: ${t[n].value}
Context:
${a}`;return new s(l,n,a)}};var vt=class{static{this.precedenceMap={or:1,and:2,"=":10,"!=":10,"<>":10,"<":10,"<=":10,">":10,">=":10,like:10,ilike:10,"not like":10,"not ilike":10,"similar to":10,"not similar to":10,in:10,"not in":10,is:10,"is not":10,between:15,"not between":15,"+":20,"-":20,"*":30,"/":30,"%":30,"^":40,"::":50,"unary+":100,"unary-":100,not:100}}static getPrecedence(e){let t=this.precedenceMap[e.toLowerCase()];return t!==void 0?t:0}static hasHigherOrEqualPrecedence(e,t){return this.getPrecedence(e)>=this.getPrecedence(t)}static isLogicalOperator(e){let t=e.toLowerCase();return t==="and"||t==="or"}static isBetweenOperator(e){let t=e.toLowerCase();return t==="between"||t==="not between"}static isComparisonOperator(e){let t=e.toLowerCase();return["=","!=","<>","<",">","<=",">=","like","ilike","similar to","in","not in"].includes(t)}};var k=class{static parse(e){let n=new P(e).readLexmes(),r=this.parseFromLexeme(n,0);if(r.newIndex<n.length)throw Ut.fromUnparsedLexemes(n,r.newIndex,"[ValueParser]");return r.value}static parseFromLexeme(e,t,n=!0,r=!0){return this.parseExpressionWithPrecedence(e,t,0,n,r)}static parseExpressionWithPrecedence(e,t,n,r=!0,i=!0){let o=t,a=e[o].comments,l=this.parseItem(e,o);l.value.comments=a,o=l.newIndex;let u=l.value;for(;o<e.length&&e[o].type&2;){let h=e[o].value;if(!r&&h.toLowerCase()==="and"||!i&&h.toLowerCase()==="or")break;let y=vt.getPrecedence(h);if(y<n)break;if(o++,vt.isBetweenOperator(h)){let d=et.parseBetweenExpression(e,o,u,h.toLowerCase().includes("not"));u=d.value,o=d.newIndex;continue}if(h==="::"){let d=et.parseTypeValue(e,o);u=new ce(u,d.value),o=d.newIndex;continue}let I=y+1,J=this.parseExpressionWithPrecedence(e,o,I,r,i);o=J.newIndex,u=new C(u,h,J.value)}return{value:u,newIndex:o}}static parseItem(e,t){let n=t;if(n>=e.length)throw new Error(`Unexpected end of lexemes at index ${t}`);let r=e[n];if(r.type&64&&r.type&2&&r.type&8192){let i=Bt.parseFromLexeme(e,n);if(i.newIndex>=e.length)return i;if(e[i.newIndex].type&1){let a=Ct.parseFromLexeme(e,i.newIndex);return{value:new ie(e[n].value,a.value),newIndex:a.newIndex}}return i}else if(r.type&64){let{namespaces:i,name:o,newIndex:a}=Te.parseFromLexeme(e,n);return e[a-1].type&10240?et.parseFromLexeme(e,n):{value:new x(i,o),newIndex:a}}else{if(r.type&1)return Ct.parseFromLexeme(e,n);if(r.type&4)return Vt.parseFromLexeme(e,n);if(r.type&2048)return et.parseFromLexeme(e,n);if(r.type&2)return Rt.parseFromLexeme(e,n);if(r.type&256)return $t.parseFromLexeme(e,n);if(r.type&4096)return Wt.parseFromLexeme(e,n);if(r.type&128)return Mt.parseFromLexeme(e,n);if(r.type&512){let{namespaces:i,name:o,newIndex:a}=Te.parseFromLexeme(e,n);return{value:new x(i,o),newIndex:a}}else if(r.type&8192){let{namespaces:i,name:o,newIndex:a}=Te.parseFromLexeme(e,n);return{value:new Ie(i,o),newIndex:a}}}throw new Error(`[ValueParser] Invalid lexeme. index: ${n}, type: ${e[n].type}, value: ${e[n].value}`)}static parseArgument(e,t,n,r){let i=r,o=[];if(i<n.length&&n[i].type===e){if(i++,i<n.length&&n[i].type===t)return i++,{value:new q([]),newIndex:i};if(i<n.length&&n[i].value==="*"){let l=new x(null,"*");if(i++,i<n.length&&n[i].type===t)return i++,{value:l,newIndex:i};throw new Error(`Expected closing parenthesis at index ${i}`)}let a=this.parseFromLexeme(n,i);for(i=a.newIndex,o.push(a.value);i<n.length&&n[i].type&16;){i++;let l=this.parseFromLexeme(n,i);i=l.newIndex,o.push(l.value)}if(i<n.length&&n[i].type===t)return i++,o.length===1?{value:o[0],newIndex:i}:{value:new q(o),newIndex:i};throw new Error(`Missing closing parenthesis at index ${i}`)}throw new Error(`Expected opening parenthesis at index ${r}`)}};var ne=class{constructor(){this.commonTables=[];this.visitedNodes=new Set;this.isRootVisit=!0;this.handlers=new Map,this.handlers.set(T.kind,e=>this.visitSimpleSelectQuery(e)),this.handlers.set(G.kind,e=>this.visitBinarySelectQuery(e)),this.handlers.set(le.kind,e=>this.visitValuesQuery(e)),this.handlers.set(ee.kind,e=>this.visitWithClause(e)),this.handlers.set(Z.kind,e=>this.visitCommonTable(e)),this.handlers.set(j.kind,e=>this.visitSelectItem(e)),this.handlers.set(E.kind,e=>this.visitIdentifierString(e)),this.handlers.set(Q.kind,e=>this.visitRawString(e)),this.handlers.set(x.kind,e=>this.visitColumnReference(e)),this.handlers.set(b.kind,e=>this.visitParameterExpression(e)),this.handlers.set(z.kind,e=>this.visitLiteralValue(e)),this.handlers.set(B.kind,e=>this.visitSourceExpression(e)),this.handlers.set(R.kind,e=>this.visitTableSource(e)),this.handlers.set(De.kind,e=>this.visitFunctionSource(e)),this.handlers.set(Me.kind,e=>this.visitParenSource(e)),this.handlers.set(_.kind,e=>this.visitSubQuerySource(e)),this.handlers.set(Le.kind,e=>this.visitInlineQuery(e)),this.handlers.set($.kind,e=>this.visitFromClause(e)),this.handlers.set(fe.kind,e=>this.visitJoinClause(e)),this.handlers.set(he.kind,e=>this.visitJoinOnClause(e)),this.handlers.set(ke.kind,e=>this.visitJoinUsingClause(e)),this.handlers.set(se.kind,e=>this.visitWhereClause(e)),this.handlers.set(Y.kind,e=>this.visitParenExpression(e)),this.handlers.set(C.kind,e=>this.visitBinaryExpression(e)),this.handlers.set(ie.kind,e=>this.visitUnaryExpression(e)),this.handlers.set(ue.kind,e=>this.visitCaseExpression(e)),this.handlers.set(ve.kind,e=>this.visitCaseKeyValuePair(e)),this.handlers.set(ye.kind,e=>this.visitSwitchCaseArgument(e)),this.handlers.set(xe.kind,e=>this.visitBetweenExpression(e)),this.handlers.set(U.kind,e=>this.visitFunctionCall(e)),this.handlers.set(Se.kind,e=>this.visitArrayExpression(e)),this.handlers.set(ge.kind,e=>this.visitArrayQueryExpression(e)),this.handlers.set(Ee.kind,e=>this.visitTupleExpression(e)),this.handlers.set(ce.kind,e=>this.visitCastExpression(e)),this.handlers.set(Qe.kind,e=>this.visitWindowFrameExpr