@hdnax/sqlingo.js 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/COPYRIGHT_NOTICE +31 -0
- package/LICENSE +21 -0
- package/README.md +79 -0
- package/dist/index.cjs +46 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +14429 -0
- package/dist/index.d.ts +14429 -0
- package/dist/index.js +46 -0
- package/dist/index.js.map +1 -0
- package/package.json +70 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var IH=Object.create;var Sw=Object.defineProperty;var yH=Object.getOwnPropertyDescriptor;var j_=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),iO=n=>{throw TypeError(n)};var CH=(n,e,t)=>e in n?Sw(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var H_=(n,e)=>Sw(n,"name",{value:e,configurable:!0});var bH=(n,e)=>{for(var t in e)Sw(n,t,{get:e[t],enumerable:!0})};var re=n=>[,,,IH(_nullishCoalesce(_optionalChain([n, 'optionalAccess', _2 => _2[j_("metadata")]]), () => (null)))],J_=["class","method","getter","setter","accessor","field","value","get","set"],nO=n=>n!==void 0&&typeof n!="function"?iO("Function expected"):n,PH=(n,e,t,s,r)=>({kind:J_[n],name:e,metadata:s,addInitializer:i=>t._?iO("Already initialized"):r.push(nO(i||null))}),te=(n,e)=>CH(e,j_("metadata"),n[3]),se=(n,e,t,s)=>{for(var r=0,i=n[e>>1],a=i&&i.length;r<a;r++)e&1?i[r].call(t):s=i[r].call(t,s);return s},T=(n,e,t,s,r,i)=>{var a,o,c,p,u,E=e&7,g=!!(e&8),A=!!(e&16),x=E>3?n.length+1:E?g?1:2:0,m=J_[E+5],N=E>3&&(n[x-1]=[]),R=n[x]||(n[x]=[]),S=E&&(!A&&!g&&(r=r.prototype),E<5&&(E>3||!A)&&yH(E<4?r:{get[t](){return V_(this,i)},set[t](y){return W_(this,i,y)}},t));E?A&&E<4&&H_(i,(E>2?"set ":E>1?"get ":"")+t):H_(r,t);for(var I=s.length-1;I>=0;I--)p=PH(E,t,c={},n[3],R),E&&(p.static=g,p.private=A,u=p.access={has:A?y=>wH(r,y):y=>t in y},E^3&&(u.get=A?y=>(E^1?V_:MH)(y,r,E^4?i:S.get):y=>y[t]),E>2&&(u.set=A?(y,P)=>W_(y,r,P,E^4?i:S.set):(y,P)=>y[t]=P)),o=(0,s[I])(E?E<4?A?i:S[m]:E>4?void 0:{get:S.get,set:S.set}:r,p),c._=1,E^4||o===void 0?nO(o)&&(E>4?N.unshift(o):E?A?i=o:S[m]=o:r=o):typeof o!="object"||o===null?iO("Object expected"):(nO(a=o.get)&&(S.get=a),nO(a=o.set)&&(S.set=a),nO(a=o.init)&&N.unshift(a));return E||te(n,r),S&&Sw(r,t,S),A?E^4?i:S:r};var jM=(n,e,t)=>e.has(n)||iO("Cannot "+t),wH=(n,e)=>Object(e)!==e?iO('Cannot use the "in" operator on this value'):n.has(e),V_=(n,e,t)=>(jM(n,e,"read from private field"),t?t.call(n):e.get(n));var W_=(n,e,t,s)=>(jM(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),MH=(n,e,t)=>(jM(n,e,"access private method"),t);var X_={$schema:"https://json.schemastore.org/package.json",name:"@hdnax/sqlingo.js",sqlglot:{commit:"264e95f04d95f2cd7bcf255ee7ae160db36882a7",version:"28.10.0",url:"https://github.com/tobymao/sqlglot"},version:"0.0.1",type:"module",description:"A JavaScript port of SQLGlot - SQL parser, transpiler, optimizer, and engine",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"}},scripts:{test:"vitest","test:ui":"vitest --ui","test:coverage":"vitest --coverage",build:"tsup",dev:"tsup --watch",typecheck:"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix",docs:"typedoc","docs:watch":"typedoc --watch","docs:serve":"typedoc && npx http-server docs -o",changeset:"changeset",version:"changeset version",release:"pnpm build && changeset publish && git push --follow-tags"},keywords:["sql","parser","transpiler","optimizer","sqlingo","sql-parser","sql-transpiler"],author:"Huy DNA",license:"MIT",packageManager:"pnpm@10.26.1",files:["dist","LICENSE","README.md","COPYRIGHT_NOTICE"],devDependencies:{"@changesets/cli":"^2.29.8","@hdnax/nuclint":"^0.9.1","@types/luxon":"^3.7.1","@types/node":"^25.2.1",eslint:"^9.39.2",tsup:"^8.5.1",typedoc:"^0.28.16","typedoc-github-theme":"^0.4.0",typescript:"^5.9.3",vitest:"^4.0.18"},peerDependencies:{luxon:"^3.7.2"}};var DH="\x1B[4m",_H="\x1B[0m";var aO=(r=>(r[r.IGNORE=0]="IGNORE",r[r.WARN=1]="WARN",r[r.RAISE=2]="RAISE",r[r.IMMEDIATE=3]="IMMEDIATE",r))(aO||{}),Bn= exports.SqlglotError =class extends Error{constructor(e){super(e),this.name="SqlglotError",Error.captureStackTrace(this,this.constructor)}},uo= exports.UnsupportedError =class extends Bn{constructor(e){super(e),this.name="UnsupportedError",Error.captureStackTrace(this,this.constructor)}},ns= exports.ParseError =class n extends Bn{constructor(e,t){super(e),this.name="ParseError",this.errors=t||[],Error.captureStackTrace(this,this.constructor)}static new(e,t,s,r,i,a,o,c){return new n(e,[{description:t,line:s,col:r,startContext:i,highlight:a,endContext:o,intoExpression:c}])}},cg= exports.TokenError =class extends Bn{constructor(e){super(e),this.name="TokenError",Error.captureStackTrace(this,this.constructor)}},is=class extends Bn{constructor(e){super(e),this.name="OptimizeError",Error.captureStackTrace(this,this.constructor)}},cn=class extends Bn{constructor(e){super(e),this.name="SchemaError",Error.captureStackTrace(this,this.constructor)}},DT=class extends Bn{constructor(e){super(e),this.name="ExecuteError",Error.captureStackTrace(this,this.constructor)}};function oO(n){let{sql:e,positions:t,contextLength:s=100}=n;if(t.length===0)throw new Error("positions must contain at least one [start, end] tuple");let r="",i="",a=0,o=[],c=0,p=[...t].sort((g,A)=>g[0]-A[0]);0<p[0][0]&&(a=p[0][0],r=e.slice(Math.max(0,a-s),a),o.push(r),c=a);for(let[g,A]of p){let x=Math.max(g,c),m=A+1;m<=x||(c<x&&o.push(e.slice(c,x)),o.push(`${DH}${e.slice(x,m)}${_H}`),c=m)}c<e.length&&(i=e.slice(c,c+s),o.push(i));let u=o.join(""),E=e.slice(a,c);return{formattedSql:u,startContext:r,highlight:E,endContext:i}}function mw(n,e){let t=n.slice(0,e).map(r=>String(r)),s=n.length-e;return 0<s&&t.push(`... and ${s} more`),t.join(`
|
|
2
|
+
|
|
3
|
+
`)}function JM(n){return n.flatMap(e=>e.errors)}var XM=new WeakMap;function kH(n){let e=[],t=n;for(;t&&t!==Object&&t.prototype;)e.push(t),t=Object.getPrototypeOf(t);return e}function Q(n,...e){class t extends n{}let s=[n,...e],r=[],i=new Set;for(let a of s){let o=kH(a);for(let c of o)i.has(c)||(i.add(c),r.push(c))}for(let a of r){for(let c of Object.getOwnPropertyNames(a.prototype))if(c!=="constructor"&&!Object.getOwnPropertyDescriptor(t.prototype,c)){let p=Object.getOwnPropertyDescriptor(a.prototype,c);p&&Object.defineProperty(t.prototype,c,p)}for(let c of Object.getOwnPropertyNames(a))if(!["prototype","length","name"].includes(c)&&!Object.getOwnPropertyDescriptor(t,c)){let p=Object.getOwnPropertyDescriptor(a,c);p&&Object.defineProperty(t,c,p)}let o=XM.get(a);o||(o=new Set,XM.set(a,o),Object.defineProperty(a,Symbol.hasInstance,{value(c){if(this.prototype.isPrototypeOf(Object(c)))return!0;let p=XM.get(this);if(!p)return!1;let u=_optionalChain([c, 'optionalAccess', _3 => _3.constructor]);for(;u&&u!==Object;){if(p.has(u))return!0;u=Object.getPrototypeOf(u)}return!1},configurable:!0})),o.add(t)}return t}var Rl=class{constructor(){this._map=new Map}get(e,t){return _optionalChain([this, 'access', _4 => _4._map, 'access', _5 => _5.get, 'call', _6 => _6(e), 'optionalAccess', _7 => _7.get, 'call', _8 => _8(t)])}set(e,t,s){let r=this._map.get(e);return r||(r=new Map,this._map.set(e,r)),r.set(t,s),this}has(e,t){return _nullishCoalesce(_optionalChain([this, 'access', _9 => _9._map, 'access', _10 => _10.get, 'call', _11 => _11(e), 'optionalAccess', _12 => _12.has, 'call', _13 => _13(t)]), () => (!1))}delete(e,t){let s=this._map.get(e);if(!s)return!1;let r=s.delete(t);return s.size===0&&this._map.delete(e),r}clear(){this._map.clear()}get size(){let e=0;for(let t of this._map.values())e+=t.size;return e}*[Symbol.iterator](){for(let[e,t]of this._map)for(let[s,r]of t)yield[[e,s],r]}*keys(){for(let[e,t]of this._map)for(let s of t.keys())yield[e,s]}*values(){for(let e of this._map.values())yield*e.values()}*entries(){yield*this}};function As(n,e){let t=Object.values(n),s=_optionalChain([e, 'optionalAccess', _14 => _14.toLowerCase, 'call', _15 => _15()]);return _nullishCoalesce(t.find(r=>r===s), () => (t.find(r=>r.toLowerCase()===s)))}function Rw(n,e){return typeof e=="string"?typeof n===e||e==="object"&&n===null:n instanceof e}function UH(n){return typeof n=="string"?`typeof === '${n}'`:_nullishCoalesce(n.name, () => (String(n)))}function D(n,...e){return e.some(t=>Rw(n,t))}function ue(n,...e){if(!e.some(t=>Rw(n,t))){let t=e.map(UH).join(" | ");throw new TypeError(`Expected ${t}, got ${typeof n}`)}}function Pt(n,...e){return e.some(t=>Rw(n,t))?n:void 0}function Xe(n,...e){let t=[];for(let s of n)e.some(r=>Rw(s,r))&&t.push(s);return t}function cO(n){return n!=null&&typeof n[Symbol.iterator]=="function"}function O(n,e){let t=new WeakMap;return e.addInitializer(function(){Object.defineProperty(this,e.name,{get(){return t.has(this)||t.set(this,n.call(this)),t.get(this)},set(s){t.set(this,s)},configurable:!0})}),n}var qH=0n,z_=new WeakMap,K_=new Map;function Q_(){return(qH++).toString()}function _T(n){if(n!==null&&typeof n=="object"||typeof n=="function"){let t=n,s=z_.get(t);return s===void 0&&(s=Q_(),z_.set(t,s)),s}let e=K_.get(n);return e===void 0&&(e=Q_(),K_.set(n,e)),e}function Z_(n){return n!==null&&typeof n=="object"&&typeof n.add=="function"}function ek(n){return n!==null&&typeof n=="object"&&typeof n.radd=="function"}function pO(n,e){return Z_(n)?n.add(e):ek(e)?e.radd(n):Array.isArray(n)&&Array.isArray(e)?[...n,...e]:n+e}function tk(n){return n!==null&&typeof n=="object"&&typeof n.sub=="function"}function sk(n){return n!==null&&typeof n=="object"&&typeof n.rsub=="function"}function QM(n,e){return tk(n)?n.sub(e):sk(e)?e.rsub(n):n instanceof Set&&e instanceof Set?new Set([...n].filter(t=>!e.has(t))):n-e}function rk(n){return n!==null&&typeof n=="object"&&typeof n.mul=="function"}function nk(n){return n!==null&&typeof n=="object"&&typeof n.rmul=="function"}function ZM(n,e){return rk(n)?n.mul(e):nk(e)?e.rmul(n):n*e}function ik(n){return n!==null&&typeof n=="object"&&typeof n.truediv=="function"}function ak(n){return n!==null&&typeof n=="object"&&typeof n.rtruediv=="function"}function Ow(n,e){return ik(n)?n.truediv(e):ak(e)?e.rtruediv(n):n/e}function ok(n){return n!==null&&typeof n=="object"&&typeof n.floorDiv=="function"}function ck(n){return n!==null&&typeof n=="object"&&typeof n.rfloorDiv=="function"}function eL(n,e){return ok(n)?n.floorDiv(e):ck(e)?e.rfloorDiv(n):Math.trunc(n/e)}function pk(n){return n!==null&&typeof n=="object"&&typeof n.mod=="function"}function lk(n){return n!==null&&typeof n=="object"&&typeof n.rmod=="function"}function tL(n,e){return pk(n)?n.mod(e):lk(e)?e.rmod(n):n%e}function uk(n){return n!==null&&typeof n=="object"&&typeof n.pow=="function"}function Ek(n){return n!==null&&typeof n=="object"&&typeof n.rpow=="function"}function sL(n,e){return uk(n)?n.pow(e):Ek(e)?e.rpow(n):n**e}function rL(n){return n!==null&&typeof n=="object"&&typeof n.lt=="function"}function Pc(n,e){return rL(n)?n.lt(e):iL(e)?e.gt(n):n<e}function nL(n){return n!==null&&typeof n=="object"&&typeof n.lte=="function"}function lO(n,e){return nL(n)?n.lte(e):oL(e)?e.gte(n):n<=e}function iL(n){return n!==null&&typeof n=="object"&&typeof n.gt=="function"}function aL(n,e){return iL(n)?n.gt(e):rL(e)?e.lt(n):e<n}function oL(n){return n!==null&&typeof n=="object"&&typeof n.gte=="function"}function cL(n,e){return oL(n)?n.gte(e):nL(e)?e.lte(n):e<=n}function zM(n){return n!==null&&typeof n=="object"&&typeof n.eq=="function"}function Nw(n,e){return zM(n)?n.eq(e):zM(e)?e.eq(n):n===e}function KM(n){return n!==null&&typeof n=="object"&&typeof n.neq=="function"}function pL(n,e){return KM(n)?n.neq(e):KM(e)?e.neq(n):!Nw(n,e)}function hk(n){return n!==null&&typeof n=="object"&&typeof n.or=="function"}function gk(n){return n!==null&&typeof n=="object"&&typeof n.ror=="function"}function lL(n,e){return hk(n)?n.or(e):gk(e)?e.ror(n):n instanceof Set&&e instanceof Set?new Set([...n,...e]):n|e}function dk(n){return n!==null&&typeof n=="object"&&typeof n.and=="function"}function Ak(n){return n!==null&&typeof n=="object"&&typeof n.rand=="function"}function uL(n,e){return dk(n)?n.and(e):Ak(e)?e.rand(n):n instanceof Set&&e instanceof Set?new Set([...n].filter(t=>e.has(t))):n&e}function fk(n){return n!==null&&typeof n=="object"&&typeof n.xor=="function"}function xk(n){return n!==null&&typeof n=="object"&&typeof n.rxor=="function"}function EL(n,e){if(fk(n))return n.xor(e);if(xk(e))return e.rxor(n);if(n instanceof Set&&e instanceof Set){let t=n,s=e;return new Set([...[...t].filter(r=>!s.has(r)),...[...s].filter(r=>!t.has(r))])}return n^e}function Tk(n){return n!==null&&typeof n=="object"&&typeof n.lshift=="function"}function Sk(n){return n!==null&&typeof n=="object"&&typeof n.rlshift=="function"}function hL(n,e){return Tk(n)?n.lshift(e):Sk(e)?e.rlshift(n):n<<e}function mk(n){return n!==null&&typeof n=="object"&&typeof n.rshift=="function"}function Rk(n){return n!==null&&typeof n=="object"&&typeof n.rrshift=="function"}function gL(n,e){return mk(n)?n.rshift(e):Rk(e)?e.rrshift(n):n>>e}var YL={};bH(YL,{ALL_FUNCTIONS:()=>fg,AbsExpr:()=>xy,AcosExpr:()=>wp,AcoshExpr:()=>ty,AddConstraintExpr:()=>Gu,AddExpr:()=>lt,AddMonthsExpr:()=>Lb,AddPartitionExpr:()=>$u,AdjacentExpr:()=>mE,AggFuncExpr:()=>q,AiAggExpr:()=>bP,AiClassifyExpr:()=>_y,AiSummarizeAggExpr:()=>PP,AlgorithmPropertyExpr:()=>zi,AliasExpr:()=>Se,AliasesExpr:()=>Rn,AllExpr:()=>qs,AllowedValuesPropertyExpr:()=>ji,AlterColumnExpr:()=>ws,AlterDistStyleExpr:()=>Gc,AlterExpr:()=>mn,AlterExprKind:()=>UT,AlterIndexExpr:()=>Oh,AlterRenameExpr:()=>Vi,AlterSessionExpr:()=>Hc,AlterSetExpr:()=>Ql,AlterSortKeyExpr:()=>$c,AnalyzeColumnsExpr:()=>Lo,AnalyzeDeleteExpr:()=>Fu,AnalyzeDeleteExprKind:()=>Fk,AnalyzeExpr:()=>Vc,AnalyzeExprKind:()=>Uk,AnalyzeHistogramExpr:()=>Uu,AnalyzeListChainedRowsExpr:()=>vu,AnalyzeSampleExpr:()=>qu,AnalyzeSampleExprKind:()=>vk,AnalyzeStatisticsExpr:()=>ku,AnalyzeStatisticsExprKind:()=>qk,AnalyzeValidateExpr:()=>Bu,AnalyzeValidateExprKind:()=>Bk,AnalyzeWithExpr:()=>Mo,AndExpr:()=>Oe,AnonymousAggFuncExpr:()=>Fw,AnonymousExpr:()=>st,AnyExpr:()=>wt,AnyValueExpr:()=>Ic,ApplyExpr:()=>WL,ApproxDistinctExpr:()=>hl,ApproxPercentileAccumulateExpr:()=>$P,ApproxPercentileCombineExpr:()=>RP,ApproxPercentileEstimateExpr:()=>qb,ApproxQuantileExpr:()=>_s,ApproxQuantilesExpr:()=>mP,ApproxTopKAccumulateExpr:()=>xP,ApproxTopKCombineExpr:()=>TP,ApproxTopKEstimateExpr:()=>Ty,ApproxTopKExpr:()=>uT,ApproxTopSumExpr:()=>SP,ApproximateSimilarityExpr:()=>IP,ArgMaxExpr:()=>Wr,ArgMinExpr:()=>jr,ArrayAggExpr:()=>nr,ArrayAllExpr:()=>zL,ArrayAnyExpr:()=>ky,ArrayAppendExpr:()=>Ng,ArrayCompactExpr:()=>Uy,ArrayConcatAggExpr:()=>wP,ArrayConcatExpr:()=>Pn,ArrayConstructCompactExpr:()=>qy,ArrayContainsAllExpr:()=>ql,ArrayContainsExpr:()=>PR,ArrayExpr:()=>Ne,ArrayFilterExpr:()=>wR,ArrayFirstExpr:()=>vy,ArrayInsertExpr:()=>KL,ArrayIntersectExpr:()=>ZL,ArrayLastExpr:()=>Fy,ArrayOverlapsExpr:()=>Yy,ArrayPrependExpr:()=>Ig,ArrayRemoveAtExpr:()=>QL,ArrayRemoveExpr:()=>RE,ArrayReverseExpr:()=>By,ArraySizeExpr:()=>lr,ArraySliceExpr:()=>Uh,ArraySortExpr:()=>Hy,ArraySumExpr:()=>Vy,ArrayToStringExpr:()=>qp,ArrayUnionAggExpr:()=>MP,ArrayUniqueAggExpr:()=>vn,ArraysZipExpr:()=>Wy,AsciiExpr:()=>Oy,AsinExpr:()=>Mp,AsinhExpr:()=>sy,AtIndexExpr:()=>Hu,AtTimeZoneExpr:()=>Or,Atan2Expr:()=>Cr,AtanExpr:()=>Lp,AtanhExpr:()=>ry,AttachExpr:()=>iS,AttachOptionExpr:()=>mS,AutoIncrementColumnConstraintExpr:()=>zT,AutoIncrementPropertyExpr:()=>Ki,AutoRefreshPropertyExpr:()=>Qi,AvgExpr:()=>hT,BackupPropertyExpr:()=>Zi,Base64DecodeBinaryExpr:()=>HC,Base64DecodeStringExpr:()=>VC,Base64EncodeExpr:()=>WC,BetweenExpr:()=>Fs,BinaryExpr:()=>Y,BitLengthExpr:()=>eT,BitStringExpr:()=>XT,BitmapBitPositionExpr:()=>hy,BitmapBucketNumberExpr:()=>Ey,BitmapConstructAggExpr:()=>AP,BitmapCountExpr:()=>kx,BitmapOrAggExpr:()=>fP,BitwiseAndAggExpr:()=>Rc,BitwiseAndExpr:()=>Cn,BitwiseCountExpr:()=>kh,BitwiseLeftShiftExpr:()=>tp,BitwiseNotExpr:()=>bn,BitwiseOrAggExpr:()=>Oc,BitwiseOrExpr:()=>ui,BitwiseRightShiftExpr:()=>nc,BitwiseXorAggExpr:()=>Nc,BitwiseXorExpr:()=>Ei,BlockCompressionPropertyExpr:()=>Go,BoolandExpr:()=>dy,BooleanExpr:()=>Et,BoolnotExpr:()=>gy,BoolorExpr:()=>Ay,BoolxorAggExpr:()=>dP,BracketExpr:()=>fs,BuildPropertyExpr:()=>PS,ByteLengthExpr:()=>Ux,ByteStringExpr:()=>Qc,COLUMN_PARTS:()=>_v,CONSTANTS:()=>TO,CacheExpr:()=>Fl,CaseExpr:()=>Ht,CaseSpecificColumnConstraintExpr:()=>Gi,CastExpr:()=>Z,CastToStrTypeExpr:()=>OO,CbrtExpr:()=>rp,CeilExpr:()=>Ir,ChangesExpr:()=>su,CharacterSetColumnConstraintExpr:()=>rE,CharacterSetExpr:()=>Bc,CharacterSetPropertyExpr:()=>ri,CheckColumnConstraintExpr:()=>Tg,CheckExpr:()=>ES,CheckJsonExpr:()=>zy,CheckXmlExpr:()=>Ky,ChecksumPropertyExpr:()=>$o,ChrExpr:()=>sp,CloneExpr:()=>Yl,ClusterExpr:()=>qi,ClusteredByPropertyExpr:()=>da,ClusteredColumnConstraintExpr:()=>Uo,CoalesceExpr:()=>St,CodePointsToBytesExpr:()=>My,CodePointsToStringExpr:()=>Dy,CollateColumnConstraintExpr:()=>nE,CollateExpr:()=>vl,CollatePropertyExpr:()=>ea,CollationExpr:()=>vx,ColumnConstraintExpr:()=>ki,ColumnConstraintExprKind:()=>wk,ColumnConstraintKindExpr:()=>qe,ColumnDefExpr:()=>we,ColumnDefExprKind:()=>bk,ColumnExpr:()=>k,ColumnPositionExpr:()=>Kl,ColumnPrefixExpr:()=>Nh,ColumnsExpr:()=>RO,CombinedAggFuncExpr:()=>DD,CombinedParameterizedAggExpr:()=>_D,CommandExpr:()=>jn,CommentColumnConstraintExpr:()=>iE,CommentExpr:()=>Zl,CommentExprKind:()=>Pk,CommitExpr:()=>Du,ComprehensionExpr:()=>eu,CompressColumnConstraintExpr:()=>kl,CompressExpr:()=>eb,ComputedColumnConstraintExpr:()=>An,ConcatExpr:()=>Vt,ConcatWsExpr:()=>xs,ConditionExpr:()=>Qe,ConditionalInsertExpr:()=>uu,ConnectByRootExpr:()=>yg,ConnectExpr:()=>ru,ConnectorExpr:()=>We,ConstraintExpr:()=>tu,ContainsExpr:()=>Qy,ConvertExpr:()=>JL,ConvertTimezoneExpr:()=>Qn,ConvertToCharsetExpr:()=>Ly,CopyExpr:()=>AE,CopyExprKind:()=>Vk,CopyGrantsPropertyExpr:()=>ta,CopyParameterExpr:()=>nu,CorrExpr:()=>pT,CosExpr:()=>_p,CoshExpr:()=>py,CosineDistanceExpr:()=>Lx,CotExpr:()=>Dp,CothExpr:()=>ny,CountExpr:()=>uc,CountIfExpr:()=>UP,CovarPopExpr:()=>mT,CovarSampExpr:()=>ST,CreateExpr:()=>us,CreateExprKind:()=>Ol,CredentialsExpr:()=>iu,CredentialsPropertyExpr:()=>Op,CscExpr:()=>iy,CschExpr:()=>ay,CteExpr:()=>Yt,CubeExpr:()=>xu,CumeDistExpr:()=>iw,CurrentAccountExpr:()=>Zy,CurrentAccountNameExpr:()=>eC,CurrentAvailableRolesExpr:()=>tC,CurrentCatalogExpr:()=>vp,CurrentClientExpr:()=>sC,CurrentDatabaseExpr:()=>Fx,CurrentDateExpr:()=>xn,CurrentDatetimeExpr:()=>lC,CurrentIpAddressExpr:()=>rC,CurrentOrganizationNameExpr:()=>EC,CurrentOrganizationUserExpr:()=>dC,CurrentRegionExpr:()=>hC,CurrentRoleExpr:()=>Cg,CurrentRoleTypeExpr:()=>gC,CurrentSchemaExpr:()=>qh,CurrentSchemasExpr:()=>nC,CurrentSecondaryRolesExpr:()=>iC,CurrentSessionExpr:()=>aC,CurrentStatementExpr:()=>oC,CurrentTimeExpr:()=>Ba,CurrentTimestampExpr:()=>ir,CurrentTimestampLtzExpr:()=>uC,CurrentTimezoneExpr:()=>Bx,CurrentTransactionExpr:()=>cC,CurrentUserExpr:()=>ap,CurrentVersionExpr:()=>Dn,CurrentWarehouseExpr:()=>pC,DPipeExpr:()=>Ar,DataBlocksizePropertyExpr:()=>Yo,DataDeletionPropertyExpr:()=>Ho,DataTypeExpr:()=>C,DataTypeExprKind:()=>Be,DataTypeParamExpr:()=>Jr,DateAddExpr:()=>ut,DateBinExpr:()=>nD,DateDiffExpr:()=>ks,DateExpr:()=>Hp,DateFormatColumnConstraintExpr:()=>aE,DateFromPartsExpr:()=>kC,DateFromUnixDateExpr:()=>Yx,DateStrToDateExpr:()=>Wa,DateSubExpr:()=>Wt,DateToDateStrExpr:()=>UC,DateToDiExpr:()=>Yp,DateTruncExpr:()=>Bs,DatetimeAddExpr:()=>Uc,DatetimeDiffExpr:()=>xC,DatetimeExpr:()=>fC,DatetimeSubExpr:()=>qc,DatetimeTruncExpr:()=>TC,DayExpr:()=>Zr,DayOfMonthExpr:()=>Kr,DayOfWeekExpr:()=>ur,DayOfWeekIsoExpr:()=>Bp,DayOfYearExpr:()=>Qr,DaynameExpr:()=>SC,DdlExpr:()=>ln,DeclareExpr:()=>jl,DeclareItemExpr:()=>Jl,DeclareItemExprKind:()=>yk,DecodeCaseExpr:()=>bg,DecodeExpr:()=>OE,DecompressBinaryExpr:()=>tb,DecompressStringExpr:()=>sb,DecryptExpr:()=>qC,DecryptRawExpr:()=>vC,DefaultColumnConstraintExpr:()=>oE,DefinerPropertyExpr:()=>sa,DegreesExpr:()=>Mx,DeleteExpr:()=>Jn,DenseRankExpr:()=>qP,DerivedTableExpr:()=>bi,DescribeExpr:()=>ei,DescribeExprKind:()=>Nk,DetachExpr:()=>aS,DiToDateExpr:()=>Vp,DictPropertyExpr:()=>zo,DictPropertyExprKind:()=>jk,DictRangeExpr:()=>Ko,DictSubPropertyExpr:()=>QT,DirectoryExpr:()=>So,DirectoryStageExpr:()=>hS,DistKeyPropertyExpr:()=>ra,DistStylePropertyExpr:()=>ia,DistanceExpr:()=>tS,DistinctExpr:()=>ct,DistributeExpr:()=>KT,DistributedByPropertyExpr:()=>na,DistributedByPropertyExprKind:()=>Wk,DivExpr:()=>jt,DmlExpr:()=>Lr,DotExpr:()=>me,DotProductExpr:()=>ly,DropExpr:()=>Tn,DropExprKind:()=>uO,DropPartitionExpr:()=>Yu,DuplicateKeyPropertyExpr:()=>Vo,DynamicPropertyExpr:()=>Aa,EltExpr:()=>wC,EmptyPropertyExpr:()=>fa,EncodeColumnConstraintExpr:()=>cE,EncodeExpr:()=>Wp,EncodePropertyExpr:()=>Cp,EncryptExpr:()=>FC,EncryptRawExpr:()=>BC,EndsWithExpr:()=>Kb,EnginePropertyExpr:()=>aa,EnviromentPropertyExpr:()=>ga,EphemeralColumnConstraintExpr:()=>Zc,EqExpr:()=>Ee,EqualNullExpr:()=>GC,EscapeExpr:()=>TE,EuclideanDistanceExpr:()=>Dx,ExceptExpr:()=>Yr,ExcludeColumnConstraintExpr:()=>pE,ExecuteAsPropertyExpr:()=>fn,ExistsExpr:()=>js,ExpExpr:()=>jp,ExplodeExpr:()=>qt,ExplodeOuterExpr:()=>Cx,ExplodingGenerateSeriesExpr:()=>wD,ExportExpr:()=>uS,Expression:()=>h,ExpressionKey:()=>kT,ExtendsLeftExpr:()=>fE,ExtendsRightExpr:()=>xE,ExternalPropertyExpr:()=>Nn,ExtractExpr:()=>Zn,FUNCTION_BY_NAME:()=>Ag,FactorialExpr:()=>Jp,FallbackPropertyExpr:()=>Wo,FarmFingerprintExpr:()=>Sy,FeaturesAtTimeExpr:()=>AD,FetchExpr:()=>Sn,FileFormatPropertyExpr:()=>$s,FilterExpr:()=>ti,FinalExpr:()=>wl,FirstExpr:()=>gT,FirstValueExpr:()=>AT,FlattenExpr:()=>VL,Float64Expr:()=>my,FloorExpr:()=>wn,ForInExpr:()=>NS,ForcePropertyExpr:()=>Pp,ForeignKeyExpr:()=>ou,FormatExpr:()=>Zx,FormatJsonExpr:()=>ju,FormatPhraseExpr:()=>OS,FreespacePropertyExpr:()=>jo,FromBase32Expr:()=>$C,FromBase64Expr:()=>Bh,FromBaseExpr:()=>CD,FromExpr:()=>Ge,FromIso8601TimestampExpr:()=>iD,FromTimeZoneExpr:()=>bh,FuncExpr:()=>d,GapFillExpr:()=>NO,GenerateDateArrayExpr:()=>Mn,GenerateEmbeddingExpr:()=>fD,GenerateSeriesExpr:()=>Os,GenerateTimestampArrayExpr:()=>jx,GeneratedAsIdentityColumnConstraintExpr:()=>Ui,GeneratedAsRowColumnConstraintExpr:()=>lE,GeneratorExpr:()=>XL,GetExpr:()=>Ch,GetExtractExpr:()=>aD,GetbitExpr:()=>KC,GlobExpr:()=>Jc,GlobalPropertyExpr:()=>pa,GrantExpr:()=>Au,GrantExprKind:()=>Lk,GrantPrincipalExpr:()=>Nu,GrantPrincipalExprKind:()=>Dk,GrantPrivilegeExpr:()=>Ou,GreatestExpr:()=>op,GroupConcatExpr:()=>tr,GroupExpr:()=>Ys,GroupingExpr:()=>ET,GroupingIdExpr:()=>yP,GroupingSetsExpr:()=>Tu,GtExpr:()=>It,GteExpr:()=>xt,HashAggExpr:()=>CP,HavingExpr:()=>$t,HavingMaxExpr:()=>On,HeapPropertyExpr:()=>oa,HeredocExpr:()=>Fc,HexDecodeStringExpr:()=>QC,HexEncodeExpr:()=>ZC,HexExpr:()=>ac,HexStringExpr:()=>Xi,HintExpr:()=>Dr,HistoricalDataExpr:()=>Cu,HistoricalDataExprKind:()=>_k,HllExpr:()=>PD,HostExpr:()=>_b,HourExpr:()=>Jx,ILikeExpr:()=>ms,INTERVAL_DAY_TIME_RE:()=>FL,INTERVAL_STRING_RE:()=>vL,IcebergPropertyExpr:()=>la,IdentifierExpr:()=>G,IfExpr:()=>He,IgnoreNullsExpr:()=>dn,InExpr:()=>it,InOutColumnConstraintExpr:()=>dE,IncludePropertyExpr:()=>bp,IndexColumnConstraintExpr:()=>Lh,IndexColumnConstraintExprKind:()=>Hk,IndexConstraintOptionExpr:()=>yr,IndexExpr:()=>pu,IndexParametersExpr:()=>lu,IndexTableHintExpr:()=>yu,InheritsPropertyExpr:()=>ua,InitcapExpr:()=>cp,InlineExpr:()=>Vx,InlineLengthColumnConstraintExpr:()=>uE,InputModelPropertyExpr:()=>Ea,InputOutputFormatExpr:()=>Co,InsertExpr:()=>Ss,InstallExpr:()=>oS,Int64Expr:()=>Qx,IntDivExpr:()=>Hi,IntersectExpr:()=>yn,IntervalExpr:()=>ze,IntervalOpExpr:()=>gn,IntervalSpanExpr:()=>Kn,IntoExpr:()=>Ro,IntroducerExpr:()=>gu,IsArrayExpr:()=>cD,IsAsciiExpr:()=>oD,IsExpr:()=>Ut,IsInfExpr:()=>rb,IsNanExpr:()=>Kx,IsNullValueExpr:()=>nb,IsolatedLoadingPropertyExpr:()=>Jo,JSON_PATH_PARTS:()=>LV,JarowinklerSimilarityExpr:()=>_x,JoinExpr:()=>z,JoinExprKind:()=>Kt,JoinHintExpr:()=>yi,JournalPropertyExpr:()=>Xo,JsonArrayAggExpr:()=>LD,JsonArrayAppendExpr:()=>hb,JsonArrayContainsExpr:()=>mp,JsonArrayExpr:()=>ab,JsonArrayInsertExpr:()=>gb,JsonBoolExpr:()=>fy,JsonCastExpr:()=>rS,JsonColumnDefExpr:()=>Xu,JsonColumnDefExprKind:()=>Gk,JsonExistsExpr:()=>pD,JsonExpr:()=>Wu,JsonExtractArrayExpr:()=>Eb,JsonExtractExpr:()=>Zt,JsonExtractQuoteExpr:()=>wh,JsonExtractScalarExpr:()=>Rr,JsonFormatExpr:()=>Sc,JsonKeyValueExpr:()=>Ju,JsonKeysAtDepthExpr:()=>ib,JsonKeysExpr:()=>IO,JsonObjectAggExpr:()=>_O,JsonObjectExpr:()=>pp,JsonPathExpr:()=>Ya,JsonPathFilterExpr:()=>Xr,JsonPathKeyExpr:()=>Gt,JsonPathPartExpr:()=>Rs,JsonPathRecursiveExpr:()=>Ai,JsonPathRootExpr:()=>Ls,JsonPathScriptExpr:()=>zr,JsonPathSelectorExpr:()=>di,JsonPathSliceExpr:()=>fi,JsonPathSubscriptExpr:()=>Ds,JsonPathUnionExpr:()=>Ln,JsonPathWildcardExpr:()=>hs,JsonRemoveExpr:()=>lb,JsonSchemaExpr:()=>zu,JsonSetExpr:()=>ob,JsonStripNullsExpr:()=>cb,JsonTableExpr:()=>yO,JsonTypeExpr:()=>ub,JsonValueArrayExpr:()=>pb,JsonValueExpr:()=>Ku,JsonbContainsAllTopKeysExpr:()=>cc,JsonbContainsAnyTopKeysExpr:()=>oc,JsonbContainsExpr:()=>lp,JsonbDeleteAtPathExpr:()=>pc,JsonbExistsExpr:()=>uD,JsonbExtractExpr:()=>sS,JsonbExtractScalarExpr:()=>bO,JsonbObjectAggExpr:()=>MD,JustifyDaysExpr:()=>jy,JustifyHoursExpr:()=>Jy,JustifyIntervalExpr:()=>Xy,KillExpr:()=>Vl,KillExprKind:()=>Ik,KurtosisExpr:()=>TT,KwargExpr:()=>Og,LagExpr:()=>LP,LambdaExpr:()=>vs,LanguagePropertyExpr:()=>ni,LastDayExpr:()=>vh,LastExpr:()=>dT,LastValueExpr:()=>fT,LateralExpr:()=>kt,LaxBoolExpr:()=>yC,LaxFloat64Expr:()=>CC,LaxInt64Expr:()=>bC,LaxStringExpr:()=>PC,LeadExpr:()=>DP,LeastExpr:()=>Pg,LeftExpr:()=>Ja,LengthExpr:()=>Er,LevenshteinExpr:()=>Si,LikeExpr:()=>Ws,LikePropertyExpr:()=>Qo,LimitExpr:()=>Ct,LimitOptionsExpr:()=>Su,ListExpr:()=>mO,LiteralExpr:()=>w,LnExpr:()=>Ga,LoadDataExpr:()=>du,LocaltimeExpr:()=>np,LocaltimestampExpr:()=>ip,LocationExpr:()=>xS,LocationPropertyExpr:()=>Es,LockExpr:()=>Kc,LockPropertyExpr:()=>Ha,LockingPropertyExpr:()=>Zo,LockingPropertyExprKind:()=>Jk,LockingStatementExpr:()=>nS,LogExpr:()=>Vr,LogPropertyExpr:()=>xa,LogicalAndExpr:()=>Al,LogicalOrExpr:()=>dl,LowerExpr:()=>hi,LowerHexExpr:()=>Ec,LtExpr:()=>Tt,LteExpr:()=>yt,MakeIntervalExpr:()=>NC,ManhattanDistanceExpr:()=>uy,MapCatExpr:()=>Rb,MapContainsKeyExpr:()=>Ob,MapDeleteExpr:()=>Nb,MapExpr:()=>Eo,MapFromEntriesExpr:()=>ED,MapInsertExpr:()=>Ib,MapKeysExpr:()=>yb,MapPickExpr:()=>Cb,MapSizeExpr:()=>bb,MaskingPolicyColumnConstraintExpr:()=>UO,MatchAgainstExpr:()=>PO,MatchExpr:()=>LS,MatchRecognizeExpr:()=>Io,MatchRecognizeMeasureExpr:()=>mu,MaterializedPropertyExpr:()=>Ta,MaxExpr:()=>rn,Md5DigestExpr:()=>en,Md5Expr:()=>Pb,Md5NumberLower64Expr:()=>wb,Md5NumberUpper64Expr:()=>Mb,MedianExpr:()=>vP,MergeBlockRatioPropertyExpr:()=>Yi,MergeExpr:()=>va,MergeTreeTtlActionExpr:()=>_i,MergeTreeTtlExpr:()=>vi,MinExpr:()=>fl,MinhashCombineExpr:()=>NP,MinhashExpr:()=>OP,MinuteExpr:()=>Xx,MlForecastExpr:()=>xD,MlTranslateExpr:()=>dD,ModExpr:()=>Hr,ModeExpr:()=>FP,ModelAttributeExpr:()=>yS,MonthExpr:()=>Js,MonthnameExpr:()=>sT,MonthsBetweenExpr:()=>Gp,MulExpr:()=>Ts,MultitableInsertsExpr:()=>Oo,MultitableInsertsExprKind:()=>Mk,NONNULL_CONSTANTS:()=>DL,NationalExpr:()=>No,NegExpr:()=>Ps,NeqExpr:()=>vt,NetFuncExpr:()=>rT,NextDayExpr:()=>EP,NextValueForExpr:()=>DO,NoPrimaryIndexPropertyExpr:()=>Sa,NonClusteredColumnConstraintExpr:()=>qo,NormalExpr:()=>Db,NormalizeExpr:()=>wg,NotExpr:()=>rt,NotForReplicationColumnConstraintExpr:()=>si,NotNullColumnConstraintExpr:()=>$i,NthValueExpr:()=>_P,NtileExpr:()=>BP,NullExpr:()=>Qt,NullSafeEqExpr:()=>fr,NullSafeNeqExpr:()=>kr,NullifExpr:()=>zx,NumberToStrExpr:()=>jh,Nvl2Expr:()=>hD,ObjectAggExpr:()=>kP,ObjectIdentifierExpr:()=>Rg,ObjectInsertExpr:()=>lD,OffsetExpr:()=>Fr,OnClusterExpr:()=>wS,OnCommitPropertyExpr:()=>Xn,OnConditionExpr:()=>hu,OnConflictExpr:()=>Eu,OnPropertyExpr:()=>Br,OnUpdateColumnConstraintExpr:()=>EE,OpclassExpr:()=>cu,OpenJsonColumnDefExpr:()=>Qu,OpenJsonColumnDefExprKind:()=>$k,OpenJsonExpr:()=>CO,OperatorExpr:()=>ic,OrExpr:()=>pt,OrderExpr:()=>ke,OrderedExpr:()=>es,OutputModelPropertyExpr:()=>ha,OverflowTruncateBehaviorExpr:()=>Vu,OverlapsExpr:()=>eS,OverlayExpr:()=>Mg,PERCENTILES:()=>BD,POSITION_META_KEYS:()=>kv,PadExpr:()=>Fa,ParameterExpr:()=>ep,ParameterizedAggExpr:()=>vw,ParenExpr:()=>Ye,ParseBignumericExpr:()=>db,ParseDatetimeExpr:()=>Sb,ParseIpExpr:()=>xb,ParseJsonExpr:()=>up,ParseNumericExpr:()=>Ab,ParseTimeExpr:()=>Tb,ParseUrlExpr:()=>fb,PartitionBoundSpecExpr:()=>yo,PartitionByListPropertyExpr:()=>fc,PartitionByRangePropertyDynamicExpr:()=>dS,PartitionByRangePropertyExpr:()=>Ac,PartitionByTruncateExpr:()=>ai,PartitionExpr:()=>Wi,PartitionIdExpr:()=>gS,PartitionListExpr:()=>yh,PartitionRangeExpr:()=>Ih,PartitionedByBucketExpr:()=>ii,PartitionedByPropertyExpr:()=>Bt,PartitionedOfPropertyExpr:()=>ec,PathColumnConstraintExpr:()=>gE,PercentRankExpr:()=>GP,PercentileContExpr:()=>yc,PercentileDiscExpr:()=>Xh,PeriodForSystemTimeConstraintExpr:()=>sE,PiExpr:()=>Ub,PivotAliasExpr:()=>ZT,PivotAnyExpr:()=>Fi,PivotExpr:()=>ls,PlaceholderExpr:()=>rr,PlaceholderExprKind:()=>Qk,PosexplodeExpr:()=>gl,PosexplodeOuterExpr:()=>DS,PositionalColumnExpr:()=>Ph,PowExpr:()=>zp,PragmaExpr:()=>Wl,PreWhereExpr:()=>Mu,PredicateExpr:()=>Ve,PredictExpr:()=>gD,PreviousDayExpr:()=>IC,PrimaryKeyColumnConstraintExpr:()=>vo,PrimaryKeyExpr:()=>mo,PriorExpr:()=>au,ProjectionDefExpr:()=>pS,ProjectionPolicyColumnConstraintExpr:()=>CR,PropertiesExpr:()=>mt,PropertiesLocation:()=>Nl,PropertyEqExpr:()=>At,PropertyExpr:()=>U,PseudoTypeExpr:()=>mg,PseudocolumnExpr:()=>Ml,PutExpr:()=>Rp,QUERY_MODIFIERS:()=>TV,QualifyExpr:()=>un,QuantileExpr:()=>eo,QuarterExpr:()=>Kp,QueryBandExpr:()=>cS,QueryExpr:()=>ce,QueryOptionExpr:()=>TS,QueryTransformExpr:()=>pr,RadiansExpr:()=>Zp,RandExpr:()=>xr,RandnExpr:()=>Eg,RandstrExpr:()=>nT,RangeBucketExpr:()=>vb,RangeNExpr:()=>SD,RankExpr:()=>YP,RawStringExpr:()=>jc,ReadCsvExpr:()=>mD,ReadParquetExpr:()=>RD,RecursiveWithSearchExpr:()=>zl,RecursiveWithSearchExprKind:()=>Ck,ReduceExpr:()=>OD,ReferenceExpr:()=>Iu,RefreshExpr:()=>Gl,RefreshExprKind:()=>Ok,RefreshTriggerPropertyExpr:()=>_h,RefreshTriggerPropertyExprKind:()=>Xk,RegDomainExpr:()=>kb,RegexpCountExpr:()=>Fb,RegexpExtractAllExpr:()=>kn,RegexpExtractExpr:()=>br,RegexpFullMatchExpr:()=>ND,RegexpILikeExpr:()=>wO,RegexpInstrExpr:()=>iT,RegexpLikeExpr:()=>lc,RegexpReplaceExpr:()=>Xa,RegexpSplitExpr:()=>$h,RegrAvgxExpr:()=>jP,RegrAvgyExpr:()=>WP,RegrCountExpr:()=>JP,RegrInterceptExpr:()=>XP,RegrR2Expr:()=>zP,RegrSlopeExpr:()=>ew,RegrSxxExpr:()=>KP,RegrSxyExpr:()=>QP,RegrSyyExpr:()=>ZP,RegrValxExpr:()=>HP,RegrValyExpr:()=>VP,RemoteWithConnectionModelPropertyExpr:()=>Ra,RenameColumnExpr:()=>Xc,RepeatExpr:()=>Qp,ReplaceExpr:()=>za,ReplacePartitionExpr:()=>RS,RespectNullsExpr:()=>Bi,ReturnExpr:()=>bo,ReturningExpr:()=>zc,ReturnsPropertyExpr:()=>oi,ReverseExpr:()=>Xp,RevokeExpr:()=>fu,RightExpr:()=>_n,RollbackExpr:()=>_u,RollupExpr:()=>Yc,RollupIndexExpr:()=>AS,RollupPropertyExpr:()=>Dh,RoundExpr:()=>Ka,RowFormatDelimitedPropertyExpr:()=>tc,RowFormatPropertyExpr:()=>Na,RowFormatSerdePropertyExpr:()=>sc,RowNumberExpr:()=>aT,RtrimmedLengthExpr:()=>mb,SAFE_IDENTIFIER_RE:()=>cw,SQLGLOT_ANONYMOUS:()=>qL,SQLGLOT_META:()=>Dv,SafeAddExpr:()=>Hb,SafeConvertBytesToStringExpr:()=>Jb,SafeDivideExpr:()=>Hh,SafeFuncExpr:()=>bx,SafeMultiplyExpr:()=>Vb,SafeNegateExpr:()=>Wb,SafeSubtractExpr:()=>jb,SamplePropertyExpr:()=>Ia,SchemaCommentPropertyExpr:()=>Nr,SchemaExpr:()=>Lt,ScopeResolutionExpr:()=>Wc,SearchExpr:()=>Qb,SearchIpExpr:()=>Zb,SecExpr:()=>Px,SechExpr:()=>oy,SecondExpr:()=>ja,SecurePropertyExpr:()=>Ma,SecurityPropertyExpr:()=>ya,SelectExpr:()=>$,SelectExprKind:()=>zk,SemanticViewExpr:()=>fS,SemicolonExpr:()=>tE,Seq1Expr:()=>Bb,Seq2Expr:()=>Gb,Seq4Expr:()=>$b,Seq8Expr:()=>Yb,SequencePropertiesExpr:()=>Wn,SerdePropertiesExpr:()=>ci,SessionParameterExpr:()=>Sg,SessionParameterExprKind:()=>Kk,SessionUserExpr:()=>Fp,SetConfigPropertyExpr:()=>Np,SetExpr:()=>fo,SetItemExpr:()=>mr,SetItemExprKind:()=>dL,SetOperationExpr:()=>be,SetOperationExprKind:()=>EO,SetPropertyExpr:()=>zn,SettingsPropertyExpr:()=>ba,Sha1DigestExpr:()=>tl,Sha2DigestExpr:()=>sl,Sha2Expr:()=>Qa,ShaExpr:()=>el,SharingPropertyExpr:()=>Ca,ShowExpr:()=>gc,SignExpr:()=>rl,SimilarToExpr:()=>SE,SinExpr:()=>kp,SinhExpr:()=>cy,SkewnessExpr:()=>aw,SliceExpr:()=>Pi,SortArrayExpr:()=>oT,SortExpr:()=>Ul,SortKeyPropertyExpr:()=>Pa,SoundexExpr:()=>tn,SoundexP123Expr:()=>Xb,SpaceExpr:()=>eP,SplitExpr:()=>nl,SplitPartExpr:()=>zb,SqlReadWritePropertyExpr:()=>qr,SqlSecurityPropertyExpr:()=>wa,SqrtExpr:()=>$a,StDistanceExpr:()=>tD,StPointExpr:()=>eD,StabilityPropertyExpr:()=>vr,StandardHashExpr:()=>yD,StarExpr:()=>ye,StarMapExpr:()=>NE,StartsWithExpr:()=>hg,StddevExpr:()=>sw,StddevPopExpr:()=>rw,StddevSampExpr:()=>nw,StorageHandlerPropertyExpr:()=>pi,StrPositionExpr:()=>ps,StrToDateExpr:()=>ar,StrToMapExpr:()=>Wh,StrToTimeExpr:()=>Jt,StrToUnixExpr:()=>Vh,StreamExpr:()=>_o,StreamingTablePropertyExpr:()=>ma,StrictPropertyExpr:()=>Oa,StringExpr:()=>Gy,StringToArrayExpr:()=>$y,StructExpr:()=>Hs,StructExtractExpr:()=>cT,StuffExpr:()=>il,SubExpr:()=>dt,SubqueryExpr:()=>ae,SubqueryPredicateExpr:()=>Vn,SubstringExpr:()=>Ms,SubstringIndexExpr:()=>ID,SumExpr:()=>tw,SummarizeExpr:()=>Hl,SwapTableExpr:()=>xo,SystimestampExpr:()=>rD,TABLE_PARTS:()=>TL,TIMESTAMP_PARTS:()=>SV,TableAliasExpr:()=>ie,TableColumnExpr:()=>Gn,TableExpr:()=>V,TableFromRowsExpr:()=>_c,TableSampleExpr:()=>wo,TagExpr:()=>yx,TagsExpr:()=>Ip,TanExpr:()=>Up,TanhExpr:()=>wx,TemporaryPropertyExpr:()=>Gr,TimeAddExpr:()=>Fh,TimeDiffExpr:()=>DC,TimeExpr:()=>tP,TimeFromPartsExpr:()=>Ti,TimeSliceExpr:()=>MC,TimeSliceExprKind:()=>Zk,TimeStrToDateExpr:()=>al,TimeStrToTimeExpr:()=>Xs,TimeStrToUnixExpr:()=>ol,TimeSubExpr:()=>LC,TimeToStrExpr:()=>Ns,TimeToTimeStrExpr:()=>sP,TimeToUnixExpr:()=>Za,TimeTruncExpr:()=>_C,TimeUnitExpr:()=>Re,TimestampAddExpr:()=>Tc,TimestampDiffExpr:()=>Va,TimestampExpr:()=>$p,TimestampFromPartsExpr:()=>Jh,TimestampLtzFromPartsExpr:()=>lP,TimestampSubExpr:()=>Hx,TimestampTruncExpr:()=>er,TimestampTzFromPartsExpr:()=>uP,TitleColumnConstraintExpr:()=>hE,ToArrayExpr:()=>jL,ToBase32Expr:()=>YC,ToBase64Expr:()=>Gh,ToBinaryExpr:()=>Wx,ToBooleanExpr:()=>Ny,ToCharExpr:()=>bR,ToCodePointsExpr:()=>Iy,ToDaysExpr:()=>mC,ToDecfloatExpr:()=>by,ToDoubleExpr:()=>Cy,ToFileExpr:()=>wy,ToMapExpr:()=>tT,ToNumberExpr:()=>yy,ToTablePropertyExpr:()=>ca,TransactionExpr:()=>Lu,TransformExpr:()=>Ry,TransformModelPropertyExpr:()=>La,TransientPropertyExpr:()=>In,TranslateCharactersExpr:()=>IS,TranslateExpr:()=>qx,TrimExpr:()=>or,TrimPosition:()=>AL,TruncExpr:()=>Yh,TruncateTableExpr:()=>$l,TryBase64DecodeBinaryExpr:()=>jC,TryBase64DecodeStringExpr:()=>JC,TryCastExpr:()=>Ft,TryExpr:()=>sD,TryHexDecodeBinaryExpr:()=>XC,TryHexDecodeStringExpr:()=>zC,TryToDecfloatExpr:()=>Py,TsOrDiToDiExpr:()=>ll,TsOrDsAddExpr:()=>sn,TsOrDsDiffExpr:()=>cl,TsOrDsToDateExpr:()=>Ue,TsOrDsToDateStrExpr:()=>rP,TsOrDsToDatetimeExpr:()=>nP,TsOrDsToTimeExpr:()=>pl,TsOrDsToTimestampExpr:()=>iP,TupleExpr:()=>Mt,TypeExpr:()=>SS,TypeofExpr:()=>HL,UNWRAPPED_QUERIES:()=>En,UdtfExpr:()=>as,UnaryExpr:()=>Zs,UncacheExpr:()=>Bl,UnhexExpr:()=>mi,UnicodeExpr:()=>ul,UnicodeStringExpr:()=>xg,UniformExpr:()=>bD,UnionExpr:()=>$r,UniqueColumnConstraintExpr:()=>Fo,UniqueKeyPropertyExpr:()=>MS,UnixDateExpr:()=>aP,UnixMicrosExpr:()=>cP,UnixMillisExpr:()=>pP,UnixSecondsExpr:()=>oP,UnixToStrExpr:()=>mc,UnixToTimeExpr:()=>Us,UnixToTimeStrExpr:()=>El,UnloggedPropertyExpr:()=>Da,UnnestExpr:()=>Pe,UnpivotColumnsExpr:()=>Pu,UpdateExpr:()=>sr,UpperExpr:()=>Ep,UppercaseColumnConstraintExpr:()=>Bo,UseExpr:()=>eE,UseExprKind:()=>Yk,UserDefinedFunctionExpr:()=>Xl,UsingDataExpr:()=>Do,UsingTemplatePropertyExpr:()=>yp,UtcDateExpr:()=>AC,UtcTimeExpr:()=>Gx,UtcTimestampExpr:()=>$x,UuidExpr:()=>Ao,ValuesExpr:()=>Gs,VarExpr:()=>Ze,VarMapExpr:()=>gr,VariadicExpr:()=>Mh,VarianceExpr:()=>xT,VariancePopExpr:()=>xl,VectorSearchExpr:()=>TD,VersionExpr:()=>bu,ViewAttributePropertyExpr:()=>_a,VolatilePropertyExpr:()=>Vs,WatermarkColumnConstraintExpr:()=>lS,WeekExpr:()=>Un,WeekOfYearExpr:()=>xi,WeekStartExpr:()=>CS,WhenExpr:()=>Ji,WhensExpr:()=>ko,WhereExpr:()=>at,WidthBucketExpr:()=>lT,WindowExpr:()=>Fe,WindowSpecExpr:()=>wu,WindowSpecExprKind:()=>kk,WithDataPropertyExpr:()=>li,WithExpr:()=>ve,WithFillExpr:()=>Ru,WithJournalTablePropertyExpr:()=>ka,WithOperatorExpr:()=>To,WithProcedureOptionsExpr:()=>qa,WithSchemaBindingPropertyExpr:()=>Ua,WithSystemVersioningPropertyExpr:()=>rc,WithTableHintExpr:()=>Po,WithinGroupExpr:()=>Cs,XmlElementExpr:()=>MO,XmlGetExpr:()=>hP,XmlKeyValueOptionExpr:()=>bS,XmlNamespaceExpr:()=>Zu,XmlTableExpr:()=>LO,XorExpr:()=>Ur,YearExpr:()=>qn,YearOfWeekExpr:()=>RC,YearOfWeekIsoExpr:()=>OC,ZeroFillColumnConstraintExpr:()=>dc,ZipfExpr:()=>gP,alias:()=>oe,and:()=>nt,array:()=>jT,case_:()=>dM,cast:()=>Le,column:()=>Ie,columnTableNames:()=>to,combine:()=>_R,condition:()=>pw,convert:()=>ts,delete_:()=>vv,except:()=>qD,expand:()=>FD,false_:()=>cs,findTables:()=>Bv,from:()=>Uv,func:()=>DR,insert:()=>qv,intersect:()=>UD,isType:()=>wi,literal:()=>gg,maybeCopy:()=>bt,maybeParse:()=>ne,merge:()=>Fv,normalizeTableName:()=>ow,not:()=>Hn,null_:()=>Ke,or:()=>bs,paren:()=>_r,parseIdentifier:()=>Cl,renameColumn:()=>CV,renameTable:()=>yV,replaceChildren:()=>Cw,replacePlaceholders:()=>MV,replaceTables:()=>wV,replaceTree:()=>PV,select:()=>ft,subquery:()=>gM,table:()=>LR,tableName:()=>bV,table_:()=>mV,toColumn:()=>Bw,toIdentifier:()=>K,toInterval:()=>RV,toTable:()=>RT,true_:()=>$e,tuple:()=>IV,union:()=>NT,update:()=>NV,values:()=>OV,var_:()=>Te,wrap:()=>xc,xor:()=>LL});var _luxon = require('luxon');var kT=(l=>(l.ABS="abs",l.ACOS="acos",l.ACOSH="acosh",l.ADD="add",l.ADD_CONSTRAINT="addConstraint",l.ADD_MONTHS="addMonths",l.ADD_PARTITION="addPartition",l.ADJACENT="adjacent",l.AGG_FUNC="aggFunc",l.AI_AGG="aiAgg",l.AI_CLASSIFY="aiClassify",l.AI_SUMMARIZE_AGG="aiSummarizeAgg",l.ALGORITHM_PROPERTY="algorithmProperty",l.ALIAS="alias",l.ALIASES="aliases",l.ALL="all",l.ALLOWED_VALUES_PROPERTY="allowedValuesProperty",l.ALTER="alter",l.ALTER_COLUMN="alterColumn",l.ALTER_DIST_STYLE="alterDistStyle",l.ALTER_INDEX="alterIndex",l.ALTER_RENAME="alterRename",l.ALTER_SESSION="alterSession",l.ALTER_SET="alterSet",l.ALTER_SORT_KEY="alterSortKey",l.ANALYZE="analyze",l.ANALYZE_COLUMNS="analyzeColumns",l.ANALYZE_DELETE="analyzeDelete",l.ANALYZE_HISTOGRAM="analyzeHistogram",l.ANALYZE_LIST_CHAINED_ROWS="analyzeListChainedRows",l.ANALYZE_SAMPLE="analyzeSample",l.ANALYZE_STATISTICS="analyzeStatistics",l.ANALYZE_VALIDATE="analyzeValidate",l.ANALYZE_WITH="analyzeWith",l.AND="and",l.ANONYMOUS="anonymous",l.ANONYMOUS_AGG_FUNC="anonymousAggFunc",l.ANY="any",l.ANY_VALUE="anyValue",l.APPLY="apply",l.APPROXIMATE_SIMILARITY="approximateSimilarity",l.APPROX_DISTINCT="approxDistinct",l.APPROX_PERCENTILE_ACCUMULATE="approxPercentileAccumulate",l.APPROX_PERCENTILE_COMBINE="approxPercentileCombine",l.APPROX_PERCENTILE_ESTIMATE="approxPercentileEstimate",l.APPROX_QUANTILE="approxQuantile",l.APPROX_QUANTILES="approxQuantiles",l.APPROX_TOP_K="approxTopK",l.APPROX_TOP_K_ACCUMULATE="approxTopKAccumulate",l.APPROX_TOP_K_COMBINE="approxTopKCombine",l.APPROX_TOP_K_ESTIMATE="approxTopKEstimate",l.APPROX_TOP_SUM="approxTopSum",l.ARG_MAX="argMax",l.ARG_MIN="argMin",l.ARRAY="array",l.ARRAYS_ZIP="arraysZip",l.ARRAY_AGG="arrayAgg",l.ARRAY_ALL="arrayAll",l.ARRAY_ANY="arrayAny",l.ARRAY_APPEND="arrayAppend",l.ARRAY_COMPACT="arrayCompact",l.ARRAY_CONCAT="arrayConcat",l.ARRAY_CONCAT_AGG="arrayConcatAgg",l.ARRAY_CONSTRUCT_COMPACT="arrayConstructCompact",l.ARRAY_CONTAINS="arrayContains",l.ARRAY_CONTAINS_ALL="arrayContainsAll",l.ARRAY_FILTER="arrayFilter",l.ARRAY_FIRST="arrayFirst",l.ARRAY_INSERT="arrayInsert",l.ARRAY_INTERSECT="arrayIntersect",l.ARRAY_LAST="arrayLast",l.ARRAY_OVERLAPS="arrayOverlaps",l.ARRAY_PREPEND="arrayPrepend",l.ARRAY_REMOVE="arrayRemove",l.ARRAY_REMOVE_AT="arrayRemoveAt",l.ARRAY_REVERSE="arrayReverse",l.ARRAY_SIZE="arraySize",l.ARRAY_SLICE="arraySlice",l.ARRAY_SORT="arraySort",l.ARRAY_SUM="arraySum",l.ARRAY_TO_STRING="arrayToString",l.ARRAY_UNION_AGG="arrayUnionAgg",l.ARRAY_UNIQUE_AGG="arrayUniqueAgg",l.ASCII="ascii",l.ASIN="asin",l.ASINH="asinh",l.ATAN="atan",l.ATAN2="atan2",l.ATANH="atanh",l.ATTACH="attach",l.ATTACH_OPTION="attachOption",l.AT_INDEX="atIndex",l.AT_TIME_ZONE="atTimeZone",l.AUTO_INCREMENT_COLUMN_CONSTRAINT="autoIncrementColumnConstraint",l.AUTO_INCREMENT_PROPERTY="autoIncrementProperty",l.AUTO_REFRESH_PROPERTY="autoRefreshProperty",l.AVG="avg",l.BACKUP_PROPERTY="backupProperty",l.BASE64_DECODE_BINARY="base64DecodeBinary",l.BASE64_DECODE_STRING="base64DecodeString",l.BASE64_ENCODE="base64Encode",l.BETWEEN="between",l.BINARY="binary",l.BITMAP_BIT_POSITION="bitmapBitPosition",l.BITMAP_BUCKET_NUMBER="bitmapBucketNumber",l.BITMAP_CONSTRUCT_AGG="bitmapConstructAgg",l.BITMAP_COUNT="bitmapCount",l.BITMAP_OR_AGG="bitmapOrAgg",l.BITWISE_AND="bitwiseAnd",l.BITWISE_AND_AGG="bitwiseAndAgg",l.BITWISE_COUNT="bitwiseCount",l.BITWISE_LEFT_SHIFT="bitwiseLeftShift",l.BITWISE_NOT="bitwiseNot",l.BITWISE_OR="bitwiseOr",l.BITWISE_OR_AGG="bitwiseOrAgg",l.BITWISE_RIGHT_SHIFT="bitwiseRightShift",l.BITWISE_XOR="bitwiseXor",l.BITWISE_XOR_AGG="bitwiseXorAgg",l.BIT_LENGTH="bitLength",l.BIT_STRING="bitString",l.BLOCK_COMPRESSION_PROPERTY="blockCompressionProperty",l.BOOLAND="booland",l.BOOLEAN="boolean",l.BOOLNOT="boolnot",l.BOOLOR="boolor",l.BOOLXOR_AGG="boolxorAgg",l.BRACKET="bracket",l.BUILD_PROPERTY="buildProperty",l.BYTE_LENGTH="byteLength",l.BYTE_STRING="byteString",l.CACHE="cache",l.CASE="case",l.CASE_SPECIFIC_COLUMN_CONSTRAINT="caseSpecificColumnConstraint",l.CAST="cast",l.CAST_TO_STR_TYPE="castToStrType",l.CBRT="cbrt",l.CEIL="ceil",l.CHANGES="changes",l.CHARACTER_SET="characterSet",l.CHARACTER_SET_COLUMN_CONSTRAINT="characterSetColumnConstraint",l.CHARACTER_SET_PROPERTY="characterSetProperty",l.CHECK="check",l.CHECKSUM_PROPERTY="checksumProperty",l.CHECK_COLUMN_CONSTRAINT="checkColumnConstraint",l.CHECK_JSON="checkJson",l.CHECK_XML="checkXml",l.CHR="chr",l.CLONE="clone",l.CLUSTER="cluster",l.CLUSTERED_BY_PROPERTY="clusteredByProperty",l.CLUSTERED_COLUMN_CONSTRAINT="clusteredColumnConstraint",l.COALESCE="coalesce",l.CODE_POINTS_TO_BYTES="codePointsToBytes",l.CODE_POINTS_TO_STRING="codePointsToString",l.COLLATE="collate",l.COLLATE_COLUMN_CONSTRAINT="collateColumnConstraint",l.COLLATE_PROPERTY="collateProperty",l.COLLATION="collation",l.COLUMN="column",l.COLUMNS="columns",l.COLUMN_CONSTRAINT="columnConstraint",l.COLUMN_CONSTRAINT_KIND="columnConstraintKind",l.COLUMN_DEF="columnDef",l.COLUMN_POSITION="columnPosition",l.COLUMN_PREFIX="columnPrefix",l.COMBINED_AGG_FUNC="combinedAggFunc",l.COMBINED_PARAMETERIZED_AGG="combinedParameterizedAgg",l.COMMAND="command",l.COMMENT="comment",l.COMMENT_COLUMN_CONSTRAINT="commentColumnConstraint",l.COMMIT="commit",l.COMPREHENSION="comprehension",l.COMPRESS="compress",l.COMPRESS_COLUMN_CONSTRAINT="compressColumnConstraint",l.COMPUTED_COLUMN_CONSTRAINT="computedColumnConstraint",l.CONCAT="concat",l.CONCAT_WS="concatWs",l.CONDITION="condition",l.CONDITIONAL_INSERT="conditionalInsert",l.CONNECT="connect",l.CONNECTOR="connector",l.CONNECT_BY_ROOT="connectByRoot",l.CONSTRAINT="constraint",l.CONTAINS="contains",l.CONVERT="convert",l.CONVERT_TIMEZONE="convertTimezone",l.CONVERT_TO_CHARSET="convertToCharset",l.COPY="copy",l.COPY_GRANTS_PROPERTY="copyGrantsProperty",l.COPY_PARAMETER="copyParameter",l.CORR="corr",l.COS="cos",l.COSH="cosh",l.COSINE_DISTANCE="cosineDistance",l.COT="cot",l.COTH="coth",l.COUNT="count",l.COUNT_IF="countIf",l.COVAR_POP="covarPop",l.COVAR_SAMP="covarSamp",l.CREATE="create",l.CREDENTIALS="credentials",l.CREDENTIALS_PROPERTY="credentialsProperty",l.CSC="csc",l.CSCH="csch",l.CTE="cte",l.CUBE="cube",l.CUME_DIST="cumeDist",l.CURRENT_ACCOUNT="currentAccount",l.CURRENT_ACCOUNT_NAME="currentAccountName",l.CURRENT_AVAILABLE_ROLES="currentAvailableRoles",l.CURRENT_CATALOG="currentCatalog",l.CURRENT_CLIENT="currentClient",l.CURRENT_DATABASE="currentDatabase",l.CURRENT_DATE="currentDate",l.CURRENT_DATETIME="currentDatetime",l.CURRENT_IP_ADDRESS="currentIpAddress",l.CURRENT_ORGANIZATION_NAME="currentOrganizationName",l.CURRENT_ORGANIZATION_USER="currentOrganizationUser",l.CURRENT_REGION="currentRegion",l.CURRENT_ROLE="currentRole",l.CURRENT_ROLE_TYPE="currentRoleType",l.CURRENT_SCHEMA="currentSchema",l.CURRENT_SCHEMAS="currentSchemas",l.CURRENT_SECONDARY_ROLES="currentSecondaryRoles",l.CURRENT_SESSION="currentSession",l.CURRENT_STATEMENT="currentStatement",l.CURRENT_TIME="currentTime",l.CURRENT_TIMESTAMP="currentTimestamp",l.CURRENT_TIMESTAMP_LTZ="currentTimestampLtz",l.CURRENT_TIMEZONE="currentTimezone",l.CURRENT_TRANSACTION="currentTransaction",l.CURRENT_USER="currentUser",l.CURRENT_VERSION="currentVersion",l.CURRENT_WAREHOUSE="currentWarehouse",l.DATA_BLOCKSIZE_PROPERTY="dataBlocksizeProperty",l.DATA_DELETION_PROPERTY="dataDeletionProperty",l.DATA_TYPE="dataType",l.DATA_TYPE_PARAM="dataTypeParam",l.DATE="date",l.DATETIME="datetime",l.DATETIME_ADD="datetimeAdd",l.DATETIME_DIFF="datetimeDiff",l.DATETIME_SUB="datetimeSub",l.DATETIME_TRUNC="datetimeTrunc",l.DATE_ADD="dateAdd",l.DATE_BIN="dateBin",l.DATE_DIFF="dateDiff",l.DATE_FORMAT_COLUMN_CONSTRAINT="dateFormatColumnConstraint",l.DATE_FROM_PARTS="dateFromParts",l.DATE_FROM_UNIX_DATE="dateFromUnixDate",l.DATE_STR_TO_DATE="dateStrToDate",l.DATE_SUB="dateSub",l.DATE_TO_DATE_STR="dateToDateStr",l.DATE_TO_DI="dateToDi",l.DATE_TRUNC="dateTrunc",l.DAY="day",l.DAYNAME="dayname",l.DAY_OF_MONTH="dayOfMonth",l.DAY_OF_WEEK="dayOfWeek",l.DAY_OF_WEEK_ISO="dayOfWeekIso",l.DAY_OF_YEAR="dayOfYear",l.DDL="ddl",l.DECLARE="declare",l.DECLARE_ITEM="declareItem",l.DECODE="decode",l.DECODE_CASE="decodeCase",l.DECOMPRESS_BINARY="decompressBinary",l.DECOMPRESS_STRING="decompressString",l.DECRYPT="decrypt",l.DECRYPT_RAW="decryptRaw",l.DEFAULT_COLUMN_CONSTRAINT="defaultColumnConstraint",l.DEFINER_PROPERTY="definerProperty",l.DEGREES="degrees",l.DELETE="delete",l.DENSE_RANK="denseRank",l.DERIVED_TABLE="derivedTable",l.DESCRIBE="describe",l.DETACH="detach",l.DICT_PROPERTY="dictProperty",l.DICT_RANGE="dictRange",l.DICT_SUB_PROPERTY="dictSubProperty",l.DIRECTORY="directory",l.DIRECTORY_STAGE="directoryStage",l.DISTANCE="distance",l.DISTINCT="distinct",l.DISTRIBUTE="distribute",l.DISTRIBUTED_BY_PROPERTY="distributedByProperty",l.DIST_KEY_PROPERTY="distKeyProperty",l.DIST_STYLE_PROPERTY="distStyleProperty",l.DIV="div",l.DI_TO_DATE="diToDate",l.DML="dml",l.DOT="dot",l.DOT_PRODUCT="dotProduct",l.DROP="drop",l.DROP_PARTITION="dropPartition",l.DUPLICATE_KEY_PROPERTY="duplicateKeyProperty",l.DYNAMIC_PROPERTY="dynamicProperty",l.D_PIPE="dPipe",l.ELT="elt",l.EMPTY_PROPERTY="emptyProperty",l.ENCODE="encode",l.ENCODE_COLUMN_CONSTRAINT="encodeColumnConstraint",l.ENCODE_PROPERTY="encodeProperty",l.ENCRYPT="encrypt",l.ENCRYPT_RAW="encryptRaw",l.ENDS_WITH="endsWith",l.ENGINE_PROPERTY="engineProperty",l.ENVIROMENT_PROPERTY="enviromentProperty",l.EPHEMERAL_COLUMN_CONSTRAINT="ephemeralColumnConstraint",l.EQ="eq",l.EqUAL_NULL="equalNull",l.ESCAPE="escape",l.EUCLIDEAN_DISTANCE="euclideanDistance",l.EXCEPT="except",l.EXCLUDE_COLUMN_CONSTRAINT="excludeColumnConstraint",l.EXECUTE_AS_PROPERTY="executeAsProperty",l.EXISTS="exists",l.EXP="exp",l.EXPLODE="explode",l.EXPLODE_OUTER="explodeOuter",l.EXPLODING_GENERATE_SERIES="explodingGenerateSeries",l.EXPORT="export",l.EXPRESSION="expression",l.EXTENDS_LEFT="extendsLeft",l.EXTENDS_RIGHT="extendsRight",l.EXTERNAL_PROPERTY="externalProperty",l.EXTRACT="extract",l.FACTORIAL="factorial",l.FALLBACK_PROPERTY="fallbackProperty",l.FARM_FINGERPRINT="farmFingerprint",l.FEATURES_AT_TIME="featuresAtTime",l.FETCH="fetch",l.FILE_FORMAT_PROPERTY="fileFormatProperty",l.FILTER="filter",l.FINAL="final",l.FIRST="first",l.FIRST_VALUE="firstValue",l.FLATTEN="flatten",l.FLOAT64="float64",l.FLOOR="floor",l.FORCE_PROPERTY="forceProperty",l.FOREIGN_KEY="foreignKey",l.FORMAT="format",l.FORMAT_JSON="formatJson",l.FORMAT_PHRASE="formatPhrase",l.FOR_IN="forIn",l.FREESPACE_PROPERTY="freespaceProperty",l.FROM="from",l.FROM_BASE="fromBase",l.FROM_BASE32="fromBase32",l.FROM_BASE64="fromBase64",l.FROM_ISO8601_TIMESTAMP="fromIso8601Timestamp",l.FROM_TIME_ZONE="fromTimeZone",l.FUNC="func",l.GAP_FILL="gapFill",l.GENERATED_AS_IDENTITY_COLUMN_CONSTRAINT="generatedAsIdentityColumnConstraint",l.GENERATED_AS_ROW_COLUMN_CONSTRAINT="generatedAsRowColumnConstraint",l.GENERATE_DATE_ARRAY="generateDateArray",l.GENERATE_EMBEDDING="generateEmbedding",l.GENERATE_SERIES="generateSeries",l.GENERATE_TIMESTAMP_ARRAY="generateTimestampArray",l.GENERATOR="generator",l.GET="get",l.GETBIT="getbit",l.GET_EXTRACT="getExtract",l.GLOB="glob",l.GLOBAL_PROPERTY="globalProperty",l.GRANT="grant",l.GRANT_PRINCIPAL="grantPrincipal",l.GRANT_PRIVILEGE="grantPrivilege",l.GREATEST="greatest",l.GROUP="group",l.GROUPING="grouping",l.GROUPING_ID="groupingId",l.GROUPING_SETS="groupingSets",l.GROUP_CONCAT="groupConcat",l.GT="gt",l.GTE="gte",l.HASH_AGG="hashAgg",l.HAVING="having",l.HAVING_MAX="havingMax",l.HEAP_PROPERTY="heapProperty",l.HEREDOC="heredoc",l.HEX="hex",l.HEX_DECODE_STRING="hexDecodeString",l.HEX_ENCODE="hexEncode",l.HEX_STRING="hexString",l.HINT="hint",l.HISTORICAL_DATA="historicalData",l.HLL="hll",l.HOST="host",l.HOUR="hour",l.ICEBERG_PROPERTY="icebergProperty",l.IDENTIFIER="identifier",l.IF="if",l.IGNORE_NULLS="ignoreNulls",l.IN="in",l.INCLUDE_PROPERTY="includeProperty",l.INDEX="index",l.INDEX_COLUMN_CONSTRAINT="indexColumnConstraint",l.INDEX_CONSTRAINT_OPTION="indexConstraintOption",l.INDEX_PARAMETERS="indexParameters",l.INDEX_TABLE_HINT="indexTableHint",l.INHERITS_PROPERTY="inheritsProperty",l.INITCAP="initcap",l.INLINE="inline",l.INLINE_LENGTH_COLUMN_CONSTRAINT="inlineLengthColumnConstraint",l.INPUT_MODEL_PROPERTY="inputModelProperty",l.INPUT_OUTPUT_FORMAT="inputOutputFormat",l.INSERT="insert",l.INSTALL="install",l.INT64="int64",l.INTERSECT="intersect",l.INTERVAL="interval",l.INTERVAL_OP="intervalOp",l.INTERVAL_SPAN="intervalSpan",l.INTO="into",l.INTRODUCER="introducer",l.INT_DIV="intDiv",l.IN_OUT_COLUMN_CONSTRAINT="inOutColumnConstraint",l.IS="is",l.ISOLATED_LOADING_PROPERTY="isolatedLoadingProperty",l.IS_ARRAY="isArray",l.IS_ASCII="isAscii",l.IS_INF="isInf",l.IS_NAN="isNan",l.IS_NULL_VALUE="isNullValue",l.ILIKE="iLike",l.JAROWINKLER_SIMILARITY="jarowinklerSimilarity",l.JOIN="join",l.JOIN_HINT="joinHint",l.JOURNAL_PROPERTY="journalProperty",l.JSON="json",l.JSON_ARRAY="jsonArray",l.JSON_ARRAY_AGG="jsonArrayAgg",l.JSON_ARRAY_APPEND="jsonArrayAppend",l.JSON_ARRAY_CONTAINS="jsonArrayContains",l.JSON_ARRAY_INSERT="jsonArrayInsert",l.JSON_BOOL="jsonBool",l.JSONB_CONTAINS="jsonbContains",l.JSONB_CONTAINS_ALL_TOP_KEYS="jsonbContainsAllTopKeys",l.JSONB_CONTAINS_ANY_TOP_KEYS="jsonbContainsAnyTopKeys",l.JSONB_DELETE_AT_PATH="jsonbDeleteAtPath",l.JSONB_EXISTS="jsonbExists",l.JSONB_EXTRACT="jsonbExtract",l.JSONB_EXTRACT_SCALAR="jsonbExtractScalar",l.JSONB_OBJECT_AGG="jsonbObjectAgg",l.JSON_CAST="jsonCast",l.JSON_COLUMN_DEF="jsonColumnDef",l.JSON_EXISTS="jsonExists",l.JSON_EXTRACT="jsonExtract",l.JSON_EXTRACT_ARRAY="jsonExtractArray",l.JSON_EXTRACT_QUOTE="jsonExtractQuote",l.JSON_EXTRACT_SCALAR="jsonExtractScalar",l.JSON_FORMAT="jsonFormat",l.JSON_KEYS="jsonKeys",l.JSON_KEYS_AT_DEPTH="jsonKeysAtDepth",l.JSON_KEY_VALUE="jsonKeyValue",l.JSON_OBJECT="jsonObject",l.JSON_OBJECT_AGG="jsonObjectAgg",l.JSON_PATH="jsonPath",l.JSON_PATH_FILTER="jsonPathFilter",l.JSON_PATH_KEY="jsonPathKey",l.JSON_PATH_PART="jsonPathPart",l.JSON_PATH_RECURSIVE="jsonPathRecursive",l.JSON_PATH_ROOT="jsonPathRoot",l.JSON_PATH_SCRIPT="jsonPathScript",l.JSON_PATH_SELECTOR="jsonPathSelector",l.JSON_PATH_SLICE="jsonPathSlice",l.JSON_PATH_SUBSCRIPT="jsonPathSubscript",l.JSON_PATH_UNION="jsonPathUnion",l.JSON_PATH_WILDCARD="jsonPathWildcard",l.JSON_REMOVE="jsonRemove",l.JSON_SCHEMA="jsonSchema",l.JSON_SET="jsonSet",l.JSON_STRIP_NULLS="jsonStripNulls",l.JSON_TABLE="jsonTable",l.JSON_TYPE="jsontype",l.JSON_VALUE="jsonValue",l.JSON_VALUE_ARRAY="jsonValueArray",l.JUSTIFY_DAYS="justifyDays",l.JUSTIFY_HOURS="justifyHours",l.JUSTIFY_INTERVAL="justifyInterval",l.KILL="kill",l.KURTOSIS="kurtosis",l.KWARG="kwarg",l.LAG="lag",l.LAMBDA="lambda",l.LANGUAGE_PROPERTY="languageProperty",l.LAST="last",l.LAST_DAY="lastDay",l.LAST_VALUE="lastValue",l.LATERAL="lateral",l.LAX_BOOL="laxBool",l.LAX_FLOAT64="laxFloat64",l.LAX_INT64="laxInt64",l.LAX_STRING="laxString",l.LEAD="lead",l.LEAST="least",l.LEFT="left",l.LENGTH="length",l.LEVENSHTEIN="levenshtein",l.LIKE="like",l.LIKE_PROPERTY="likeProperty",l.LIMIT="limit",l.LIMIT_OPTIONS="limitOptions",l.LIST="list",l.LITERAL="literal",l.LN="ln",l.LOAD_DATA="loadData",l.LOCALTIME="localtime",l.LOCALTIMESTAMP="localtimestamp",l.LOCATION="location",l.LOCATION_PROPERTY="locationProperty",l.LOCK="lock",l.LOCKING_PROPERTY="lockingProperty",l.LOCKING_STATEMENT="lockingStatement",l.LOCK_PROPERTY="lockProperty",l.LOG="log",l.LOGICAL_AND="logicalAnd",l.LOGICAL_OR="logicalOr",l.LOG_PROPERTY="logProperty",l.LOWER="lower",l.LOWER_HEX="lowerHex",l.LT="lt",l.LTE="lte",l.MAKE_INTERVAL="makeInterval",l.MANHATTAN_DISTANCE="manhattanDistance",l.MAP="map",l.MAP_CAT="mapCat",l.MAP_CONTAINS_KEY="mapContainsKey",l.MAP_DELETE="mapDelete",l.MAP_FROM_ENTRIES="mapFromEntries",l.MAP_INSERT="mapInsert",l.MAP_KEYS="mapkeys",l.MAP_PICK="mapPick",l.MAP_SIZE="mapSize",l.MASKING_POLICY_COLUMN_CONSTRAINT="maskingPolicyColumnConstraint",l.MATCH="match",l.MATCH_AGAINST="matchAgainst",l.MATCH_RECOGNIZE="matchRecognize",l.MATCH_RECOGNIZE_MEASURE="matchRecognizeMeasure",l.MATERIALIZED_PROPERTY="materializedProperty",l.MAX="max",l.MD5="md5",l.MD5_DIGEST="md5Digest",l.MD5_NUMBER_LOWER64="md5NumberLower64",l.MD5_NUMBER_UPPER64="md5NumberUpper64",l.MEDIAN="median",l.MERGE="merge",l.MERGE_BLOCK_RATIO_PROPERTY="mergeBlockRatioProperty",l.MERGE_TREE_TTL="mergeTreeTtl",l.MERGE_TREE_TTL_ACTION="mergeTreeTtlAction",l.MIN="min",l.MINHASH="minhash",l.MINHASH_COMBINE="minhashCombine",l.MINUTE="minute",l.ML_FORECAST="mlForecast",l.ML_TRANSLATE="mlTranslate",l.MOD="mod",l.MODE="mode",l.MODEL_ATTRIBUTE="modelAttribute",l.MONTH="month",l.MONTHNAME="monthname",l.MONTHS_BETWEEN="monthsBetween",l.MUL="mul",l.MULTITABLE_INSERTS="multitableInserts",l.NATIONAL="national",l.NEG="neg",l.NEQ="neq",l.NET_FUNC="netFunc",l.NEXT_DAY="nextDay",l.NEXT_VALUE_FOR="nextValueFor",l.NON_CLUSTERED_COLUMN_CONSTRAINT="nonClusteredColumnConstraint",l.NORMAL="normal",l.NORMALIZE="normalize",l.NOT="not",l.NOT_FOR_REPLICATION_COLUMN_CONSTRAINT="notForReplicationColumnConstraint",l.NOT_NULL_COLUMN_CONSTRAINT="notNullColumnConstraint",l.NO_PRIMARY_INDEX_PROPERTY="noPrimaryIndexProperty",l.NTH_VALUE="nthValue",l.NTILE="ntile",l.NULL="null",l.NULLIF="nullif",l.NULL_SAFE_EQ="nullSafeEq",l.NULL_SAFE_NEQ="nullSafeNeq",l.NUMBER_TO_STR="numberToStr",l.NVL2="nvl2",l.OBJECT_AGG="objectAgg",l.OBJECT_IDENTIFIER="objectIdentifier",l.OBJECT_INSERT="objectInsert",l.OFFSET="offset",l.ON_CLUSTER="onCluster",l.ON_COMMIT_PROPERTY="onCommitProperty",l.ON_CONDITION="onCondition",l.ON_CONFLICT="onConflict",l.ON_PROPERTY="onProperty",l.ON_UPDATE_COLUMN_CONSTRAINT="onUpdateColumnConstraint",l.OPCLASS="opclass",l.OPEN_JSON="openJson",l.OPEN_JSON_COLUMN_DEF="openJsonColumnDef",l.OPERATOR="operator",l.OR="or",l.ORDER="order",l.ORDERED="ordered",l.OUTPUT_MODEL_PROPERTY="outputModelProperty",l.OVERFLOW_TRUNCATE_BEHAVIOR="overflowTruncateBehavior",l.OVERLAPS="overlaps",l.OVERLAY="overlay",l.PAD="pad",l.PARAMETER="parameter",l.PARAMETERIZED_AGG="parameterizedAgg",l.PAREN="paren",l.PARSE_BIGNUMERIC="parseBignumeric",l.PARSE_DATETIME="parseDatetime",l.PARSE_IP="parseIp",l.PARSE_JSON="parseJson",l.PARSE_NUMERIC="parseNumeric",l.PARSE_TIME="parseTime",l.PARSE_URL="parseUrl",l.PARTITION="partition",l.PARTITIONED_BY_BUCKET="partitionedByBucket",l.PARTITIONED_BY_PROPERTY="partitionedByProperty",l.PARTITIONED_OF_PROPERTY="partitionedOfProperty",l.PARTITION_BOUND_SPEC="partitionBoundSpec",l.PARTITION_BY_LIST_PROPERTY="partitionByListProperty",l.PARTITION_BY_RANGE_PROPERTY="partitionByRangeProperty",l.PARTITION_BY_RANGE_PROPERTY_DYNAMIC="partitionByRangePropertyDynamic",l.PARTITION_BY_TRUNCATE="partitionByTruncate",l.PARTITION_ID="partitionId",l.PARTITION_LIST="partitionList",l.PARTITION_RANGE="partitionRange",l.PATH_COLUMN_CONSTRAINT="pathColumnConstraint",l.PERCENTILE_CONT="percentileCont",l.PERCENTILE_DISC="percentileDisc",l.PERCENT_RANK="percentRank",l.PERIOD_FOR_SYSTEM_TIME_CONSTRAINT="periodForSystemTimeConstraint",l.PI="pi",l.PIVOT="pivot",l.PIVOT_ALIAS="pivotAlias",l.PIVOT_ANY="pivotAny",l.PLACEHOLDER="placeholder",l.POSEXPLODE="posexplode",l.POSEXPLODE_OUTER="posexplodeOuter",l.POSITIONAL_COLUMN="positionalColumn",l.POW="pow",l.PRAGMA="pragma",l.PREDICATE="predicate",l.PREDICT="predict",l.PREVIOUS_DAY="previousDay",l.PRE_WHERE="preWhere",l.PRIMARY_KEY="primaryKey",l.PRIMARY_KEY_COLUMN_CONSTRAINT="primaryKeyColumnConstraint",l.PRIOR="prior",l.PROJECTION_DEF="projectionDef",l.PROJECTION_POLICY_COLUMN_CONSTRAINT="projectionPolicyColumnConstraint",l.PROPERTIES="properties",l.PROPERTY="property",l.PROPERTY_EQ="propertyEq",l.PSEUDOCOLUMN="pseudocolumn",l.PSEUDO_TYPE="pseudoType",l.PUT="put",l.QUALIFY="qualify",l.QUANTILE="quantile",l.QUARTER="quarter",l.QUERY="query",l.QUERY_BAND="queryBand",l.QUERY_OPTION="queryOption",l.QUERY_TRANSFORM="queryTransform",l.RADIANS="radians",l.RAND="rand",l.RANDN="randn",l.RANDSTR="randstr",l.RANGE_BUCKET="rangeBucket",l.RANGE_N="rangeN",l.RANK="rank",l.RAW_STRING="rawString",l.READ_CSV="readCsv",l.READ_PARQUET="readParquet",l.RECURSIVE_WITH_SEARCH="recursiveWithSearch",l.REDUCE="reduce",l.REFERENCE="reference",l.REFRESH="refresh",l.REFRESH_TRIGGER_PROPERTY="refreshTriggerProperty",l.REGEXP_COUNT="regexpCount",l.REGEXP_EXTRACT="regexpExtract",l.REGEXP_EXTRACT_ALL="regexpExtractAll",l.REGEXP_FULL_MATCH="regexpFullMatch",l.REGEXP_INSTR="regexpInstr",l.REGEXP_ILIKE="regexpIlike",l.REGEXP_LIKE="regexpLike",l.REGEXP_REPLACE="regexpReplace",l.REGEXP_SPLIT="regexpSplit",l.REGR_AVGX="regrAvgx",l.REGR_AVGY="regrAvgy",l.REGR_COUNT="regrCount",l.REGR_INTERCEPT="regrIntercept",l.REGR_R2="regrR2",l.REGR_SLOPE="regrSlope",l.REGR_SXX="regrSxx",l.REGR_SXY="regrSxy",l.REGR_SYY="regrSyy",l.REGR_VALX="regrValx",l.REGR_VALY="regrValy",l.REG_DOMAIN="regDomain",l.REMOTE_WITH_CONNECTION_MODEL_PROPERTY="remoteWithConnectionModelProperty",l.RENAME_COLUMN="renameColumn",l.REPEAT="repeat",l.REPLACE="replace",l.REPLACE_PARTITION="replacePartition",l.RESPECT_NULLS="respectNulls",l.RETURN="return",l.RETURNING="returning",l.RETURNS_PROPERTY="returnsProperty",l.REVERSE="reverse",l.REVOKE="revoke",l.RIGHT="right",l.ROLLBACK="rollback",l.ROLLUP="rollup",l.ROLLUP_INDEX="rollupIndex",l.ROLLUP_PROPERTY="rollupProperty",l.ROUND="round",l.ROW_FORMAT_DELIMITED_PROPERTY="rowFormatDelimitedProperty",l.ROW_FORMAT_PROPERTY="rowFormatProperty",l.ROW_FORMAT_SERDE_PROPERTY="rowFormatSerdeProperty",l.ROW_NUMBER="rowNumber",l.RTRIMMED_LENGTH="rtrimmedLength",l.SAFE_ADD="safeAdd",l.SAFE_CONVERT_BYTES_TO_STRING="safeConvertBytesToString",l.SAFE_DIVIDE="safeDivide",l.SAFE_FUNC="safeFunc",l.SAFE_MULTIPLY="safeMultiply",l.SAFE_NEGATE="safeNegate",l.SAFE_SUBTRACT="safeSubtract",l.SAMPLE_PROPERTY="sampleProperty",l.SCHEMA="schema",l.SCHEMA_COMMENT_PROPERTY="schemaCommentProperty",l.SCOPE_RESOLUTION="scopeResolution",l.SEARCH="search",l.SEARCH_IP="searchIp",l.SEC="sec",l.SECH="sech",l.SECOND="second",l.SECURE_PROPERTY="secureProperty",l.SECURITY_PROPERTY="securityProperty",l.SELECT="select",l.SEMANTIC_VIEW="semanticView",l.SEMICOLON="semicolon",l.SEQ1="seq1",l.SEQ2="seq2",l.SEQ4="seq4",l.SEQ8="seq8",l.SEQUENCE_PROPERTIES="sequenceProperties",l.SERDE_PROPERTIES="serdeProperties",l.SESSION_PARAMETER="sessionParameter",l.SESSION_USER="sessionUser",l.SET="set",l.SETTINGS_PROPERTY="settingsProperty",l.SET_CONFIG_PROPERTY="setConfigProperty",l.SET_ITEM="setItem",l.SET_OPERATION="setOperation",l.SET_PROPERTY="setProperty",l.SHA="sha",l.Sha1_DIGEST="sha1Digest",l.Sha2="sha2",l.Sha2_DIGEST="sha2Digest",l.SHARING_PROPERTY="sharingProperty",l.SHOW="show",l.SIGN="sign",l.SIMILAR_TO="similarTo",l.SIN="sin",l.SINH="sinh",l.SKEWNESS="skewness",l.SLICE="slice",l.SORT="sort",l.SORT_ARRAY="sortArray",l.SORT_KEY_PROPERTY="sortKeyProperty",l.SOUNDEX="soundex",l.SOUNDEX_P123="soundexP123",l.SPACE="space",l.SPLIT="split",l.SPLIT_PART="splitPart",l.SQL_READ_WRITE_PROPERTY="sqlReadWriteProperty",l.SQL_SECURITY_PROPERTY="sqlSecurityProperty",l.SQRT="sqrt",l.STABILITY_PROPERTY="stabilityProperty",l.STANDARD_HASH="standardHash",l.STAR="star",l.STARTS_WITH="startswith",l.STAR_MAP="starMap",l.STDDEV="stddev",l.STDDEV_POP="stddevPop",l.STDDEV_SAMP="stddevSamp",l.STORAGE_HANDLER_PROPERTY="storageHandlerProperty",l.STREAM="stream",l.STREAMING_TABLE_PROPERTY="streamingTableProperty",l.STRICT_PROPERTY="strictProperty",l.STRING="string",l.STRING_TO_ARRAY="stringToArray",l.STRUCT="struct",l.STRUCT_EXTRACT="structExtract",l.STR_POSITION="strPosition",l.STR_TO_DATE="strToDate",l.STR_TO_MAP="strToMap",l.STR_TO_TIME="strToTime",l.STR_TO_UNIX="strToUnix",l.STUFF="stuff",l.ST_DISTANCE="stDistance",l.ST_POINT="stPoint",l.SUB="sub",l.SUBQUERY="subquery",l.SUBQUERY_PREDICATE="subqueryPredicate",l.SUBSTRING="substring",l.SUBSTRING_INDEX="substringIndex",l.SUM="sum",l.SUMMARIZE="summarize",l.SWAP_TABLE="swapTable",l.SYSTIMESTAMP="systimestamp",l.TABLE="table",l.TABLE_ALIAS="tableAlias",l.TABLE_COLUMN="tableColumn",l.TABLE_FROM_ROWS="tableFromRows",l.TABLE_SAMPLE="tableSample",l.TAG="tag",l.TAGS="tags",l.TAN="tan",l.TANH="tanh",l.TEMPORARY_PROPERTY="temporaryProperty",l.TIME="time",l.TIMESTAMP="timestamp",l.TIMESTAMP_ADD="timestampAdd",l.TIMESTAMP_DIFF="timestampDiff",l.TIMESTAMP_FROM_PARTS="timestampFromParts",l.TIMESTAMP_LTZ_FROM_PARTS="timestampLtzFromParts",l.TIMESTAMP_SUB="timestampSub",l.TIMESTAMP_TRUNC="timestampTrunc",l.TIMESTAMP_TZ_FROM_PARTS="timestampTzFromParts",l.TIME_ADD="timeAdd",l.TIME_DIFF="timeDiff",l.TIME_FROM_PARTS="timeFromParts",l.TIME_SLICE="timeSlice",l.TIME_STR_TO_DATE="timeStrToDate",l.TIME_STR_TO_TIME="timeStrToTime",l.TIME_STR_TO_UNIX="timeStrToUnix",l.TIME_SUB="timeSub",l.TIME_TO_STR="timeToStr",l.TIME_TO_TIME_STR="timeToTimeStr",l.TIME_TO_UNIX="timeToUnix",l.TIME_TRUNC="timeTrunc",l.TIME_UNIT="timeUnit",l.TITLE_COLUMN_CONSTRAINT="titleColumnConstraint",l.TO_ARRAY="toArray",l.TO_BASE32="toBase32",l.TO_BASE64="toBase64",l.TO_BINARY="toBinary",l.TO_BOOLEAN="toBoolean",l.TO_CHAR="toChar",l.TO_CODE_POINTS="toCodePoints",l.TO_DAYS="toDays",l.TO_DECFLOAT="toDecfloat",l.TO_DOUBLE="toDouble",l.TO_FILE="toFile",l.TO_MAP="toMap",l.TO_NUMBER="toNumber",l.TO_TABLE_PROPERTY="toTableProperty",l.TRANSACTION="transaction",l.TRANSFORM="transform",l.TRANSFORM_MODEL_PROPERTY="transformModelProperty",l.TRANSIENT_PROPERTY="transientProperty",l.TRANSLATE="translate",l.TRANSLATE_CHARACTERS="translateCharacters",l.TRIM="trim",l.TRUNC="trunc",l.TRUNCATE_TABLE="truncateTable",l.TRY="try",l.TRY_BASE64_DECODE_BINARY="tryBase64DecodeBinary",l.TRY_BASE64_DECODE_STRING="tryBase64DecodeString",l.TRY_CAST="tryCast",l.TRY_HEX_DECODE_BINARY="tryHexDecodeBinary",l.TRY_HEX_DECODE_STRING="tryHexDecodeString",l.TRY_TO_DECFLOAT="tryToDecfloat",l.TS_OR_DI_TO_DI="tsOrDiToDi",l.TS_OR_DS_ADD="tsOrDsAdd",l.TS_OR_DS_DIFF="tsOrDsDiff",l.TS_OR_DS_TO_DATE="tsOrDsToDate",l.TS_OR_DS_TO_DATETIME="tsOrDsToDatetime",l.TS_OR_DS_TO_DATE_STR="tsOrDsToDateStr",l.TS_OR_DS_TO_TIME="tsOrDsToTime",l.TS_OR_DS_TO_TIMESTAMP="tsOrDsToTimestamp",l.TUPLE="tuple",l.TYPE="type",l.TYPEOF="typeof",l.UDTF="udtf",l.UNARY="unary",l.UNCACHE="uncache",l.UNHEX="unhex",l.UNICODE="unicode",l.UNICODE_STRING="unicodeString",l.UNIFORM="uniform",l.UNION="union",l.UNIQUE_COLUMN_CONSTRAINT="uniqueColumnConstraint",l.UNIQUE_KEY_PROPERTY="uniqueKeyProperty",l.UNIX_DATE="unixDate",l.UNIX_MICROS="unixMicros",l.UNIX_MILLIS="unixMillis",l.UNIX_SECONDS="unixSeconds",l.UNIX_TO_STR="unixToStr",l.UNIX_TO_TIME="unixToTime",l.UNIX_TO_TIME_STR="unixToTimeStr",l.UNLOGGED_PROPERTY="unloggedProperty",l.UNNEST="unnest",l.UNPIVOT_COLUMNS="unpivotColumns",l.UPDATE="update",l.UPPER="upper",l.UPPERCASE_COLUMN_CONSTRAINT="uppercaseColumnConstraint",l.USE="use",l.USER_DEFINED_FUNCTION="userDefinedFunction",l.USING_DATA="usingData",l.USING_TEMPLATE_PROPERTY="usingTemplateProperty",l.UTC_DATE="utcDate",l.UTC_TIME="utcTime",l.UTC_TIMESTAMP="utcTimestamp",l.UUID="uuid",l.VALUES="values",l.VAR="var",l.VARIADIC="variadic",l.VARIANCE="variance",l.VARIANCE_POP="variancePop",l.VAR_MAP="varMap",l.VECTOR_SEARCH="vectorSearch",l.VERSION="version",l.VIEW_ATTRIBUTE_PROPERTY="viewAttributeProperty",l.VOLATILE_PROPERTY="volatileProperty",l.WATERMARK_COLUMN_CONSTRAINT="watermarkColumnConstraint",l.WEEK="week",l.WEEK_OF_YEAR="weekOfYear",l.WEEK_START="weekStart",l.WHEN="when",l.WHENS="whens",l.WHERE="where",l.WIDTH_BUCKET="widthBucket",l.WINDOW="window",l.WINDOW_SPEC="windowSpec",l.WITH="with",l.WITHIN_GROUP="withinGroup",l.WITH_DATA_PROPERTY="withDataProperty",l.WITH_FILL="withFill",l.WITH_JOURNAL_TABLE_PROPERTY="withJournalTableProperty",l.WITH_OPERATOR="withOperator",l.WITH_PROCEDURE_OPTIONS="withProcedureOptions",l.WITH_SCHEMA_BINDING_PROPERTY="withSchemaBindingProperty",l.WITH_SYSTEM_VERSIONING_PROPERTY="withSystemVersioningProperty",l.WITH_TABLE_HINT="withTableHint",l.XML_ELEMENT="xmlElement",l.XML_GET="xmlGet",l.XML_KEY_VALUE_OPTION="xmlKeyValueOption",l.XML_NAMESPACE="xmlNamespace",l.XML_TABLE="xmlTable",l.XOR="xor",l.YEAR="year",l.YEAR_OF_WEEK="yearOfWeek",l.YEAR_OF_WEEK_ISO="yearOfWeekIso",l.ZERO_FILL_COLUMN_CONSTRAINT="zeroFillColumnConstraint",l.ZIPF="zipf",l))(kT||{}),Ok=(t=>(t.INCREMENTAL="incremental",t.FULL="full",t))(Ok||{}),Ol=(u=>(u.TABLE="table",u.VIEW="view",u.INDEX="index",u.SCHEMA="schema",u.DATABASE="database",u.FUNCTION="function",u.PROCEDURE="procedure",u.TRIGGER="trigger",u.SEQUENCE="sequence",u.TEMPORARY_VIEW="temporary view",u))(Ol||{}),Nk=(i=>(i.TABLE="table",i.VIEW="view",i.SCHEMA="schema",i.FUNCTION="function",i.PROCEDURE="procedure",i))(Nk||{}),Ik=(t=>(t.CONNECTION="connection",t.QUERY="query",t))(Ik||{}),yk=(r=>(r.CURSOR="cursor",r.VARIABLE="variable",r.TABLE="table",r.CONSTANT="constant",r))(yk||{}),dL=(i=>(i.SESSION="session",i.GLOBAL="global",i.LOCAL="local",i.PERSIST="persist",i.PERSIST_ONLY="persistOnly",i))(dL||{}),Ck=(t=>(t.BREADTH="breadth",t.DEPTH="depth",t))(Ck||{}),bk=(r=>(r.GENERATED="generated",r.STORED="stored",r.VIRTUAL="virtual",r.DEFAULT="default",r))(bk||{}),Pk=(s=>(s.TABLE="table",s.COLUMN="column",s.VIEW="view",s))(Pk||{}),wk=(a=>(a.PRIMARY_KEY="primaryKey",a.UNIQUE="unique",a.NOT_NULL="notNull",a.CHECK="check",a.DEFAULT="default",a.FOREIGN_KEY="foreignKey",a))(wk||{}),uO=(E=>(E.TABLE="table",E.VIEW="view",E.INDEX="index",E.SCHEMA="schema",E.DATABASE="database",E.FUNCTION="function",E.PROCEDURE="procedure",E.TRIGGER="trigger",E.SEQUENCE="sequence",E.CONSTRAINT="constraint",E.COLUMN="column",E))(uO||{}),Mk=(t=>(t.CONDITIONAL="conditional",t.UNCONDITIONAL="unconditional",t))(Mk||{}),Lk=(t=>(t.GRANT="grant",t.REVOKE="revoke",t))(Lk||{}),Kt=(u=>(u.INNER="inner",u.OUTER="outer",u.LEFT="left",u.RIGHT="right",u.FULL="full",u.CROSS="cross",u.SEMI="semi",u.ANTI="anti",u.STRAIGHT_JOIN="straightJoin",u.ARRAY="array",u))(Kt||{}),Dk=(r=>(r.USER="user",r.ROLE="role",r.GROUP="group",r.PUBLIC="public",r))(Dk||{}),_k=(t=>(t.SYSTEM_TIME="systemTime",t.TRANSACTION_TIME="transactionTime",t))(_k||{}),kk=(s=>(s.ROWS="rows",s.RANGE="range",s.GROUPS="groups",s))(kk||{}),Be=(_=>(_.ARRAY="array",_.AGGREGATEFUNCTION="aggregatefunction",_.SIMPLEAGGREGATEFUNCTION="simpleaggregatefunction",_.BIGDECIMAL="bigdecimal",_.BIGINT="bigint",_.BIGNUM="bignum",_.BIGSERIAL="bigserial",_.BINARY="binary",_.BIT="bit",_.BLOB="blob",_.BOOLEAN="boolean",_.BPCHAR="bpchar",_.CHAR="char",_.DATE="date",_.DATE32="date32",_.DATEMULTIRANGE="datemultirange",_.DATERANGE="daterange",_.DATETIME="datetime",_.DATETIME2="datetime2",_.DATETIME64="datetime64",_.DECIMAL="decimal",_.DECIMAL32="decimal32",_.DECIMAL64="decimal64",_.DECIMAL128="decimal128",_.DECIMAL256="decimal256",_.DECFLOAT="decfloat",_.DOUBLE="double",_.DYNAMIC="dynamic",_.ENUM="enum",_.ENUM8="enum8",_.ENUM16="enum16",_.FILE="file",_.FIXEDSTRING="fixedstring",_.FLOAT="float",_.GEOGRAPHY="geography",_.GEOGRAPHYPOINT="geographypoint",_.GEOMETRY="geometry",_.POINT="point",_.RING="ring",_.LINESTRING="linestring",_.MULTILINESTRING="multilinestring",_.POLYGON="polygon",_.MULTIPOLYGON="multipolygon",_.HLLSKETCH="hllsketch",_.HSTORE="hstore",_.IMAGE="image",_.INET="inet",_.INT="int",_.INT128="int128",_.INT256="int256",_.INT4MULTIRANGE="int4multirange",_.INT4RANGE="int4range",_.INT8MULTIRANGE="int8multirange",_.INT8RANGE="int8range",_.INTERVAL="interval",_.IPADDRESS="ipaddress",_.IPPREFIX="ipprefix",_.IPV4="ipv4",_.IPV6="ipv6",_.JSON="json",_.JSONB="jsonb",_.LIST="list",_.LONGBLOB="longblob",_.LONGTEXT="longtext",_.LOWCARDINALITY="lowcardinality",_.MAP="map",_.MEDIUMBLOB="mediumblob",_.MEDIUMINT="mediumint",_.MEDIUMTEXT="mediumtext",_.MONEY="money",_.NAME="name",_.NCHAR="nchar",_.NESTED="nested",_.NOTHING="nothing",_.NULL="null",_.NUMMULTIRANGE="nummultirange",_.NUMRANGE="numrange",_.NVARCHAR="nvarchar",_.OBJECT="object",_.RANGE="range",_.ROWVERSION="rowversion",_.SERIAL="serial",_.SET="set",_.SMALLDATETIME="smalldatetime",_.SMALLINT="smallint",_.SMALLMONEY="smallmoney",_.SMALLSERIAL="smallserial",_.STRUCT="struct",_.SUPER="super",_.TEXT="text",_.TINYBLOB="tinyblob",_.TINYTEXT="tinytext",_.TIME="time",_.TIMETZ="timetz",_.TIME_NS="timeNs",_.TIMESTAMP="timestamp",_.TIMESTAMPNTZ="timestampntz",_.TIMESTAMPLTZ="timestampltz",_.TIMESTAMPTZ="timestamptz",_.TIMESTAMP_S="timestampS",_.TIMESTAMP_MS="timestampMs",_.TIMESTAMP_NS="timestampNs",_.TINYINT="tinyint",_.TSMULTIRANGE="tsmultirange",_.TSRANGE="tsrange",_.TSTZMULTIRANGE="tstzmultirange",_.TSTZRANGE="tstzrange",_.UBIGINT="ubigint",_.UINT="uint",_.UINT128="uint128",_.UINT256="uint256",_.UMEDIUMINT="umediumint",_.UDECIMAL="udecimal",_.UDOUBLE="udouble",_.UNION="union",_.UNKNOWN="unknown",_.USERDEFINED="user-defined",_.USMALLINT="usmallint",_.UTINYINT="utinyint",_.UUID="uuid",_.VARBINARY="varbinary",_.VARCHAR="varchar",_.VARIANT="variant",_.VECTOR="vector",_.XML="xml",_.YEAR="year",_.TDIGEST="tdigest",_))(Be||{}),UT=(a=>(a.TABLE="table",a.VIEW="view",a.SCHEMA="schema",a.DATABASE="database",a.INDEX="index",a.COLUMN="column",a))(UT||{}),Uk=(s=>(s.STATISTICS="statistics",s.COMPUTE="compute",s.TABLE="table",s))(Uk||{}),qk=(s=>(s.ALL="all",s.DEFAULT="default",s.COLUMNS="columns",s))(qk||{}),vk=(t=>(t.PERCENT="percent",t.ROWS="rows",t))(vk||{}),Fk=(e=>(e.STATISTICS="statistics",e))(Fk||{}),Bk=(t=>(t.REF_UPDATE="refUpdate",t.STRUCTURE="structure",t))(Bk||{}),Gk=(r=>(r.PATH="path",r.EXISTS="exists",r.VALUE="value",r.QUERY="query",r))(Gk||{}),$k=(r=>(r.PATH="path",r.EXISTS="exists",r.VALUE="value",r.QUERY="query",r))($k||{}),Yk=(i=>(i.DATABASE="database",i.SCHEMA="schema",i.WAREHOUSE="warehouse",i.ROLE="role",i.CATALOG="catalog",i))(Yk||{}),Hk=(r=>(r.PRIMARY="primary",r.UNIQUE="unique",r.FULLTEXT="fulltext",r.SPATIAL="spatial",r))(Hk||{}),Vk=(t=>(t.LOCAL="local",t.REMOTE="remote",t))(Vk||{}),Wk=(r=>(r.HASH="hash",r.RANGE="range",r.LIST="list",r.REPLICATE="replicate",r))(Wk||{}),jk=(o=>(o.FLAT="flat",o.HASHED="hashed",o.RANGE_HASHED="rangeHashed",o.CACHE="cache",o.DIRECT="direct",o.IP_TRIE="ipTrie",o.POLYGON="polygon",o))(jk||{}),Jk=(r=>(r.DEFAULT="default",r.ALL="all",r.FALLBACK="fallback",r.LOCKING="locking",r))(Jk||{}),Xk=(r=>(r.ON_COMMIT="onCommit",r.ON_DEMAND="onDemand",r.START_WITH="startWith",r.NEXT="next",r))(Xk||{}),Nl=(c=>(c.POST_CREATE="postCreate",c.POST_NAME="postName",c.POST_SCHEMA="postSchema",c.POST_WITH="postWith",c.POST_ALIAS="postAlias",c.POST_EXPRESSION="postExpression",c.POST_INDEX="postIndex",c.UNSUPPORTED="unsupported",c))(Nl||{}),EO=(i=>(i.UNION="union",i.INTERSECT="intersect",i.EXCEPT="except",i.INNER="inner",i.OUTER="outer",i))(EO||{}),zk=(i=>(i.STRUCT="struct",i.VALUE="value",i.OBJECT="object",i.ALL="all",i.DISTINCT="distinct",i))(zk||{}),Kk=(r=>(r.SESSION="session",r.GLOBAL="global",r.LOCAL="local",r.VARIABLE="variable",r))(Kk||{}),Qk=(i=>(i.POSITIONAL="positional",i.NAMED="named",i.QUESTION="question",i.NUMERIC="numeric",i.DOLLAR="dollar",i))(Qk||{}),Zk=(t=>(t.START="start",t.END="end",t))(Zk||{}),AL=(s=>(s.LEADING="leading",s.TRAILING="trailing",s.BOTH="both",s))(AL||{});function hr(n,e){let t=_nullishCoalesce(e, () => ({}));for(let s of n){let r=t;for(let i of s)r[i]||(r[i]={}),r=r[i];r["\0"]=!0}return t}function Il(n,e){let t=Array.from(e);if(!t.length)return[0,n];let s=n;for(let r of t){if(!s[r])return[0,s];s=s[r]}return s["\0"]?[2,s]:[1,s]}function Mc(n,e,t=[]){let s=[],r=_nullishCoalesce(e, () => (Ii(n)-1));for(let[i,a]of Object.entries(n))r===1||typeof a!="object"||a===void 0?s.push([...t,i]):2<=r&&s.push(...Mc(a,r-1,[...t,i]));return s}function pg(n,e,t={}){let{raiseOnMissing:s=!0}=t,r=n;for(let[i,a]of e){if(typeof r!="object"||r===void 0){if(s)throw new cn(`Unknown ${i==="this"?"table":i}: ${a}`);return}let o=r[a];if(o===void 0||o===void 0){if(s)throw new cn(`Unknown ${i==="this"?"table":i}: ${a}`);return}r=o}return r}function hO(n,e,t){if(!e.length)return n;if(e.length===1)return n[e[0]]=t,n;let s=n;for(let r=0;r<e.length-1;r++)(!(e[r]in s)||typeof s[e[r]]!="object"||s[e[r]]===void 0)&&(s[e[r]]={}),s=s[e[r]];return s[e[e.length-1]]=t,n}function vH(n){if(n==null)return{};if(typeof n=="object"&&!Array.isArray(n))return n;if(typeof n=="string")return Object.fromEntries(n.split(",").map(e=>{let[t,s]=e.split(":").map(r=>r.trim());return[t,s]}));if(Array.isArray(n))return Object.fromEntries(n.map(e=>[e.trim(),void 0]));throw new Error(`Invalid mapping provided: ${typeof n}`)}function wc(n,e={}){let{dialect:t,isTable:s=!1,normalize:r=!0}=e,i=typeof n=="string"?Cl(n,{dialect:t}):n.copy();return r?(i.meta.isTable=s,W.getOrRaise(t).normalizeIdentifier(i)):i}var qT=class{get dialect(){}get empty(){return!0}hasColumn(e,t,s){let r=typeof t=="string"?t:t.name;return this.columnNames(e,s).includes(r)}getUdfType(e,t){return C.build("unknown")}},fL=class extends qT{constructor(e,t){super(),this.mapping=e||{},this.udfMapping=t||{},this.mappingTrie=hr(Mc(this.mapping,this.depth()).map(s=>[...s].reverse())),this.udfTrie=hr(Mc(this.udfMapping,this.udfDepth()).map(s=>[...s].reverse()))}get empty(){return Object.keys(this.mapping).length===0}depth(){return Ii(this.mapping)}udfDepth(){return Ii(this.udfMapping)}get supportedTableArgs(){if(!this._supportedTableArgs&&!this.empty){let e=this.depth();if(!e)this._supportedTableArgs=[];else if(1<=e&&e<=3)this._supportedTableArgs=TL.slice(0,e);else throw new cn(`Invalid mapping shape. Depth: ${e}`)}return this._supportedTableArgs||[]}tableParts(e){return[...e.parts].reverse().map(t=>t.name)}udfParts(e){let t=e.parent;return[...t instanceof me?[...t.flatten()].map(r=>r.name):[e.name]].reverse().slice(0,this.udfDepth())}findInTrie(e,t,s){let{raiseOnMissing:r}=s,[i,a]=Il(t,e);if(i!==0){if(i===1){let o=Mc(a);if(o.length===1)e.push(...o[0]);else{if(r){let c=e.join("."),p=o.map(u=>u.join(".")).join(", ");throw new cn(`Ambiguous mapping for ${c}: ${p}.`)}return}}return e}}find(e,t={}){let{raiseOnMissing:s=!0}=t,r=this.tableParts(e).slice(0,this.supportedTableArgs.length),i=this.findInTrie(r,this.mappingTrie,{raiseOnMissing:s});if(i)return this.nestedGet(i,void 0,{raiseOnMissing:s})}findUdf(e,t={}){let{raiseOnMissing:s=!1}=t,r=this.udfParts(e),i=this.findInTrie(r,this.udfTrie,{raiseOnMissing:s});if(!i)return;let a=[...i].reverse();return pg(this.udfMapping,i.map((o,c)=>[o,a[c]]),{raiseOnMissing:s})}nestedGet(e,t,s={}){let{raiseOnMissing:r=!0}=s,i=[...e].reverse();return pg(t||this.mapping,this.supportedTableArgs.map((a,o)=>[a,i[o]]),{raiseOnMissing:r})}},yl= exports.MappingSchema =class n extends Q(fL,qT){constructor(t,s={}){let r,i,a,o,c;if(t&&("schema"in t||"udfMapping"in t||"visible"in t||"dialect"in t||"normalize"in t)){let E=t;r=E.schema||{},i=E.visible,a=E.dialect,o=_nullishCoalesce(E.normalize, () => (!0)),c=E.udfMapping}else r=t||{},{visible:i,dialect:a,normalize:o=!0,udfMapping:c}=s;let p=a?W.getOrRaise(a):new W,u=c||{};super(o?n.normalizeSchemaStatic(r,p,{normalize:o}):r,o?n.normalizeUdfsStatic(u,p,{normalize:o}):u);this._typeCache={};this._depth=0;this.visible=i||{},this.normalize=o,this._dialect=p}static fromMappingSchema(t){return new n(t.mapping,{visible:t.visible,dialect:t.dialect,normalize:t.normalize,udfMapping:t.udfMapping})}get dialect(){return this._dialect}depth(){return!this.empty&&!this._depth&&(this._depth=super.depth()-1),this._depth}copy(t={}){return new n(_nullishCoalesce(t.schema, () => ({...this.mapping})),{visible:_nullishCoalesce(t.visible, () => ({...this.visible})),dialect:_nullishCoalesce(t.dialect, () => (this.dialect)),normalize:_nullishCoalesce(t.normalize, () => (this.normalize)),udfMapping:_nullishCoalesce(t.udfMapping, () => ({...this.udfMapping}))})}find(t,s={}){let{ensureDataTypes:r=!1}=s,i=super.find(t,s);return!r||typeof i!="object"||i===null?i:Object.fromEntries(Object.entries(i).map(([a,o])=>[a,typeof o=="string"?this.toDataType(o):o]))}addTable(t,s,r={}){let{dialect:i,normalize:a,matchDepth:o=!0}=r,c=this.normalizeTable(t,i,a);if(o&&!this.empty&&c.parts.length!==this.depth())throw new cn(`Table ${c.sql()} must match the schema's nesting level: ${this.depth()}.`);let p=Object.fromEntries(Object.entries(vH(s)).map(([g,A])=>[this.normalizeName(g,i,{isTable:!1,normalize:a}),A]));if(this.find(c,{raiseOnMissing:!1})&&!Object.keys(p).length)return;let E=this.tableParts(c);hO(this.mapping,[...E].reverse(),p),hr([E],this.mappingTrie)}columnNames(t,s={}){let{onlyVisible:r=!1,dialect:i,normalize:a}=s,o=this.normalizeTable(t,i,a),c=this.find(o);if(!c||typeof c!="object")return[];let p=Object.keys(c);if(!r||!Object.keys(this.visible).length)return p;let u=this.nestedGet(this.tableParts(o),this.visible,{raiseOnMissing:!1}),E=u instanceof Set?u:u||[];return p.filter(g=>E instanceof Set?E.has(g):E.includes(g))}getColumnType(t,s,r={}){let{dialect:i,normalize:a}=r,o=this.normalizeTable(t,i,a),c=this.normalizeName(typeof s=="string"?s:s.args.this,i,{isTable:!1,normalize:a}),p=this.find(o,{raiseOnMissing:!1});if(p&&typeof p=="object"){let u=p[c];if(u instanceof C)return u;if(typeof u=="string")return this.toDataType(u,i)}return C.build("unknown")}hasColumn(t,s,r){let{dialect:i,normalize:a}=r||{},o=this.normalizeTable(t,i,a),c=this.normalizeName(typeof s=="string"?s:s.args.this,i,{isTable:!1,normalize:a}),p=this.find(o,{raiseOnMissing:!1});return p?c in p:!1}getUdfType(t,s={}){let{dialect:r,normalize:i}=s,a=this.normalizeUdf(t,r,i),o=this.findInTrie(a,this.udfTrie,{raiseOnMissing:!1});if(!o)return C.build("unknown");let c=[...o].reverse(),p=pg(this.udfMapping,o.map((u,E)=>[u,c[E]]),{raiseOnMissing:!1});return p instanceof C?p:typeof p=="string"?this.toDataType(p,r):C.build("unknown")}normalizeUdf(t,s,r){let i=s?W.getOrRaise(s):this._dialect,a=_nullishCoalesce(r, () => (this.normalize)),o;if(typeof t=="string"){let p=ne(t,{dialect:i});if(p instanceof st)o=p;else if(p instanceof me){let u=[...p.flatten()],E=u[u.length-1];if(!(E instanceof st))throw new cn(`Unable to parse UDF from: ${JSON.stringify(t)}`);o=E}else throw new cn(`Unable to parse UDF from: ${JSON.stringify(t)}`)}else o=t;let c=this.udfParts(o);return a?c.map(p=>this.normalizeName(p,s,{isTable:!0,normalize:r})):c}toDataType(t,s){if(!this._typeCache[t]){let r=s?W.getOrRaise(s):this._dialect,i=C.build(t,{dialect:r,udt:r._constructor.SUPPORTS_USER_DEFINED_TYPES});_optionalChain([i, 'optionalAccess', _16 => _16.transform, 'call', _17 => _17(a=>r.normalizeIdentifier(a),{copy:!1})]),this._typeCache[t]=i}return this._typeCache[t]}normalizeTable(t,s,r){let i=s?W.getOrRaise(s):this._dialect,a=_nullishCoalesce(r, () => (this.normalize)),o=ne(t,{into:V,dialect:i,copy:a});if(a)for(let c of o.parts)c instanceof G&&c.replace(wc(c,{dialect:i,isTable:!0,normalize:a}));return o}normalizeName(t,s,r={}){let{isTable:i=!1,normalize:a}=r,o=s?W.getOrRaise(s):this._dialect;return wc(t,{dialect:o,isTable:i,normalize:_nullishCoalesce(a, () => (this.normalize))}).name}static normalizeSchemaStatic(t,s,r){let{normalize:i}=r;if(!i||!Object.keys(t).length)return t;let a={},o=Mc(t);if(!o.length)return t;for(let c of o){let p=pg(t,c.map(A=>[A,A]),{raiseOnMissing:!1});if(typeof p!="object"||p===void 0)throw new cn(`Table ${c.slice(0,-1).join(".")} must match the schema's nesting level: ${o[0].length}.`);let u=Object.entries(p);if(!u.length)throw new cn(`Table ${c.slice(0,-1).join(".")} must have at least one column`);let E=u[0][1];if(E!=null&&typeof E=="object"&&!(E instanceof h)){let A=Mc(p);throw new cn(`Table ${[...c,...A[0]||[]].join(".")} must match the schema's nesting level: ${o[0].length}.`)}let g=c.map(A=>wc(A,{dialect:s,isTable:!0,normalize:i}).name);for(let[A,x]of u)hO(a,[...g,wc(A,{dialect:s,normalize:i}).name],x)}return a}static normalizeUdfsStatic(t,s,r){let{normalize:i}=r;if(!i||!Object.keys(t).length)return t;let a={};for(let o of Mc(t,Ii(t))){let c=pg(t,o.map(u=>[u,u]),{raiseOnMissing:!1}),p=o.map(u=>wc(u,{dialect:s,isTable:!0,normalize:i}).name);hO(a,p,c)}return a}};function Qs(n,e={}){return n instanceof qT?n:new yl(n,e)}var Ce=class n{constructor(e){this._collected=!1;let{expression:t,sources:s,outerColumns:r,parent:i,scopeType:a="root",lateralSources:o,cteSources:c,canBeCorrelated:p}=e;this.expression=t,this.sources=s||new Map,this.lateralSources=o||new Map,this.cteSources=c||new Map;for(let[u,E]of this.lateralSources)this.sources.set(u,E);for(let[u,E]of this.cteSources)this.sources.set(u,E);this.outerColumns=r||[],this.parent=i,this.scopeType=a,this.subqueryScopes=[],this.derivedTableScopes=[],this.tableScopes=[],this.cteScopes=[],this.unionScopes=[],this.udtfScopes=[],this.canBeCorrelated=_nullishCoalesce(p, () => (!1)),this.clearCache()}clearCache(){this._collected=!1,this._rawColumns=void 0,this._tableColumns=void 0,this._stars=void 0,this._derivedTables=void 0,this._udtfs=void 0,this._tables=void 0,this._ctes=void 0,this._subqueries=void 0,this._selectedSources=void 0,this._columns=void 0,this._externalColumns=void 0,this._localColumns=void 0,this._joinHints=void 0,this._pivots=void 0,this._references=void 0,this._semiAntiJoinTables=void 0,this._columnIndex=void 0}branch(e){let{expression:t,scopeType:s,sources:r,cteSources:i,lateralSources:a,...o}=e,c=new Map(this.cteSources);if(i)for(let[p,u]of i)c.set(p,u);return new n({expression:t.unnest(),sources:r?new Map(r):void 0,parent:this,scopeType:s,cteSources:c,lateralSources:a?new Map(a):void 0,canBeCorrelated:this.canBeCorrelated||s==="subquery"||s==="udtf",...o})}collect(){this._tables=[],this._ctes=[],this._subqueries=[],this._derivedTables=[],this._udtfs=[],this._rawColumns=[],this._tableColumns=[],this._stars=[],this._joinHints=[],this._semiAntiJoinTables=new Set,this._columnIndex=new WeakSet;for(let e of this.walk({bfs:!1}))if(e!==this.expression)if(e instanceof me&&e.isStar)this._stars.push(e);else if(e instanceof k&&!(e instanceof Ml))this._columnIndex.add(e),e.args.this instanceof ye?this._stars.push(e):this._rawColumns.push(e);else if(e instanceof V&&!(e.parent instanceof yi)){let t=e.parent;if(t instanceof z){let s=t;(s.args.kind==="semi"||s.args.kind==="anti")&&this._semiAntiJoinTables.add(e.aliasOrName)}this._tables.push(e)}else if(e instanceof yi)this._joinHints.push(e);else if(e instanceof as)this._udtfs.push(e);else if(e instanceof Yt)this._ctes.push(e);else if(e instanceof ae){let t=tU(e);SL(e)&&t&&this._derivedTables.push(e)}else En.some(t=>e instanceof t)&&!tU(e)?this._subqueries.push(e):e instanceof Gn&&this._tableColumns.push(e);this._collected=!0}ensureCollected(){this._collected||this.collect()}walk(e={}){return Lc(this.expression,e)}find(...e){return Pl(this.expression,e,{bfs:!0})}findAll(...e){return Mr(this.expression,e,{bfs:!0})}replace(e,t){e.replace(t),this.clearCache()}get tables(){return this.ensureCollected(),_nullishCoalesce(this._tables, () => ([]))}get ctes(){return this.ensureCollected(),_nullishCoalesce(this._ctes, () => ([]))}get derivedTables(){return this.ensureCollected(),_nullishCoalesce(this._derivedTables, () => ([]))}get udtfs(){return this.ensureCollected(),_nullishCoalesce(this._udtfs, () => ([]))}get subqueries(){return this.ensureCollected(),_nullishCoalesce(this._subqueries, () => ([]))}get stars(){return this.ensureCollected(),_nullishCoalesce(this._stars, () => ([]))}get columnIndex(){return this.ensureCollected(),_nullishCoalesce(this._columnIndex, () => (new WeakSet))}get isSubquery(){return this.scopeType==="subquery"}get isDerivedTable(){return this.scopeType==="derivedTable"}get isUnion(){return this.scopeType==="union"}get isCte(){return this.scopeType==="cte"}get isRoot(){return this.scopeType==="root"}get isUdtf(){return this.scopeType==="udtf"}get isCorrelatedSubquery(){return!!(this.canBeCorrelated&&0<this.externalColumns.length)}get columns(){if(this._columns===void 0){this.ensureCollected();let e=_nullishCoalesce(this._rawColumns, () => ([])),t=[];for(let r of[...this.subqueryScopes,...this.udtfScopes,...this.derivedTableScopes.filter(i=>i.canBeCorrelated)])t.push(...r.externalColumns);let s=new Set(this.expression.namedSelects);this._columns=[];for(let r of[...e,...t]){let i=r.findAncestor($,un,ke,$t,Dr,V,ye,ct);(!i||r.table||i instanceof $||i instanceof V&&!(i.args.this instanceof d)||(i instanceof ke||i instanceof ct)&&(i.parent instanceof Fe||i.parent instanceof Cs||!(i.parent instanceof $)||!s.has(r.name))||i instanceof ye&&r.argKey!=="except")&&this._columns.push(r)}}return this._columns}get tableColumns(){return this._tableColumns===void 0&&this.ensureCollected(),_nullishCoalesce(this._tableColumns, () => ([]))}get externalColumns(){return this._externalColumns===void 0&&(this._externalColumns=this.columns.filter(e=>!this.sources.has(e.table)&&!this.semiOrAntiJoinTables.has(e.table))),this._externalColumns}get localColumns(){if(this._localColumns===void 0){let e=new Set(this.externalColumns);this._localColumns=this.columns.filter(t=>!e.has(t))}return this._localColumns}get unqualifiedColumns(){return this.columns.filter(e=>!e.table)}get joinHints(){return this._joinHints===void 0?[]:this._joinHints}get pivots(){if(!this._pivots){this._pivots=[];for(let[,e]of this.references){let t=e.args.pivots;t&&Array.isArray(t)&&this._pivots.push(...t)}}return this._pivots}get semiOrAntiJoinTables(){return this._semiAntiJoinTables||new Set}get references(){if(this._references===void 0){this._references=[];for(let e of this.tables)this._references.push([e.aliasOrName,e]);for(let e of[...this.derivedTables,...this.udtfs]){let t=mL(e),s=e.getArgKey("pivots")?e:e.unnest();this._references.push([t,s])}}return this._references}get selectedSources(){if(this._selectedSources===void 0){this._selectedSources={};for(let[e,t]of this.references){if(this.semiOrAntiJoinTables.has(e))continue;if(e in this._selectedSources)throw new is(`Alias already used: ${e}`);let s=this.sources.get(e);s!==void 0&&(this._selectedSources[e]=[t,s])}}return this._selectedSources}sourceColumns(e){return this.columns.filter(t=>t.table===e)}renameSource(e,t){let s=e||"",r=this.sources.get(s);r!==void 0&&(this.sources.delete(s),this.sources.set(t,r))}addSource(e,t){this.sources.set(e,t),this.clearCache()}removeSource(e){this.sources.delete(e),this.clearCache()}*traverse(){let e=[this],t=[];for(;0<e.length;){let s=e.pop();t.push(s),e.push(...s.cteScopes,...s.unionScopes,...s.tableScopes,...s.subqueryScopes)}for(let s=t.length-1;0<=s;s--)yield t[s]}refCount(){let e=new Map;for(let t of this.traverse()){for(let[,s]of Object.values(t.selectedSources))s instanceof n&&e.set(s,(e.get(s)||0)+1);for(let s of t.semiOrAntiJoinTables){let r=t.sources.get(s);r!==void 0&&r instanceof n&&e.set(r,(e.get(r)||0)+1)}}return e}toString(){return`<Scope ${this.scopeType}>`}};function _t(n){if(![ce,ln,Lr].some(s=>n instanceof s))return[];let t=[];for(let s of bl(new Ce({expression:n})))t.push(s);return t}function*bl(n){let e=n.expression;if(e instanceof $)yield*eU(n);else if(e instanceof be){yield*gO(n),yield*FH(n);return}else if(e instanceof ae)n.isRoot?yield*eU(n):yield*rU(n);else if(e instanceof V)yield*sU(n);else if(e instanceof as)yield*BH(n);else if(e instanceof ln){e.args.expression instanceof ce&&(yield*gO(n),yield*bl(new Ce({expression:e.args.expression,cteSources:n.cteSources})));return}else if(e instanceof Lr){yield*gO(n);for(let t of Mr(e,[ce])){let s=t.parent;s&&!(s instanceof Yt)&&!(s instanceof ae)&&(yield*bl(new Ce({expression:t,cteSources:n.cteSources})))}return}else return;yield n}function*eU(n){yield*gO(n),yield*sU(n),yield*rU(n)}function*FH(n){let e,t=[n],s=n.expression,r=[s.right,s.left];for(;0<r.length;){let i=r.pop(),a=t[t.length-1],o=a.branch({expression:i,outerColumns:a.outerColumns,scopeType:"union"});if(i instanceof be){yield*gO(o),t.push(o),r.push(i.right),r.push(i.left);continue}let c;for(let p of bl(o))yield p,c=p;e&&c?(t.pop(),a.unionScopes=[e,c],e=a,yield a):e=c}}function*gO(n){let e=new Map;for(let t of n.ctes){let s=t.alias,r=n.expression.args.with;if(r&&D(r,ve)&&r.args.recursive){let o=t.args.this;o instanceof be&&o.args.this&&e.set(s,n.branch({expression:o.args.this,scopeType:"cte"}))}let i=t.args.this;if(!i)continue;let a;for(let o of bl(n.branch({expression:i,cteSources:e,outerColumns:t.aliasColumnNames||[],scopeType:"cte"})))yield o,a=o;a&&(e.set(s,a),n.cteScopes.push(a))}for(let[t,s]of e)n.sources.set(t,s),n.cteSources.set(t,s)}function SL(n){return!!(n instanceof ae&&(n.alias||En.some(e=>n.args.this instanceof e)))}function tU(n){let e=n.parent;for(;e instanceof ae;)e=e.parent;return e instanceof Ge||e instanceof z}function mL(n){let e=n.getArgKey("alias"),t=n.alias;return!t&&e instanceof ie&&e.columns.length===1&&(t=e.columns[0].name),t}function*sU(n){let e=new Map,t=[],s=n.expression.getArgKey("from");_optionalChain([s, 'optionalAccess', _18 => _18.args, 'access', _19 => _19.this])&&t.push(s.args.this);for(let i of n.expression.getArgKey("joins")||[])i.args.this&&t.push(i.args.this);n.expression instanceof V&&t.push(n.expression);for(let i of n.expression.getArgKey("laterals")||[])t.push(i);let r=0;for(;r<t.length;){let i=t[r++];if(i instanceof wl&&(i=i.getArgKey("this")),i instanceof V){let u=i.name,E=i.aliasOrName;if(n.sources.has(u)&&!i.db){let g=i.args.pivots;g&&0<g.length?e.set(g[0].alias,i):e.set(E,n.sources.get(u))}else e.has(E)?e.set(pn(Array.from(e.keys()),u),i):e.set(E,i);if(i!==n.expression)for(let g of i.args.joins||[])D(g.args.this,h)&&t.push(g.args.this);continue}if(!(i instanceof bi))continue;let a,o,c;if(i instanceof as)a=e,o="udtf",c=n.udtfScopes;else if(i instanceof ae&&SL(i)){a=void 0,o="derivedTable",c=n.derivedTableScopes;for(let u of i.getArgKey("joins")||[])u.args.this&&t.push(u.args.this)}else{t.push(i.getArgKey("this"));for(let u of i.getArgKey("joins")||[])u.args.this&&t.push(u.args.this);continue}let p;for(let u of bl(n.branch({expression:i,lateralSources:a,outerColumns:i.aliasColumnNames||[],scopeType:o})))yield u,p=u,e.set(mL(i),p);p&&(c.push(p),n.tableScopes.push(p))}for(let[i,a]of e)n.sources.set(i,a)}function*rU(n){for(let e of n.subqueries){let t;for(let s of bl(n.branch({expression:e,scopeType:"subquery"})))yield s,t=s;t&&n.subqueryScopes.push(t)}}function*BH(n){let e;n.expression instanceof Pe?e=_nullishCoalesce(n.expression.args.expressions, () => ([])):n.expression instanceof kt&&n.expression.args.this?e=[n.expression.args.this]:e=[];let t=new Map;for(let s of e){if(!(s instanceof ae))continue;let r;for(let i of bl(n.branch({expression:s,scopeType:"subquery",outerColumns:s.aliasColumnNames||[]})))yield i,r=i,t.set(mL(s),i);r&&n.subqueryScopes.push(r)}for(let[s,r]of t)n.sources.set(s,r)}function Ci(n){let e=_t(n);return b(e,-1)}function*Lc(n,e={}){let{bfs:t=!0,prune:s}=e,r=!1;for(let i of n.walk({bfs:t,prune:a=>r||(s?s(a):!1)}))if(r=!1,yield i,i!==n&&(i instanceof Yt||(i.parent instanceof Ge||i.parent instanceof z)&&SL(i)||i.parent instanceof as&&i instanceof ce||En.some(a=>i instanceof a))&&(r=!0,i instanceof ae||i instanceof as))for(let a of["joins","laterals","pivots"]){let o=i.getArgKey(a);if(Array.isArray(o))for(let c of o)yield*Lc(c,{bfs:t})}}function Mr(n,e,t={}){let{bfs:s=!0}=t,r=[];for(let i of Lc(n,{bfs:s}))for(let a of e)if(i instanceof a){r.push(i);break}return r}function Pl(n,e,t={}){let{bfs:s=!0}=t;for(let r of Lc(n,{bfs:s}))for(let i of pe(e))if(r instanceof i)return r}var GH=new Set(["EPOCH_SECOND","EPOCH_MILLISECOND","EPOCH_MICROSECOND","EPOCH_NANOSECOND","NANOSECOND"]);function os(n,e={}){let{schema:t,expressionMetadata:s,coercesTo:r,dialect:i,overwriteTypes:a=!0}=e,o=Qs(t,{dialect:i});return new $n({schema:o,expressionMetadata:s,coercesTo:r,overwriteTypes:a}).annotate(n)}function nU(n,e){let t=n.name,s=vT(t);return s&&FT(e)?"date":s||AO(t)?"datetime":"unknown"}function iU(n,e){if(!FT(e))return"datetime";let t=_optionalChain([n, 'access', _20 => _20.type, 'optionalAccess', _21 => _21.args, 'access', _22 => _22.this]);return typeof t=="string"?t:t instanceof G?t.args.this:"unknown"}function $H(n){return(e,t)=>n(t,e)}function YH(n){let e=new Rl;for(let[[t,s],r]of n)e.set(t,s,r),e.set(s,t,$H(r));return e}var aU,oU,cU,dO;cU=[O],oU=[O],aU=[O];var Dc=class Dc{constructor(e){this.schema=void 0;this.dialect=void 0;this.overwriteTypes=void 0;this.expressionMetadata=void 0;this.coercesTo=void 0;this.binaryCoercions=void 0;this.visited=void 0;this.nullExpressions=void 0;this.supportsNullType=void 0;this.setopColumnTypes=void 0;this.scopeSelects=void 0;let{schema:t,expressionMetadata:s,coercesTo:r,binaryCoercions:i,overwriteTypes:a=!0}=e;if(this.schema=t,this.dialect=t.dialect||new W,this.overwriteTypes=a,this.expressionMetadata=_nullishCoalesce(s, () => (this.dialect._constructor.EXPRESSION_METADATA)),r)this.coercesTo=r;else{let o=this.dialect._constructor.COERCES_TO;o instanceof Map&&0<o.size?this.coercesTo=o:!(o instanceof Map)&&0<Object.keys(o).length?this.coercesTo=new Map(Object.entries(o).map(([c,p])=>[c,new Set(p)])):this.coercesTo=Dc.COERCES_TO}this.binaryCoercions=_nullishCoalesce(i, () => (Dc.BINARY_COERCIONS)),this.visited=new Set,this.nullExpressions=new Map,this.supportsNullType=this.dialect._constructor.SUPPORTS_NULL_TYPE,this.setopColumnTypes=new Map,this.scopeSelects=new Map}static get NESTED_TYPES(){return new Set(["array"])}static get COERCES_TO(){let e=new Map,t=["text","nvarchar","varchar","nchar","char"],s=["decfloat","double","float","bigdecimal","decimal","bigint","int","smallint","tinyint"],r=["timestampltz","timestamptz","timestamp","datetime","date"];for(let i of[t,s,r]){let a=new Set;for(let o of i)e.set(o,new Set(a)),a.add(o)}return e}static get BINARY_COERCIONS(){return YH((()=>{let e=new Rl;for(let t of C.TEXT_TYPES)e.set(t,"interval",(s,r)=>nU(s,r.unit));for(let t of C.TEXT_TYPES)for(let s of C.NUMERIC_TYPES)e.set(t,s,(r,i)=>{let a=_optionalChain([r, 'access', _23 => _23.type, 'optionalAccess', _24 => _24.args, 'access', _25 => _25.this]);return C.NUMERIC_TYPES.has(a)?a:_optionalChain([i, 'access', _26 => _26.type, 'optionalAccess', _27 => _27.args, 'access', _28 => _28.this])});return e.set("date","interval",(t,s)=>iU(t,s.unit)),e})())}clear(){this.visited.clear(),this.nullExpressions.clear(),this.setopColumnTypes.clear(),this.scopeSelects.clear()}annotate(e,t={}){let{annotateScope:s=!0}=t;if(s)for(let i of _t(e))this.annotateScope(i);this.annotateExpression(e);let r=this.dialect._constructor.DEFAULT_NULL_TYPE;for(let[,i]of this.nullExpressions)i.type=r;return e}annotateScope(e){if(this.schema instanceof yl)for(let t of e.tableColumns){let s=e.sources.get(t.name);if(s instanceof V){let r=this.schema.find(s,{raiseOnMissing:!1,ensureDataTypes:!0});if(typeof r!="object"||!r)continue;let i=new C({this:"struct",expressions:Object.entries(r).map(([a,o])=>new we({this:K(a),kind:o})),nested:!0});this.setType(t,i)}else s instanceof Ce&&s.expression instanceof ce&&(s.expression.meta.queryType||C.build("unknown")).isType("struct")&&this.setType(t,s.expression.meta.queryType)}if(this.annotateExpression(e.expression,e),this.dialect._constructor.QUERY_RESULTS_ARE_STRUCTS&&e.expression instanceof ce){let t=new C({this:"struct",expressions:e.expression.selects.map(s=>new we({this:K(s.outputName),kind:s.type instanceof h?s.type.name:s.type||""})),nested:!0});_optionalChain([t, 'access', _29 => _29.args, 'access', _30 => _30.expressions, 'optionalAccess', _31 => _31.some, 'call', _32 => _32(s=>{let r=s.args.kind;return r?typeof r=="string"?r==="unknown":r.isType("unknown"):!0})])||(e.expression.meta.queryType=t)}}getScopeSelects(e){let t=this.scopeSelects.get(e);if(t!==void 0)return t;let s=new Map;for(let[r,i]of e.sources){if(!(i instanceof Ce))continue;let a=i.expression;if(a instanceof as&&!(a instanceof _c)){let o=[];if(a instanceof kt){let p=a.args.this;p instanceof qt&&(o=[p.args.this])}else if(a instanceof Pe)o=[a];else{let p=b(_nullishCoalesce(a.args.expressions, () => ([])),0);p&&(o=p instanceof h?p.args.expressions:[])}if(o.length===0)continue;let c=a.aliasColumnNames;if(a instanceof Pe&&a.type instanceof h&&a.type.isType("struct")){let p={};for(let u of a.type.args.expressions||[]){let E=u.name,g=u.args.kind;E&&(p[E]=g)}s.set(r,p)}else{let p={};for(let u=0;u<c.length&&u<o.length;u++){let E=o[u].type;p[c[u]]=D(E,C)||D(E,we)?E:void 0}s.set(r,p)}}else if(a instanceof be&&D(a.left,ce)&&D(a.right,ce)&&a.left.selects.length===a.right.selects.length)s.set(r,this.getSetopColumnTypes(a));else{let o={};for(let c of a.selects){let p=c.type;o[c.aliasOrName]=D(p,C)||D(p,we)?p:void 0}s.set(r,o)}}return this.scopeSelects.set(e,s),s}getSetopColumnTypes(e){let t=this.setopColumnTypes.get(e);if(t!==void 0)return t;let s={},r=e.left,i=e.right;if(!D(r,ce)||!D(i,ce)||!r.selects.length||!i.selects.length||r.selects.length!==i.selects.length)return s;for(let a of e.walk({prune:o=>!(o instanceof be)&&!(o instanceof ae)})){if(!(a instanceof be))continue;let o,c=a.left,p=a.right;if(ue(c,ce),ue(p,ce),a.args.byName){let u={};for(let E of p.selects){let g=E.type;u[E.aliasOrName]=D(g,C)||D(g,we)?g:void 0}o={};for(let E of c.selects){let g=E.type,A=_nullishCoalesce((D(g,C)?g:void 0), () => ("unknown")),x=_nullishCoalesce(u[E.aliasOrName], () => ("unknown"));o[E.aliasOrName]=this.maybeCoerce(A,x)}}else{o={};for(let u=0;u<c.selects.length;u++){let E=c.selects[u],g=p.selects[u],A=E.type,x=g.type,m=_nullishCoalesce((D(A,C)?A:void 0), () => ("unknown")),N=_nullishCoalesce((D(x,C)?x:void 0), () => ("unknown"));o[E.aliasOrName]=this.maybeCoerce(m,N)}}for(let[u,E]of Object.entries(o)){let g=_nullishCoalesce(s[u], () => ("null"));s[u]=this.maybeCoerce(E,g)}}return this.setopColumnTypes.set(e,s),s}annotateExpression(e,t){let s=[[e,!1]];for(;0<s.length;){let[r,i]=s.pop();if(this.visited.has(r)||!this.overwriteTypes&&r.type&&!r.isType("unknown"))continue;if(!i){s.push([r,!0]);for(let o of r.iterExpressions())s.push([o,!1]);continue}if(t&&r instanceof k&&r.args.table){let o,c=t;for(;c&&!o;)o=c.sources.get(r.table),o||(c=c.parent);if(o instanceof V)this.setType(r,_optionalChain([this, 'access', _33 => _33.schema, 'access', _34 => _34.getColumnType, 'optionalCall', _35 => _35(o,r)]));else if(o){let p=c?_optionalChain([this, 'access', _36 => _36.getScopeSelects, 'call', _37 => _37(c), 'access', _38 => _38.get, 'call', _39 => _39(r.table), 'optionalAccess', _40 => _40[r.name]]):void 0;if(p)this.setType(r,p);else if(o.expression instanceof Pe){let u=o.expression.type;this.setType(r,D(u,C)?u:void 0)}else this.setType(r,"unknown")}else this.setType(r,"unknown");_optionalChain([r, 'access', _41 => _41.type, 'optionalAccess', _42 => _42.getArgKey, 'call', _43 => _43("nullable")])===!1&&(r.meta.nonnull=!0);continue}let a=this.expressionMetadata.get(r._constructor);if(a){if(a.annotator){a.annotator(this,r);continue}if(a.returns!==void 0){this.setType(r,a.returns);continue}}if(r instanceof fs){this.annotateBracket(r);continue}if(r instanceof Y){this.annotateBinary(r);continue}if(r instanceof Zs){this.annotateUnary(r);continue}this.setType(r,"unknown")}}maybeCoerce(e,t){let s;if(e instanceof C){if(e.args.expressions&&0<e.args.expressions.length)return e;s=e.args.this}else s=_nullishCoalesce(e, () => ("unknown"));let r;if(t instanceof C){if(t.args.expressions&&0<t.args.expressions.length)return t;r=t.args.this}else r=_nullishCoalesce(t, () => ("unknown"));return s==="unknown"||r==="unknown"?"unknown":s==="null"?r:r==="null"?s:_optionalChain([this, 'access', _44 => _44.coercesTo, 'access', _45 => _45.get, 'call', _46 => _46(s), 'optionalAccess', _47 => _47.has, 'call', _48 => _48(r)])?r:s}setType(e,t){let s=e.type;if(e.type=_nullishCoalesce(t, () => ("unknown")),this.visited.add(e),!this.supportsNullType&&_optionalChain([e, 'access', _49 => _49.type, 'optionalAccess', _50 => _50.args, 'access', _51 => _51.this])==="null"?this.nullExpressions.set(e,e):_optionalChain([s, 'optionalAccess', _52 => _52.isType, 'call', _53 => _53("null")])&&this.nullExpressions.delete(e),e instanceof k&&e.isType("json")&&e.meta.dotParts){let i=e.meta.dotParts[Symbol.iterator](),a=e.parent;for(;a instanceof me;){let o=i.next();o.done||a.setArgKey("expression",K(o.value,{quoted:!0})),a=a.parent}delete e.meta.dotParts}return e}annotateBinary(e){let t=e.left,s=e.right;if(!t||!s){this.setType(e);return}let r=_optionalChain([t, 'access', _54 => _54.type, 'optionalAccess', _55 => _55.args, 'access', _56 => _56.this, 'optionalAccess', _57 => _57.toString, 'call', _58 => _58()]),i=_optionalChain([s, 'access', _59 => _59.type, 'optionalAccess', _60 => _60.args, 'access', _61 => _61.this, 'optionalAccess', _62 => _62.toString, 'call', _63 => _63()]);if(e instanceof We||e instanceof Ve)this.setType(e,"boolean");else{let a=this.binaryCoercions.get(r,i);a?this.setType(e,a(t,s)):this.annotateByArgs(e,[t,s])}(e instanceof Ut||t.meta.nonnull===!0&&s.meta.nonnull===!0)&&(e.meta.nonnull=!0)}annotateUnary(e){if(e instanceof rt)this.setType(e,"boolean");else{let r=_optionalChain([e, 'access', _64 => _64.args, 'access', _65 => _65.this, 'optionalAccess', _66 => _66.type]);this.setType(e,r)}_optionalChain([e, 'access', _67 => _67.args, 'access', _68 => _68.this, 'optionalAccess', _69 => _69.meta, 'access', _70 => _70.nonnull])===!0&&(e.meta.nonnull=!0)}annotateLiteral(e){e.args.isString?this.setType(e,"varchar"):e.isInteger?this.setType(e,"int"):this.setType(e,"double"),e.meta.nonnull=!0}annotateByArgs(e,t,s={}){let{promote:r=!1,array:i=!1}=s,a=null,o=null,c;e:for(let u of t){let E;if(typeof u=="string"){let g=e.args[u];E=pe(g)}else Array.isArray(u)?E=u:E=[u];for(let g of E){if(!(g instanceof h))continue;let A=g.type;if(!A)continue;let x=D(A,C)||D(A,we)?A:void 0;if(x){if(x.getArgKey("nested")){c=x;break e}g instanceof w?a=this.maybeCoerce(_nullishCoalesce(a, () => (x)),x):o=this.maybeCoerce(_nullishCoalesce(o, () => (x)),x)}}}let p;if(c)p=c;else if(a!==null&&o!==null){if(this.dialect._constructor.PRIORITIZE_NON_LITERAL_TYPES){let u=a instanceof C?a.args.this:a,E=o instanceof C?o.args.this:o;(C.INTEGER_TYPES.has(u)&&C.INTEGER_TYPES.has(E)||C.REAL_TYPES.has(u)&&C.REAL_TYPES.has(E))&&(p=o)}}else p=_nullishCoalesce(_nullishCoalesce(a, () => (o)), () => ("unknown"));if(this.setType(e,_nullishCoalesce(p, () => (this.maybeCoerce(_nullishCoalesce(o, () => (void 0)),_nullishCoalesce(a, () => (void 0)))))),r){let u=_optionalChain([e, 'access', _71 => _71.type, 'optionalAccess', _72 => _72.args, 'access', _73 => _73.this]);C.INTEGER_TYPES.has(u)?this.setType(e,"bigint"):C.FLOAT_TYPES.has(u)&&this.setType(e,"double")}if(i){let u=_nullishCoalesce(_optionalChain([e, 'access', _74 => _74.type, 'optionalAccess', _75 => _75.copy, 'call', _76 => _76()]), () => (new C({this:"unknown"})));this.setType(e,new C({this:"array",expressions:[u],nested:!0}))}}annotateTimeunit(e){let t=e.args.this;if(!_optionalChain([t, 'optionalAccess', _77 => _77.type])){this.setType(e,"unknown");return}let s=t.type.args.this,r;if(C.TEXT_TYPES.has(s)){let i=e.unit;r=nU(t,i)}else if(C.TEMPORAL_TYPES.has(s)){let i=e.unit;r=iU(t,i)}else r="unknown";this.setType(e,r)}annotateBracket(e){let t=b(_nullishCoalesce(e.args.expressions, () => ([])),0),s=e.args.this;if(t instanceof Pi){let r=s.type;this.setType(e,D(r,C)?r:void 0)}else if(_optionalChain([s, 'access', _78 => _78.type, 'optionalAccess', _79 => _79.isType, 'call', _80 => _80("array")])){let r=b(_nullishCoalesce(s.type.args.expressions, () => ([])),0);this.setType(e,r)}else if(s instanceof Eo||s instanceof gr){let r=s.keys;if(t){let i=r.findIndex(a=>a instanceof h&&a.equals(t));if(0<=i){let a=s.values,o=b(a,i),c=o instanceof h?o.type:void 0;this.setType(e,D(c,C)?c:void 0)}else this.setType(e,"unknown")}else this.setType(e,"unknown")}else this.setType(e,"unknown")}annotateDiv(e){let t=e.left,s=e.right,r=_optionalChain([t, 'optionalAccess', _81 => _81.type, 'optionalAccess', _82 => _82.args, 'access', _83 => _83.this]),i=_optionalChain([s, 'optionalAccess', _84 => _84.type, 'optionalAccess', _85 => _85.args, 'access', _86 => _86.this]);if(e.args.typed&&C.INTEGER_TYPES.has(r)&&C.INTEGER_TYPES.has(i))this.setType(e,"bigint");else{this.setType(e,this.maybeCoerce(r,i));let a=_optionalChain([e, 'access', _87 => _87.type, 'optionalAccess', _88 => _88.args, 'access', _89 => _89.this]);if(!C.REAL_TYPES.has(a)){let o=e.type;this.setType(e,this.maybeCoerce(D(o,C)?o:void 0,"double"))}}}annotateDot(e){this.setType(e);let t=e.args.expression;if(t instanceof st){let r=t.type;this.setType(e,D(r,C)?r:void 0);return}let s=_optionalChain([e, 'access', _90 => _90.args, 'access', _91 => _91.this, 'optionalAccess', _92 => _92.type]);if(wi(s,"struct")){for(let r of _optionalChain([s, 'optionalAccess', _93 => _93.args, 'access', _94 => _94.expressions])||[])if(r.name===_optionalChain([t, 'optionalAccess', _95 => _95.name])){let i=r.args.kind;this.setType(e,i);break}}}annotateExtract(e){let t=_optionalChain([e, 'access', _96 => _96.name, 'optionalAccess', _97 => _97.toUpperCase, 'call', _98 => _98()]);t==="TIME"?this.setType(e,"time"):t==="DATE"?this.setType(e,"date"):t&&GH.has(t)?this.setType(e,"bigint"):this.setType(e,"int")}annotateExplode(e){let t=e.args.this,s=b(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _99 => _99.type, 'optionalAccess', _100 => _100.args, 'access', _101 => _101.expressions]), () => ([])),0);this.setType(e,s)}annotateUnnest(e){let t=b(_nullishCoalesce(e.args.expressions, () => ([])),0),s;t instanceof h&&t.isType("array")&&(s=b(_nullishCoalesce(_optionalChain([t, 'access', _102 => _102.type, 'optionalAccess', _103 => _103.args, 'access', _104 => _104.expressions]), () => ([])),0)),this.setType(e,s)}annotateSubquery(e){let t=e.unnest();if(t instanceof ce){let s=t.selects;if(s.length===1){let r=s[0].type;this.setType(e,D(r,C)||D(r,we)?r:void 0);return}}this.setType(e,"unknown")}annotateStructValue(e){let t,s=e.type,r=D(s,C)||D(s,we)?s:void 0,i=e.args.alias;if(i instanceof h)t=i.copy();else if(e.args.expression instanceof h){t=_optionalChain([e, 'access', _105 => _105.args, 'access', _106 => _106.this, 'optionalAccess', _107 => _107.copy, 'call', _108 => _108()]);let a=_optionalChain([e, 'access', _109 => _109.args, 'access', _110 => _110.expression, 'optionalAccess', _111 => _111.type]);r=D(a,C)||D(a,we)?a:void 0}else e instanceof k&&(t=_optionalChain([e, 'access', _112 => _112.args, 'access', _113 => _113.this, 'optionalAccess', _114 => _114.copy, 'call', _115 => _115()]));return D(r,C)&&r.isType("unknown")?null:t?new we({this:t,kind:r}):_nullishCoalesce(r, () => ("unknown"))}annotateStruct(e){let t=[];for(let s of e.args.expressions){let r=this.annotateStructValue(s);if(r===null){this.setType(e);return}t.push(r)}this.setType(e,new C({this:"struct",expressions:t,nested:!0}))}annotateMap(e){let t,s;if(e instanceof gr)t=e.args.keys,s=e.args.values;else{let i=e.args.keys,a=e.args.values;t=_optionalChain([i, 'optionalAccess', _116 => _116[0]])instanceof Ne?i[0]:void 0,s=_optionalChain([a, 'optionalAccess', _117 => _117[0]])instanceof Ne?a[0]:void 0}let r=new C({this:"map"});if(t instanceof Ne&&s instanceof Ne){let i=b(_nullishCoalesce(_optionalChain([t, 'access', _118 => _118.type, 'optionalAccess', _119 => _119.args, 'access', _120 => _120.expressions]), () => ([])),0),a=b(_nullishCoalesce(_optionalChain([s, 'access', _121 => _121.type, 'optionalAccess', _122 => _122.args, 'access', _123 => _123.expressions]), () => ([])),0),o=i instanceof C?i.args.this:i,c=a instanceof C?a.args.this:a;o!=="unknown"&&c!=="unknown"&&(r.setArgKey("expressions",[_nullishCoalesce(i, () => (new C({this:"unknown"}))),_nullishCoalesce(a, () => (new C({this:"unknown"})))]),r.setArgKey("nested",!0))}this.setType(e,r)}annotateToMap(e){let t=new C({this:"map"}),s=e.args.this;if(_optionalChain([s, 'optionalAccess', _124 => _124.isType, 'call', _125 => _125("struct")])&&s.type instanceof h)for(let r of s.type.args.expressions||[]){let i=r.args.kind,a=i instanceof C?i.args.this:i;if(a!=="unknown"){let o=C.build("varchar");t.setArgKey("expressions",[...o?[o]:[],i instanceof C?i:new C({this:_nullishCoalesce(a, () => ("unknown"))})]),t.args.nested=!0;break}}this.setType(e,t)}annotateByArrayElement(e){let t=e.args.this;if(_optionalChain([t, 'optionalAccess', _126 => _126.type, 'optionalAccess', _127 => _127.isType, 'call', _128 => _128("array")])){let s=b(_nullishCoalesce(t.type.args.expressions, () => ([])),0);this.setType(e,_nullishCoalesce(s, () => ("unknown")))}else this.setType(e,"unknown")}};dO=re(null),T(dO,10,"NESTED_TYPES",cU,Dc),T(dO,10,"COERCES_TO",oU,Dc),T(dO,10,"BINARY_COERCIONS",aU,Dc),te(dO,Dc),se(dO,3,Dc);var $n=Dc;function RL(n,e={}){let{dnf:t=!1,maxDistance:s=128}=e,r=new ug({annotateNewExpressions:!1}),i=[];for(let a of n.walk({prune:o=>o instanceof We}))a instanceof We&&i.push(a);for(let a of i){if(Mi(a,{dnf:t}))continue;let o=a===n,c=a.copy();a.transform(u=>r.rewriteBetween(u),{copy:!1});let p=OL(a,{dnf:t,max:s});if(s<p)return n;try{let u=yw(a,E=>pU(E,{dnf:t,maxDistance:s,simplifier:r}));a=a.replace(u)}catch(u){if(u instanceof is)return a.replace(c),o?c:n;throw u}o&&(n=a)}return n}function Mi(n,e={}){let{dnf:t=!1}=e,[s,r]=t?[Oe,pt]:[pt,Oe];return!Mr(n,[r]).some(i=>i.findAncestor(s))}function OL(n,e={}){let{dnf:t=!1,max:s=1/0}=e,r=-1;for(let i of n.findAll(We))r-=1;for(let i of fO(n,{dnf:t,max:s}))if(r+=i,s<r)return r;return r}function*fO(n,e){let{dnf:t,max:s=1/0,depth:r=0}=e;if(s<r){yield r;return}let i=n.unnest();if(!(i instanceof We)){yield 1;return}let a=r+1,o=i.left,c=i.right;if(!o||!c){yield 1;return}if(i instanceof(t?Oe:pt))for(let u of fO(o,{dnf:t,max:s,depth:a}))for(let E of fO(c,{dnf:t,max:s,depth:a}))yield u+E;else yield*fO(o,{dnf:t,max:s,depth:a}),yield*fO(c,{dnf:t,max:s,depth:a})}function pU(n,e){let{dnf:t,maxDistance:s,simplifier:r}=e;if(Mi(n,{dnf:t}))return n;let i=OL(n,{dnf:t,max:s});if(s<i)throw new is(`Normalization distance ${i} exceeds max ${s}`);Cw(n,A=>pU(A,e));let[a,o]=t?[pt,Oe]:[Oe,pt];if(!(n instanceof o))return n;let[c,p]=n.unnestOperands();if(!c||!p)return n;let u=o===Oe?nt:bs,E=a===Oe?nt:bs,g=_nullishCoalesce(r, () => (new ug({annotateNewExpressions:!1})));if(c instanceof a&&p instanceof a){let A=Array.from(c.findAll(We)).length;return Array.from(p.findAll(We)).length<A?Iw(c,p,u,E,g):Iw(p,c,u,E,g)}return c instanceof a?Iw(p,c,u,E,g):p instanceof a?Iw(c,p,u,E,g):n}function Iw(n,e,t,s,r){let i=e.left,a=e.right;if(!i||!a)return n;if(n instanceof We)return Cw(n,p=>{let u=lg(t([p,i])),E=lg(t([p,a]));return s([r.uniqSort(u),r.uniqSort(E)],{copy:!1})}),n;let o=lg(t([n,i])),c=lg(t([n,a]));return s([r.uniqSort(o),r.uniqSort(c)],{copy:!1})}var Dl="final";function vc(n,e={}){let{constantPropagation:t=!1,coalesceSimplification:s=!1,dialect:r}=e;return new ug({dialect:r}).simplify(n,{constantPropagation:t,coalesceSimplification:s})}var Di=class extends Error{constructor(e){super(e),this.name="UnsupportedUnit"}};function BT(...n){return function(e,t){return function(...s){try{return e.apply(this,s)}catch(r){if(n.some(i=>r instanceof i))return s[0];throw r}}}}function ho(n,e){return function(...t){let s=t[0],r=n.apply(this,t);if(r===void 0)return r;if(this.annotateNewExpressions&&s!==r&&r instanceof h){this._annotator.clear();let i=this._annotator.annotate(r,{annotateScope:!1});return i.type=s.type,i}return r}}function lg(n){if(!(n instanceof We))return n;let e=n.args,t=Object.values(e);for(let s of t){if(!(s instanceof h))continue;let r=s.unnest();r._constructor===n._constructor&&s.replace(r)}return n}function wL(n,e){if(!(n instanceof Ye))return n;let t=n.args.this,s=n.parent,r=s instanceof Ve;return t instanceof $||s instanceof Vn||s instanceof fs||W.getOrRaise(e)._constructor.REQUIRES_PARENTHESIZED_STRUCT_ACCESS&&s instanceof me&&(s.right instanceof G||s.right instanceof ye)?n:!(s instanceof Qe||s instanceof Y)||s instanceof Ye||!(t instanceof Y)&&!((t instanceof rt||t instanceof Ut)&&r)||t instanceof Ve&&!(r||s instanceof Ps)||t instanceof lt&&s instanceof lt||t instanceof Ts&&s instanceof Ts||t instanceof Ts&&(s instanceof lt||s instanceof dt)?_nullishCoalesce(t, () => (n)):n}function HH(n,e={}){let{root:t=!0}=e;if(n instanceof Oe&&(t||!n.sameParent)&&Mi(n,{dnf:!0})){let s=new Map;for(let r of Lc(n,{prune:i=>i instanceof He}))if(r instanceof Ee){let i=r.left,a=r.right;i instanceof k&&a instanceof w?s.set(i.sql(),[i,a]):a instanceof k&&i instanceof w&&s.set(a.sql(),[a,i])}if(0<s.size)for(let r of Mr(n,[k])){let i=r.parent,a=s.get(r.sql()),[o,c]=a||[void 0,void 0];o!==void 0&&r!==o&&!(i instanceof Ut&&i.args.expression instanceof Qt)&&r.replace(c.copy())}}return n}function VH(n,e,t=28){let s=m=>{let N=m.indexOf("."),R=N===-1?0:N-m.length+1;return[BigInt(m.replace(".","")),R]},[r,i]=s(n),[a,o]=s(e),c=r*10n**BigInt(t+1)/a,u=c.toString().length-t,E;if(u<=0)E=c;else if(u===1)E=c/10n+(5n<=c%10n?1n:0n);else{let m=10n**BigInt(u),N=10n**BigInt(u-1)*5n;E=c/m+(N<=c%m?1n:0n)}let g=E.toString(),A=g.length+(i-o-t-1+u),x;return A<=0?x="0."+"0".repeat(-A)+g:g.length<=A?x=g+"0".repeat(A-g.length):x=g.slice(0,A)+"."+g.slice(A),x.includes(".")?x.replace(/\.?0+$/,"")||"0":x}function lU(n){return n instanceof h&&n.isNumber}function WH(n){return n instanceof ze&&CL(n)!==void 0}function jH(n){return DL.some(e=>n instanceof e)||kc(n)}function xO(n){return TO.some(e=>n instanceof e)||kc(n)}function ML(n,e,t){let s=HT(n,e,t);if(n.toMillis()===s.toMillis())return[s,s.plus(VT(e))]}function JH(n){if(n.length===0)return[];let e=[...n].sort((s,r)=>s[0].toMillis()-r[0].toMillis()),t=[e[0]];for(let[s,r]of e.slice(1)){let i=t[t.length-1];s.toMillis()<=i[1].toMillis()?t[t.length-1]=[i[0],i[1].toMillis()<r.toMillis()?r:i[1]]:t.push([s,r])}return t}function $U(n,e,t){return nt([new xt({this:n,expression:Yn(e[0],t)}),new Tt({this:n,expression:Yn(e[1],t)})],{copy:!1})}function XH(n,e,t,s,r){let i=ML(e,t,s);if(i)return $U(n,i,r)}function zH(n,e,t,s,r){let i=ML(e,t,s);if(i)return nt([new Tt({this:n,expression:Yn(i[0],r)}),new xt({this:n,expression:Yn(i[1],r)})],{copy:!1})}function hn(n){return n instanceof Et&&n.args.this||n instanceof w&&n.isNumber&&!ww(n)}function bw(n){return YT(n)||dr(n)||ww(n)}function ww(n){return n instanceof w&&n.toValue()===0}function YT(n){return n instanceof Et&&!n.args.this}function dr(n){return n instanceof Qt}function NL(n,e,t){if(n instanceof Ee||n instanceof Ut)return $T(e===t);if(n instanceof vt)return $T(e!==t);if(n instanceof It)return $T(t<e);if(n instanceof xt)return $T(t<=e);if(n instanceof Tt)return $T(e<t);if(n instanceof yt)return $T(e<=t)}function YU(n){let e=_luxon.DateTime.fromISO(n,{zone:"utc"});return e.isValid?e:_luxon.DateTime.fromSQL(n,{zone:"utc"})}function KH(n){if(_luxon.DateTime.isDateTime(n))return n.toUTC().startOf("day");let e=typeof n=="string"?YU(n):_luxon.DateTime.fromMillis(n,{zone:"utc"});return e.isValid?e.startOf("day"):void 0}function yL(n){if(_luxon.DateTime.isDateTime(n))return n.toUTC();let e=typeof n=="string"?YU(n):_luxon.DateTime.fromMillis(n,{zone:"utc"});return e.isValid?e:void 0}function QH(n,e){if(n){if(e.isType("date"))return KH(n);if(e.isType(Array.from(C.TEMPORAL_TYPES)))return yL(n)}}function Li(n){let e;if(n instanceof Z&&n.to instanceof C)e=n.to;else if(n instanceof Ue&&!n.args.format)e=new C({this:"date"});else return;let t,s=n.args.this;if(s instanceof w)t=s.name;else if(s instanceof Z||s instanceof Ue)t=Li(s);else return;return QH(t,e)}function kc(n){return Li(n)!==void 0}function CL(n){if(n.args.this!==void 0)try{let e=parseInt(String(n.args.this.toValue())),t=n.text("unit").toLowerCase();return VT(t,e)}catch(e){if(e instanceof Di||e instanceof Error)return;throw e}}function GT(...n){let e;for(let t of n){if(t instanceof Z){let s=t.to;e=D(s,C)||D(s,we)?s:void 0}else{let s=t.type;e=D(s,C)||D(s,we)?s:void 0}if(e)break}return e}function Yn(n,e){let t;!e||!e.isType(Array.from(C.TEMPORAL_TYPES))?t=n.hour===0&&n.minute===0&&n.second===0?"date":"datetime":t=e.args.this;let s=t==="date"?n.toISODate():n.toFormat("yyyy-MM-dd HH:mm:ss");return new Z({this:w.string(s),to:new C({this:t})})}function VT(n,e=1){switch(n.toLowerCase()){case"year":return _luxon.Duration.fromObject({years:e});case"quarter":return _luxon.Duration.fromObject({months:3*e});case"month":return _luxon.Duration.fromObject({months:e});case"week":return _luxon.Duration.fromObject({weeks:e});case"day":return _luxon.Duration.fromObject({days:e});case"hour":return _luxon.Duration.fromObject({hours:e});case"minute":return _luxon.Duration.fromObject({minutes:e});case"second":return _luxon.Duration.fromObject({seconds:e});default:throw new Di(`Unsupported unit: ${n}`)}}function HT(n,e,t){switch(e.toLowerCase()){case"year":return n.set({month:1,day:1,hour:0,minute:0,second:0,millisecond:0});case"quarter":{let s=Math.floor((n.month-1)/3)*3+1;return n.set({month:s,day:1,hour:0,minute:0,second:0,millisecond:0})}case"month":return n.set({day:1,hour:0,minute:0,second:0,millisecond:0});case"week":return n.startOf("week").plus({days:t._constructor.WEEK_OFFSET||0});case"day":return n;default:throw new Di(`Unsupported unit: ${e}`)}}function ZH(n,e,t){let s=HT(n,e,t);return s.toMillis()===n.toMillis()?n:s.plus(VT(e))}function $T(n){return n?$e():cs()}var uU,EU,hU,gU,dU,AU,fU,xU,TU,SU,mU,RU,OU,NU,IU,yU,CU,bU,PU,wU,MU,LU,DU,_U,kU,UU,qU,vU,FU,BU,GU,je;GU=[O],BU=[O],FU=[O],vU=[O],qU=[O],UU=[O],kU=[O],_U=[O],DU=[O],LU=[O],MU=[O],wU=[O],PU=[O],bU=[O],CU=[O],yU=[O],IU=[O],NU=[O],OU=[BT(Di)],RU=[ho],mU=[ho],SU=[ho,BT(Di)],TU=[ho,BT(Di)],xU=[BT(Di)],fU=[ho],AU=[ho],dU=[BT(Di)],gU=[ho,BT(Di)],hU=[ho],EU=[ho],uU=[ho];var j=class j{constructor(e={}){se(je,5,this);this.dialect=void 0;this.annotateNewExpressions=void 0;this._annotator=void 0;let{dialect:t,annotateNewExpressions:s=!0}=e;this.dialect=W.getOrRaise(t),this.annotateNewExpressions=s,this._annotator=new $n({schema:Qs(void 0,{dialect:this.dialect}),overwriteTypes:!1})}static get SIMPLIFIABLE(){return[Y,d,vs,Ve,Zs]}static get COMPLEMENT_COMPARISONS(){return{[Tt.key]:xt,[It.key]:yt,[yt.key]:It,[xt.key]:Tt,[Ee.key]:vt,[vt.key]:Ee}}static get COMPLEMENT_SUBQUERY_PREDICATES(){return{[qs.key]:wt,[wt.key]:qs}}static get LT_LTE(){return[Tt,yt]}static get GT_GTE(){return[It,xt]}static get COMPARISONS(){return[...j.LT_LTE,...j.GT_GTE,Ee,vt,Ut]}static get INVERSE_COMPARISONS(){return{[Tt.key]:It,[It.key]:Tt,[yt.key]:xt,[xt.key]:yt}}static get NONDETERMINISTIC(){return[xr,Eg]}static get AND_OR(){return[Oe,pt]}static get INVERSE_DATE_OPS(){return{[ut.key]:dt,[Wt.key]:lt,[Uc.key]:dt,[qc.key]:lt}}static get INVERSE_OPS(){return{...j.INVERSE_DATE_OPS,[lt.key]:dt,[dt.key]:lt}}static get NULL_OK(){return[fr,kr,At]}static get CONCATS(){return[Vt,Ar]}static get DATETRUNC_BINARY_COMPARISONS(){return{[Tt.key]:(e,t,s,r,i)=>{let a=HT(t,s,r),o=t.toMillis()===a.toMillis()?t:a.plus(VT(s));return new Tt({this:e,expression:Yn(o,i)})},[It.key]:(e,t,s,r,i)=>{let a=HT(t,s,r);return new xt({this:e,expression:Yn(a.plus(VT(s)),i)})},[yt.key]:(e,t,s,r,i)=>{let a=HT(t,s,r);return new Tt({this:e,expression:Yn(a.plus(VT(s)),i)})},[xt.key]:(e,t,s,r,i)=>{let a=ZH(t,s,r);return new xt({this:e,expression:Yn(a,i)})},[Ee.key]:XH,[vt.key]:zH}}static get DATETRUNC_COMPARISONS(){return new Set([it.key,...Object.keys(j.DATETRUNC_BINARY_COMPARISONS)])}static get DATETRUNCS(){return[Bs,er]}static get SAFE_CONNECTOR_ELIMINATION_RESULT(){return[We,Et]}static get JOINS(){return[["",""],["","inner"],["right",""],["right","outer"]]}simplify(e,t={}){let{constantPropagation:s=!1,coalesceSimplification:r=!1}=t,i=[],a=[];for(let o of e.walk({prune:c=>c instanceof Qe?!0:!!c.meta[Dl]})){if(o.meta[Dl])continue;let c=o.getArgKey("group");if(c instanceof h&&o instanceof $){let p=c.args.expressions;if(p){let u=new Set(p.map(A=>A.hash()));c.meta[Dl]=!0;let E=o.selects;for(let A of E)for(let x of A.walk({prune:m=>!!m.meta[Dl]}))if(u.has(x.hash())){A.meta[Dl]=!0;break}let g=o.args.having;if(g){for(let A of g.walk())if(u.has(A.hash())){g.meta[Dl]=!0;break}}}}if(o instanceof Qe){let p=yw(o,u=>this._simplify(u,{constantPropagation:s,coalesceSimplification:r}));o===e&&(e=p)}else if(o instanceof at)i.push(o);else if(o instanceof z){let p=o.args.matchCondition;p&&(p.meta[Dl]=!0),a.push(o)}}for(let o of i)hn(o.args.this)&&o.pop();for(let o of a){let c=o.args.on,p=o.args.using,u=o.args.method,E=o.args.side||"",g=o.args.kind||"";c&&hn(c)&&!p&&!u&&j.JOINS.some(([A,x])=>A===E&&x===g)&&(c.pop(),o.setArgKey("side",void 0),o.setArgKey("kind","cross"))}return e}_simplify(e,t){let{constantPropagation:s,coalesceSimplification:r}=t,i=[e],a=[];for(;0<i.length;){let c=i.pop();if(!c)continue;let p=c;if(!j.SIMPLIFIABLE.some(g=>p instanceof g)){p instanceof ce&&this.simplify(p,{constantPropagation:s,coalesceSimplification:r});continue}let u=p.parent,E=p===e;p=this.rewriteBetween(p),p=this.uniqSort(p,{root:E}),p=this.absorbAndEliminate(p,{root:E}),p=this.simplifyConcat(p),p=this.simplifyConditionals(p),s&&(p=HH(p,{root:E})),p!==c&&_optionalChain([c, 'optionalAccess', _129 => _129.replace, 'call', _130 => _130(p)]);for(let g of p.iterExpressions({reverse:!0}))g.meta[Dl]||i.push(g);a.push([p,u])}let o=e;for(;0<a.length;){let[c,p]=a.pop(),u=c===e;for(let[g,A]of Object.entries(c.args))_optionalChain([c, 'optionalAccess', _131 => _131.setArgKey, 'call', _132 => _132(g,A)]);let E=this.simplifyNot(c);E=lg(E),E=this.simplifyConnectors(E,{root:u}),E=this.removeComplements(E,{root:u}),r&&(E=this.simplifyCoalesce(E)),E.parent=p,E=this.simplifyLiterals(E,{root:u}),E=this.simplifyEquality(E),E=wL(E,this.dialect),E=this.simplifyDateTrunc(E),E=this.sortComparison(E),E=this.simplifyStartsWith(E),E!==c&&c.replace(E),o=E}return o}absorbAndEliminate(e,t={}){let{root:s=!0}=t;if(j.AND_OR.some(r=>e instanceof r)&&(s||!e.sameParent)){let r=e instanceof Oe?pt:Oe,i=Array.from(e.flatten()),a=new Set,o=new Map,c=new Map;for(let p of i){let u=this.genSql(p);if(a.add(u),!(p instanceof r)){let x=o.get(u);x||(x=[],o.set(u,x)),x.push(new Set([u]));continue}let E=new Set(Array.from(p.flatten()).map(x=>this.genSql(x)));for(let x of E){let m=o.get(x);m||(m=[],o.set(x,m)),m.push(E)}let[g,A]=p.unnestOperands();if(g&&A){if(g instanceof rt&&g.args.this instanceof h){let x=`${this.genSql(g.args.this)}|${this.genSql(A)}`;c.has(x)||c.set(x,[]),c.get(x).push([p,A])}if(A instanceof rt&&A.args.this instanceof h){let x=`${this.genSql(A.args.this)}|${this.genSql(g)}`;c.has(x)||c.set(x,[]),c.get(x).push([p,g])}}}for(let p of i){if(!(p instanceof r))continue;let[u,E]=p.unnestOperands();if(!u||!E)continue;if(u instanceof rt&&u.args.this instanceof h&&a.has(this.genSql(u.args.this))){u.replace(r===Oe?$e():cs());continue}if(E instanceof rt&&E.args.this instanceof h&&a.has(this.genSql(E.args.this))){E.replace(r===Oe?$e():cs());continue}let g=new Set(Array.from(p.flatten()).map(S=>this.genSql(S)));if(Array.from(g).some(S=>{let I=o.get(S);return I?I.some(y=>{if(g.size<=y.size)return!1;for(let P of y)if(!g.has(P))return!1;return!0}):!1})){p.replace(r===Oe?cs():$e());continue}let x=this.genSql(u),m=this.genSql(E),N=`${x}|${m}`,R=`${m}|${x}`;for(let[S,I]of[...c.get(N)||[],...c.get(R)||[]])p.replace(I),S.replace(I)}}return e}simplifyConcat(e){if(!j.CONCATS.some(p=>e instanceof p))return e;if(e instanceof xs){let[p]=_nullishCoalesce(e.args.expressions, () => ([]));if(!(p instanceof h)||!p.isString)return e}let t,s,r,i,a;if(e instanceof xs){let[p,...u]=_nullishCoalesce(e.args.expressions, () => ([]));t=p,s=u,r=t.name,i=xs,a={}}else s=_nullishCoalesce(e.args.expressions, () => ([])),r="",i=Vt,a={safe:e.args.safe,coalesce:e.args.coalesce};let o=[],c=[];for(let p of 0<s.length?s:Array.from(e.flatten()))p instanceof h&&(p.isString?c.push(p.name):(0<c.length&&(o.push(w.string(c.join(r))),c=[]),o.push(p)));return 0<c.length&&o.push(w.string(c.join(r))),o.length===1&&o[0].isString?o[0]:i===xs&&t?new xs({expressions:[t,...o]}):e instanceof Ar?o.reduce((p,u)=>new Ar({this:p,expression:u})):new i({expressions:o,...a})}simplifyConditionals(e){if(e instanceof Ht){let t=e.args.this;for(let s of e.args.ifs||[]){let r=s.args.this;if(t&&(r=r.replace(t.pop().eq(r))),hn(r))return s.getArgKey("true");if(bw(r)){s.pop();let i=e.args.ifs;if(!i||i.length===0)return e.args.default||Ke()}}}else if(e instanceof He&&!(e.parent instanceof Ht)){let t=e.args.this;if(hn(t))return _nullishCoalesce(Pt(e.args.true,h), () => (e));if(bw(t))return _nullishCoalesce(Pt(e.args.false,h), () => (Ke()))}return e}simplifyNot(e){if(e instanceof rt){let t=e.args.this;if(dr(t))return nt([Ke(),$e()],{copy:!1});if(t instanceof h){let s=j.COMPLEMENT_COMPARISONS[t._constructor.key];if(s){let r=t.args.expression;if(r instanceof h){let i=j.COMPLEMENT_SUBQUERY_PREDICATES[r._constructor.key];i&&(r=new i({this:r.args.this}))}return new s({this:t.args.this,expression:r})}}if(t instanceof Ye){let s=t.unnest();if(s instanceof Oe)return _r(bs([Hn(s.args.this!==void 0?Pw(s.args.this):void 0,{copy:!1}),Hn(s.args.expression!==void 0?Pw(s.args.expression):void 0,{copy:!1})],{copy:!1}),{copy:!1});if(s instanceof pt)return _r(nt([Hn(s.args.this,{copy:!1}),Hn(s.args.expression!==void 0?Pw(s.args.expression):void 0,{copy:!1})],{copy:!1}),{copy:!1});if(dr(s))return nt([Ke(),$e()],{copy:!1})}if(hn(t))return cs();if(YT(t))return $e();if(t instanceof rt&&this.dialect._constructor.SAFE_TO_ELIMINATE_DOUBLE_NEGATION){let s=t.args.this;if(wi(s,"boolean"))return _nullishCoalesce(s, () => (e))}}return e}simplifyConnectors(e,t={}){let{root:s=!0}=t;if(e instanceof We){let r=e.parent;if(e=this.flatSimplify(e,(i,a,o)=>{if(i instanceof Oe)return YT(a)||YT(o)?cs():ww(a)||ww(o)?cs():dr(a)&&dr(o)||dr(a)&&hn(o)||hn(a)&&dr(o)?Ke():hn(a)&&hn(o)?$e():hn(a)?o:hn(o)?a:this.simplifyComparison(i,a,o,{or:!1});if(i instanceof pt)return hn(a)||hn(o)?$e():dr(a)&&dr(o)||dr(a)&&bw(o)||bw(a)&&dr(o)?Ke():YT(a)?o:YT(o)?a:this.simplifyComparison(i,a,o,{or:!0})},{root:s}),!j.SAFE_CONNECTOR_ELIMINATION_RESULT.some(i=>e instanceof i)&&!e.isType("boolean")){let i=r;for(;!(i instanceof We);){if(!(i instanceof Ye)){e=nt([e,$e()],{copy:!1});break}i=i.parent}}}return e}simplifyComparison(e,t,s,r){let{or:i=!1}=r;if(j.COMPARISONS.some(a=>t instanceof a)&&j.COMPARISONS.some(a=>s instanceof a)){let a=t.args.this,o=t.args.expression,c=s.args.this,p=s.args.expression;if(!a||!o||!c||!p)return;let u=[a,o],E=[c,p],g=new Map(u.map(R=>[_optionalChain([Pt, 'call', _133 => _133(R,h), 'optionalAccess', _134 => _134.hash, 'call', _135 => _135()]),R])),A=new Map(E.map(R=>[_optionalChain([Pt, 'call', _136 => _136(R,h), 'optionalAccess', _137 => _137.hash, 'call', _138 => _138()]),R])),x=new Set([...g.keys()].filter(R=>A.has(R))),m=[...x].map(R=>g.get(R)).filter(R=>!xO(R)&&!_optionalChain([Pt, 'call', _139 => _139(R,h), 'optionalAccess', _140 => _140.find, 'call', _141 => _141(j.NONDETERMINISTIC)])),N=new Set(m.map(R=>_optionalChain([Pt, 'call', _142 => _142(R,h), 'optionalAccess', _143 => _143.hash, 'call', _144 => _144()])));if(0<x.size&&0<m.length){let R=u.filter(_e=>!N.has(_optionalChain([Pt, 'call', _145 => _145(_e,h), 'optionalAccess', _146 => _146.hash, 'call', _147 => _147()]))),S=E.filter(_e=>!N.has(_optionalChain([Pt, 'call', _148 => _148(_e,h), 'optionalAccess', _149 => _149.hash, 'call', _150 => _150()])));if(R.length===0||S.length===0)return e;let I,y;try{I=PL(R),y=PL(S)}catch (e2){return e}if(!(I instanceof h)||!(y instanceof h))return;let P=I,v=y,H,B;if(P.isNumber&&v.isNumber)H=P.toValue(),B=v.toValue();else if(P.isString&&v.isString)H=P.name,B=v.name;else{let _e=Li(P);if(!_e)return;let Is=Li(v);if(!Is)return;H=yL(_e),B=yL(Is)}let fe=[[[t,H],[s,B]],[[s,B],[t,H]]];for(let[[_e,Is],[zt,on]]of fe){let ys=typeof Is=="number"?Is:_luxon.DateTime.isDateTime(Is)?Is.toMillis():String(Is),rs=typeof on=="number"?on:_luxon.DateTime.isDateTime(on)?on.toMillis():String(on);if(j.LT_LTE.some(wr=>_e instanceof wr)&&j.LT_LTE.some(wr=>zt instanceof wr))return i?rs<ys?t:s:ys<=rs?t:s;if(j.GT_GTE.some(wr=>_e instanceof wr)&&j.GT_GTE.some(wr=>zt instanceof wr))return i?ys<rs?t:s:rs<=ys?t:s;if(!i){if(_e instanceof Tt&&j.GT_GTE.some(wr=>zt instanceof wr)){if(ys<=rs)return cs()}else if(_e instanceof It&&j.LT_LTE.some(wr=>zt instanceof wr)){if(rs<=ys)return cs()}else if(_e instanceof Ee){if(zt instanceof Tt)return rs<=ys?cs():_e;if(zt instanceof yt)return rs<ys?cs():_e;if(zt instanceof It)return ys<=rs?cs():_e;if(zt instanceof xt)return ys<rs?cs():_e;if(zt instanceof vt)return ys===rs?cs():_e}}}}}}flatSimplify(e,t,s){let{root:r}=s;if(!r&&e.sameParent)return e;let i=[],a=Array.from(e.flatten({unnest:!1})),o=a.length;for(;a.length;){let c=a.shift(),p=!1;for(let u of a){let E=t(e,c,u);if(E&&E!==e){a.splice(a.indexOf(u),1),a.unshift(E),p=!0;break}}p||i.push(c)}return i.length<o?i.reduce((c,p)=>new e._constructor({this:c,expression:p})):e}removeComplements(e,t={}){let{root:s=!0}=t;if(j.AND_OR.some(r=>e instanceof r)&&(s||!e.sameParent)){let r=Array.from(e.flatten()),i=new Set(r.map(a=>a.hash()));for(let a of r)if(a instanceof rt){let o=a.args.this;if(o&&i.has(o.hash())&&e.meta.nonnull===!0)return e instanceof Oe?cs():$e()}}return e}simplifyCoalesce(e){if(e instanceof St&&(_optionalChain([e, 'access', _151 => _151.args, 'access', _152 => _152.expressions, 'optionalAccess', _153 => _153.length])===0||jH(e.args.this))&&!(e.parent instanceof Dr))return e.args.this;if(this.dialect._constructor.COALESCE_COMPARISON_NON_STANDARD||!j.COMPARISONS.some(p=>e instanceof p))return e;let t,s,r=e.args.this,i=e.args.expression;if(r instanceof St)t=r,s=i;else if(i instanceof St)t=i,s=r;else return e;if(!xO(s))return e;let a=-1;for(let p=0;p<(_nullishCoalesce(_optionalChain([t, 'access', _154 => _154.args, 'access', _155 => _155.expressions, 'optionalAccess', _156 => _156.length]), () => (0)));p++){let u=_optionalChain([t, 'access', _157 => _157.args, 'access', _158 => _158.expressions, 'optionalAccess', _159 => _159[p]]);if(xO(u)){a=p;break}}if(a===-1)return e;let o=_optionalChain([t, 'access', _160 => _160.args, 'access', _161 => _161.expressions, 'optionalAccess', _162 => _162[a]]);t.setArgKey("expressions",_optionalChain([t, 'access', _163 => _163.args, 'access', _164 => _164.expressions, 'optionalAccess', _165 => _165.slice, 'call', _166 => _166(0,a)]));let c=0<(_nullishCoalesce(_optionalChain([t, 'access', _167 => _167.args, 'access', _168 => _168.expressions, 'optionalAccess', _169 => _169.length]), () => (0)))?t:t.args.this;return _r(bs([nt([Hn(_optionalChain([c, 'optionalAccess', _170 => _170.is, 'call', _171 => _171(Ke())]),{copy:!1}),e.copy()],{copy:!1}),nt([_optionalChain([c, 'optionalAccess', _172 => _172.is, 'call', _173 => _173(Ke())]),new e._constructor({this:o.copy(),expression:s.copy()})],{copy:!1})],{copy:!1}),{copy:!1})}simplifyLiterals(e,t={}){let{root:s=!0}=t;if(e instanceof Y&&!(e instanceof We))return this.flatSimplify(e,(r,i,a)=>this.simplifyBinary(r,i,a),{root:s});if(e instanceof Ps&&e.args.this instanceof Ps)return _nullishCoalesce(e.args.this.args.this, () => (e));if(j.INVERSE_DATE_OPS[e._constructor.key]){let r=e.args.this;if(r instanceof h&&e instanceof gn)return this.simplifyBinary(e,r,e.interval())||e}return e}simplifyIntegerCast(e){if(!(e instanceof Z))return e;let t=e.args.this,s;if(t instanceof Z?s=this.simplifyIntegerCast(t):s=t,s instanceof h&&s.isInteger){let r=s.toValue(),i=e.args.to;if(!i)return e;if(i instanceof h&&(j.TINYINT_MIN<=r&&r<=j.TINYINT_MAX&&i.args.this&&C.SIGNED_INTEGER_TYPES.has(i.args.this)||j.UTINYINT_MIN<=r&&r<=j.UTINYINT_MAX&&i.args.this&&C.UNSIGNED_INTEGER_TYPES.has(i.args.this)))return s}return e}simplifyBinary(e,t,s){if(j.COMPARISONS.some(r=>e instanceof r)&&(t=this.simplifyIntegerCast(t),s=this.simplifyIntegerCast(s)),e instanceof Ut){let r,i;if(s instanceof rt?(r=s.args.this,i=!0):(r=s,i=!1),dr(r)){if(t instanceof w)return i?$e():cs();if(dr(t))return i?cs():$e()}}else{if(j.NULL_OK.some(r=>e instanceof r))return;if((dr(t)||dr(s))&&e.parent instanceof He)return Ke()}if(t.isNumber&&s.isNumber){let r=t.toValue(),i=s.toValue(),a=A=>{let x=A.match(/[eE]([+-]?\d+)/),m=x?parseInt(x[1]):0,N=A.replace(/[eE][+-]?\d+/,"").match(/\.(\d+)/),R=N?N[1].length:0;return Math.max(0,R-m)},o=String(_nullishCoalesce(t.args.this, () => (""))),c=String(_nullishCoalesce(s.args.this, () => (""))),p=a(o),u=a(c),E=(A,x)=>0<x?A.toFixed(x):String(A);if(e instanceof lt)return w.number(E(r+i,Math.max(p,u)));if(e instanceof Ts)return w.number(E(r*i,p+u));if(e instanceof dt)return t.parent===s.parent?w.number(E(r-i,Math.max(p,u))):void 0;if(e instanceof jt){let A=!o.includes(".")&&!o.toLowerCase().includes("e"),x=!c.includes(".")&&!c.toLowerCase().includes("e");return A&&x||t.parent!==s.parent?void 0:w.number(VH(o,c))}let g=NL(e,r,i);if(g)return g}else if(t.isString&&s.isString){let r=t.args.this,i=s.args.this,a=NL(e,r,i);if(a)return a}else if(kc(t)&&s instanceof ze){let r=Li(t),i=CL(s);if(r&&i!==void 0){if(e instanceof lt||e instanceof ut||e instanceof Uc)return Yn(r.plus(i),GT(t));if(e instanceof dt||e instanceof Wt||e instanceof qc)return Yn(r.minus(i),GT(t))}}else if(t instanceof ze&&kc(s)){let r=CL(t),i=Li(s);if(r!==void 0&&i&&e instanceof lt)return Yn(i.plus(r),GT(s))}else if(kc(t)&&kc(s)&&e instanceof Ve){let r=Li(t),i=Li(s);if(r&&i){let a=NL(e,r.toMillis(),i.toMillis());if(a)return a}}}simplifyEquality(e){if(j.COMPARISONS.some(t=>e instanceof t)){let t=e.args.this,s=e.args.expression;if(!(t instanceof h)||!(s instanceof h))return e;let r=j.INVERSE_OPS[t._constructor.key];if(!r)return e;let i,a;if(s.isNumber)i=lU,a=lU;else if(kc(s))i=kc,a=WH;else return e;let o,c;if(j.INVERSE_DATE_OPS[t._constructor.key]?(o=t.args.this,c=t.interval()):(o=t.args.this,c=t.args.expression),!o||!c)return e;if(!(!i(o)&&a(c)))if(!i(c)&&a(o))[o,c]=[c,o];else return e;return new e._constructor({this:o,expression:new r({this:s,expression:c})})}return e}isDatetruncPredicate(e,t){return j.DATETRUNCS.some(s=>e instanceof s)&&kc(t)}simplifyDateTrunc(e){let t=e._constructor;if(j.DATETRUNCS.some(s=>e instanceof s)){let s=e,r=s.args.this,i=r&>(r),a=Li(r);if(a&&s.args.unit){let o=s.args.unit.name.toLowerCase();return Yn(HT(a,o,this.dialect),i)}}else if(!j.DATETRUNC_COMPARISONS.has(t.key))return e;if(e instanceof Y){let s=e.args.this,r=e.args.expression;if(!this.isDatetruncPredicate(s,r))return e;let i=s.args.unit.name.toLowerCase(),a=s.args.this,o=Li(r);return o&&_optionalChain([j, 'access', _174 => _174.DATETRUNC_BINARY_COMPARISONS, 'access', _175 => _175[t.key], 'optionalCall', _176 => _176(a,o,i,this.dialect,GT(r))])||e}if(e instanceof it){let s=e.args.this,r=e.args.expressions;if(r&&r.every(i=>this.isDatetruncPredicate(s,i))){let i=s.args.unit.name.toLowerCase(),a=[];for(let p of r){let u=Li(p);if(!u)return e;let E=ML(u,i,this.dialect);E&&a.push(E)}if(a.length===0)return e;let o=JH(a),c=GT(...r.filter(p=>p instanceof h));return bs(o.map(p=>$U(s,p,c)),{copy:!1})}}return e}sortComparison(e){if(Object.values(j.COMPLEMENT_COMPARISONS).some(t=>e instanceof t)){let t=e.args.this,s=e.args.expression,r=t instanceof k,i=s instanceof k,a=xO(t),o=xO(s);if(r&&!i||o&&!a||s instanceof Vn)return e;if(i&&!r||a&&!o||IL(s)<IL(t)){let c=j.INVERSE_COMPARISONS[e._constructor.key]||e._constructor;return new c({this:s,expression:t})}}return e}simplifyStartsWith(e){return e instanceof hg&&e.args.this instanceof h&&e.args.expression instanceof h&&e.args.this.isString&&e.args.expression.isString?e.args.this.name.startsWith(e.args.expression.name)?$e():cs():e}rewriteBetween(e){if(!(e instanceof Fs))return e;let s=e.parent instanceof rt,r=e.args.this,i=e.args.low,a=e.args.high;if(!(r instanceof h)||!(i instanceof h)||!(a instanceof h))return e;let o=nt([new xt({this:r.copy(),expression:i}),new yt({this:r.copy(),expression:a})],{copy:!1});return s&&(o=_r(o,{copy:!1})),o}uniqSort(e,t={}){let{root:s=!0}=t;if(!(e instanceof We)||!s&&e.sameParent)return e;let r=Array.from(e.flatten()),i,a,o;if(e instanceof Ur)i=LL,a=void 0,o=r.map(c=>[this.genSql(c),c]);else{i=e instanceof Oe?nt:bs,a=new Map;for(let c of r){let p=this.genSql(c);a.has(p)||a.set(p,c)}o=Array.from(a.entries())}for(let c=1;c<o.length;c++)if(o[c][0]<o[c-1][0]){let p=o.sort((u,E)=>u[0]<E[0]?-1:E[0]<u[0]?1:0);return e=i(p.map(([,u])=>u),{copy:!1}),e}if(a&&a.size<r.length){let c=r[0];a.size===1?c instanceof h&&(e=nt([c,$e()],{copy:!1})):e=i(Array.from(a.values()),{copy:!1})}return e}genSql(e){return IL(e)}};je=re(null),T(je,10,"SIMPLIFIABLE",GU,j),T(je,10,"COMPLEMENT_COMPARISONS",BU,j),T(je,10,"COMPLEMENT_SUBQUERY_PREDICATES",FU,j),T(je,10,"LT_LTE",vU,j),T(je,10,"GT_GTE",qU,j),T(je,10,"COMPARISONS",UU,j),T(je,10,"INVERSE_COMPARISONS",kU,j),T(je,10,"NONDETERMINISTIC",_U,j),T(je,10,"AND_OR",DU,j),T(je,10,"INVERSE_DATE_OPS",LU,j),T(je,10,"INVERSE_OPS",MU,j),T(je,10,"NULL_OK",wU,j),T(je,10,"CONCATS",PU,j),T(je,10,"DATETRUNC_BINARY_COMPARISONS",bU,j),T(je,10,"DATETRUNC_COMPARISONS",CU,j),T(je,10,"DATETRUNCS",yU,j),T(je,10,"SAFE_CONNECTOR_ELIMINATION_RESULT",IU,j),T(je,10,"JOINS",NU,j),T(je,1,"absorbAndEliminate",OU,j),T(je,1,"simplifyConcat",RU,j),T(je,1,"simplifyConditionals",mU,j),T(je,1,"simplifyNot",SU,j),T(je,1,"simplifyConnectors",TU,j),T(je,1,"removeComplements",xU,j),T(je,1,"simplifyCoalesce",fU,j),T(je,1,"simplifyLiterals",AU,j),T(je,1,"simplifyEquality",dU,j),T(je,1,"simplifyDateTrunc",gU,j),T(je,1,"sortComparison",hU,j),T(je,1,"simplifyStartsWith",EU,j),T(je,1,"uniqSort",uU,j),te(je,j),se(je,3,j),j.TINYINT_MIN=-128,j.TINYINT_MAX=127,j.UTINYINT_MIN=0,j.UTINYINT_MAX=255;var ug=j;function IL(n,e={}){return new bL().gen(n,e)}var bL=class{constructor(){this.stack=[];this.sqls=[]}gen(e,t={}){let{comments:s=!1}=t;for(this.stack=[e],this.sqls=[];0<this.stack.length;){let r=this.stack.pop();if(r instanceof h){s&&r.comments&&0<r.comments.length&&this.stack.push(` /*${r.comments.join(",")}*/`);let i=`${r._constructor.key}Sql`;if(typeof this[i]=="function")this[i].call(this,r);else if(r instanceof d)this.function(r);else{let a=r._constructor.key.toUpperCase();this.stack.push(this.args(r)?`${a} `:a)}}else if(Array.isArray(r)){let i=!1;for(let a=r.length-1;0<=a;a--){let o=r[a];if(o!=null)if(Array.isArray(o)&&typeof o[0]=="string"&&o[0].startsWith(":")){let[c,p]=o;this.stack.push(p),this.stack.push(c),i=!1}else Array.isArray(o)?(this.stack.push(o),this.stack.push(","),i=!0):(this.stack.push(o),this.stack.push(","),i=!0)}i&&this.stack.pop()}else r!=null&&this.sqls.push(String(r))}return this.sqls.join("")}addDql(e){this.binary(e," + ")}aliasSql(e){this.stack.push(e.args.alias," AS ",e.args.this)}andSql(e){this.binary(e," AND ")}anonymousSql(e){let t=e.args.this,s;if(typeof t=="string")s=t.toUpperCase();else if(t instanceof G){let r=t.args.this;s=t.args.quoted?`"${r}"`:String(r).toUpperCase()}else throw new Error(`Anonymous.args.this expects a string or an Identifier, got '${_optionalChain([t, 'optionalAccess', _177 => _177._constructor, 'optionalAccess', _178 => _178.name])||typeof t}'.`);this.stack.push(")",e.args.expressions||[],"(",s)}betweenSql(e){this.stack.push(e.args.high," AND ",e.args.low," BETWEEN ",e.args.this)}booleanSql(e){this.stack.push(e.args.this?"TRUE":"FALSE")}bracketSql(e){this.stack.push("]",e.args.expressions||[],"[",e.args.this)}columnSql(e){let t=e.parts;for(let s=t.length-1;0<=s;s--)this.stack.push(t[s],".");this.stack.pop()}dataTypeSql(e){this.args(e,1);let t=e.args.this,s=typeof t=="string"?t:String(t);this.stack.push(`${s} `)}divSql(e){this.binary(e," / ")}dotSql(e){this.binary(e,".")}eqSql(e){this.binary(e," = ")}fromSql(e){this.stack.push(e.args.this,"FROM ")}gtSql(e){this.binary(e," > ")}gteSql(e){this.binary(e," >= ")}identifierSql(e){let t=e.args.this,s=String(t);this.stack.push(e.args.quoted?`"${s}"`:s)}iLikeSql(e){this.binary(e," ILIKE ")}inSql(e){this.stack.push(")"),this.args(e,1),this.stack.push("("," IN ",e.args.this)}intdivSql(e){this.binary(e," DIV ")}isSql(e){this.binary(e," IS ")}likeSql(e){this.binary(e," LIKE ")}literalSql(e){let t=e.args.this;this.stack.push(e.isString?`'${t}'`:String(t))}ltSql(e){this.binary(e," < ")}lteSql(e){this.binary(e," <= ")}modSql(e){this.binary(e," % ")}mulSql(e){this.binary(e," * ")}negSql(e){this.unary(e,"-")}neqSql(e){this.binary(e," <> ")}notSql(e){this.unary(e,"NOT ")}nullSql(e){this.stack.push("NULL")}orSql(e){this.binary(e," OR ")}parenSql(e){this.stack.push(")",e.args.this,"(")}subSql(e){this.binary(e," - ")}subquerySql(e){this.args(e,2);let t=e.args.alias;t&&this.stack.push(t),this.stack.push(")",e.args.this,"(")}tableSql(e){this.args(e,4);let t=e.args.alias;t&&this.stack.push(t);let s=e.parts;for(let r=s.length-1;0<=r;r--)this.stack.push(s[r],".");this.stack.pop()}tableAliasSql(e){let t=e.columns;t&&0<t.length&&this.stack.push(")",t,"("),this.stack.push(e.args.this||[]," AS ")}varSql(e){this.stack.push(String(e.args.this))}binary(e,t){this.stack.push(e.args.expression,t,e.args.this)}unary(e,t){this.stack.push(e.args.this,t)}function(e){this.stack.push(")",Object.values(e.args),"(",e._constructor.sqlName())}args(e,t=0){let s=[],r=Array.from(e._constructor.availableArgs||[]),i=0<t?r.slice(t):r;for(let a of i){let o=e.getArgKey(a);o!=null&&s.push([`:${a}`,o])}return 0<s.length?(this.stack.push(s),!0):!1}};function _L(n,e,t){let s=eV(e,t,1),r=b(s,0),i=r?` Did you mean ${r}?`:"";throw new Error(`Unknown ${n} '${e}'.${i}`)}function b(n,e){if(Array.isArray(n)){let r=e<0?n.length+e:e;return 0<=r&&r<n.length?n[r]:void 0}let t=[...n],s=e<0?t.length+e:e;return 0<=s&&s<t.length?t[s]:void 0}function Pw(n){return typeof n=="boolean"||typeof n=="number"?String(n):n}function pe(n){return n===void 0?[]:n instanceof h?[n]:typeof n!="string"&&cO(n)?[...n]:[n]}function SO(n,e={}){let{sep:t=", "}=e,s=[];for(let r of n)r&&s.push(r);return s.join(_nullishCoalesce(t, () => (", ")))}function eV(n,e,t,s=.6){let r=[];for(let i of e){let a=tV(n,i);s<=a&&r.push({match:i,ratio:a})}return r.sort((i,a)=>a.ratio-i.ratio),r.slice(0,t).map(i=>i.match)}function tV(n,e){let t=e.length<n.length?n:e,s=e.length<n.length?e:n;if(t.length===0)return 1;let r=sV(s,t);return(t.length-r)/t.length}function sV(n,e){let t=[];for(let s=0;s<=e.length;s++)t[s]=[s];for(let s=0;s<=n.length;s++)t[0][s]=s;for(let s=1;s<=e.length;s++)for(let r=1;r<=n.length;r++)e.charAt(s-1)===n.charAt(r-1)?t[s][r]=t[s-1][r-1]:t[s][r]=Math.min(t[s-1][r-1]+1,t[s][r-1]+1,t[s-1][r]+1);return t[e.length][n.length]}function WU(n){return n.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}function yw(n,e){let t=n;for(;;){let s=HU(t);t=e(t);let r=HU(t);if(s===r)break}return t}function HU(n){return n instanceof h?n.sql():JSON.stringify(n)}function jU(n){let e=[],t=new Map(n);for(let[s,r]of Array.from(n.entries()))for(let i of Array.from(r))t.has(i)||t.set(i,new Set);for(;0<t.size;){let s=new Set;for(let[r,i]of Array.from(t.entries()))i.size===0&&s.add(r);if(s.size===0)throw new Error("Cycle error");for(let r of Array.from(s))t.delete(r);for(let r of Array.from(t.values()))for(let i of Array.from(s))r.delete(i);e.push(...Array.from(s).sort())}return e}function pn(n,e){let t=new Set(n);if(!t.has(e))return e;let s=2,r=`${e}_${s}`;for(;t.has(r);)s++,r=`${e}_${s}`;return r}function kL(n){return rV(n,e=>{let t=Number(e);return Number.isInteger(t)})}function rV(n,e){try{return e(n)}catch (e3){return!1}}function go(n){let e=0;return()=>`${n}${e++}`}function JU(n,e,t,s={}){let{fillFromStart:r=!0}=s,i=n.split(e),a=Math.max(0,t-i.length);return r?[...Array(a).fill(void 0),...i]:[...i,...Array(a).fill(void 0)]}function Ii(n){try{if(typeof n!="object"||n===null||n.constructor!==Object)return 0;let e=Object.values(n);return e.length===0?1:1+Ii(e[0])}catch (e4){return 0}}function PL(n){for(let e of n)return e;throw new Error("Iterable is empty")}function XU(n){if(typeof n=="boolean"||n===void 0)return n;let e=n.toLowerCase();return e==="true"||e==="1"?!0:e==="false"||e==="0"?!1:n}function vT(n){return _luxon.DateTime.fromISO(n).isValid&&/^\d{4}-\d{2}-\d{2}$/.test(n)}function AO(n){return _luxon.DateTime.fromSQL(n).isValid}var nV=new Set(["day","week","month","quarter","year","year_month"]);function FT(n){return n!==void 0&&nV.has(n.name.toLowerCase())}var Mw=class{constructor(e,t){this._keys=new Set(e),this._value=t}get(e){return this._keys.has(e)?this._value:void 0}has(e){return this._keys.has(e)}get size(){return this._keys.size}*[Symbol.iterator](){for(let e of Array.from(this._keys))yield[e,this._value]}*entries(){for(let e of Array.from(this._keys))yield[e,this._value]}keys(){return this._keys.values()}*values(){for(let e of Array.from(this._keys))yield this._value}forEach(e,t){for(let s of Array.from(this._keys))e.call(t,this._value,s,this)}clear(){throw new Error("Method not supported")}delete(e){throw new Error("Method not supported")}set(e,t){throw new Error("Method not supported")}get[Symbol.toStringTag](){return"SingleValuedMapping"}};function WT(n,e,t,s){let r=[...e];if(!t||r.length!==1)return r;let i=r[0];n.type||os(n,{dialect:_optionalChain([s, 'optionalAccess', _179 => _179.dialect])});let a=n.type;if(_optionalChain([a, 'optionalAccess', _180 => _180.args, 'access', _181 => _181.this])!=="unknown"&&_optionalChain([a, 'optionalAccess', _182 => _182.args, 'access', _183 => _183.this])!=="array")return r;i.type||os(i,{dialect:_optionalChain([s, 'optionalAccess', _184 => _184.dialect])});let o=i.type;if(_optionalChain([o, 'optionalAccess', _185 => _185.args, 'access', _186 => _186.this])&&_optionalChain([C, 'access', _187 => _187.INTEGER_TYPES, 'optionalAccess', _188 => _188.has, 'call', _189 => _189(o.args.this)])){let c=new lt({this:i,expression:gg(t)});return[vc(c)]}return r}function zU(n,e){return n instanceof h?e==="name"?n.name:e==="sql"?n.sql():e(n):n}function Lw(n){return n.replace(/([A-Z])/g,"_$1").toUpperCase()}function dg(n,e,t){if(!n)return;let s=0,r=1,i=n.length,a=_nullishCoalesce(t, () => (hr(Object.keys(e).map(u=>Array.from(u))))),o=a,c=[],p;for(;r<=i;){let u=n.substring(s,r),[E,g]=Il(o,[u[u.length-1]]);o=g,E===0?(p?(r-=1,u=p,p=void 0):(u=u[0],r=s+1),s+=u.length,c.push(u),o=a):E===2&&(p=u),r+=1,E!==0&&i<r&&c.push(u)}return c.map(u=>_nullishCoalesce(e[u], () => (u))).join("")}function KU(n){try{if(!_luxon.DateTime.fromISO(n).isValid)return 0;let t=n.match(/\.(\d+)/);if(!t)return 0;let r=t[1].replace(/0+$/,"").length;return 3<r?6:0<r?3:0}catch (e5){return 0}}function Tr(n,e={}){let{dialect:t,storeOriginalColumnIdentifiers:s=!1}=e,r=W.getOrRaise(t),i;typeof n=="string"?i=Cl(n,{dialect:r}):i=n;for(let a of i.walk({prune:o=>!!_optionalChain([o, 'access', _190 => _190.meta, 'optionalAccess', _191 => _191.caseSensitive])}))if(!_optionalChain([a, 'access', _192 => _192.meta, 'optionalAccess', _193 => _193.caseSensitive])){if(s&&a instanceof k){let o=a;for(;o&&o.parent instanceof me;)o=o.parent;"parts"in o&&Array.isArray(o.parts)&&(a.meta.dotParts=o.parts.map(c=>c.name))}r.normalizeIdentifier(a)}return i}var Ag=new Map,fg=new Set;function QU(n){fg.add(n);let e=n.sqlNames();for(let t of e)Ag.set(t.toUpperCase(),n)}function Iv(n,e){return W.getOrRaise(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _194 => _194.read]), () => (_optionalChain([e, 'optionalAccess', _195 => _195.dialect])))).parse(n,e)}function _w(n,e){let t=W.getOrRaise(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _196 => _196.read]), () => (_optionalChain([e, 'optionalAccess', _197 => _197.dialect])))),s=_optionalChain([e, 'optionalAccess', _198 => _198.into])?t.parseIntoTypes(e.into,n,e):t.parse(n,e);for(let r of s){if(!r)throw new ns(`No expression was parsed from '${n}'`);return r}throw new ns(`No expression was parsed from '${n}'`)}var aV=/:.*?[a-zA-Z+\-]/;function oV(n){if(n.length<1)throw new Error("buildVarMap only accepts an expression list with at least one expression");if(n.length===1&&n[0].isStar)return new NE({this:n[0]});let e=[],t=[];for(let s=0;s<n.length;s+=2)e.push(n[s]),t.push(n[s+1]);return new gr({keys:jT(e,{copy:!1}),values:jT(t,{copy:!1})})}function cV(n){if(n.length<2)throw new Error("buildLike only accept expression lists with at least 2 expressions");let e=new Ws({this:n[1],expression:n[0]});return 2<n.length?new TE({this:e,expression:n[2]}):e}function Sr(n,e={}){let{reverseArgs:t=!1}=e;return function(r){let i=this.parseBitwise(),a=r;return t&&([a,i]=[i,a]),this.parseEscape(this.expression(n,{this:a,expression:i}))}}function pV(n,{dialect:e}){if(n.length<1)throw new Error("buildAlgorithm only accepts an expression list with at least one expression");let t=b(n,0),s=b(n,1);return t&&s?(e._constructor.LOG_BASE_FIRST||([t,s]=[s,t]),new Vr({this:t,expression:s})):_nullishCoalesce(_optionalChain([e, 'access', _199 => _199._constructor, 'access', _200 => _200.parserClass, 'optionalAccess', _201 => _201.LOG_DEFAULTS_TO_LN]), () => (!1))?new Ga({this:t}):new Vr({this:t})}function ZU(n,{dialect:e}){if(n.length<1)throw new Error("buildHex only accepts an expression list with at least one expression");let t=n[0];return e._constructor.HEX_LOWERCASE?new Ec({this:t}):new ac({this:t})}function lV(n){if(n.length<1)throw new Error("buildLower only accepts an expression list with at least one expression");let e=n[0];return e instanceof ac?new Ec({this:e.args.this}):new hi({this:e})}function uV(n){if(n.length<1)throw new Error("buildUpper only accepts an expression list with at least one expression");let e=n[0];return e instanceof Ec?new ac({this:e.args.this}):new Ep({this:e})}function UL(n){return function(t,{dialect:s}){if(t.length<2)throw new Error("buildExtractJsonWithPath only accepts an expression list with at least two expressions");let r=new n({this:t[0],expression:s.toJsonPath(b(t,1))});return 2<t.length&&r instanceof Zt&&r.setArgKey("expressions",t.slice(2)),r instanceof Rr&&r.setArgKey("scalarOnly",s._constructor.JSON_EXTRACT_SCALAR_SCALAR_ONLY),r}}function EV(n){if(n.length<2)throw new Error("buildMod only accepts an expression list with at least two expressions");let e=n[0],t=n[1];return e=e instanceof Y?new Ye({this:e}):e,t=t instanceof Y?new Ye({this:t}):t,new Hr({this:e,expression:t})}function Dw(n,e={}){if(n.length<2)throw new Error("buildPad only accepts an expression list with at least two expressions");let{isLeft:t=!0}=e;return new Fa({this:b(n,0),expression:b(n,1),fillPattern:b(n,2),isLeft:t})}function eq(n,e,t,s){let r=new n({expressions:e});return r instanceof Ne&&s._constructor.HAS_DISTINCT_ARRAY_CONSTRUCTORS&&r.setArgKey("bracketNotation",t==="lBracket"),r}function hV(n,e={}){if(n.length<2)throw new Error("buildConvertTimezone only accepts an expression list with at least two expressions");let{defaultSourceTz:t}=e;if(n.length===2){let s=t?w.string(t):void 0,r=b(n,0),i=typeof r=="string"?w.string(r):r,a=b(n,1),o=typeof a=="string"?w.string(a):a;return new Qn({sourceTz:s,targetTz:i,timestamp:o})}return Qn.fromArgList(n)}function tq(n,e={}){if(n.length<1)throw new Error("buildTrim only accepts an expression list with at least one expression");let{isLeft:t=!0,reverseArgs:s=!1}=e,r=b(n,0),i=b(n,1);return i&&s&&([r,i]=[i,r]),new or({this:r,expression:i,position:t?"leading":"trailing"})}function gV(n,e={}){if(n.length<1)throw new Error("buildCoalesce only accepts an expression list with at least one expression");let{isNvl:t,isNull:s}=e;return new St({this:b(n,0),expressions:n.slice(1),isNvl:t,isNull:s})}function sq(n){if(n.length<2)throw new Error("buildLocateStrposition only accepts an expression list with at least two expressions");return new ps({this:b(n,1),substr:b(n,0),position:b(n,2)})}function dV(n,{dialect:e}){if(n.length<2)throw new Error("buildArrayAppend only accepts an expression list with at least two expressions");return new Ng({this:b(n,0),expression:b(n,1),nullPropagation:e._constructor.ARRAY_FUNCS_PROPAGATES_NULLS})}function AV(n,{dialect:e}){if(n.length<2)throw new Error("buildArrayPrepend only accepts an expression list with at least two expressions");return new Ig({this:n[0],expression:n[1],nullPropagation:e._constructor.ARRAY_FUNCS_PROPAGATES_NULLS})}function rq(n,{dialect:e}){if(n.length<1)throw new Error("buildArrayConcat only accepts an expression list with at least one expression");return new Pn({this:n[0],expressions:n.slice(1),nullPropagation:e._constructor.ARRAY_FUNCS_PROPAGATES_NULLS})}function fV(n,{dialect:e}){if(n.length<2)throw new Error("buildArrayRemove only accepts an expression list with at least two expressions");return new RE({this:n[0],expression:n[1],nullPropagation:e._constructor.ARRAY_FUNCS_PROPAGATES_NULLS})}var nq,iq,aq,oq,cq,pq,lq,uq,Eq,hq,gq,dq,Aq,fq,xq,Tq,Sq,mq,Rq,Oq,Nq,Iq,yq,Cq,bq,Pq,wq,Mq,Lq,Dq,_q,kq,Uq,qq,vq,Fq,Bq,Gq,$q,Yq,Hq,Vq,Wq,jq,Jq,Xq,zq,Kq,Qq,Zq,ev,tv,sv,rv,nv,iv,av,ov,cv,pv,lv,uv,Ev,hv,gv,dv,Av,fv,xv,Tv,Sv,mv,Rv,Ov,Nv,J;Nv=[O],Ov=[O],Rv=[O],mv=[O],Sv=[O],Tv=[O],xv=[O],fv=[O],Av=[O],dv=[O],gv=[O],hv=[O],Ev=[O],uv=[O],lv=[O],pv=[O],cv=[O],ov=[O],av=[O],iv=[O],nv=[O],rv=[O],sv=[O],tv=[O],ev=[O],Zq=[O],Qq=[O],Kq=[O],zq=[O],Xq=[O],Jq=[O],jq=[O],Wq=[O],Vq=[O],Hq=[O],Yq=[O],$q=[O],Gq=[O],Bq=[O],Fq=[O],vq=[O],qq=[O],Uq=[O],kq=[O],_q=[O],Dq=[O],Lq=[O],Mq=[O],wq=[O],Pq=[O],bq=[O],Cq=[O],yq=[O],Iq=[O],Nq=[O],Oq=[O],Rq=[O],mq=[O],Sq=[O],Tq=[O],xq=[O],fq=[O],Aq=[O],dq=[O],gq=[O],hq=[O],Eq=[O],uq=[O],lq=[O],pq=[O],cq=[O],oq=[O],aq=[O],iq=[O],nq=[O];var M=class M{constructor(e={}){this.sql=void 0;this.dialect=void 0;this.errorLevel=void 0;this.errorMessageContext=void 0;this.maxErrors=void 0;this.errors=void 0;this.tokens=void 0;this.index=void 0;this.curr=void 0;this.next=void 0;this.prev=void 0;this.prevComments=void 0;this.pipeCteCounter=void 0;let{errorLevel:t=3,errorMessageContext:s=100,maxErrors:r=3}=e;this.sql="",this.dialect=W.getOrRaise(e.dialect),this.errorLevel=t,this.errorMessageContext=s,this.maxErrors=r,this.errors=[],this.tokens=[],this.index=0,this.curr=void 0,this.next=void 0,this.prev=void 0,this.prevComments=void 0,this.pipeCteCounter=0,this.reset()}static get SHOW_TRIE(){return this._showTrie||(this._showTrie=hr(Object.keys(this.SHOW_PARSERS).map(e=>e.split(" ")))),this._showTrie}static get SET_TRIE(){return this._setTrie||(this._setTrie=hr(Object.keys(this.SET_PARSERS).map(e=>e.split(" ")))),this._setTrie}static get FUNCTIONS(){return{...Object.fromEntries(Array.from(Ag.entries()).map(([e,t])=>[e,(s,r)=>t.fromArgList(s)])),...Object.fromEntries(["COALESCE","IFNULL","NVL"].map(e=>[e,(t,s)=>gV(t)])),ARRAY:(e,t)=>new Ne({expressions:e}),ARRAYAGG:(e,{dialect:t})=>new nr({this:e[0],nullsExcluded:t._constructor.ARRAY_AGG_INCLUDES_NULLS===void 0?!0:void 0}),ARRAY_AGG:(e,{dialect:t})=>new nr({this:e[0],nullsExcluded:t._constructor.ARRAY_AGG_INCLUDES_NULLS===void 0?!0:void 0}),ARRAY_APPEND:dV,ARRAY_CAT:rq,ARRAY_CONCAT:rq,ARRAY_PREPEND:AV,ARRAY_REMOVE:fV,COUNT:(e,t)=>new uc({this:e[0],expressions:e.slice(1),bigInt:!0}),CONCAT:(e,{dialect:t})=>new Vt({expressions:e,safe:!t._constructor.STRICT_STRING_CONCAT,coalesce:t._constructor.CONCAT_COALESCE}),CONCAT_WS:(e,{dialect:t})=>new xs({expressions:e,safe:!t._constructor.STRICT_STRING_CONCAT,coalesce:t._constructor.CONCAT_COALESCE}),CONVERT_TIMEZONE:(e,t)=>hV(e),DATE_ADD:e=>e.length===3?JT(ut)([e[2],e[1],e[0]]):new ut({this:b(e,0),expression:b(e,1)}),DATE_SUB:e=>e.length===3?JT(Wt)([e[2],e[1],e[0]]):new Wt({this:b(e,0),expression:b(e,1)}),DATE_TO_DATE_STR:(e,t)=>new Z({this:e[0],to:new C({this:"text"})}),TIME_TO_TIME_STR:(e,t)=>new Z({this:e[0],to:new C({this:"text"})}),GENERATE_DATE_ARRAY:(e,t)=>new Mn({start:e[0],end:e[1],step:b(e,2)||new ze({this:w.string("1"),unit:Te("DAY")})}),GENERATE_UUID:(e,{dialect:t})=>new Ao({isString:t._constructor.UUID_IS_STRING_TYPE||void 0}),GLOB:(e,t)=>new Jc({this:e[1],expression:e[0]}),LIKE:(e,t)=>cV(e),GREATEST:(e,{dialect:t})=>new op({this:e[0],expressions:e.slice(1),ignoreNulls:t._constructor.LEAST_GREATEST_IGNORES_NULLS}),LEAST:(e,{dialect:t})=>new Pg({this:e[0],expressions:e.slice(1),ignoreNulls:t._constructor.LEAST_GREATEST_IGNORES_NULLS}),HEX:(e,{dialect:t})=>ZU(e,{dialect:t}),TO_HEX:(e,{dialect:t})=>ZU(e,{dialect:t}),JSON_EXTRACT:UL(Zt),JSON_EXTRACT_SCALAR:UL(Rr),JSON_EXTRACT_PATH_TEXT:UL(Rr),JSON_KEYS:(e,{dialect:t})=>new IO({this:e[0],expression:t.toJsonPath(b(e,1))}),LOG:(e,{dialect:t})=>pV(e,{dialect:t}),LOG2:(e,t)=>new Vr({this:w.number(2),expression:b(e,0)}),LOG10:(e,t)=>new Vr({this:w.number(10),expression:b(e,0)}),MOD:(e,t)=>EV(e),LOWER:(e,t)=>lV(e),UPPER:(e,t)=>uV(e),LPAD:(e,t)=>Dw(e),LEFTPAD:(e,t)=>Dw(e),RPAD:(e,t)=>Dw(e,{isLeft:!1}),RIGHTPAD:(e,t)=>Dw(e,{isLeft:!1}),LTRIM:(e,t)=>tq(e),RTRIM:(e,t)=>tq(e,{isLeft:!1}),STRPOS:(e,t)=>ps.fromArgList(e),INSTR:(e,t)=>ps.fromArgList(e),CHARINDEX:(e,t)=>sq(e),LOCATE:(e,t)=>sq(e),SCOPE_RESOLUTION:(e,t)=>e.length!==2?new Wc({expression:e[0]}):new Wc({this:b(e,0),expression:e[1]}),TS_OR_DS_TO_DATE_STR:(e,t)=>new Ms({this:new Z({this:e[0],to:new C({this:"text"})}),start:w.number(1),length:w.number(10)}),UNNEST:(e,t)=>new Pe({expressions:[e[0]]}),UUID:(e,{dialect:t})=>new Ao({isString:t._constructor.UUID_IS_STRING_TYPE||void 0}),VAR_MAP:(e,t)=>oV(e)}}static get NO_PAREN_FUNCTIONS(){return{currentDate:xn,currentDatetime:xn,currentTime:Ba,currentTimestamp:ir,currentUser:ap,localtime:np,localtimestamp:ip,currentRole:Cg}}static get STRUCT_TYPE_TOKENS(){return new Set(["file","nested","object","struct","union"])}static get NESTED_TYPE_TOKENS(){return new Set(["array","list","lowcardinality","map","nullable","range",...M.STRUCT_TYPE_TOKENS])}static get ENUM_TYPE_TOKENS(){return new Set(["dynamic","enum","enum8","enum16"])}static get AGGREGATE_TYPE_TOKENS(){return new Set(["aggregatefunction","simpleaggregatefunction"])}static get TYPE_TOKENS(){return new Set(["bit","boolean","tinyint","utinyint","smallint","usmallint","int","uint","bigint","ubigint","bignum","int128","uint128","int256","uint256","mediumint","umediumint","fixedstring","float","double","udouble","char","nchar","varchar","nvarchar","bpchar","text","mediumtext","longtext","blob","mediumblob","longblob","binary","varbinary","json","jsonb","interval","tinyblob","tinytext","time","timetz","timeNs","timestamp","timestampS","timestampMs","timestampNs","timestamptz","timestampltz","timestampntz","datetime","datetime2","datetime64","smalldatetime","date","date32","int4range","int4multirange","int8range","int8multirange","numrange","nummultirange","tsrange","tsmultirange","tstzrange","tstzmultirange","daterange","datemultirange","decimal","decimal32","decimal64","decimal128","decimal256","decfloat","udecimal","bigdecimal","uuid","geography","geographypoint","geometry","point","ring","linestring","multilinestring","polygon","multipolygon","hllsketch","hstore","pseudoType","super","serial","smallserial","bigserial","xml","year","userdefined","money","smallmoney","rowversion","image","variant","vector","void","object","objectIdentifier","inet","ipaddress","ipprefix","ipv4","ipv6","unknown","nothing","null","name","tdigest","dynamic",...M.ENUM_TYPE_TOKENS,...M.NESTED_TYPE_TOKENS,...M.AGGREGATE_TYPE_TOKENS])}static get SIGNED_TO_UNSIGNED_TYPE_TOKEN(){return{bigint:"ubigint",int:"uint",mediumint:"umediumint",smallint:"usmallint",tinyint:"utinyint",decimal:"udecimal",double:"udouble"}}static get SUBQUERY_PREDICATES(){return{any:wt,all:qs,exists:js,some:wt}}static get RESERVED_TOKENS(){return new Set([...Object.values(Dt.SINGLE_TOKENS),"select"].filter(e=>e!=="identifier"))}static get DB_CREATABLES(){return new Set(["database","dictionary","fileFormat","model","namespace","schema","semanticView","sequence","sink","source","stage","storageIntegration","streamlit","table","tag","view","warehouse"])}static get CREATABLES(){return new Set(["column","constraint","foreignKey","function","index","procedure",...M.DB_CREATABLES])}static get ALTERABLES(){return new Set(["index","table","view","session"])}static get ID_VAR_TOKENS(){return(()=>{let e=new Set(["all","analyze","attach","var","anti","apply","asc","asof","autoIncrement","begin","bpchar","cache","case","collate","command","comment","commit","constraint","copy","cube","currentSchema","default","delete","desc","describe","detach","dictionary","div","end","execute","export","escape","false","first","filter","final","format","full","get","identifier","inout","is","isnull","interval","keep","kill","left","limit","load","lock","match","merge","natural","next","offset","operator","ordinality","over","overlaps","overwrite","partition","percent","pivot","pragma","put","range","recursive","references","refresh","rename","replace","right","rollup","row","rows","semi","set","settings","show","temporary","top","true","truncate","unique","unnest","unpivot","update","use","volatile","window",...M.ALTERABLES,...M.CREATABLES,...Object.keys(M.SUBQUERY_PREDICATES),...M.TYPE_TOKENS,...Object.keys(M.NO_PAREN_FUNCTIONS)]);return e.delete("union"),e})()}static get TABLE_ALIAS_TOKENS(){return new Set([...M.ID_VAR_TOKENS].filter(e=>!["anti","asof","full","left","lock","natural","right","semi","window"].includes(e)))}static get ALIAS_TOKENS(){return M.ID_VAR_TOKENS}static get COLON_PLACEHOLDER_TOKENS(){return M.ID_VAR_TOKENS}static get ARRAY_CONSTRUCTORS(){return{ARRAY:Ne,LIST:mO}}static get COMMENT_TABLE_ALIAS_TOKENS(){return new Set([...M.TABLE_ALIAS_TOKENS].filter(e=>e!=="is"))}static get UPDATE_ALIAS_TOKENS(){return new Set([...M.TABLE_ALIAS_TOKENS].filter(e=>e!=="set"))}static get TRIM_TYPES(){return new Set(["leading".toUpperCase(),"trailing".toUpperCase(),"both".toUpperCase()])}static get FUNC_TOKENS(){return new Set(["collate","command","currentDate","currentDatetime","currentSchema","currentTimestamp","currentTime","currentUser","currentCatalog","filter","first","format","get","glob","identifier","index","isnull","ilike","insert","like","localtime","localtimestamp","merge","next","offset","primaryKey","range","replace","rlike","row","sessionUser","unnest","var","left","right","sequence","date","datetime","table","timestamp","timestamptz","truncate","utcDate","utcTime","utcTimestamp","window","xor",...M.TYPE_TOKENS,...Object.keys(M.SUBQUERY_PREDICATES)])}static get CONJUNCTION(){return{and:Oe}}static get ASSIGNMENT(){return{colonEq:At}}static get DISJUNCTION(){return{or:pt}}static get EQUALITY(){return{eq:Ee,neq:vt,nullsafeEq:fr}}static get COMPARISON(){return{gt:It,gte:xt,lt:Tt,lte:yt}}static get BITWISE(){return{amp:Cn,caret:Ei,pipe:ui}}static get TERM(){return{dash:dt,plus:lt,mod:Hr,collate:vl}}static get FACTOR(){return{div:Hi,lrArrow:tS,slash:jt,star:Ts}}static get EXPONENT(){return{}}static get TIMES(){return new Set(["time","timetz"])}static get TIMESTAMPS(){return new Set(["timestamp","timestampntz","timestamptz","timestampltz",...M.TIMES])}static get SET_OPERATIONS(){return new Set(["union","intersect","except"])}static get JOIN_METHODS(){return new Set(["asof","natural","positional"])}static get JOIN_SIDES(){return new Set(["left","right","full"])}static get JOIN_KINDS(){return new Set(["anti","cross","inner","outer","semi","straightJoin"])}static get LAMBDAS(){return{arrow:function(e){return this.expression(vs,{this:this.replaceLambda(this.parseDisjunction(),e),expressions:e})},farrow:function(e){return this.expression(Og,{this:Te(e[0].name),expression:this.parseDisjunction()})}}}static get COLUMN_OPERATORS(){return{dot:void 0,dotcolon:function(e,t){return this.expression(rS,{this:e,to:t})},dcolon:function(e,t){return this.buildCast({strict:this._constructor.STRICT_CAST,this:e,to:t})},arrow:function(e,t){return this.expression(Zt,{this:e,expression:this.dialect.toJsonPath(t),onlyJsonTypes:this._constructor.JSON_ARROWS_REQUIRE_JSON_TYPE})},darrow:function(e,t){return this.expression(Rr,{this:e,expression:this.dialect.toJsonPath(t),onlyJsonTypes:this._constructor.JSON_ARROWS_REQUIRE_JSON_TYPE,scalarOnly:this._dialectConstructor.JSON_EXTRACT_SCALAR_SCALAR_ONLY})},hashArrow:function(e,t){return this.expression(sS,{this:e,expression:t})},dhashArrow:function(e,t){return this.expression(bO,{this:e,expression:t})},placeholder:function(e,t){return this.expression(lp,{this:e,expression:t})}}}static get CAST_COLUMN_OPERATORS(){return new Set(["dotcolon","dcolon"])}static get EXPRESSION_PARSERS(){return{cluster:function(){return this.parseSort(qi,"clusterBy")},column:function(){return this.parseColumn()},columnDef:function(){return this.parseColumnDef(this.parseColumn())},condition:function(){return this.parseDisjunction()},dataType:function(){return this.parseTypes({allowIdentifiers:!1,schema:!0})},expression:function(){return this.parseExpression()},from:function(){return this.parseFrom({joins:!0})},grantPrincipal:function(){return this.parseGrantPrincipal()},grantPrivilege:function(){return this.parseGrantPrivilege()},group:function(){return this.parseGroup()},having:function(){return this.parseHaving()},hint:function(){return this.parseHintBody()},identifier:function(){return this.parseIdVar()},join:function(){return this.parseJoin()},lambda:function(){return this.parseLambda()},lateral:function(){return this.parseLateral()},limit:function(){return this.parseLimit()},offset:function(){return this.parseOffset()},order:function(){return this.parseOrder()},ordered:function(){return this.parseOrdered()},properties:function(){return this.parseProperties()},partitionedByProperty:function(){return this.parsePartitionedBy()},qualify:function(){return this.parseQualify()},returning:function(){return this.parseReturning()},select:function(){return this.parseSelect()},sort:function(){return this.parseSort(Ul,"sortBy")},table:function(){return this.parseTableParts()},tableAlias:function(){return this.parseTableAlias()},tuple:function(){return this.parseValue({values:!1})},whens:function(){return this.parseWhenMatched()},where:function(){return this.parseWhere()},window:function(){return this.parseNamedWindow()},with:function(){return this.parseWith()},JOIN_TYPE:function(){let{method:e,side:t,kind:s}=this.parseJoinParts();return new z({method:_optionalChain([e, 'optionalAccess', _202 => _202.text]),side:As(Kt,_optionalChain([t, 'optionalAccess', _203 => _203.text])),kind:As(Kt,_optionalChain([s, 'optionalAccess', _204 => _204.text]))})}}}static get STATEMENT_PARSERS(){return{alter:function(){return this.parseAlter()},analyze:function(){return this.parseAnalyze()},begin:function(){return this.parseTransaction()},cache:function(){return this.parseCache()},comment:function(){return this.parseComment()},commit:function(){return this.parseCommitOrRollback()},copy:function(){return this.parseCopy()},create:function(){return this.parseCreate()},delete:function(){return this.parseDelete()},desc:function(){return this.parseDescribe()},describe:function(){return this.parseDescribe()},drop:function(){return this.parseDrop()},grant:function(){return this.parseGrant()},revoke:function(){return this.parseRevoke()},insert:function(){return this.parseInsert()},kill:function(){return this.parseKill()},load:function(){return this.parseLoad()},merge:function(){return this.parseMerge()},pivot:function(){return this.parseSimplifiedPivot()},pragma:function(){return this.expression(Wl,{this:this.parseExpression()})},refresh:function(){return this.parseRefresh()},rollback:function(){return this.parseCommitOrRollback()},set:function(){return this.parseSet()},truncate:function(){return this.parseTruncateTable()},uncache:function(){return this.parseUncache()},unpivot:function(){return this.parseSimplifiedPivot({isUnpivot:!0})},update:function(){return this.parseUpdate()},use:function(){return this.parseUse()},semicolon:()=>new tE({})}}static get UNARY_PARSERS(){return{plus:function(){return this.parseUnary()},not:function(){return this.expression(rt,{this:this.parseEquality()})},tilde:function(){return this.expression(bn,{this:this.parseUnary()})},dash:function(){return this.expression(Ps,{this:this.parseUnary()})},pipeSlash:function(){return this.expression($a,{this:this.parseUnary()})},dpipeSlash:function(){return this.expression(rp,{this:this.parseUnary()})}}}static get STRING_PARSERS(){return{heredocString:function(e){return this.expression(jc,{token:e})},nationalString:function(e){return this.expression(No,{token:e})},rawString:function(e){return this.expression(jc,{token:e})},string:function(e){return this.expression(w,{token:e,isString:!0})},unicodeString:function(e){return this.expression(xg,{token:e,escape:this.matchTextSeq("UESCAPE")&&this.parseString()})}}}static get NUMERIC_PARSERS(){return{bitString:function(e){return this.expression(XT,{token:e})},byteString:function(e){return this.expression(Qc,{token:e,isBytes:this._dialectConstructor.BYTE_STRING_IS_BYTES_TYPE||void 0})},hexString:function(e){return this.expression(Xi,{token:e,isInteger:this._dialectConstructor.HEX_STRING_IS_INTEGER_TYPE||void 0})},number:function(e){return this.expression(w,{token:e,isString:!1})}}}static get PRIMARY_PARSERS(){return{...M.STRING_PARSERS,...M.NUMERIC_PARSERS,introducer:function(e){return this.parseIntroducer(e)},null:function(e){return this.expression(Qt,{})},true:function(e){return this.expression(Et,{this:!0})},false:function(e){return this.expression(Et,{this:!1})},sessionParameter:function(e){return this.parseSessionParameter()},star:function(e){return this.parseStarOps()}}}static get PLACEHOLDER_PARSERS(){return{placeholder:function(){return this.expression(rr)},parameter:function(){return this.parseParameter()},colon:function(){return this.matchSet(this._constructor.COLON_PLACEHOLDER_TOKENS)?this.expression(rr,{this:_optionalChain([this, 'access', _205 => _205.prev, 'optionalAccess', _206 => _206.text])}):void 0}}}static get RANGE_PARSERS(){return{atGt:Sr(ql),between:function(e){return this.parseBetween(e)},glob:Sr(Jc),ilike:Sr(ms),in:function(e){return this.parseIn(e)},irlike:Sr(wO),is:function(e){return this.parseIs(e)},like:Sr(Ws),ltAt:Sr(ql,{reverseArgs:!0}),overlaps:Sr(eS),rlike:Sr(lc),similarTo:Sr(SE),for:function(e){return this.parseComprehension(e)},qmarkAmp:Sr(cc),qmarkPipe:Sr(oc),hashDash:Sr(pc),adjacent:Sr(mE),operator:function(e){return this.parseOperator(e)},ampLt:Sr(fE),ampGt:Sr(xE)}}static get PIPE_SYNTAX_TRANSFORM_PARSERS(){return{AGGREGATE:function(e){return this.parsePipeSyntaxAggregate(e)},AS:function(e){return this.buildPipeCte({query:e,expressions:[new ye({})],aliasCte:this.parseTableAlias()})},EXTEND:function(e){return this.parsePipeSyntaxExtend(e)},LIMIT:function(e){return this.parsePipeSyntaxLimit(e)},"ORDER BY":function(e){return e.orderBy(this.parseOrder(),{append:!1,copy:!1})},PIVOT:function(e){return this.parsePipeSyntaxPivot(e)},SELECT:function(e){return this.parsePipeSyntaxSelect(e)},TABLESAMPLE:function(e){return this.parsePipeSyntaxTablesample(e)},UNPIVOT:function(e){return this.parsePipeSyntaxPivot(e)},WHERE:function(e){return e.where(this.parseWhere(),{copy:!1})}}}static get PROPERTY_PARSERS(){return{ALLOWED_VALUES:function(){return this.expression(ji,{expressions:this.parseCsv(this.parsePrimary.bind(this))})},ALGORITHM:function(){return this.parsePropertyAssignment(zi)},AUTO:function(){return this.parseAutoProperty()},AUTO_INCREMENT:function(){return this.parsePropertyAssignment(Ki)},BACKUP:function(){return this.expression(Zi,{this:this.parseVar({anyToken:!0})})},BLOCKCOMPRESSION:function(){return this.parseBlockCompression()},CHARSET:function(e){return this.parseCharacterSet(e)},"CHARACTER SET":function(e){return this.parseCharacterSet(e)},CHECKSUM:function(){return this.parseChecksum()},"CLUSTER BY":function(){return this.parseCluster()},CLUSTERED:function(){return this.parseClusteredBy()},COLLATE:function(){return this.parsePropertyAssignment(ea)},COMMENT:function(){return this.parsePropertyAssignment(Nr)},CONTAINS:function(){return this.parseContainsProperty()},COPY:function(){return this.parseCopyProperty()},DATABLOCKSIZE:function(e){return this.parseDataBlocksize(e)},DATA_DELETION:function(){return this.parseDataDeletionProperty()},DEFINER:function(){return this.parseDefiner()},DETERMINISTIC:function(){return this.expression(vr,{this:w.string("IMMUTABLE")})},DISTRIBUTED:function(){return this.parseDistributedProperty()},DUPLICATE:function(){return this.parseCompositeKeyProperty(Vo)},DYNAMIC:function(){return this.expression(Aa,{})},DISTKEY:function(){return this.parseDistkey()},DISTSTYLE:function(){return this.parsePropertyAssignment(ia)},EMPTY:function(){return this.expression(fa,{})},ENGINE:function(){return this.parsePropertyAssignment(aa)},ENVIRONMENT:function(){return this.expression(ga,{expressions:this.parseWrappedCsv(this.parseAssignment.bind(this))})},EXECUTE:function(){return this.parsePropertyAssignment(fn)},EXTERNAL:function(){return this.expression(Nn,{})},FALLBACK:function(e){return this.parseFallback(e)},FORMAT:function(){return this.parsePropertyAssignment($s)},FREESPACE:function(){return this.parseFreespace()},GLOBAL:function(){return this.expression(pa,{})},HEAP:function(){return this.expression(oa,{})},ICEBERG:function(){return this.expression(la,{})},IMMUTABLE:function(){return this.expression(vr,{this:w.string("IMMUTABLE")})},INHERITS:function(){return this.expression(ua,{expressions:this.parseWrappedCsv(this.parseTable.bind(this))})},INPUT:function(){return this.expression(Ea,{this:this.parseSchema()})},JOURNAL:function(e){return this.parseJournal(e)},LANGUAGE:function(){return this.parsePropertyAssignment(ni)},LAYOUT:function(){return this.parseDictProperty({this:"LAYOUT"})},LIFETIME:function(){return this.parseDictRange({this:"LIFETIME"})},LIKE:function(){return this.parseCreateLike()},LOCATION:function(){return this.parsePropertyAssignment(Es)},LOCK:function(){return this.parseLocking()},LOCKING:function(){return this.parseLocking()},LOG:function(e){return this.parseLog(e)},MATERIALIZED:function(){return this.expression(Ta,{})},MERGEBLOCKRATIO:function(e){return this.parseMergeBlockRatio(e)},MODIFIES:function(){return this.parseModifiesProperty()},MULTISET:function(){return this.expression(zn,{multi:!0})},NO:function(){return this.parseNoProperty()},ON:function(){return this.parseOnProperty()},"ORDER BY":function(){return this.parseOrder({skipOrderToken:!0})},OUTPUT:function(){return this.expression(ha,{this:this.parseSchema()})},PARTITION:function(){return this.parsePartitionedOf()},"PARTITION BY":function(){return this.parsePartitionedBy()},"PARTITIONED BY":function(){return this.parsePartitionedBy()},PARTITIONED_BY:function(){return this.parsePartitionedBy()},"PRIMARY KEY":function(){return this.parsePrimaryKey({inProps:!0})},RANGE:function(){return this.parseDictRange({this:"RANGE"})},READS:function(){return this.parseReadsProperty()},REMOTE:function(){return this.parseRemoteWithConnection()},RETURNS:function(){return this.parseReturns()},STRICT:function(){return this.expression(Oa,{})},STREAMING:function(){return this.expression(ma,{})},ROW:function(){return this.parseRow()},ROW_FORMAT:function(){return this.parsePropertyAssignment(Na)},SAMPLE:function(){return this.expression(Ia,{this:this.matchTextSeq("BY")&&this.parseBitwise()})},SECURE:function(){return this.expression(Ma,{})},SECURITY:function(){return this.parseSecurity()},SET:function(){return this.expression(zn,{multi:!1})},SETTINGS:function(){return this.parseSettingsProperty()},SHARING:function(){return this.parsePropertyAssignment(Ca)},SORTKEY:function(){return this.parseSortkey()},SOURCE:function(){return this.parseDictProperty({this:"SOURCE"})},STABLE:function(){return this.expression(vr,{this:w.string("STABLE")})},STORED:function(){return this.parseStored()},SYSTEM_VERSIONING:function(){return this.parseSystemVersioningProperty()},TBLPROPERTIES:function(){return this.parseWrappedProperties()},TEMP:function(){return this.expression(Gr,{})},TEMPORARY:function(){return this.expression(Gr,{})},TO:function(){return this.parseToTable()},TRANSIENT:function(){return this.expression(In,{})},TRANSFORM:function(){return this.expression(La,{expressions:this.parseWrappedCsv(this.parseExpression.bind(this))})},TTL:function(){return this.parseTtl()},USING:function(){return this.parsePropertyAssignment($s)},UNLOGGED:function(){return this.expression(Da,{})},VOLATILE:function(){return this.parseVolatileProperty()},WITH:function(){return this.parseWithProperty()}}}static get CONSTRAINT_PARSERS(){return{AUTOINCREMENT:function(){return this.parseAutoIncrement()},AUTO_INCREMENT:function(){return this.parseAutoIncrement()},CASESPECIFIC:function(){return this.expression(Gi,{not:!1})},"CHARACTER SET":function(){return this.expression(rE,{this:this.parseVarOrString()})},CHECK:function(){return this.parseCheckConstraint()},COLLATE:function(){return this.expression(nE,{this:this.parseIdentifier()||this.parseColumn()})},COMMENT:function(){return this.expression(iE,{this:this.parseString()})},COMPRESS:function(){return this.parseCompress()},CLUSTERED:function(){return this.expression(Uo,{this:this.parseWrappedCsv(()=>this.parseOrdered())})},NONCLUSTERED:function(){return this.expression(qo,{this:this.parseWrappedCsv(()=>this.parseOrdered())})},DEFAULT:function(){return this.expression(oE,{this:this.parseBitwise()})},ENCODE:function(){return this.expression(cE,{this:this.parseVar()})},EPHEMERAL:function(){return this.expression(Zc,{this:this.parseBitwise()})},EXCLUDE:function(){return this.expression(pE,{this:this.parseIndexParams()})},"FOREIGN KEY":function(){return this.parseForeignKey()},FORMAT:function(){return this.expression(aE,{this:this.parseVarOrString()})},GENERATED:function(){return this.parseGeneratedAsIdentity()},IDENTITY:function(){return this.parseAutoIncrement()},INLINE:function(){return this.parseInline()},LIKE:function(){return this.parseCreateLike()},NOT:function(){return this.parseNotConstraint()},NULL:function(){return this.expression($i,{allowNull:!0})},ON:function(){return this.match("update")&&this.expression(EE,{this:this.parseFunction()})||this.expression(Br,{this:this.parseIdVar()})},PATH:function(){return this.expression(gE,{this:this.parseString()})},PERIOD:function(){return this.parsePeriodForSystemTime()},"PRIMARY KEY":function(){return this.parsePrimaryKey()},REFERENCES:function(){return this.parseReferences({match:!1})},TITLE:function(){return this.expression(hE,{this:this.parseVarOrString()})},TTL:function(){return this.expression(vi,{expressions:[this.parseBitwise()]})},UNIQUE:function(){return this.parseUnique()},UPPERCASE:function(){return this.expression(Bo)},WITH:function(){return this.expression(mt,{expressions:this.parseWrappedProperties()})},BUCKET:function(){return this.parsePartitionedByBucketOrTruncate()},TRUNCATE:function(){return this.parsePartitionedByBucketOrTruncate()}}}static get ALTER_PARSERS(){return{ADD:function(){return this.parseAlterTableAdd()},AS:function(){return this.parseSelect()},ALTER:function(){return this.parseAlterTableAlter()},"CLUSTER BY":function(){return this.parseCluster({wrapped:!0})},DELETE:function(){return this.expression(Jn,{where:this.parseWhere()})},DROP:function(){return this.parseAlterTableDrop()},RENAME:function(){return this.parseAlterTableRename()},SET:function(){return this.parseAlterTableSet()},SWAP:function(){return this.expression(xo,{this:this.match("with")&&this.parseTable({schema:!0})})}}}static get NO_PAREN_FUNCTION_PARSERS(){return{ANY:function(){return this.expression(wt,{this:this.parseBitwise()})},CASE:function(){return this.parseCase()},CONNECT_BY_ROOT:function(){return this.expression(yg,{this:this.parseColumn()})},IF:function(){return this.parseIf()}}}static get INVALID_FUNC_NAME_TOKENS(){return new Set(["identifier","string"])}static get KEY_VALUE_DEFINITIONS(){return new Set([Se,Ee,At,Pi])}static get FUNCTION_PARSERS(){return{...Object.fromEntries(Wr.sqlNames().map(e=>[e,function(){return this.parseMaxMinBy(Wr)}])),...Object.fromEntries(jr.sqlNames().map(e=>[e,function(){return this.parseMaxMinBy(jr)}])),CAST:function(){return this.parseCast({strict:this._constructor.STRICT_CAST})},CEIL:function(){return this.parseCeilFloor(Ir)},CONVERT:function(){return this.parseConvert({strict:this._constructor.STRICT_CAST})},CHAR:function(){return this.parseChar()},CHR:function(){return this.parseChar()},DECODE:function(){return this.parseDecode()},EXTRACT:function(){return this.parseExtract()},FLOOR:function(){return this.parseCeilFloor(wn)},GAP_FILL:function(){return this.parseGapFill()},INITCAP:function(){return this.parseInitcap()},JSON_OBJECT:function(){return this.parseJsonObject()},JSON_OBJECTAGG:function(){return this.parseJsonObject({agg:!0})},JSON_TABLE:function(){return this.parseJsonTable()},MATCH:function(){return this.parseMatchAgainst()},NORMALIZE:function(){return this.parseNormalize()},OPENJSON:function(){return this.parseOpenJson()},OVERLAY:function(){return this.parseOverlay()},POSITION:function(){return this.parsePosition()},SAFE_CAST:function(){return this.parseCast({strict:!1,safe:!0})},STRING_AGG:function(){return this.parseStringAgg()},SUBSTRING:function(){return this.parseSubstring()},TRIM:function(){return this.parseTrim()},TRY_CAST:function(){return this.parseCast({strict:!1,safe:!0})},TRY_CONVERT:function(){return this.parseConvert({strict:!1,safe:!0})},XMLELEMENT:function(){return this.parseXmlElement()},XMLTABLE:function(){return this.parseXmlTable()}}}static get QUERY_MODIFIER_PARSERS(){return{matchRecognize:function(){return["match",this.parseMatchRecognize()]},prewhere:function(){return["prewhere",this.parsePrewhere()]},where:function(){return["where",this.parseWhere()]},groupBy:function(){return["group",this.parseGroup()]},having:function(){return["having",this.parseHaving()]},qualify:function(){return["qualify",this.parseQualify()]},window:function(){return["windows",this.parseWindowClause()]},orderBy:function(){return["order",this.parseOrder()]},limit:function(){return["limit",this.parseLimit()]},fetch:function(){return["limit",this.parseLimit()]},offset:function(){return["offset",this.parseOffset()]},for:function(){return["locks",this.parseLocks()]},lock:function(){return["locks",this.parseLocks()]},tableSample:function(){return["sample",this.parseTableSample({asModifier:!0})]},using:function(){return["sample",this.parseTableSample({asModifier:!0})]},clusterBy:function(){return["cluster",this.parseSort(qi,"clusterBy")]},distributeBy:function(){return["distribute",this.parseSort(KT,"distributeBy")]},sortBy:function(){return["sort",this.parseSort(Ul,"sortBy")]},connectBy:function(){return["connect",this.parseConnect({skipStartToken:!0})]},startWith:function(){return["connect",this.parseConnect()]}}}static get QUERY_MODIFIER_TOKENS(){return new Set(Object.keys(M.QUERY_MODIFIER_PARSERS))}static get TYPE_LITERAL_PARSERS(){return{json:function(e,t){return this.expression(up,{this:e})}}}static get TYPE_CONVERTERS(){return{}}static get DDL_SELECT_TOKENS(){return new Set(["select","with","lParen"])}static get PRE_VOLATILE_TOKENS(){return new Set(["create","replace","unique"])}static get OPTYPE_FOLLOW_TOKENS(){return new Set(["comma","rParen"])}static get TABLE_INDEX_HINT_TOKENS(){return new Set(["force","ignore","use"])}static get WINDOW_ALIAS_TOKENS(){return(()=>{let e=new Set(M.ID_VAR_TOKENS);return e.delete("range"),e.delete("rows"),e})()}static get WINDOW_BEFORE_PAREN_TOKENS(){return new Set(["over"])}static get JSON_KEY_VALUE_SEPARATOR_TOKENS(){return new Set(["colon","comma","is"])}static get FETCH_TOKENS(){return(()=>{let e=new Set(M.ID_VAR_TOKENS);return e.delete("row"),e.delete("rows"),e.delete("percent"),e})()}static get ADD_CONSTRAINT_TOKENS(){return new Set(["constraint","foreignKey","index","key","primaryKey","unique"])}static get DISTINCT_TOKENS(){return new Set(["distinct"])}static get UNNEST_OFFSET_ALIAS_TOKENS(){return(()=>{let e=new Set(M.TABLE_ALIAS_TOKENS);for(let t of M.SET_OPERATIONS)e.delete(t);return e})()}static get SELECT_START_TOKENS(){return new Set(["lParen","with","select"])}static get PRIVILEGE_FOLLOW_TOKENS(){return new Set(["on","comma","lParen"])}static get AMBIGUOUS_ALIAS_TOKENS(){return["limit","offset"]}static get MODIFIABLES(){return[ce,V,_c,Gs]}reset(){this.sql="",this.errors=[],this.tokens=[],this.index=0,this.curr=void 0,this.next=void 0,this.prev=void 0,this.prevComments=void 0,this.pipeCteCounter=0}parse(e,t){return this._parse({parseMethod:function(){return this.parseStatement()},rawTokens:e,sql:t})}_parse(e){let{parseMethod:t,rawTokens:s,sql:r}=e;this.reset(),this.sql=r||"";let i=s.length,a=[[]];for(let c=0;c<s.length;c++){let p=s[c];p.tokenType==="semicolon"?(p.comments.length&&a.push([p]),c<i-1&&a.push([])):a[a.length-1].push(p)}let o=[];for(let c of a)this.index=-1,this.tokens=c,this.advance(),o.push(t.call(this)),this.index<this.tokens.length&&this.raiseError("Invalid expression / Unexpected token"),this.checkErrors();return o}parseIntoTypes(e,t,s){let r=[],i=pe(e);for(let c of i){let p=typeof c=="string"?_nullishCoalesce(this._constructor.EXPRESSION_PARSERS[c], () => (this._constructor.EXPRESSION_PARSERS[c.charAt(0).toLowerCase()+c.slice(1)])):this._constructor.EXPRESSION_PARSERS[c.key];if(!p)throw new TypeError(`No parser registered for ${c}`);try{return this._parse({parseMethod:p,rawTokens:t,sql:s})}catch(u){if(u instanceof ns)u.errors[0].intoExpression=typeof c=="string"?c:c.name,r.push(u);else throw u}}let o=`[${pe(e).map(c=>typeof c=="string"?c:c.name).join(", ")}]`;throw new ns(`Failed to parse '${s||t}' into ${o}`,JM(r))}findSql(e,t){return this.sql.slice(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _207 => _207.start]), () => (0)),(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _208 => _208.end]), () => (0)))+1)}isConnected(){return!!(this.prev&&this.curr&&(_nullishCoalesce(this.prev.end, () => (0)))+1===(_nullishCoalesce(this.curr.start, () => (0))))}advance(e=1){this.index+=e,this.curr=b(this.tokens,this.index),this.next=b(this.tokens,this.index+1),0<this.index?(this.prev=this.tokens[this.index-1],this.prevComments=this.prev.comments):(this.prev=void 0,this.prevComments=void 0)}retreat(e){e!==this.index&&this.advance(e-this.index)}warnUnsupported(){if(this.tokens.length<=1)return;let e=this.findSql(this.tokens[0],this.tokens[this.tokens.length-1]).slice(0,this.errorMessageContext);console.warn(`'${e}' contains unsupported syntax. Falling back to parsing as a 'Command'.`)}match(e,t={}){let{advance:s=!0,expression:r}=t;return _optionalChain([this, 'access', _209 => _209.curr, 'optionalAccess', _210 => _210.tokenType])===e?(s&&this.advance(),this.addComments(r),!0):!1}tryParse(e,t={}){let{retreat:s=!1}=t,r=this.index,i=this.errorLevel;this.errorLevel=3;let a;try{a=e()}catch(o){if(o instanceof ns)a=void 0;else throw o}finally{(!a||s)&&this.retreat(r),this.errorLevel=i}return a}parseParen(){if(!this.match("lParen"))return;let e=this.prevComments,t=this.parseSelect(),s;t?s=[t]:s=this.parseExpressions();let r=b(s,0);return!r&&this.match("rParen",{advance:!1})?r=this.expression(Mt,{}):r&&En.some(i=>r instanceof i)?r=this.parseSubquery(r,{parseAlias:!1}):r instanceof ae||r instanceof Gs?r=this.parseSubquery(this.parseQueryModifiers(this.parseSetOperations(r)),{parseAlias:!1}):1<s.length||_optionalChain([this, 'access', _211 => _211.prev, 'optionalAccess', _212 => _212.tokenType])==="comma"?r=this.expression(Mt,{expressions:s}):r=this.expression(Ye,{this:r}),r&&e&&r.addComments(e),this.matchRParen(r),r instanceof Ye&&r.args.this instanceof q?this.parseWindow(r):r}parseDrop(e={}){let{exists:t}=e,s=this.prev,r=this.match("temporary")||void 0,i=this.matchTextSeq("MATERIALIZED")||void 0,a=(this.matchSet(this._constructor.CREATABLES)||void 0)&&_optionalChain([this, 'access', _213 => _213.prev, 'optionalAccess', _214 => _214.text, 'access', _215 => _215.toUpperCase, 'call', _216 => _216()]);if(!a)return this.parseAsCommand(s);let o=this.matchTextSeq("CONCURRENTLY")||void 0,c=t||this.parseExists(),p;a==="COLUMN"?p=this.parseColumn():p=this.parseTableParts({schema:!0,isDbReference:_optionalChain([this, 'access', _217 => _217.prev, 'optionalAccess', _218 => _218.tokenType])==="schema"});let u=this.match("on")?this.parseOnProperty():void 0,E;return this.match("lParen",{advance:!1})&&(E=this.parseWrappedCsv(()=>this.parseTypes())),this.expression(Tn,{exists:c,this:p,expressions:E,kind:_nullishCoalesce(As(uO,this._dialectConstructor.CREATABLE_KIND_MAPPING[a]||a), () => ((this._dialectConstructor.CREATABLE_KIND_MAPPING[a]||a))),temporary:r,materialized:i,cascade:this.matchTextSeq("CASCADE"),constraints:this.matchTextSeq("CONSTRAINTS"),purge:this.matchTextSeq("PURGE"),cluster:u,concurrently:o})}parseExists(e={}){let{not:t}=e;return this.matchTextSeq("IF")&&(!t||this.match("not"))&&this.match("exists")?!0:void 0}parseCreate(){let e=this.prev,t=_optionalChain([e, 'optionalAccess', _219 => _219.tokenType])==="replace"||this.matchPair("or","replace")||this.matchPair("or","alter"),s=this.matchPair("or","refresh")||void 0,r=this.match("unique")||void 0,i;this.matchTextSeq(["CLUSTERED","COLUMNSTORE"])?i=!0:(this.matchTextSeq(["NONCLUSTERED","COLUMNSTORE"])||this.matchTextSeq("COLUMNSTORE"))&&(i=!1),this.matchPair("table","function",{advance:!1})&&this.advance();let a,o=(this.matchSet(this._constructor.CREATABLES)||void 0)&&this.prev;if(!o&&(a=this.parseProperties(),o=(this.matchSet(this._constructor.CREATABLES)||void 0)&&this.prev,!a||!o))return this.parseAsCommand(e);let c=this.matchTextSeq("CONCURRENTLY")||void 0,p=this.parseExists({not:!0}),u,E,g,A,x,m,N,R=y=>{a&&y?_optionalChain([a, 'access', _220 => _220.args, 'access', _221 => _221.expressions, 'optionalAccess', _222 => _222.push, 'call', _223 => _223(..._nullishCoalesce(y.args.expressions, () => ([])))]):y&&(a=y)};if(o.tokenType==="function"||o.tokenType==="procedure"){if(u=this.parseUserDefinedFunction({kind:o.tokenType}),R(this.parseProperties()),E=this.match("alias")&&this.parseHeredoc()||void 0,R(this.parseProperties()),!E)if(this.match("command"))E=this.parseAsCommand(this.prev);else{x=this.match("begin")||void 0;let y=this.matchTextSeq("RETURN")||void 0;this.match("string",{advance:!1})?(E=this.parseString(),R(this.parseProperties())):E=this.parseUserDefinedFunctionExpression(),m=this.matchTextSeq("END")||void 0,y&&(E=this.expression(bo,{this:E}))}}else if(o.tokenType==="index"){let y,P;this.match("on")?(y=void 0,P=!0):(y=this.parseIdVar(),P=!1),u=this.parseIndex({index:y,anonymous:P})}else if(this._constructor.DB_CREATABLES.has(o.tokenType)){let y=this.parseTableParts({schema:!0,isDbReference:o.tokenType==="schema"});this.match("comma"),R(this.parseProperties({before:!0})),u=this.parseSchema({this:y}),R(this.parseProperties());let P=this.match("alias")||void 0;if(this.matchSet(this._constructor.DDL_SELECT_TOKENS,{advance:!1})||R(this.parseProperties()),o.tokenType==="sequence"){E=this.parseTypes();let H=this.parseProperties();if(H){let B=new Wn({}),fe=[];for(let _e of _nullishCoalesce(H.args.expressions, () => ([])))if(_e instanceof Wn){for(let[Is,zt]of Object.entries(_e.args))Is==="options"?fe.push(...zt):B.setArgKey(Is,zt);_e.pop()}0<fe.length&&B.setArgKey("options",fe),_optionalChain([H, 'access', _224 => _224.args, 'access', _225 => _225.expressions, 'optionalAccess', _226 => _226.push, 'call', _227 => _227(B)]),R(H)}}else E=this.parseDdlSelect(),!E&&P&&(E=this.tryParse(()=>this.parseTableParts()));if(o.tokenType==="table")for(R(this.parseProperties()),g=[];;){let H=this.parseIndex();if(R(this.parseProperties()),H)this.match("comma"),g.push(H);else break}else o.tokenType==="view"?this.matchTextSeq(["WITH","NO","SCHEMA","BINDING"])&&(A=!0):(o.tokenType==="sink"||o.tokenType==="source")&&R(this.parseProperties());let v=this.matchTextSeq("SHALLOW")||void 0;if(this.matchTexts(this._constructor.CLONE_KEYWORDS)){let H=_optionalChain([this, 'access', _228 => _228.prev, 'optionalAccess', _229 => _229.text, 'access', _230 => _230.toLowerCase, 'call', _231 => _231()])==="copy";N=this.expression(Yl,{this:this.parseTable({schema:!0}),shallow:v,copy:H})}}if(this.curr&&!this.matchSet(new Set(["rParen","comma"]),{advance:!1}))return this.parseAsCommand(e);let S=o.text.toUpperCase(),I=this._dialectConstructor.CREATABLE_KIND_MAPPING[S]||S;return this.expression(us,{this:u,kind:_nullishCoalesce(As(Ol,I), () => (I)),replace:t,refresh:s,unique:r,expression:E,exists:p,properties:a,indexes:g,noSchemaBinding:A,begin:x,end:m,clone:N,concurrently:c,clustered:i})}parseCommand(){return this.warnUnsupported(),this.expression(jn,{comments:this.prevComments,this:_optionalChain([this, 'access', _232 => _232.prev, 'optionalAccess', _233 => _233.text, 'access', _234 => _234.toUpperCase, 'call', _235 => _235()]),expression:this.parseString()})}parseSequenceProperties(){let e=new Wn({}),t=[],s=this.index;for(;this.curr;)if(this.match("comma"),this.matchTextSeq("INCREMENT"))this.matchTextSeq("BY"),this.matchTextSeq("="),e.setArgKey("increment",this.parseTerm());else if(this.matchTextSeq("MINVALUE"))e.setArgKey("minvalue",this.parseTerm());else if(this.matchTextSeq("MAXVALUE"))e.setArgKey("maxvalue",this.parseTerm());else if(this.match("startWith")||this.matchTextSeq("START"))this.matchTextSeq("="),e.setArgKey("start",this.parseTerm());else if(this.matchTextSeq("CACHE"))e.setArgKey("cache",this.parseNumber()||!0);else if(this.matchTextSeq(["OWNED","BY"]))e.setArgKey("owned",this.matchTextSeq("NONE")?void 0:this.parseColumn());else{let r=this.parseVarFromOptions(this._constructor.CREATE_SEQUENCE,{raiseUnmatched:!1});if(r)t.push(r);else break}return e.setArgKey("options",0<t.length?t:void 0),this.index===s?void 0:e}parsePropertyBefore(){this.match("comma");let e={no:this.matchTextSeq("NO")||!1,dual:this.matchTextSeq("DUAL")||!1,before:this.matchTextSeq("BEFORE")||!1,default:this.matchTextSeq("DEFAULT")||!1,local:this.matchTextSeq("LOCAL")&&"LOCAL"||this.matchTextSeq(["NOT","LOCAL"])&&"NOT LOCAL"||!1,after:this.matchTextSeq("AFTER")||!1,minimum:this.matchTexts(["MIN","MINIMUM"])||!1,maximum:this.matchTexts(["MAX","MAXIMUM"])||!1};if(this.matchTexts(Object.keys(this._constructor.PROPERTY_PARSERS))){let t=this._constructor.PROPERTY_PARSERS[(_nullishCoalesce(_optionalChain([this, 'access', _236 => _236.prev, 'optionalAccess', _237 => _237.text]), () => (""))).toUpperCase()];try{let s=Object.fromEntries(Object.entries(e).filter(([,i])=>i));return _nullishCoalesce(t.call(this,s), () => (void 0))}catch(s){if(s instanceof ns)throw s;this.raiseError(`Cannot parse property '${_nullishCoalesce(_optionalChain([this, 'access', _238 => _238.prev, 'optionalAccess', _239 => _239.text]), () => (""))}'`)}}}parseWrappedProperties(){return this.parseWrappedCsv(()=>this.parseProperty())}parseProperty(){if(this.matchTexts(Object.keys(this._constructor.PROPERTY_PARSERS)))return _nullishCoalesce(this._constructor.PROPERTY_PARSERS[(_nullishCoalesce(_optionalChain([this, 'access', _240 => _240.prev, 'optionalAccess', _241 => _241.text]), () => (""))).toUpperCase()].call(this), () => (void 0));if(this.match("default")&&this.matchTexts(Object.keys(this._constructor.PROPERTY_PARSERS)))return _nullishCoalesce(this._constructor.PROPERTY_PARSERS[(_nullishCoalesce(_optionalChain([this, 'access', _242 => _242.prev, 'optionalAccess', _243 => _243.text]), () => (""))).toUpperCase()].call(this,{default:!0}), () => (void 0));if(this.matchTextSeq(["COMPOUND","SORTKEY"]))return this.parseSortkey({compound:!0});if(this.matchTextSeq(["SQL","SECURITY"]))return this.expression(wa,{this:this.matchTexts(["DEFINER","INVOKER"])&&(_nullishCoalesce(_optionalChain([this, 'access', _244 => _244.prev, 'optionalAccess', _245 => _245.text]), () => (""))).toUpperCase()});let e=this.index,t=this.parseSequenceProperties();if(t)return t;this.retreat(e);let s=this.parseColumn();if(!this.match("eq")){this.retreat(e);return}s instanceof k&&(s=s.parts&&1<s.parts.length?s.toDot()||Te(s.name):Te(s.name));let r=this.parseBitwise()||this.parseVar({anyToken:!0});return r instanceof k&&(r=Te(r.name)),this.expression(U,{this:s,value:r})}parseStored(){if(this.matchTextSeq("BY"))return this.expression(pi,{this:this.parseVarOrString()});this.match("alias");let e=(this.matchTextSeq("INPUTFORMAT")||void 0)&&this.parseString(),t=(this.matchTextSeq("OUTPUTFORMAT")||void 0)&&this.parseString();return this.expression($s,{this:e||t?this.expression(Co,{inputFormat:e,outputFormat:t}):this.parseVarOrString()||this.parseNumber()||this.parseIdVar(),hiveFormat:!0})}parseUnquotedField(){let e=this.parseField();return e instanceof G&&!e.args.quoted?Te(e):e}parsePropertyAssignment(e,t){return this.match("eq"),this.match("alias"),this.expression(e,{this:this.parseUnquotedField(),...t})}parseProperties(e){let t=[];for(;;){let s=_optionalChain([e, 'optionalAccess', _246 => _246.before])?this.parsePropertyBefore():this.parseProperty();if(s===void 0||Array.isArray(s)&&s.length===0)break;let r=Array.isArray(s)?s:[s];for(let i of r)t.push(i)}if(0<t.length)return this.expression(mt,{expressions:t})}parseFallback(e){return this.expression(Wo,{no:_optionalChain([e, 'optionalAccess', _247 => _247.no]),protection:this.matchTextSeq("PROTECTION")})}parseSecurity(){if(this.matchTexts(["NONE","DEFINER","INVOKER"])){let e=_optionalChain([this, 'access', _248 => _248.prev, 'optionalAccess', _249 => _249.text, 'access', _250 => _250.toUpperCase, 'call', _251 => _251()]);return this.expression(ya,{this:e})}}parseSettingsProperty(){return this.expression(ba,{expressions:this.parseCsv(()=>this.parseAssignment())})}parseVolatileProperty(){let e;return 2<=this.index&&(e=this.tokens[this.index-2]),e&&this._constructor.PRE_VOLATILE_TOKENS.has(e.tokenType)?new Vs({}):this.expression(vr,{this:w.string("VOLATILE")})}parseRetentionPeriod(){let e=this.parseNumber(),t=e?`${e} `:"",s=this.parseVar({anyToken:!0});return Te(`${t}${s}`)}parseSystemVersioningProperty(e={}){let{with:t=!1}=e;this.match("eq");let s=this.expression(rc,{on:!0,with:t});if(this.matchTextSeq("OFF"))return s.setArgKey("on",!1),s;if(this.match("on"),this.match("lParen"))for(;this.curr&&!this.match("rParen");)this.matchTextSeq(["HISTORY_TABLE","="])?s.setArgKey("this",this.parseTableParts()):this.matchTextSeq(["DATA_CONSISTENCY_CHECK","="])?(this.advance(),s.setArgKey("dataConsistency",_optionalChain([this, 'access', _252 => _252.prev, 'optionalAccess', _253 => _253.text, 'access', _254 => _254.toUpperCase, 'call', _255 => _255()]))):this.matchTextSeq(["HISTORY_RETENTION_PERIOD","="])&&s.setArgKey("retentionPeriod",this.parseRetentionPeriod()),this.match("comma");return s}parseDataDeletionProperty(){this.match("eq");let e=this.matchTextSeq("ON")||!this.matchTextSeq("OFF"),t=this.expression(Ho,{on:e});if(this.match("lParen"))for(;this.curr&&!this.match("rParen");)this.matchTextSeq(["FILTER_COLUMN","="])?t.setArgKey("filterColumn",this.parseColumn()):this.matchTextSeq(["RETENTION_PERIOD","="])&&t.setArgKey("retentionPeriod",this.parseRetentionPeriod()),this.match("comma");return t}parseDistributedProperty(){let e="HASH",t;this.matchTextSeq(["BY","HASH"])?t=this.parseWrappedCsv(()=>this.parseIdVar()):this.matchTextSeq(["BY","RANDOM"])&&(e="RANDOM");let s;return this.matchTextSeq("BUCKETS")&&!this.matchTextSeq("AUTO")&&(s=this.parseNumber()),this.expression(na,{expressions:t,kind:e,buckets:s,order:this.parseOrder()})}parseCompositeKeyProperty(e){this.matchTextSeq("KEY");let t=this.parseWrappedIdVars();return this.expression(e,{expressions:t})}parseWithProperty(){if(this.matchTextSeq(["(","SYSTEM_VERSIONING"])){let e=this.parseSystemVersioningProperty({with:!0});return this.matchRParen(),e}if(this.match("lParen",{advance:!1}))return this.parseWrappedProperties();if(this.matchTextSeq("JOURNAL"))return this.parseWithjournaltable();if(this.matchTexts(Array.from(this._constructor.VIEW_ATTRIBUTES)))return this.expression(_a,{this:_optionalChain([this, 'access', _256 => _256.prev, 'optionalAccess', _257 => _257.text, 'access', _258 => _258.toUpperCase, 'call', _259 => _259()])});if(this.matchTextSeq("DATA"))return this.parseWithdata({no:!1});if(this.matchTextSeq(["NO","DATA"]))return this.parseWithdata({no:!0});if(this.match("serdeProperties",{advance:!1}))return this.parseSerdeProperties({with:!0});if(this.match("schema"))return this.expression(Ua,{this:this.parseVarFromOptions(this._constructor.SCHEMA_BINDING_OPTIONS)});if(this.matchTexts(Object.keys(this._constructor.PROCEDURE_OPTIONS),{advance:!1}))return this.expression(qa,{expressions:this.parseCsv(()=>this.parseProcedureOption())});if(this.next)return this.parseWithIsolatedLoading()}parseProcedureOption(){return this.matchTextSeq(["EXECUTE","AS"])?this.expression(fn,{this:this.parseVarFromOptions(this._constructor.EXECUTE_AS_OPTIONS,{raiseUnmatched:!1})||this.parseString()}):this.parseVarFromOptions(this._constructor.PROCEDURE_OPTIONS)}parseDefiner(){this.match("eq");let e=this.parseIdVar();this.match("parameter");let t=this.parseIdVar()||this.match("mod")&&_optionalChain([this, 'access', _260 => _260.prev, 'optionalAccess', _261 => _261.text]);if(!(!e||!t))return new sa({this:`${e}@${t}`})}parseWithjournaltable(){return this.match("table"),this.match("eq"),this.expression(ka,{this:this.parseTableParts()})}parseLog(e={}){let{no:t=!1}=e;return this.expression(xa,{no:t})}parseJournal(e){return this.expression(Xo,e)}parseChecksum(){this.match("eq");let e;return this.match("on")?e=!0:this.matchTextSeq("OFF")&&(e=!1),this.expression($o,{on:e,default:this.match("default")})}parseCluster(e={}){let{wrapped:t=!1}=e;return this.expression(qi,{expressions:t?this.parseWrappedCsv(()=>this.parseOrdered()):this.parseCsv(()=>this.parseOrdered())})}parseClusteredBy(){this.matchTextSeq("BY"),this.matchLParen();let e=this.parseCsv(()=>this.parseColumn());this.matchRParen();let t;this.matchTextSeq(["SORTED","BY"])&&(this.matchLParen(),t=this.parseCsv(()=>this.parseOrdered()),this.matchRParen()),this.match("into");let s=this.parseNumber();return this.matchTextSeq("BUCKETS"),this.expression(da,{expressions:e,sortedBy:t,buckets:s})}parseCopyProperty(){if(!this.matchTextSeq("GRANTS")){this.retreat(this.index-1);return}return this.expression(ta,{})}parseFreespace(){return this.match("eq"),this.expression(jo,{this:this.parseNumber(),percent:this.match("percent")})}parseMergeBlockRatio(e={}){let{no:t=!1,default:s=!1}=e;return this.match("eq")?this.expression(Yi,{this:this.parseNumber(),percent:this.match("percent")}):this.expression(Yi,{no:t,default:s})}parseDataBlocksize(e={}){let{default:t,minimum:s,maximum:r}=e;this.match("eq");let i=this.parseNumber(),a;return this.matchTexts(["BYTES","KBYTES","KILOBYTES"])&&(a=_nullishCoalesce(_optionalChain([this, 'access', _262 => _262.prev, 'optionalAccess', _263 => _263.text]), () => (""))),this.expression(Yo,{size:i,units:a,default:t,minimum:s,maximum:r})}parseBlockCompression(){this.match("eq");let e=this.matchTextSeq("ALWAYS")||void 0,t=this.matchTextSeq("MANUAL")||void 0,s=this.matchTextSeq("NEVER")||void 0,r=this.matchTextSeq("DEFAULT")||void 0,i;return this.matchTextSeq("AUTOTEMP")&&(i=this.parseSchema()),this.expression(Go,{always:e,manual:t,never:s,default:r,autotemp:i})}parseWithIsolatedLoading(){let e=this.index,t=this.matchTextSeq("NO")||void 0,s=this.matchTextSeq("CONCURRENT")||void 0;if(!this.matchTextSeq(["ISOLATED","LOADING"])){this.retreat(e);return}let r=this.parseVarFromOptions(this._constructor.ISOLATED_LOADING_OPTIONS,{raiseUnmatched:!1});return this.expression(Jo,{no:t,concurrent:s,target:r})}parseLocking(){let e;this.match("table")?e="TABLE":this.match("view")?e="VIEW":this.match("row")?e="ROW":this.matchTextSeq("DATABASE")&&(e="DATABASE");let t;(e==="DATABASE"||e==="TABLE"||e==="VIEW")&&(t=this.parseTableParts());let s;this.match("for")?s="FOR":this.match("in")&&(s="IN");let r;this.matchTextSeq("ACCESS")?r="ACCESS":this.matchTexts(["EXCL","EXCLUSIVE"])?r="EXCLUSIVE":this.matchTextSeq("SHARE")?r="SHARE":this.matchTextSeq("READ")?r="READ":this.matchTextSeq("WRITE")?r="WRITE":this.matchTextSeq("CHECKSUM")&&(r="CHECKSUM");let i=this.matchTextSeq("OVERRIDE")||void 0;return this.expression(Zo,{this:t,kind:e,forOrIn:s,lockType:r,override:i})}parsePartitionBy(){return this.match("partitionBy")?this.parseCsv(()=>this.parseDisjunction()):[]}parsePartitionBoundSpec(){let e=()=>this.matchTextSeq("MINVALUE")?Te("MINVALUE"):this.matchTextSeq("MAXVALUE")?Te("MAXVALUE"):this.parseBitwise(),t,s,r,i;return this.match("in")?t=this.parseWrappedCsv(()=>this.parseBitwise()):this.match("from")?(r=this.parseWrappedCsv(e),this.matchTextSeq("TO"),i=this.parseWrappedCsv(e)):this.matchTextSeq(["WITH","(","MODULUS"])?(t=this.parseNumber(),this.matchTextSeq([",","REMAINDER"]),s=this.parseNumber(),this.matchRParen()):this.raiseError("Failed to parse partition bound spec."),this.expression(yo,{this:t,expression:s,fromExpressions:r,toExpressions:i})}parsePartitionedOf(){if(!this.matchTextSeq("OF")){this.retreat(this.index-1);return}let e=this.parseTable({schema:!0}),t;return this.match("default")?t=Te("DEFAULT"):this.matchTextSeq(["FOR","VALUES"])?t=this.parsePartitionBoundSpec():(this.raiseError("Expecting either DEFAULT or FOR VALUES clause."),t=Te("DEFAULT")),this.expression(ec,{this:e,expression:t})}parsePartitionedBy(){return this.match("eq"),this.expression(Bt,{this:this.parseSchema()||this.parseBracket(this.parseField())})}parseWithdata(e={}){let t;return this.matchTextSeq(["AND","STATISTICS"])?t=!0:this.matchTextSeq(["AND","NO","STATISTICS"])&&(t=!1),this.expression(li,{no:_optionalChain([e, 'optionalAccess', _264 => _264.no]),statistics:t})}parseContainsProperty(){if(this.matchTextSeq("SQL"))return this.expression(qr,{this:"CONTAINS SQL"})}parseModifiesProperty(){if(this.matchTextSeq(["SQL","DATA"]))return this.expression(qr,{this:"MODIFIES SQL DATA"})}parseNoProperty(){if(this.matchTextSeq(["PRIMARY","INDEX"]))return new Sa({});if(this.matchTextSeq("SQL"))return this.expression(qr,{this:"NO SQL"})}parseOnProperty(){return this.matchTextSeq(["COMMIT","PRESERVE","ROWS"])?new Xn({}):this.matchTextSeq(["COMMIT","DELETE","ROWS"])?new Xn({delete:!0}):this.expression(Br,{this:this.parseSchema({this:this.parseIdVar()})})}parseReadsProperty(){if(this.matchTextSeq(["SQL","DATA"]))return this.expression(qr,{this:"READS SQL DATA"})}parseDistkey(){return this.expression(ra,{this:this.parseWrapped(()=>this.parseIdVar())})}parseCreateLike(){let e=this.parseTable({schema:!0}),t=[];for(;this.matchTexts(["INCLUDING","EXCLUDING"]);){let s=(_nullishCoalesce(_optionalChain([this, 'access', _265 => _265.prev, 'optionalAccess', _266 => _266.text]), () => (""))).toUpperCase(),r=this.parseIdVar();if(!r)return;let i=r.args.this;t.push(this.expression(U,{this:s,value:Te(typeof i=="string"?i.toUpperCase():"")}))}return this.expression(Qo,{this:e,expressions:t})}parseSortkey(e={}){let t=this.parseWrappedIdVars(),s=t.length===1?t[0]:this.expression(Mt,{expressions:t});return this.expression(Pa,{this:s,compound:_optionalChain([e, 'optionalAccess', _267 => _267.compound])})}parseCharacterSet(e={}){return this.match("eq"),this.expression(ri,{this:this.parseVarOrString(),default:_optionalChain([e, 'optionalAccess', _268 => _268.default])})}parseRemoteWithConnection(){return this.matchTextSeq(["WITH","CONNECTION"]),this.expression(Ra,{this:this.parseTableParts()})}parseReturns(){let e,t,s=this.match("table")||void 0;return s?this.match("lt")?(e=this.expression(Lt,{this:"TABLE",expressions:this.parseCsv(()=>this.parseStructTypes())}),this.match("gt")||this.raiseError("Expecting >")):e=this.parseSchema({this:Te("TABLE")}):this.matchTextSeq(["NULL","ON","NULL","INPUT"])?(t=!0,e=void 0):e=this.parseTypes(),this.expression(oi,{this:e,isTable:s,null:t})}parseDescribe(){let e=(this.matchSet(this._constructor.CREATABLES)||void 0)&&_optionalChain([this, 'access', _269 => _269.prev, 'optionalAccess', _270 => _270.text]),t=(this.matchTexts(Array.from(this._constructor.DESCRIBE_STYLES))||void 0)&&_optionalChain([this, 'access', _271 => _271.prev, 'optionalAccess', _272 => _272.text, 'access', _273 => _273.toUpperCase, 'call', _274 => _274()]);this.match("dot")&&(t=void 0,this.retreat(this.index-2));let s=this.match("format",{advance:!1})?this.parseProperty():void 0,r;this.matchSet(new Set(Object.keys(this._constructor.STATEMENT_PARSERS)),{advance:!1})?r=this.parseStatement():r=this.parseTable({schema:!0});let a=_optionalChain([this, 'access', _275 => _275.parseProperties, 'call', _276 => _276(), 'optionalAccess', _277 => _277.args, 'access', _278 => _278.expressions]),o=this.parsePartition();return this.expression(ei,{this:r,style:t,kind:e,expressions:a,partition:o,format:s,asJson:this.matchTextSeq(["AS","JSON"])})}parseMultitableInserts(e){let t=(_nullishCoalesce(_optionalChain([this, 'access', _279 => _279.prev, 'optionalAccess', _280 => _280.text]), () => (""))).toUpperCase(),s=[],r=()=>{let a;this.match("when")&&(a=this.parseDisjunction(),this.match("then"));let o=this.match("else")||void 0;if(this.match("into"))return this.expression(uu,{this:this.expression(Ss,{this:this.parseTable({schema:!0}),expression:this.parseDerivedTableValues()}),expression:a,else:o})},i=r();for(;i!==void 0;)s.push(i),i=r();return this.expression(Oo,{kind:t,comments:e,expressions:s,source:this.parseTable()})}parseInsert(){let e=[],t=this.parseHint(),s=this.match("overwrite")||void 0,r=this.match("ignore")||void 0,i=this.matchTextSeq("LOCAL")||void 0,a,o,c;if(this.matchTextSeq("DIRECTORY"))c=this.expression(So,{this:this.parseVarOrString(),local:i,rowFormat:this.parseRowFormat({matchRow:!0})});else{if(this.matchSet(new Set(["first","all"])))return e.push(...pe(this.prevComments)),this.parseMultitableInserts(e);this.match("or")&&(a=this.matchTexts(Array.from(this._constructor.INSERT_ALTERNATIVES))&&_optionalChain([this, 'access', _281 => _281.prev, 'optionalAccess', _282 => _282.text])||void 0),this.match("into"),e.push(...pe(this.prevComments)),this.match("table"),o=this.match("function")||void 0,c=o?this.parseFunction():this.parseInsertTable()}let p=this.parseReturning();return this.expression(Ss,{comments:e,hint:t,isFunction:o,this:c,stored:this.matchTextSeq("STORED")&&this.parseStored(),byName:this.matchTextSeq(["BY","NAME"]),exists:this.parseExists(),where:this.matchPair("replace","where")&&this.parseDisjunction(),partition:this.match("partitionBy")&&this.parsePartitionedBy(),settings:this.matchTextSeq("SETTINGS")&&this.parseSettingsProperty(),default:this.matchTextSeq(["DEFAULT","VALUES"]),expression:this.parseDerivedTableValues()||this.parseDdlSelect(),conflict:this.parseOnConflict(),returning:p||this.parseReturning(),overwrite:s,alternative:a,ignore:r,source:this.match("table")&&this.parseTable()})}parseInsertTable(){let e=this.parseTable({schema:!0,parsePartition:!0});return e instanceof V&&this.match("alias",{advance:!1})&&e.setArgKey("alias",this.parseTableAlias()),e}parseKill(){let e=this.matchTexts(["CONNECTION","QUERY"])?Te(_nullishCoalesce(_optionalChain([this, 'access', _283 => _283.prev, 'optionalAccess', _284 => _284.text]), () => (""))):void 0;return this.expression(Vl,{this:this.parsePrimary(),kind:e})}parseOnConflict(){let e=this.matchTextSeq(["ON","CONFLICT"])||void 0,t=this.matchTextSeq(["ON","DUPLICATE","KEY"])||void 0;if(!e&&!t)return;let s,r;e&&(this.matchTextSeq(["ON","CONSTRAINT"])?r=this.parseIdVar():this.match("lParen")&&(s=this.parseCsv(()=>this.parseIdVar()),this.matchRParen()));let i=this.parseWhere(),a=this.parseVarFromOptions(this._constructor.CONFLICT_ACTIONS),o;return _optionalChain([this, 'access', _285 => _285.prev, 'optionalAccess', _286 => _286.tokenType])==="update"&&(this.match("set"),o=this.parseCsv(()=>this.parseEquality())),this.expression(Eu,{duplicate:t,expressions:o,action:a,conflictKeys:s,indexPredicate:i,constraint:r,where:this.parseWhere()})}parseReturning(){if(this.match("returning"))return this.expression(zc,{expressions:this.parseCsv(()=>this.parseExpression()),into:this.match("into")&&this.parseTablePart()})}parseRow(){if(this.match("format"))return this.parseRowFormat()}parseSerdeProperties(e={}){let t=this.index,s=_optionalChain([e, 'optionalAccess', _287 => _287.with])||this.matchTextSeq("WITH");if(!this.match("serdeProperties")){this.retreat(t);return}return this.expression(ci,{expressions:this.parseWrappedProperties(),with:s})}parseRowFormat(e={}){if(_optionalChain([e, 'optionalAccess', _288 => _288.matchRow])&&!this.matchPair("row","format"))return;if(this.matchTextSeq("SERDE")){let s=this.parseString(),r=this.parseSerdeProperties();return this.expression(sc,{this:s,serdeProperties:r})}this.matchTextSeq("DELIMITED");let t={};return this.matchTextSeq(["FIELDS","TERMINATED","BY"])&&(t.fields=this.parseString(),this.matchTextSeq(["ESCAPED","BY"])&&(t.escaped=this.parseString())),this.matchTextSeq(["COLLECTION","ITEMS","TERMINATED","BY"])&&(t.collectionItems=this.parseString()),this.matchTextSeq(["MAP","KEYS","TERMINATED","BY"])&&(t.mapKeys=this.parseString()),this.matchTextSeq(["LINES","TERMINATED","BY"])&&(t.lines=this.parseString()),this.matchTextSeq(["NULL","DEFINED","AS"])&&(t.null=this.parseString()),this.expression(tc,t)}parseSelect(e={}){let{nested:t=!1,table:s=!1,parseSubqueryAlias:r=!0,parseSetOperation:i=!0,consumePipe:a=!0,from:o}=e,c=this.parseSelectQuery({nested:t,table:s,parseSubqueryAlias:r,parseSetOperation:i});return a&&this.match("pipeGt",{advance:!1})&&(!c&&o&&(c=ft("*").from(o)),c instanceof ce&&(c=this.parsePipeSyntaxQuery(c),c=c&&s?c.subquery(void 0,{copy:!1}):c)),c}parseSelectQuery(e={}){let{nested:t=!1,table:s=!1,parseSubqueryAlias:r=!0,parseSetOperation:i=!0}=e,a=this.parseWith(),o;if(a){if(o=this.parseStatement(),!o)return this.raiseError("Failed to parse any statement following CTE"),a;for(;o instanceof ae&&o.isWrapper;)o=o.args.this;return _optionalChain([o, 'optionalAccess', _289 => _289._constructor, 'access', _290 => _290.availableArgs, 'access', _291 => _291.has, 'call', _292 => _292("with")])?o.setArgKey("with",a):(this.raiseError(`${_optionalChain([o, 'optionalAccess', _293 => _293._constructor, 'access', _294 => _294.key])||"Unknown expression"} does not support CTE`),o=a),o}let c;if(this.match("from",{advance:!1})&&(c=this.parseFrom({joins:!0,consumePipe:!0})),this.match("select")){let p=this.prevComments,u=this.parseHint(),E,g;this.next&&this.next.tokenType!=="dot"&&(E=this.match("all")||void 0,g=this.matchSet(this._constructor.DISTINCT_TOKENS)?new ct:void 0);let A=this.match("alias")&&this.matchTexts(["STRUCT","VALUE"])&&_optionalChain([this, 'access', _295 => _295.prev, 'optionalAccess', _296 => _296.text, 'access', _297 => _297.toUpperCase, 'call', _298 => _298()])||void 0;g&&(g=this.expression(ct,{on:this.match("on")?this.parseValue({values:!1}):void 0})),E&&g&&this.raiseError("Cannot specify both ALL and DISTINCT after SELECT");let x=[];for(;this.curr&&this.matchTexts(Array.from(this._constructor.OPERATION_MODIFIERS));)x.push(Te((_nullishCoalesce(_optionalChain([this, 'access', _299 => _299.prev, 'optionalAccess', _300 => _300.text]), () => (""))).toUpperCase()));let m=this.parseLimit(void 0,{top:!0}),N=this.parseProjections();o=this.expression($,{kind:A,hint:u,distinct:g,expressions:N,limit:m,operationModifiers:0<x.length?x:void 0}),o.comments=p;let R=this.parseInto();R&&o.setArgKey("into",R),c||(c=this.parseFrom()),c&&o.setArgKey("from",c),o=this.parseQueryModifiers(o)}else{if((s||t)&&this.match("lParen"))return o=this.parseWrappedSelect({table:s}),this.matchRParen(),this.parseSubquery(o,{parseAlias:r});if(this.match("values",{advance:!1}))o=this.parseDerivedTableValues();else if(c)o=ft("*").from(c.args.this,{copy:!1});else if(this.match("summarize")){let p=this.match("table")||void 0;return o=this.parseSelect()||this.parseString()||this.parseTable(),this.expression(Hl,{this:o,table:p})}else{if(this.match("describe"))return this.parseDescribe();o=void 0}}return i?this.parseSetOperations(o):o}parseRecursiveWithSearch(){this.matchTextSeq("SEARCH");let e=(this.matchTexts(Array.from(this._constructor.RECURSIVE_CTE_SEARCH_KIND))||void 0)&&_optionalChain([this, 'access', _301 => _301.prev, 'optionalAccess', _302 => _302.text, 'access', _303 => _303.toUpperCase, 'call', _304 => _304()]);if(e)return this.matchTextSeq(["FIRST","BY"]),this.expression(zl,{kind:e,this:this.parseIdVar(),expression:this.matchTextSeq("SET")&&this.parseIdVar(),using:this.matchTextSeq("USING")&&this.parseIdVar()})}parseWith(e={}){let{skipWithToken:t=!1}=e;if(!t&&!this.match("with"))return;let s=this.prevComments,r=this.match("recursive")||void 0,i,a=[];for(;;){let o=this.parseCte();if(o instanceof Yt&&(a.push(o),i&&o.addComments(i)),!this.match("comma")&&!this.match("with"))break;this.match("with"),i=this.prevComments}return this.expression(ve,{comments:s,expressions:a,recursive:r,search:this.parseRecursiveWithSearch()})}parseCte(){let e=this.index,t=this.parseTableAlias({aliasTokens:this._constructor.ID_VAR_TOKENS});(!t||!t.args.this)&&this.raiseError("Expected CTE to have alias");let s=this.matchTextSeq(["USING","KEY"])?this.parseWrappedIdVars():void 0;if(!this.match("alias")&&!this._constructor.OPTIONAL_ALIAS_TOKEN_CTE){this.retreat(e);return}let r=this.prevComments,i;this.matchTextSeq(["NOT","MATERIALIZED"])?i=!1:this.matchTextSeq("MATERIALIZED")&&(i=!0);let a=this.expression(Yt,{this:this.parseWrapped(()=>this.parseStatement()),alias:t,materialized:i,keyExpressions:s,comments:r}),o=a.args.this;return o instanceof Gs&&(o.alias?a.setArgKey("this",ft("*").from(o)):a.setArgKey("this",ft("*").from(oe(o,"_values",{table:!0})))),a}parseTableAlias(e={}){let{aliasTokens:t}=e;if(this.canParseLimitOrOffset())return;let s=this.match("alias"),r=this.parseIdVar({anyToken:s,tokens:t||this._constructor.TABLE_ALIAS_TOKENS})||this.parseStringAsIdentifier(),i=this.index,a;if(this.match("lParen")?(a=this.parseCsv(()=>this.parseFunctionParameter()),!a||a.length===0?this.retreat(i):this.matchRParen()):a=void 0,!r&&(!a||a.length===0))return;let o=this.expression(ie,{this:r,columns:a});return r instanceof G&&o.addComments(r.popComments()),o}parseSubquery(e,t={}){let{parseAlias:s=!0}=t;if(e)return this.expression(ae,{this:e,pivots:this.parsePivots(),alias:s?this.parseTableAlias():void 0,sample:this.parseTableSample()})}implicitUnnestsToExplicit(e){let t=new Set,s=e.args;if("from"in s){let i=_optionalChain([s, 'access', _305 => _305.from, 'optionalAccess', _306 => _306.args, 'access', _307 => _307.this]);if(i){let a=Tr(i.copy(),{dialect:this.dialect});t.add(a.aliasOrName||"")}}if("joins"in s){let r=s.joins?Xe(s.joins,z):void 0;if(r)for(let i of r){let a=i.args.this;if(a instanceof V&&!i.args.on){let o=a.copy();o.meta.maybeColumn=!0;let c=Tr(o,{dialect:this.dialect}),p=c.parts;if(p&&0<p.length&&t.has(p[0].name||"")){let u=a.toColumn();if(u){let E=new Pe({expressions:[u]});if(a.args.alias instanceof ie&&u.args.this instanceof h){u.replace(u.args.this);let g=_optionalChain([a, 'access', _308 => _308.args, 'access', _309 => _309.alias, 'optionalAccess', _310 => _310.args, 'access', _311 => _311.this]),A={table:g?typeof g=="string"?[g]:(ue(g,G),[g]):void 0,copy:!1};oe(E,void 0,A)}a.replace(E)}}t.add(c.aliasOrName||"")}}}return e}parseQueryModifiers(e){if(e&&this._constructor.MODIFIABLES.some(t=>e instanceof t)){for(let s of this.parseJoins())e.append("joins",s);let t=this.parseLateral();for(;t;)e.append("laterals",t),t=this.parseLateral();for(;;){if(this.matchSet(new Set(Object.keys(this._constructor.QUERY_MODIFIER_PARSERS)),{advance:!1})){let s=this.curr,r=this._constructor.QUERY_MODIFIER_PARSERS[s.tokenType],[i,a]=_optionalChain([r, 'optionalAccess', _312 => _312.call, 'call', _313 => _313(this)])||[];if(i!==void 0&&a!==void 0){if(e.getArgKey(i)&&this.raiseError(`Found multiple '${s.text.toUpperCase()}' clauses`,s),e.setArgKey(i,a),i==="limit"){let o=a,c=o.args.offset;if(o.setArgKey("offset",void 0),c){let p=new Fr({expression:c});e.setArgKey("offset",p);let u=a.args.expressions;o.setArgKey("expressions",void 0),p.setArgKey("expressions",u)}}continue}}break}}return this._constructor.SUPPORTS_IMPLICIT_UNNEST&&e&&e.args.from&&(e=this.implicitUnnestsToExplicit(e)),e}parseHintFallbackToString(){let e=this.curr;for(;this.curr;)this.advance();let t=this.tokens[this.index-1];return new Dr({expressions:[this.findSql(e,t)]})}parseHintFunctionCall(){return this.parseFunctionCall()}parseHintBody(){let e=this.index,t=!1,s=[];try{let r=this.parseCsv(()=>this.parseHintFunctionCall()||this.parseVar({upper:!0}));for(;0<r.length;)s.push(...r),r=this.parseCsv(()=>this.parseHintFunctionCall()||this.parseVar({upper:!0}))}catch (e6){t=!0}return t||this.curr?(this.retreat(e),this.parseHintFallbackToString()):this.expression(Dr,{expressions:s})}parseHint(){if(this.match("hint")&&this.prevComments&&0<this.prevComments.length)return ne(this.prevComments[0],{into:"hint",dialect:this.dialect})}parseInto(){if(!this.match("into"))return;let e=this.match("temporary")||void 0,t=this.matchTextSeq("UNLOGGED")||void 0;return this.match("table"),this.expression(Ro,{this:this.parseTable({schema:!0}),temporary:e,unlogged:t})}parseFrom(e={}){let{joins:t=!1,skipFromToken:s=!1,consumePipe:r=!1}=e;if(!(!s&&!this.match("from")))return this.expression(Ge,{comments:this.prevComments,this:this.parseTable({joins:t,consumePipe:r})})}parseMatchRecognizeMeasure(){return this.expression(mu,{windowFrame:this.matchTexts(["FINAL","RUNNING"])&&(_nullishCoalesce(_optionalChain([this, 'access', _314 => _314.prev, 'optionalAccess', _315 => _315.text]), () => (""))).toUpperCase(),this:this.parseExpression()})}parseMatchRecognize(){if(!this.match("matchRecognize"))return;this.matchLParen();let e=this.parsePartitionBy(),t=this.parseOrder(),s=this.matchTextSeq("MEASURES")?this.parseCsv(()=>this.parseMatchRecognizeMeasure()):void 0,r;if(this.matchTextSeq(["ONE","ROW","PER","MATCH"]))r=Te("ONE ROW PER MATCH");else if(this.matchTextSeq(["ALL","ROWS","PER","MATCH"])){let c="ALL ROWS PER MATCH";this.matchTextSeq(["SHOW","EMPTY","MATCHES"])?c+=" SHOW EMPTY MATCHES":this.matchTextSeq(["OMIT","EMPTY","MATCHES"])?c+=" OMIT EMPTY MATCHES":this.matchTextSeq(["WITH","UNMATCHED","ROWS"])&&(c+=" WITH UNMATCHED ROWS"),r=Te(c)}let i;if(this.matchTextSeq(["AFTER","MATCH","SKIP"])){let c="AFTER MATCH SKIP";this.matchTextSeq(["PAST","LAST","ROW"])?c+=" PAST LAST ROW":this.matchTextSeq(["TO","NEXT","ROW"])?c+=" TO NEXT ROW":this.matchTextSeq(["TO","FIRST"])?(this.advance(),c+=` TO FIRST ${_optionalChain([this, 'access', _316 => _316.prev, 'optionalAccess', _317 => _317.text])}`):this.matchTextSeq(["TO","LAST"])&&(this.advance(),c+=` TO LAST ${_optionalChain([this, 'access', _318 => _318.prev, 'optionalAccess', _319 => _319.text])}`),i=Te(c)}let a;if(this.matchTextSeq("PATTERN")){this.matchLParen(),this.curr||this.raiseError("Expecting )",this.curr);let c=1,p=this.curr,u=this.prev;for(;this.curr&&0<c;)this.curr.tokenType==="lParen"&&c++,this.curr.tokenType==="rParen"&&c--,u=this.prev,this.advance();0<c&&this.raiseError("Expecting )",this.curr),a=Te(this.findSql(p,u))}let o=this.matchTextSeq("DEFINE")?this.parseCsv(()=>this.parseNameAsExpression()):void 0;return this.matchRParen(),this.expression(Io,{partitionBy:e,order:t,measures:s,rows:r,after:i,pattern:a,define:o,alias:this.parseTableAlias()})}parseLateral(){let e=this.matchPair("cross","apply")||void 0;!e&&this.matchPair("outer","apply")&&(e=!1);let t,s,r;if(e!==void 0)t=this.parseSelect({table:!0}),s=void 0,r=void 0;else if(this.match("lateral"))t=this.parseSelect({table:!0}),s=this.match("view")||void 0,r=this.match("outer")||void 0;else return;if(!t)for(t=this.parseUnnest()||this.parseFunction()||this.parseIdVar({anyToken:!1});this.match("dot");){let o=this.parseFunction()||this.parseIdVar({anyToken:!1});t=new me({this:t,expression:o})}let i,a;if(s){let o=this.parseIdVar({anyToken:!1}),c=this.match("alias")?this.parseCsv(()=>this.parseIdVar()):[];a=this.expression(ie,{this:o,columns:c})}else(t instanceof ae||t instanceof Pe)&&t.alias?a=_optionalChain([t, 'access', _320 => _320.args, 'access', _321 => _321.alias, 'optionalAccess', _322 => _322.pop, 'call', _323 => _323()]):(i=this.matchPair("with","ordinality")||void 0,a=this.parseTableAlias());return this.expression(kt,{this:t,view:s,outer:r,alias:a,crossApply:e,ordinality:i})}parseStream(){let e=this.index;if(this.matchTextSeq("STREAM")){let t=this.tryParse(this.parseTable.bind(this));if(t)return this.expression(_o,{this:t})}this.retreat(e)}parseJoinParts(){return{method:this.matchSet(this._constructor.JOIN_METHODS)?this.prev:void 0,side:this.matchSet(this._constructor.JOIN_SIDES)?this.prev:void 0,kind:this.matchSet(this._constructor.JOIN_KINDS)?this.prev:void 0}}parseUsingIdentifiers(){let e=()=>{let t=this.parseColumn();return t instanceof k?t.args.this instanceof h?t.args.this:K(t.args.this):t};return this.parseWrappedCsv(e,{optional:!0})}parseJoin(e={}){let{skipJoinToken:t=!1,parseBracket:s=!1}=e;if(this.match("comma")){let N=this.tryParse(this.parseTable.bind(this)),R=N?this.expression(z,{this:N}):void 0;return R&&this._constructor.JOINS_HAVE_EQUAL_PRECEDENCE&&R.setArgKey("kind","cross"),R}let r=this.index,{method:i,side:a,kind:o}=this.parseJoinParts(),c=this.matchTextSeq("DIRECTED")||void 0,p=(this.matchTexts(this._constructor.JOIN_HINTS)||void 0)&&_optionalChain([this, 'access', _324 => _324.prev, 'optionalAccess', _325 => _325.text]),u=this.match("join")||_optionalChain([o, 'optionalAccess', _326 => _326.tokenType])==="straightJoin",E=this.prevComments;!t&&!u&&(this.retreat(r),o=void 0,i=void 0,a=void 0);let g=this.matchPair("outer","apply",{advance:!1})||void 0,A=this.matchPair("cross","apply",{advance:!1})||void 0;if(!t&&!u&&!g&&!A)return;let x={this:g||A?this.parseLateral():this.parseTable({parseBracket:s})};if(_optionalChain([o, 'optionalAccess', _327 => _327.tokenType])==="array"&&this.match("comma")&&(x.expressions=this.parseCsv(()=>this.parseTable({parseBracket:s}))),i&&(x.method=i.text.toUpperCase()),a&&(x.side=As(Kt,a.text)),o&&(x.kind=o.tokenType==="straightJoin"?"straightJoin":As(Kt,o.text)),p&&(x.hint=p),this.match("matchCondition")&&(x.matchCondition=this.parseWrapped(()=>this.parseComparison())),this.match("on"))x.on=this.parseDisjunction();else if(this.match("using"))x.using=this.parseUsingIdentifiers();else if(!i&&!(g||A)&&!(x.this instanceof Pe)&&!(_optionalChain([o, 'optionalAccess', _328 => _328.tokenType])==="cross"||_optionalChain([o, 'optionalAccess', _329 => _329.tokenType])==="array")){let N=this.index,R=[...this.parseJoins()];0<R.length&&this.match("on")?x.on=this.parseDisjunction():0<R.length&&this.match("using")?x.using=this.parseUsingIdentifiers():this.retreat(N),0<R.length&&(x.on||x.using)&&_optionalChain([x, 'access', _330 => _330.this, 'optionalAccess', _331 => _331.setArgKey, 'call', _332 => _332("joins",R)])}x.pivots=this.parsePivots();let m=[...E||[],...[i,a,o].flatMap(N=>_optionalChain([N, 'optionalAccess', _333 => _333.comments])||[])];return this._constructor.ADD_JOIN_ON_TRUE&&!x.on&&!x.using&&!x.method&&(!x.kind||x.kind==="inner"||x.kind==="outer")&&(x.on=new Et({this:!0})),c&&(x.directed=c),this.expression(z,{comments:m,...x})}parseOpClass(){let e=this.parseDisjunction();return this.matchTexts(Array.from(this._constructor.OPCLASS_FOLLOW_KEYWORDS),{advance:!1})||this.matchSet(this._constructor.OPTYPE_FOLLOW_TOKENS,{advance:!1})?e:this.expression(cu,{this:e,expression:this.parseTableParts()})}parseIndexParams(){let e=this.match("using")?this.parseVar({anyToken:!0}):void 0,t=this.match("lParen",{advance:!1})?this.parseWrappedCsv(()=>this.parseWithOperator()):void 0,s=this.matchTextSeq("INCLUDE")?this.parseWrappedIdVars():void 0,r=this.parsePartitionBy(),i=(this.match("with")||void 0)&&this.parseWrappedProperties(),a=this.matchTextSeq(["USING","INDEX","TABLESPACE"])?this.parseVar({anyToken:!0}):void 0,o=this.parseWhere(),c=this.match("on")?this.parseField():void 0;return this.expression(lu,{using:e,columns:t,include:s,partitionBy:r,where:o,withStorage:i,tablespace:a,on:c})}parseIndex(e={}){let{anonymous:t=!1,index:s}=e,r=s,i,a,o,c;if(r||t)i=void 0,a=void 0,o=void 0,this.match("on"),this.match("table"),c=this.parseTableParts({schema:!0});else{if(i=this.match("unique")||void 0,a=this.matchTextSeq("PRIMARY")||void 0,o=this.matchTextSeq("AMP")||void 0,!this.match("index"))return;r=this.parseIdVar(),c=void 0}let p=this.parseIndexParams();return this.expression(pu,{this:r,table:c,unique:i,primary:a,amp:o,params:p})}parseTableHints(){let e=[];if(this.matchPair("with","lParen"))e.push(this.expression(Po,{expressions:this.parseCsv(()=>this.parseFunction()||this.parseVar({anyToken:!0}))})),this.matchRParen();else for(;this.matchSet(this._constructor.TABLE_INDEX_HINT_TOKENS);){let t=new yu({this:(_nullishCoalesce(_optionalChain([this, 'access', _334 => _334.prev, 'optionalAccess', _335 => _335.text]), () => (""))).toUpperCase()});this.matchSet(new Set(["index","key"])),this.match("for")&&(this.advanceAny(),t.setArgKey("target",(_nullishCoalesce(_optionalChain([this, 'access', _336 => _336.prev, 'optionalAccess', _337 => _337.text]), () => (""))).toUpperCase())),t.setArgKey("expressions",this.parseWrappedIdVars()),e.push(t)}return 0<e.length?e:void 0}parseTablePart(e={}){let{schema:t=!1}=e;return!t&&this.parseFunction({optionalParens:!1})||this.parseIdVar({anyToken:!1})||this.parseStringAsIdentifier()||this.parsePlaceholder()}parseTableParts(e={}){let{schema:t=!1,isDbReference:s=!1,wildcard:r=!1}=e,i,a,o=this.parseTablePart({schema:t});for(;this.match("dot");)i?o=this.expression(me,{this:o,expression:this.parseTablePart({schema:t})}):(i=a,a=o,o=this.parseTablePart({schema:t})||"");r&&this.isConnected()&&(o instanceof G||!o)&&this.match("star")&&(o instanceof G?o.args.this+="*":o=new G({this:"*"}));let c=o instanceof h?o.popComments():void 0;s&&(i=a,a=o,o=void 0),!o&&!s&&this.raiseError(`Expected table name but got ${this.curr}`,this.curr),!a&&s&&this.raiseError(`Expected database name but got ${this.curr}`,this.curr);let p=this.expression(V,{comments:c,this:o,db:a,catalog:i}),u=this.parseChanges();u&&p.setArgKey("changes",u);let E=this.parseHistoricalData();E&&p.setArgKey("when",E);let g=this.parsePivots();return g&&p.setArgKey("pivots",g),p}parseTable(e={}){let{schema:t=!1,joins:s=!1,aliasTokens:r,parseBracket:i=!1,isDbReference:a=!1,parsePartition:o=!1,consumePipe:c=!1}=e,p=this.parseStream();if(p)return p;let u=this.parseLateral();if(u)return u;let E=this.parseUnnest();if(E)return E;let g=this.parseDerivedTableValues();if(g)return g;let A=this.parseSelect({table:!0,consumePipe:c});if(A)return A.args.pivots||A.setArgKey("pivots",this.parsePivots()),A;let x=i&&this.parseBracket(void 0);x=x?this.expression(V,{this:x}):void 0;let m=(this.matchTextSeq(["ROWS","FROM"])||void 0)&&this.parseWrappedCsv(()=>this.parseTable());m=m?this.expression(V,{rowsFrom:m}):void 0;let N=this.match("only")||void 0,R=x||m||this.parseBracket(this.parseTableParts({schema:t,isDbReference:a}));if(N&&_optionalChain([R, 'optionalAccess', _338 => _338.setArgKey, 'call', _339 => _339("only",N)]),this.matchTextSeq("*"),(o||this._constructor.SUPPORTS_PARTITION_SELECTION)&&this.match("partition",{advance:!1})&&_optionalChain([R, 'optionalAccess', _340 => _340.setArgKey, 'call', _341 => _341("partition",this.parsePartition())]),t)return this.parseSchema({this:R});let I=this.parseVersion();I&&_optionalChain([R, 'optionalAccess', _342 => _342.setArgKey, 'call', _343 => _343("version",I)]),this._dialectConstructor.ALIAS_POST_TABLESAMPLE&&_optionalChain([R, 'optionalAccess', _344 => _344.setArgKey, 'call', _345 => _345("sample",this.parseTableSample())]);let y=this.parseTableAlias({aliasTokens:r||this._constructor.TABLE_ALIAS_TOKENS});if(y&&_optionalChain([R, 'optionalAccess', _346 => _346.setArgKey, 'call', _347 => _347("alias",y)]),this.match("indexedBy")?_optionalChain([R, 'optionalAccess', _348 => _348.setArgKey, 'call', _349 => _349("indexed",this.parseTableParts())]):this.matchTextSeq(["NOT","INDEXED"])&&_optionalChain([R, 'optionalAccess', _350 => _350.setArgKey, 'call', _351 => _351("indexed",!1)]),R instanceof V&&this.matchTextSeq("AT"))return this.expression(Hu,{this:_optionalChain([R, 'access', _352 => _352.toColumn, 'optionalCall', _353 => _353({copy:!1})]),expression:this.parseIdVar()});if(_optionalChain([R, 'optionalAccess', _354 => _354.setArgKey, 'call', _355 => _355("hints",this.parseTableHints())]),_optionalChain([R, 'optionalAccess', _356 => _356.args, 'access', _357 => _357.pivots])||_optionalChain([R, 'optionalAccess', _358 => _358.setArgKey, 'call', _359 => _359("pivots",this.parsePivots())]),this._dialectConstructor.ALIAS_POST_TABLESAMPLE||_optionalChain([R, 'optionalAccess', _360 => _360.setArgKey, 'call', _361 => _361("sample",this.parseTableSample())]),s)for(let P of this.parseJoins())_optionalChain([R, 'optionalAccess', _362 => _362.append, 'call', _363 => _363("joins",P)]);return this.matchPair("with","ordinality")&&(_optionalChain([R, 'optionalAccess', _364 => _364.setArgKey, 'call', _365 => _365("ordinality",!0)]),_optionalChain([R, 'optionalAccess', _366 => _366.setArgKey, 'call', _367 => _367("alias",this.parseTableAlias())])),R}parseVersion(){let e;if(this.match("timestampSnapshot"))e="TIMESTAMP";else if(this.match("versionSnapshot"))e="VERSION";else return;let t,s;if(this.matchSet(new Set(["from","between"]))){t=(_nullishCoalesce(_optionalChain([this, 'access', _368 => _368.prev, 'optionalAccess', _369 => _369.text]), () => (""))).toUpperCase();let r=this.parseBitwise();this.matchTexts(["TO","AND"]);let i=this.parseBitwise();s=this.expression(Mt,{expressions:[r,i]})}else this.matchTextSeq(["CONTAINED","IN"])?(t="CONTAINED IN",s=this.expression(Mt,{expressions:this.parseWrappedCsv(()=>this.parseBitwise())})):this.match("all")?(t="ALL",s=void 0):(this.matchTextSeq(["AS","OF"]),t="AS OF",s=this.parseType());return this.expression(bu,{this:e,expression:s,kind:t})}parseHistoricalData(){let e=this.index,t;if(this.matchTexts(Array.from(this._constructor.HISTORICAL_DATA_PREFIX))){let s=(_nullishCoalesce(_optionalChain([this, 'access', _370 => _370.prev, 'optionalAccess', _371 => _371.text]), () => (""))).toUpperCase(),r=this.match("lParen")&&this.matchTexts(Array.from(this._constructor.HISTORICAL_DATA_KIND))&&(_nullishCoalesce(_optionalChain([this, 'access', _372 => _372.prev, 'optionalAccess', _373 => _373.text]), () => (""))).toUpperCase(),i=(this.match("farrow")||void 0)&&this.parseBitwise();i?(this.matchRParen(),t=this.expression(Cu,{this:s,kind:r,expression:i})):this.retreat(e)}return t}parseChanges(){if(!this.matchTextSeq(["CHANGES","(","INFORMATION","=>"]))return;let e=this.parseVar({anyToken:!0});return this.matchRParen(),this.expression(su,{information:e,atBefore:this.parseHistoricalData(),end:this.parseHistoricalData()})}parseUnnest(e={}){let{withAlias:t=!0}=e;if(!this.matchPair("unnest","lParen",{advance:!1}))return;this.advance();let s=this.parseWrappedCsv(()=>this.parseEquality()),r=this.matchPair("with","ordinality")||void 0,i=t?this.parseTableAlias():void 0;if(i){this._dialectConstructor.UNNEST_COLUMN_ONLY&&(i.args.columns&&this.raiseError("Unexpected extra column alias in unnest."),i.setArgKey("columns",[i.args.this]),i.setArgKey("this",void 0));let a=i.args.columns;r&&a&&s.length<a.length&&(r=a.pop())}return!r&&this.matchPair("with","offset")&&(this.match("alias"),r=this.parseIdVar({anyToken:!1,tokens:this._constructor.UNNEST_OFFSET_ALIAS_TOKENS})||K("offset")),this.expression(Pe,{expressions:s,alias:i,offset:r})}parseDerivedTableValues(){let e=this.matchPair("lParen","values")||void 0;if(!e&&!(this.matchTextSeq("VALUES")||this.matchTextSeq(["FORMAT","VALUES"])))return;let t=this.parseCsv(()=>this.parseValue()),s=this.parseTableAlias();return e&&this.matchRParen(),this.expression(Gs,{expressions:t,alias:s||this.parseTableAlias()})}parseTableSample(e={}){let{asModifier:t=!1}=e;if(!this.match("tableSample")&&!(t&&this.matchTextSeq(["USING","SAMPLE"])))return;let s,r,i,a,o,c,p=this.parseVar({tokens:new Set(["row"]),upper:!0}),u=this.match("lParen")||void 0,E,g;return this._constructor.TABLESAMPLE_CSV?(g=void 0,E=this.parseCsv(()=>this.parsePrimary())):(E=void 0,g=this.match("number",{advance:!1})?this.parseFactor():this.parsePrimary()||this.parsePlaceholder()),this.matchTextSeq("BUCKET")?(s=this.parseNumber(),this.matchTextSeq(["OUT","OF"]),r=this.parseNumber(),this.match("on"),i=this.parseField()):this.matchSet(new Set(["percent","mod"]))?a=g:this.match("rows")||!this._dialectConstructor.TABLESAMPLE_SIZE_IS_PERCENT?o=g:a=g,u&&this.matchRParen(),this.match("lParen")?(p=this.parseVar({upper:!0}),c=(this.match("comma")||void 0)&&this.parseNumber(),this.matchRParen()):this.matchTexts(["SEED","REPEATABLE"])&&(c=this.parseWrapped(()=>this.parseNumber())),!p&&this._constructor.DEFAULT_SAMPLING_METHOD&&(p=Te(this._constructor.DEFAULT_SAMPLING_METHOD)),this.expression(wo,{expressions:E,method:p,bucketNumerator:s,bucketDenominator:r,bucketField:i,percent:a,size:o,seed:c})}parsePivots(){let e=[],t=this.parsePivot();for(;t;)e.push(t),t=this.parsePivot();return 0<e.length?e:void 0}parseJoins(){let e=[],t=this.parseJoin();for(;t;)e.push(t),t=this.parseJoin();return e}parseUnpivotColumns(){if(this.match("into"))return this.expression(Pu,{this:this.matchTextSeq("NAME")&&this.parseColumn(),expressions:this.matchTextSeq("VALUE")&&this.parseCsv(()=>this.parseColumn())})}parseSimplifiedPivot(e={}){let{isUnpivot:t}=e,s=()=>{let p=this.parseBitwise();return this.match("in")?this.parseIn(p):this.match("alias",{advance:!1})?this.parseAlias(p):p},r=this.parseTable(),i=(this.match("on")||void 0)&&this.parseCsv(s),a=this.parseUnpivotColumns(),o=(this.match("using")||void 0)&&this.parseCsv(()=>this.parseAlias(this.parseColumn())),c=this.parseGroup();return this.expression(ls,{this:r,expressions:i,using:o,group:c,unpivot:t,into:a})}parsePivotIn(){let e=()=>{let i=this.parseSelectOrExpression();this.match("alias");let a=this.parseBitwise();if(a){let o=a;return a instanceof k&&!a.args.db&&(ue(a.args.this,h),o=a.args.this),this.expression(ZT,{this:i,alias:o})}return i},t=this.parseColumn();this.match("in")||this.raiseError("Expecting IN",this.curr);let s;if(this.match("lParen"))return this.match("any")?s=[...pe(new Fi({this:this.parseOrder()}))]:s=this.parseCsv(e),this.matchRParen(),this.expression(it,{this:t,expressions:s});let r=this.parseIdVar();return this.expression(it,{this:t,field:r})}parsePivotAggregation(){let e=this.parseFunction();if(!e){if(this.prev&&this.prev.tokenType==="comma")return;this.raiseError("Expecting an aggregation function in PIVOT",this.curr)}return this.parseAlias(e)}parsePivot(){let e=this.index,t,s;if(this.match("pivot"))s=!1;else if(this.match("unpivot"))s=!0,this.matchTextSeq(["INCLUDE","NULLS"])?t=!0:this.matchTextSeq(["EXCLUDE","NULLS"])&&(t=!1);else return;if(!this.match("lParen")){this.retreat(e);return}let r;s?r=this.parseCsv(()=>this.parseColumn()):r=this.parseCsv(()=>this.parsePivotAggregation()),r.length===0&&this.raiseError("Failed to parse PIVOT's aggregation list",this.curr),this.match("for")||this.raiseError("Expecting FOR",this.curr);let i=[];for(;;){let p=this.tryParse(()=>this.parsePivotIn());if(!p)break;i.push(p)}let a=(this.matchTextSeq(["DEFAULT","ON","NULL"])||void 0)&&this.parseWrapped(()=>this.parseBitwise()),o=this.parseGroup();this.matchRParen();let c=this.expression(ls,{expressions:r,fields:i,unpivot:s,includeNulls:t,defaultOnNull:a,group:o});if(this.matchSet(new Set(["pivot","unpivot"]),{advance:!1})||c.setArgKey("alias",this.parseTableAlias()),!s){let p=this.pivotColumnNames(r),u=[],E=[];for(let g of c.args.fields){let A=g.args.expressions;_optionalChain([A, 'optionalAccess', _374 => _374[0]])instanceof Fi||A&&E.push(A.map(x=>this._constructor.IDENTIFY_PIVOT_STRINGS?x.sql():x.aliasOrName||""))}if(0<E.length){0<p.length&&E.push(p);for(let g of this.product(E)){let A=[...g];0<p.length&&this._constructor.PREFIXED_PIVOT_COLUMNS&&A.unshift(A.pop()),u.push(K(A.join("_")))}}c.setArgKey("columns",u)}return c}pivotColumnNames(e){return e.map(t=>t.alias).filter(t=>t)}product(e){if(e.length===0)return[[]];if(e.length===1)return e[0].map(a=>[a]);let t=[],[s,...r]=e,i=this.product(r);for(let a of s)for(let o of i)t.push([a,...o]);return t}parsePrewhere(e={}){let{skipWhereToken:t=!1}=e;if(!(!t&&!this.match("prewhere")))return this.expression(Mu,{comments:this.prevComments,this:this.parseDisjunction()})}parseWhere(e={}){let{skipWhereToken:t=!1}=e;if(!(!t&&!this.match("where")))return this.expression(at,{comments:this.prevComments,this:this.parseDisjunction()})}parseGroup(e={}){let{skipGroupByToken:t=!1}=e;if(!t&&!this.match("groupBy"))return;let s=this.prevComments,r={expressions:[],rollup:[],cube:[],groupingSets:[]};if(this.match("all")?r.all=!0:this.match("distinct")&&(r.all=!1),this.matchSet(this._constructor.QUERY_MODIFIER_TOKENS,{advance:!1}))return this.expression(Ys,{comments:s,...r});for(;;){let i=this.index;r.expressions.push(...this.parseCsv(()=>this.matchSet(new Set(["cube","rollup"]),{advance:!1})?void 0:this.parseDisjunction()));let a=this.index,o=this.match("with")||void 0,c=this.parseCubeOrRollup({withPrefix:o});if(c){let p=c instanceof Yc?"rollup":"cube";r[p].push(c)}else{let p=this.parseGroupingSets();p?r.groupingSets.push(p):this.matchTextSeq("TOTALS")&&(r.totals=!0)}if(a<=this.index&&this.index<=a+1){this.retreat(a);break}if(i===this.index)break}return this.expression(Ys,{comments:s,...r})}parseCubeOrRollup(e={}){let{withPrefix:t=!1}=e,s;if(this.match("cube"))s=xu;else if(this.match("rollup"))s=Yc;else return;return this.expression(s,{expressions:t?[]:this.parseWrappedCsv(()=>this.parseBitwise())})}parseGroupingSets(){if(this.match("groupingSets"))return this.expression(Tu,{expressions:this.parseWrappedCsv(()=>this.parseGroupingSet())})}parseGroupingSet(){return this.parseGroupingSets()||this.parseCubeOrRollup()||this.parseBitwise()}parseHaving(e={}){let{skipHavingToken:t=!1}=e;if(!(!t&&!this.match("having")))return this.expression($t,{comments:this.prevComments,this:this.parseDisjunction()})}parseQualify(){if(this.match("qualify"))return this.expression(un,{this:this.parseDisjunction()})}parseConnectWithPrior(){this._constructor.NO_PAREN_FUNCTION_PARSERS.PRIOR=function(){return this.expression(au,{this:this.parseBitwise()})};let e=this.parseDisjunction();return delete this._constructor.NO_PAREN_FUNCTION_PARSERS.PRIOR,e}parseConnect(e={}){let{skipStartToken:t=!1}=e,s;if(t)s=void 0;else if(this.match("startWith"))s=this.parseDisjunction();else return;this.match("connectBy");let r=this.matchTextSeq("NOCYCLE")||void 0,i=this.parseConnectWithPrior();return!s&&this.match("startWith")&&(s=this.parseDisjunction()),this.expression(ru,{start:s,connect:i,nocycle:r})}parseNameAsExpression(){let e=this.parseIdVar({anyToken:!0});return this.match("alias")&&(e=this.expression(Se,{alias:e,this:this.parseDisjunction()})),e}parseInterpolate(){if(this.matchTextSeq("INTERPOLATE"))return this.parseWrappedCsv(()=>this.parseNameAsExpression())}parseOrder(e={}){let{thisExpr:t,skipOrderToken:s=!1}=e,r;if(!s&&!this.match("orderBy")){if(!this.match("orderSiblingsBy"))return t;r=!0}return this.expression(ke,{comments:this.prevComments,this:t,expressions:this.parseCsv(()=>this.parseOrdered()),siblings:r})}parseSort(e,t){if(this.match(t))return this.expression(e,{expressions:this.parseCsv(()=>this.parseOrdered())})}parseOrdered(e){let t=e?e():this.parseDisjunction();if(!t)return;let s=t;_optionalChain([t, 'access', _375 => _375.name, 'optionalAccess', _376 => _376.toUpperCase, 'call', _377 => _377()])==="ALL"&&this._dialectConstructor.SUPPORTS_ORDER_BY_ALL&&(s=Te("ALL"));let r=this.match("asc")||void 0,i=this.match("desc")||void 0||r&&!1,a=this.matchTextSeq(["NULLS","FIRST"])||void 0,o=this.matchTextSeq(["NULLS","LAST"])||void 0,c=a||!1;!(a||o)&&(!i&&this._dialectConstructor.NULL_ORDERING==="nulls_are_small"||i&&this._dialectConstructor.NULL_ORDERING!=="nulls_are_small")&&this._dialectConstructor.NULL_ORDERING!=="nulls_are_last"&&(c=!0);let u;return this.matchTextSeq(["WITH","FILL"])&&(u=this.expression(Ru,{fromValue:this.match("from")&&this.parseBitwise(),to:this.matchTextSeq("TO")&&this.parseBitwise(),step:this.matchTextSeq("STEP")&&this.parseBitwise(),interpolate:this.parseInterpolate()})),this.expression(es,{this:s,desc:i,nullsFirst:c,withFill:u})}parseLimitOptions(){let e=this.matchSet(new Set(["percent","mod"]))||void 0,t=this.matchSet(new Set(["row","rows"]))||void 0;this.matchTextSeq("ONLY");let s=this.matchTextSeq(["WITH","TIES"])||void 0;if(e||t||s)return this.expression(Su,{percent:e,rows:t,withTies:s})}parseLimit(e,t={}){let{top:s=!1,skipLimitToken:r=!1}=t;if(r||this.match(s?"top":"limit")){let i=this.prevComments,a;if(s){let u=this.match("lParen")||void 0;a=u?this.parseTerm():this.parseNumber(),u&&this.matchRParen()}else{let u=this.index;a=this.tryParse(()=>this.parseTerm()),a instanceof Hr?(this.retreat(u),a=this.parseFactor()):a||(a=this.parseFactor())}let o=this.parseLimitOptions(),c;return this.match("comma")&&(c=a,a=this.parseTerm()),this.expression(Ct,{this:e,expression:a,offset:c,comments:i,limitOptions:o,expressions:this.parseLimitBy()})}if(this.match("fetch")){let a=this.matchSet(new Set(["first","next"]))||void 0?(_nullishCoalesce(_optionalChain([this, 'access', _378 => _378.prev, 'optionalAccess', _379 => _379.text]), () => (""))).toUpperCase():"FIRST",o=this.parseField({tokens:this._constructor.FETCH_TOKENS});return this.expression(Sn,{direction:a,count:o,limitOptions:this.parseLimitOptions()})}return e}parseOffset(e){if(!this.match("offset"))return e;let t=this.parseTerm();return this.matchSet(new Set(["row","rows"])),this.expression(Fr,{this:e,expression:t,expressions:this.parseLimitBy()})}canParseLimitOrOffset(){if(!this.matchSet(new Set(this._constructor.AMBIGUOUS_ALIAS_TOKENS),{advance:!1}))return!1;let e=this.index,t=!!(this.tryParse(()=>this.parseLimit(),{retreat:!0})||this.tryParse(()=>this.parseOffset(),{retreat:!0}));return this.retreat(e),this.next&&this.next.tokenType==="matchCondition"?!1:t}parseLimitBy(){return this.matchTextSeq("BY")?this.parseCsv(()=>this.parseBitwise()):void 0}parseLocks(){let e=[];for(;;){let t,s;if(this.matchTextSeq(["FOR","UPDATE"]))t=!0;else if(this.matchTextSeq(["FOR","SHARE"])||this.matchTextSeq(["LOCK","IN","SHARE","MODE"]))t=!1;else if(this.matchTextSeq(["FOR","KEY","SHARE"]))t=!1,s=!0;else if(this.matchTextSeq(["FOR","NO","KEY","UPDATE"]))t=!0,s=!0;else break;let r;this.matchTextSeq("OF")&&(r=this.parseCsv(()=>this.parseTable({schema:!0})));let i;this.matchTextSeq("NOWAIT")?i=!0:this.matchTextSeq("WAIT")?i=this.parsePrimary():this.matchTextSeq(["SKIP","LOCKED"])&&(i=!1),e.push(this.expression(Kc,{update:t,expressions:r,wait:i,key:s}))}return e}parseSetOperation(e,t={}){let{consumePipe:s=!1}=t,r=this.index,{side:i,kind:a}=this.parseJoinParts(),o=As(Kt,_optionalChain([i, 'optionalAccess', _380 => _380.text])),c=As(EO,_optionalChain([a, 'optionalAccess', _381 => _381.text]));if(!this.matchSet(this._constructor.SET_OPERATIONS)){this.retreat(r);return}let p=_optionalChain([this, 'access', _382 => _382.prev, 'optionalAccess', _383 => _383.tokenType]),u;p==="union"?u=$r:p==="except"?u=Yr:u=yn;let E=_optionalChain([this, 'access', _384 => _384.prev, 'optionalAccess', _385 => _385.comments]),g;this.match("distinct")?g=!0:this.match("all")?g=!1:(g=this._dialectConstructor.SET_OP_DISTINCT_BY_DEFAULT[u.key],g===void 0&&this.raiseError(`Expected DISTINCT or ALL for ${u.name}`,this.curr));let A=this.matchTextSeq(["BY","NAME"])||this.matchTextSeq(["STRICT","CORRESPONDING"])||void 0;this.matchTextSeq("CORRESPONDING")&&(A=!0,!o&&!c&&(c="inner"));let x;A&&this.matchTexts(["ON","BY"])&&(x=this.parseWrappedCsv(()=>this.parseColumn()));let m=this.parseSelect({nested:!0,parseSetOperation:!1,consumePipe:s});return this.expression(u,{comments:E,this:e,distinct:g,byName:A,expression:m,side:o,kind:c,on:x})}parseSetOperations(e){let t=e;for(;t;){let s=this.parseSetOperation(t);if(!s)break;t=s}if(t instanceof be&&this._constructor.MODIFIERS_ATTACHED_TO_SET_OP){let s=t.args.expression;if(s)for(let r of this._constructor.SET_OP_MODIFIERS){let i=s.args[r];i instanceof h&&t.setArgKey(r,i.pop())}}return t}parseExpression(){return this.parseAlias(this.parseAssignment())}parseAssignment(){let e=this.parseDisjunction();if(!e&&this.next&&this.next.tokenType in this._constructor.ASSIGNMENT){let s=this.advanceAny({ignoreReserved:!0});e=Ie({col:s&&_optionalChain([this, 'access', _386 => _386.prev, 'optionalAccess', _387 => _387.text])})}let t=Object.keys(this._constructor.ASSIGNMENT);for(;this.matchSet(t);)e instanceof k&&e.parts.length===1&&(e=e.args.this),e=this.expression(this._constructor.ASSIGNMENT[this.prev.tokenType],{this:e,comments:this.prevComments,expression:this.parseAssignment()});return e}parseDisjunction(){return this.parseTokens(()=>this.parseConjunction(),this._constructor.DISJUNCTION)}parseConjunction(){return this.parseTokens(()=>this.parseEquality(),this._constructor.CONJUNCTION)}parseEquality(){return this.parseTokens(()=>this.parseComparison(),this._constructor.EQUALITY)}parseComparison(){return this.parseTokens(()=>this.parseRange(),this._constructor.COMPARISON)}parseRange(e){let t=e||this.parseBitwise(),s=this.match("not")||void 0;if(this.matchSet(Object.keys(this._constructor.RANGE_PARSERS))){let r=this._constructor.RANGE_PARSERS[_nullishCoalesce(_optionalChain([this, 'access', _388 => _388.prev, 'optionalAccess', _389 => _389.tokenType]), () => ("unknown"))];if(r&&t){let i=r.call(this,t);if(!i)return t;t=i}}else(this.match("isnull")||s&&this.match("null"))&&(t=this.expression(Ut,{this:t,expression:Ke()}));return this.match("notnull")&&(t=this.expression(Ut,{this:t,expression:Ke()}),t=this.expression(rt,{this:t})),s&&(t=this.negateRange(t)),this.match("is")&&(t=this.parseIs(t)),t}negateRange(e){return e&&this.expression(rt,{this:e})}parseIs(e){let t=this.index-1,s=this.match("not")||void 0;if(this.matchTextSeq(["DISTINCT","FROM"])){let a=s?fr:kr;return this.expression(a,{this:e,expression:this.parseBitwise()})}let r;if(this.match("json")){let a=(this.matchTexts(Array.from(this._constructor.IS_JSON_PREDICATE_KIND))||void 0)&&(_nullishCoalesce(_optionalChain([this, 'access', _390 => _390.prev, 'optionalAccess', _391 => _391.text]), () => (""))).toUpperCase(),o;this.matchTextSeq("WITH")?o=!0:this.matchTextSeq("WITHOUT")&&(o=!1);let c=this.match("unique")||void 0;this.matchTextSeq("KEYS"),r=this.expression(Wu,{this:a,with:o,unique:c})}else if(r=this.parseNull()||this.parseBitwise(),!r){this.retreat(t);return}let i=this.expression(Ut,{this:e,expression:r});return s?this.expression(rt,{this:i}):this.parseColumnOps(i)}parseIn(e,t={}){let{alias:s=!1}=t,r=this.parseUnnest({withAlias:!1}),i;if(r)i=this.expression(it,{this:e,unnest:r});else if(this.matchSet(new Set(["lParen","lBracket"]))){let a=_optionalChain([this, 'access', _392 => _392.prev, 'optionalAccess', _393 => _393.tokenType])==="lParen",o=this.parseCsv(()=>this.parseSelectOrExpression({alias:s}));if(o.length===1&&o[0]instanceof ce){let c=o[0],u=this.parseQueryModifiers(c).subquery(void 0,{copy:!1});i=this.expression(it,{this:e,query:u})}else i=this.expression(it,{this:e,expressions:o});a?this.matchRParen(i):this.match("rBracket",{expression:i})||this.raiseError("Expecting ]",this.curr)}else i=this.expression(it,{this:e,field:this.parseColumn()});return i}parseBetween(e){let t;this.matchTextSeq("SYMMETRIC")?t=!0:this.matchTextSeq("ASYMMETRIC")&&(t=!1);let s=this.parseBitwise();this.match("and");let r=this.parseBitwise();return this.expression(Fs,{this:e,low:s,high:r,symmetric:t})}parseEscape(e){return this.match("escape")?this.expression(TE,{this:e,expression:this.parseString()||this.parseNull()}):e}parseIntervalSpan(e){let t;if(e&&e.isString&&this._constructor.SUPPORTS_OMITTED_INTERVAL_SPAN_UNIT&&_optionalChain([e, 'access', _394 => _394.name, 'optionalAccess', _395 => _395.match, 'optionalCall', _396 => _396(FL)])){let i=this.index,a=this.parseVar({anyToken:!0,upper:!0}),o;a&&this.matchTextSeq("TO")&&(o=this.parseVar({anyToken:!0,upper:!0})),t=!(a&&o),this.retreat(i)}let s=t?void 0:this.parseFunction()||!this.match("alias",{advance:!1})&&this.parseVar({anyToken:!0,upper:!0})||void 0,r=e;if(e&&e.isNumber)r=w.string(e.toValue()||e.sql());else if(e&&e.isString){let i=Array.from(_optionalChain([e, 'access', _397 => _397.name, 'optionalAccess', _398 => _398.matchAll, 'call', _399 => _399(new RegExp(vL,"g"))])||[]);0<i.length&&s&&(s=void 0,this.retreat(this.index-1)),i.length===1&&(r=w.string(i[0][1]),s=this.expression(Ze,{this:i[0][2].toUpperCase()}))}return this._constructor.INTERVAL_SPANS&&this.matchTextSeq("TO")&&(s=this.expression(Kn,{this:s,expression:this.parseFunction()||this.parseVar({anyToken:!0,upper:!0})})),this.expression(ze,{this:r,unit:s})}parseInterval(e={}){let{matchInterval:t=!0}=e,s=this.index;if(!this.match("interval")&&t)return;let r;if(this.match("string",{advance:!1})?r=this.parsePrimary():r=this.parseTerm(),!r||r instanceof k&&!r.args.table&&r.args.this instanceof G&&!r.args.this.args.quoted&&this.curr&&!this._dialectConstructor.VALID_INTERVAL_UNITS.has(this.curr.text.toUpperCase())){this.retreat(s);return}let i=this.parseIntervalSpan(r),a=this.index;return this.match("plus"),this.matchSet(new Set(["string","number"]),{advance:!1})?this.expression(lt,{this:i,expression:this.parseInterval({matchInterval:!1})}):(this.retreat(a),i)}parseBitwise(){let e=this.parseTerm(),t=Object.keys(this._constructor.BITWISE);for(;;)if(this.matchSet(t)){let s=this._constructor.BITWISE[_nullishCoalesce(_optionalChain([this, 'access', _400 => _400.prev, 'optionalAccess', _401 => _401.tokenType]), () => ("unknown"))];s&&(e=this.expression(s,{this:e,expression:this.parseTerm()}))}else if(this._dialectConstructor.DPIPE_IS_STRING_CONCAT&&this.match("dpipe"))e=this.expression(Ar,{this:e,expression:this.parseTerm(),safe:!this._dialectConstructor.STRICT_STRING_CONCAT});else if(this.match("dqmark"))e=this.expression(St,{this:e,expressions:pe(this.parseTerm())});else if(this.matchPair("lt","lt"))e=this.expression(tp,{this:e,expression:this.parseTerm()});else if(this.matchPair("gt","gt"))e=this.expression(nc,{this:e,expression:this.parseTerm()});else break;return e}parseTerm(){let e=this.parseFactor(),t=Object.keys(this._constructor.TERM);for(;this.matchSet(t);){let s=this._constructor.TERM[_nullishCoalesce(_optionalChain([this, 'access', _402 => _402.prev, 'optionalAccess', _403 => _403.tokenType]), () => ("unknown"))],r=this.prevComments,i=this.parseFactor();if(s&&(e=this.expression(s,{this:e,comments:r,expression:i}),e instanceof vl)){let a=e.args.expression;if(a instanceof k&&a.parts.length===1){let o=a.args.this;o instanceof G&&e.setArgKey("expression",o.args.quoted?o:Te(o.name))}}}return e}parseFactor(){let e=this._constructor.EXPONENT?()=>this.parseExponent():()=>this.parseUnary(),t=this.parseAtTimeZone(e()),s=Object.keys(this._constructor.FACTOR);for(;this.matchSet(s);){let r=this._constructor.FACTOR[_nullishCoalesce(_optionalChain([this, 'access', _404 => _404.prev, 'optionalAccess', _405 => _405.tokenType]), () => ("unknown"))],i=this.prevComments,a=e();if(!a&&r===Hi&&/^[a-zA-Z]/.test(_nullishCoalesce(_optionalChain([this, 'access', _406 => _406.prev, 'optionalAccess', _407 => _407.text]), () => (""))))return this.retreat(this.index-1),t;r&&(t=this.expression(r,{this:t,comments:i,expression:a}),t instanceof jt&&(t.setArgKey("typed",this._dialectConstructor.TYPED_DIVISION),t.setArgKey("safe",this._dialectConstructor.SAFE_DIVISION)))}return t}parseExponent(){return this.parseTokens(()=>this.parseUnary(),this._constructor.EXPONENT)}parseUnary(){if(this.matchSet(Object.keys(this._constructor.UNARY_PARSERS))){let e=this._constructor.UNARY_PARSERS[_nullishCoalesce(_optionalChain([this, 'access', _408 => _408.prev, 'optionalAccess', _409 => _409.tokenType]), () => ("unknown"))];return e?e.call(this):void 0}return this.parseType()}parseType(e={}){let{parseInterval:t=!0,fallbackToIdentifier:s=!1}=e,r=t&&this.parseInterval();if(r)return this.parseColumnOps(r);let i=this.index,a=this.parseTypes({checkFunc:!0,allowIdentifiers:!1});if(a instanceof Z)return this.parseColumnOps(a);if(a){let c=this.index,p=this.parsePrimary();if(p instanceof w){let u=p.name,E=this.parseColumnOps(p),g=typeof a.args.this=="string"?this._constructor.TYPE_LITERAL_PARSERS[a.args.this]:void 0;return g?g.call(this,E,a):(this._constructor.ZONE_AWARE_TIMESTAMP_CONSTRUCTOR&&_optionalChain([a, 'access', _410 => _410.isType, 'optionalCall', _411 => _411(["timestamp"])])&&aV.test(u)&&a.setArgKey("this","timestamptz"),this.expression(Z,{this:E,to:a}))}if(a.args.expressions&&1<c-i)return this.retreat(c),this.parseColumnOps(a);this.retreat(i)}if(s)return this.parseIdVar();let o=this.parseColumn();return o&&this.parseColumnOps(o)}parseTypeSize(){let e=this.parseType();if(e)return e instanceof k&&!e.args.table&&(e=Te(e.name.toUpperCase())),this.expression(Jr,{this:e,expression:this.parseVar({anyToken:!0})})}parseUserDefinedType(e){let t=e.name;for(;this.match("dot");)this.advanceAny(),t=`${t}.${_nullishCoalesce(_optionalChain([this, 'access', _412 => _412.prev, 'optionalAccess', _413 => _413.text]), () => (""))}`;return C.build(t,{dialect:this.dialect,udt:!0})}parseTypes(e={}){let{checkFunc:t=!1,schema:s=!1,allowIdentifiers:r=!0}=e,i=this.index,a,o=this.matchTextSeq(["SYSUDTLIB","."])||void 0,c,p;if(this.matchSet(this._constructor.TYPE_TOKENS))c=_optionalChain([this, 'access', _414 => _414.prev, 'optionalAccess', _415 => _415.tokenType]),p=_optionalChain([this, 'access', _416 => _416.prev, 'optionalAccess', _417 => _417.text]);else{let S=r&&this.parseIdVar({anyToken:!1,tokens:new Set(["var"])});if(S instanceof G){let I;try{I=_optionalChain([this, 'access', _418 => _418.dialect, 'access', _419 => _419.tokenize, 'optionalCall', _420 => _420(S.name)])}catch (e7){I=void 0}if(I&&I.length===1&&this._constructor.TYPE_TOKENS.has(I[0].tokenType))c=I[0].tokenType,p=I[0].text;else if(this._dialectConstructor.SUPPORTS_USER_DEFINED_TYPES)a=this.parseUserDefinedType(S);else{this.retreat(this.index-1);return}}else return}if(c==="pseudoType")return this.expression(mg,{this:(_nullishCoalesce(_optionalChain([this, 'access', _421 => _421.prev, 'optionalAccess', _422 => _422.text]), () => (""))).toUpperCase()});if(c==="objectIdentifier")return this.expression(Rg,{this:(_nullishCoalesce(_optionalChain([this, 'access', _423 => _423.prev, 'optionalAccess', _424 => _424.text]), () => (""))).toUpperCase()});if(c==="map"&&this.match("lBracket")){let S=this.parseTypes({checkFunc:t,schema:s,allowIdentifiers:r});if(!this.match("farrow")){this.retreat(i);return}let I=this.parseTypes({checkFunc:t,schema:s,allowIdentifiers:r});if(!this.match("rBracket")){this.retreat(i);return}return new C({this:"map",expressions:[S,I],nested:!0,prefix:o})}let u=c&&this._constructor.NESTED_TYPE_TOKENS.has(c),E=c&&this._constructor.STRUCT_TYPE_TOKENS.has(c),g=c&&this._constructor.AGGREGATE_TYPE_TOKENS.has(c),A,x=!1;if(this.match("lParen")){if(E)A=this.parseCsv(()=>this.parseStructTypes({typeRequired:!0}));else if(u){if(A=this.parseCsv(()=>this.parseTypes({checkFunc:t,schema:s,allowIdentifiers:r})),c==="nullable"&&A.length===1)return a=A[0],a.setArgKey("nullable",!0),this.matchRParen(),a}else if(c&&this._constructor.ENUM_TYPE_TOKENS.has(c))A=this.parseCsv(()=>this.parseEquality());else if(g){let S=this.parseFunction({anonymous:!0})||this.parseIdVar({anyToken:!1,tokens:new Set(["var","any"])});if(!S)return;A=[S],this.match("comma")&&A.push(...this.parseCsv(()=>this.parseTypes({checkFunc:t,schema:s,allowIdentifiers:r})))}else A=this.parseCsv(()=>this.parseTypeSize()),c==="vector"&&A.length===2&&(A=this.parseVectorExpressions(A));if(!this.match("rParen")){this.retreat(i);return}x=!0}let m;if(u&&this.match("lt")&&(E?A=this.parseCsv(()=>this.parseStructTypes({typeRequired:!0})):A=this.parseCsv(()=>this.parseTypes({checkFunc:t,schema:s,allowIdentifiers:r})),this.match("gt")||this.raiseError("Expecting >",this.curr),this.matchSet(new Set(["lBracket","lParen"]))&&(m=this.parseCsv(()=>this.parseDisjunction()),!m&&E?(m=void 0,this.retreat(this.index-1)):this.matchSet(new Set(["rBracket","rParen"])))),c&&this._constructor.TIMESTAMPS.has(c))if(this.matchTextSeq(["WITH","TIME","ZONE"])){x=!1;let S=this._constructor.TIMES.has(c)?"timetz":"timestamptz";a=new C({this:S,expressions:A})}else this.matchTextSeq(["WITH","LOCAL","TIME","ZONE"])?(x=!1,a=new C({this:"timestampltz",expressions:A})):this.matchTextSeq(["WITHOUT","TIME","ZONE"])&&(x=!1);else if(c==="interval")if(this.curr&&this._dialectConstructor.VALID_INTERVAL_UNITS.has(this.curr.text.toUpperCase())){let S=this.parseVar({upper:!0});this.matchTextSeq("TO")&&(S=new Kn({this:S,expression:this.parseVar({upper:!0})})),a=this.expression(C,{this:new ze({unit:S})})}else a=this.expression(C,{this:"interval"});else c==="void"&&(a=new C({this:"null"}));if(x&&t){let S=this.index;if(!this.parseString()){this.retreat(i);return}this.retreat(S)}if(a)A&&a.setArgKey("expressions",A);else{if(this.matchTextSeq("UNSIGNED")){let S=c&&this._constructor.SIGNED_TO_UNSIGNED_TYPE_TOKEN[c];S||this.raiseError(`Cannot convert ${_optionalChain([c, 'optionalAccess', _425 => _425.valueOf, 'call', _426 => _426()])} to unsigned.`,this.curr),c=S||c}if(c==="nullable"&&!A){this.retreat(i);return}if(c&&(a=new C({this:Be[Lw(c)],expressions:A,nested:u,prefix:o}),m!==void 0)){let S=E?Hs:Ne;a=Le(new S({expressions:m}),a,{copy:!1})}}for(;this.match("list");)a=new C({this:"list",expressions:[a],nested:!0});let N=this.index,R=this.match("array")||!1;for(;this.curr;){let S=_optionalChain([this, 'access', _427 => _427.prev, 'optionalAccess', _428 => _428.tokenType]);if(!(this.match("lBracket")||void 0)&&!R||S==="array"&&this.match("rBracket"))break;R=!1;let y=this.parseCsv(()=>this.parseDisjunction());if(0<y.length&&!s&&(!this._dialectConstructor.SUPPORTS_FIXED_SIZE_ARRAYS||S==="array"||!this.match("rBracket",{advance:!1}))){this.retreat(N);break}a=new C({this:"array",expressions:[a],values:y,nested:!0}),this.match("rBracket")}if(a&&this._constructor.TYPE_CONVERTERS&&typeof a.args.this=="string"){let S=this._constructor.TYPE_CONVERTERS[a.args.this];S&&(a=S(a))}return a}parseVectorExpressions(e){let t=C.build(e[0].name,{dialect:this.dialect});return[...t?[t]:[],...e.slice(1)]}parseStructTypes(e={}){let{typeRequired:t=!1}=e,s=this.index,r;return this.curr&&this.next&&this._constructor.TYPE_TOKENS.has(this.curr.tokenType)&&this._constructor.TYPE_TOKENS.has(this.next.tokenType)?r=this.parseIdVar():r=this.parseType({parseInterval:!1,fallbackToIdentifier:!0})||this.parseIdVar(),this.match("colon"),t&&!(r instanceof C)&&!this.matchSet(this._constructor.TYPE_TOKENS,{advance:!1})?(this.retreat(s),this.parseTypes()):this.parseColumnDef(r)}parseAtTimeZone(e){return this.matchTextSeq(["AT","TIME","ZONE"])?this.parseAtTimeZone(this.expression(Or,{this:e,zone:this.parseUnary()})):e}parseColumn(){let e=this.parseColumnReference(),t=e?this.parseColumnOps(e):this.parseBracket(e);return this._dialectConstructor.SUPPORTS_COLUMN_JOIN_MARKS&&t&&t.setArgKey("joinMark",this.match("joinMarker")),t}parseColumnReference(){let e=this.parseField();return!e&&this.match("values",{advance:!1})&&this._constructor.VALUES_FOLLOWED_BY_PAREN&&(!this.next||this.next.tokenType!=="lParen")&&(e=this.parseIdVar()),e instanceof G&&(e=this.expression(k,{comments:e.popComments(),this:e})),e}parseColonAsVariantExtract(e){let t=[],s=[],r;for(;this.match("colon");){let i=this.index,a=this.parseColumnOps(this.parseField({anyToken:!0,tokens:new Set(["select"])}));for(;a instanceof Z;)t.push(a.args.to),a=a.args.this;let o;if(0<t.length){let c=this.tokens.slice(i).findIndex(p=>p.tokenType==="dcolon");o=this.tokens[i+c-1]}else o=this.prev;a&&(a instanceof G&&a.args.quoted&&(r=!0),s.push(this.findSql(this.tokens[i],o)))}if(0<s.length){let i=_optionalChain([this, 'access', _429 => _429.dialect, 'access', _430 => _430.toJsonPath, 'optionalCall', _431 => _431(w.string("."+s.join(".")))]);for(i&&i.setArgKey("escape",r),e=this.expression(Zt,{this:e,expression:i,variantExtract:!0,requiresJson:this._constructor.JSON_EXTRACT_REQUIRES_JSON_EXPRESSION});0<t.length;)e=this.expression(Z,{this:e,to:t.pop()})}return e}parseDcolon(){return this.parseTypes()}parseColumnOps(e){let t=this.parseBracket(e);for(;this.matchSet(Object.keys(this._constructor.COLUMN_OPERATORS));){let s=_nullishCoalesce(_optionalChain([this, 'access', _432 => _432.prev, 'optionalAccess', _433 => _433.tokenType]), () => ("unknown")),r=this._constructor.COLUMN_OPERATORS[s],i;if(this._constructor.CAST_COLUMN_OPERATORS.has(s)?(i=this.parseDcolon(),i||this.raiseError("Expected type",this.curr)):r&&this.curr?(i=this.parseColumnReference()||this.parseBitwise(),i instanceof k&&this.match("dot",{advance:!1})&&(i=this.parseColumnOps(i))):i=this.parseField({anyToken:!0,anonymousFunc:!0}),(i instanceof d||i instanceof Fe)&&t&&(t=t.transform(a=>a instanceof k&&_optionalChain([a, 'access', _434 => _434.toDot, 'optionalCall', _435 => _435({includeDots:!1})])||a)),r)t=r.call(this,t,i);else if(t instanceof k&&!t.args.catalog)t=this.expression(k,{comments:t.comments,this:i,table:t.args.this,db:t.args.table,catalog:t.args.db});else if(i instanceof Fe){let a=this.expression(me,{this:t,expression:i.args.this});i.setArgKey("this",a),t=i}else t=this.expression(me,{this:t,expression:i});_optionalChain([i, 'optionalAccess', _436 => _436.comments])&&_optionalChain([t, 'optionalAccess', _437 => _437.addComments, 'optionalCall', _438 => _438(i.popComments())]),t=this.parseBracket(t)}return this._constructor.COLON_IS_VARIANT_EXTRACT?this.parseColonAsVariantExtract(t):t}parseComment(e={}){let{allowExists:t=!0}=e,s=this.prev,r=t?this.parseExists():void 0;this.match("on");let i=this.matchTextSeq("MATERIALIZED")||void 0,a=(this.matchSet(this._constructor.CREATABLES)||void 0)&&this.prev;if(!a)return this.parseAsCommand(s);let o;return a.tokenType==="function"||a.tokenType==="procedure"?o=this.parseUserDefinedFunction({kind:a.tokenType}):a.tokenType==="table"?o=this.parseTable({aliasTokens:this._constructor.COMMENT_TABLE_ALIAS_TOKENS}):a.tokenType==="column"?o=this.parseColumn():o=this.parseIdVar(),this.match("is"),this.expression(Zl,{this:o,kind:a.text,expression:this.parseString(),exists:r,materialized:i})}parseToTable(){let e=this.parseTableParts({schema:!0});return this.expression(ca,{this:e})}parseTtl(){let e=()=>{let a=this.parseBitwise();return this.matchTextSeq("DELETE")?this.expression(_i,{this:a,delete:!0}):this.matchTextSeq("RECOMPRESS")?this.expression(_i,{this:a,recompress:this.parseBitwise()}):this.matchTextSeq(["TO","DISK"])?this.expression(_i,{this:a,toDisk:this.parseString()}):this.matchTextSeq(["TO","VOLUME"])?this.expression(_i,{this:a,toVolume:this.parseString()}):a},t=this.parseCsv(e),s=this.parseWhere(),r=this.parseGroup(),i;return r&&this.match("set")&&(i=this.parseCsv(this.parseSetItem.bind(this))),this.expression(vi,{expressions:t,where:s,group:r,aggregates:i})}parseStatement(){if(this.curr===void 0)return;let e=Object.keys(this._constructor.STATEMENT_PARSERS);if(this.matchSet(e)){let s=this.prevComments,r=_optionalChain([this, 'access', _439 => _439._constructor, 'access', _440 => _440.STATEMENT_PARSERS, 'access', _441 => _441[_nullishCoalesce(_optionalChain([this, 'access', _442 => _442.prev, 'optionalAccess', _443 => _443.tokenType]), () => ("unknown"))], 'optionalAccess', _444 => _444.call, 'call', _445 => _445(this)]);return _optionalChain([r, 'optionalAccess', _446 => _446.addComments, 'call', _447 => _447(s,{prepend:!0})]),r}if(this.matchSet(this._dialectConstructor.tokenizerClass.COMMANDS))return this.parseCommand();let t=this.parseExpression();return t=t?this.parseSetOperations(t):this.parseSelect(),this.parseQueryModifiers(t)}parsePartitionedByBucketOrTruncate(){if(_optionalChain([this, 'access', _448 => _448.curr, 'optionalAccess', _449 => _449.tokenType])!=="lParen"){this.retreat(this.index-1);return}let e=_optionalChain([this, 'access', _450 => _450.prev, 'optionalAccess', _451 => _451.text, 'access', _452 => _452.toUpperCase, 'call', _453 => _453()])==="BUCKET"?ii:ai,t=this.parseWrappedCsv(()=>this.parsePrimary()||this.parseColumn()),s=b(t,0),r=b(t,1);return s instanceof w&&([s,r]=[r,s]),this.expression(e,{this:s,expression:r})}raiseError(e,t){let s=t||this.curr||this.prev||Lg.string(""),{formattedSql:r,startContext:i,highlight:a,endContext:o}=oO({sql:this.sql,positions:[[_nullishCoalesce(s.start, () => (0)),_nullishCoalesce(s.end, () => (0))]],contextLength:this.errorMessageContext}),c=`${e}. Line ${s.line}, Col: ${s.col}.
|
|
4
|
+
${r}`,p=new ns(c,[{description:e,line:s.line,col:s.col,startContext:i,highlight:a,endContext:o}]);if(this.errorLevel===3)throw p;this.errors.push(p)}checkErrors(){if(this.errorLevel===1)for(let e of this.errors)console.error(e.toString());else if(this.errorLevel===2&&0<this.errors.length)throw new ns(mw(this.errors,this.maxErrors),JM(this.errors))}expression(e,t={}){let{token:s,comments:r,...i}=t,a;return s?(a=new e({this:s.text,...i}),a.updatePositions(s)):a=new e(i),_optionalChain([r, 'optionalAccess', _454 => _454.length])?a.addComments(r):this.addComments(a),this.validateExpression(a)}addComments(e){e&&_optionalChain([this, 'access', _455 => _455.prevComments, 'optionalAccess', _456 => _456.length])&&(e.addComments(this.prevComments),this.prevComments=void 0)}parseIdVar(e={}){let{anyToken:t=!0,tokens:s}=e,r=this.parseIdentifier();if(!r&&(t&&this.advanceAny()||this.matchSet(s||this._constructor.ID_VAR_TOKENS))){let i=_optionalChain([this, 'access', _457 => _457.prev, 'optionalAccess', _458 => _458.tokenType])==="string";r=this.identifierExpression(void 0,{quoted:i})}return r}parseGrantPrincipal(){let e=(this.matchTexts(["ROLE","GROUP"])||void 0)&&_optionalChain([this, 'access', _459 => _459.prev, 'optionalAccess', _460 => _460.text, 'access', _461 => _461.toUpperCase, 'call', _462 => _462()]),t=this.parseIdVar();if(t)return this.expression(Nu,{this:t,kind:e})}parseGrantPrivilege(){let e=[];for(;this.curr&&!this.matchSet(this._constructor.PRIVILEGE_FOLLOW_TOKENS,{advance:!1});)e.push(this.curr.text.toUpperCase()),this.advance();let t=this.expression(Ze,{this:e.join(" ")}),s=this.match("lParen",{advance:!1})?this.parseWrappedCsv(()=>this.parseColumn()):void 0;return this.expression(Ou,{this:t,expressions:s})}matchTexts(e,t={}){let{advance:s=!0}=t,r=Array.from(e instanceof Set?e:pe(e));return this.curr&&this.curr.tokenType!=="string"&&r.includes(this.curr.text.toUpperCase())?(s&&this.advance(),!0):!1}matchSet(e,t={}){let{advance:s=!0}=t;return this.curr&&(Array.isArray(e)?e.includes(this.curr.tokenType):e.has(this.curr.tokenType))?(s&&this.advance(),!0):!1}matchPair(e,t,s={}){let{advance:r=!0}=s;return!this.curr||!this.next?!1:this.curr.tokenType===e&&this.next.tokenType===t?(r&&this.advance(2),!0):!1}matchLParen(e){this.match("lParen",{advance:!0,expression:e})||this.raiseError("Expecting (")}matchRParen(e){this.match("rParen",{advance:!0,expression:e})||this.raiseError("Expecting )")}matchTextSeq(e,t={}){let{advance:s=!0}=t,r=pe(e),i=this.index;for(let a of r)if(this.curr&&this.curr.tokenType!=="string"&&this.curr.text.toUpperCase()===a)this.advance();else return this.retreat(i),!1;return s||this.retreat(i),!0}replaceLambda(e,t){if(!e)return e;let s={};for(let r of t)s[r.name]=r.args.to||!1;for(let r of e.findAll(k)){let i=s[_optionalChain([r, 'access', _463 => _463.parts, 'access', _464 => _464[0], 'optionalAccess', _465 => _465.name])||""];if(i!==void 0){let a=r.args.this;ue(a,G);let o=r.table?r.toDot():a;i&&(o=this.expression(Z,{this:o,to:i}));let c=r.parent;for(;c instanceof me;){if(!(c.parent instanceof me)){c.replace(o);break}c=c.parent}(!c||!(c instanceof me))&&(r===e?e=o:r.replace(o))}}return e}parseTruncateTable(){let e=this.prev;if(this.match("lParen"))return this.retreat(this.index-2),this.parseFunction();let t=this.match("database")||void 0;this.match("table");let s=this.parseExists({not:!1}),r=this.parseCsv(()=>this.parseTable({schema:!0,isDbReference:t})),i=this.match("on")?this.parseOnProperty():void 0,a;this.matchTextSeq(["RESTART","IDENTITY"])?a="RESTART":this.matchTextSeq(["CONTINUE","IDENTITY"])?a="CONTINUE":a=void 0;let o;this.matchTextSeq("CASCADE")||this.matchTextSeq("RESTRICT")?o=_optionalChain([this, 'access', _466 => _466.prev, 'optionalAccess', _467 => _467.text]):o=void 0;let c=this.parsePartition();return this.curr?this.parseAsCommand(e):this.expression($l,{expressions:r,isDatabase:t,exists:s,cluster:i,identity:a,option:o,partition:c})}parseWithOperator(){let e=this.parseOrdered(()=>this.parseOpClass());if(!this.match("with"))return e;let t=this.parseVar({anyToken:!0,tokens:this._constructor.RESERVED_TOKENS});return this.expression(To,{this:e,op:t})}parseWrappedOptions(){this.match("eq"),this.match("lParen");let e=[],t;for(;this.curr&&!this.match("rParen");){if(this.matchTextSeq(["FORMAT_NAME","="])?t=this.parseFormatName():t=this.parseProperty(),t===void 0){this.raiseError("Unable to parse option");break}e.push(...Array.isArray(t)?t:[t])}return e}parseCopyParameters(){let e=this._dialectConstructor.COPY_PARAMS_ARE_CSV?"comma":void 0,t=[];for(;this.curr&&!this.match("rParen",{advance:!1});){let s=this.parseVar({anyToken:!0}),r=_optionalChain([this, 'access', _468 => _468.prev, 'optionalAccess', _469 => _469.text, 'access', _470 => _470.toUpperCase, 'call', _471 => _471()]);this.match("eq"),this.match("alias");let i=this.expression(nu,{this:s});r&&this._constructor.COPY_INTO_VARLEN_OPTIONS.has(r)&&this.match("lParen",{advance:!1})?i.setArgKey("expressions",this.parseWrappedOptions()):r==="FILE_FORMAT"?i.setArgKey("expression",this.parseField()):r==="FORMAT"&&_optionalChain([this, 'access', _472 => _472.prev, 'optionalAccess', _473 => _473.tokenType])==="alias"&&this.matchTexts(["AVRO","JSON"])?(i.setArgKey("this",this.expression(Ze,{this:`FORMAT AS ${_optionalChain([this, 'access', _474 => _474.prev, 'optionalAccess', _475 => _475.text, 'access', _476 => _476.toUpperCase, 'call', _477 => _477()])}`})),i.setArgKey("expression",this.parseField())):i.setArgKey("expression",this.parseUnquotedField()||this.parseBracket()),t.push(i),e&&this.match(e)}return t}parseCredentials(){let e=this.expression(iu,{});if(this.matchTextSeq(["STORAGE_INTEGRATION","="])&&e.setArgKey("storage",this.parseField()),this.matchTextSeq("CREDENTIALS")){let t=this.match("eq")?this.parseWrappedOptions():this.parseField();e.setArgKey("credentials",t)}return this.matchTextSeq("ENCRYPTION")&&e.setArgKey("encryption",this.parseWrappedOptions()),this.matchTextSeq("IAM_ROLE")&&e.setArgKey("iamRole",this.match("default")?this.expression(Ze,{this:_optionalChain([this, 'access', _478 => _478.prev, 'optionalAccess', _479 => _479.text])}):this.parseField()),this.matchTextSeq("REGION")&&e.setArgKey("region",this.parseField()),e}parseFileLocation(){return this.parseField()}parseCopy(){let e=this.prev;this.match("into");let t=this.match("lParen",{advance:!1})?this.parseSelect({nested:!0,parseSubqueryAlias:!1}):this.parseTable({schema:!0}),s=this.match("from")||!this.matchTextSeq("TO"),r=this.parseCsv(()=>this.parseFileLocation());this.match("eq",{advance:!1})&&(this.advance(-1),r=[]);let i=this.parseCredentials();this.matchTextSeq("WITH");let a=this.parseWrapped(()=>this.parseCopyParameters(),{optional:!0});return this.curr?this.parseAsCommand(e):this.expression(AE,{this:t,kind:s,credentials:i,files:r,params:a})}parseNormalize(){return this.expression(wg,{this:this.parseBitwise(),form:this.match("comma")&&this.parseVar()})}parseCeilFloor(e){let t=this.parseCsv(()=>this.parseLambda()),s=b(t,0),r=b(t,1);return new e({this:s,decimals:r,to:this.matchTextSeq("TO")&&this.parseVar()})}parseStarOps(){let e=this.prev;if(this.matchTextSeq(["COLUMNS","("],{advance:!1})){let t=this.parseFunction();return t instanceof RO&&t.setArgKey("unpack",!0),t}return this.expression(ye,{except:this.parseStarOp("EXCEPT")||this.parseStarOp("EXCLUDE"),replace:this.parseStarOp("REPLACE"),rename:this.parseStarOp("RENAME")}).updatePositions(e)}parseGrantRevokeCommon(){let e=this.parseCsv(()=>this.parseGrantPrivilege());this.match("on");let t=(this.matchSet(this._constructor.CREATABLES)||void 0)&&_optionalChain([this, 'access', _480 => _480.prev, 'optionalAccess', _481 => _481.text, 'access', _482 => _482.toUpperCase, 'call', _483 => _483()]),s=this.tryParse(()=>this.parseTableParts());return{privileges:e,kind:t,securable:s}}parseGrant(){let e=this.prev,{privileges:t,kind:s,securable:r}=this.parseGrantRevokeCommon();if(!r||!this.matchTextSeq("TO"))return this.parseAsCommand(e);let i=this.parseCsv(()=>this.parseGrantPrincipal()),a=this.matchTextSeq(["WITH","GRANT","OPTION"])||void 0;return this.curr?this.parseAsCommand(e):this.expression(Au,{privileges:t,kind:s,securable:r,principals:i,grantOption:a})}parseRevoke(){let e=this.prev,t=this.matchTextSeq(["GRANT","OPTION","FOR"])||void 0,{privileges:s,kind:r,securable:i}=this.parseGrantRevokeCommon();if(!i||!this.matchTextSeq("FROM"))return this.parseAsCommand(e);let a=this.parseCsv(()=>this.parseGrantPrincipal()),o;return this.matchTexts(["CASCADE","RESTRICT"])&&(o=_optionalChain([this, 'access', _484 => _484.prev, 'optionalAccess', _485 => _485.text, 'access', _486 => _486.toUpperCase, 'call', _487 => _487()])),this.curr?this.parseAsCommand(e):this.expression(fu,{privileges:s,kind:r,securable:i,principals:a,grantOption:t,cascade:o})}parseOverlay(){let e=t=>(this.match("comma")||this.matchTextSeq(t)||void 0)&&this.parseBitwise();return this.expression(Mg,{this:this.parseBitwise(),expression:e("PLACING"),from:e("FROM"),for:e("FOR")})}parseFormatName(){return this.expression(U,{this:this.expression(Ze,{this:"FORMAT_NAME"}),value:this.parseString()||this.parseTableParts()})}parseMaxMinBy(e){let t=[];return this.match("distinct")&&(t.push(this.expression(ct,{expressions:[this.parseLambda()]})),this.match("comma")),t.push(...this.parseFunctionArgs()),this.expression(e,{this:b(t,0),expression:b(t,1),count:b(t,2)})}identifierExpression(e,t){return this.expression(G,{token:e||this.prev,...t})}parseTokens(e,t){let s=e(),r=new Set(Object.keys(t));for(;this.matchSet(r);){let i=t[_nullishCoalesce(_optionalChain([this, 'access', _488 => _488.prev, 'optionalAccess', _489 => _489.tokenType]), () => ("unknown"))];if(!i)break;s=this.expression(i,{this:s,comments:this.prevComments,expression:e()})}return s}parseWrappedIdVars(e={}){let{optional:t=!1}=e;return this.parseWrappedCsv(()=>this.parseIdVar(),{optional:t})}parseWrappedCsv(e,t={}){let{sep:s="comma",optional:r=!1}=t;return this.parseWrapped(()=>this.parseCsv(e,{sep:s}),{optional:r})}parseWrapped(e,t={}){let{optional:s=!1}=t,r=this.match("lParen")||void 0;!r&&!s&&this.raiseError("Expecting (");let i=e();return r&&this.matchRParen(),i}parseExpressions(){return this.parseCsv(()=>this.parseExpression())}parseSelectOrExpression(e={}){let{alias:t=!1}=e;return this.parseSetOperations(t?this.parseAlias(this.parseAssignment(),{explicit:!0}):this.parseAssignment())||this.parseSelect()}parseDdlSelect(){return this.parseQueryModifiers(this.parseSetOperations(this.parseSelect({nested:!0,parseSubqueryAlias:!1})))}parseTransaction(){let e;this.matchTexts(this._constructor.TRANSACTION_KIND)&&(e=_optionalChain([this, 'access', _490 => _490.prev, 'optionalAccess', _491 => _491.text])),this.matchTexts(["TRANSACTION","WORK"]);let t=[];for(;;){let s=[];for(;this.match("var")||this.match("not");)s.push(_nullishCoalesce(_optionalChain([this, 'access', _492 => _492.prev, 'optionalAccess', _493 => _493.text]), () => ("")));if(0<s.length&&t.push(s.join(" ")),!this.match("comma"))break}return this.expression(Lu,{this:e,modes:t})}parseStar(){return this.match("star")?_optionalChain([this, 'access', _494 => _494._constructor, 'access', _495 => _495.PRIMARY_PARSERS, 'access', _496 => _496.star, 'optionalAccess', _497 => _497.call, 'call', _498 => _498(this,this.prev)]):this.parsePlaceholder()}parseParameter(){let e=this.parseIdentifier()||this.parsePrimaryOrVar();return this.expression(ep,{this:e})}parsePlaceholder(){if(this.matchSet(new Set(Object.keys(this._constructor.PLACEHOLDER_PARSERS)))){let e=_optionalChain([this, 'access', _499 => _499._constructor, 'access', _500 => _500.PLACEHOLDER_PARSERS, 'access', _501 => _501[_nullishCoalesce(_optionalChain([this, 'access', _502 => _502.prev, 'optionalAccess', _503 => _503.tokenType]), () => ("unknown"))], 'optionalAccess', _504 => _504.call, 'call', _505 => _505(this)]);if(e)return e;this.advance(-1)}}parseStarOp(...e){if(!this.matchTexts(e))return;if(this.match("lParen",{advance:!1}))return this.parseWrappedCsv(()=>this.parseExpression());let t=this.parseAlias(this.parseDisjunction(),{explicit:!0});return t?[t]:void 0}parseCsv(e,t={}){let{sep:s="comma"}=t,r=e(),i=r!==void 0?[r]:[];for(;this.match(s);)this.addComments(r),r=e(),r!==void 0&&i.push(r);return i}parseIdentifier(){return this.match("identifier")?this.identifierExpression(void 0,{quoted:!0}):this.parsePlaceholder()}parseVar(e={}){let{anyToken:t=!1,tokens:s,upper:r=!1}=e;if(t&&this.advanceAny()||this.match("var")||s&&this.matchSet(s)){let i=r?(_nullishCoalesce(_optionalChain([this, 'access', _506 => _506.prev, 'optionalAccess', _507 => _507.text]), () => (""))).toUpperCase():_nullishCoalesce(_optionalChain([this, 'access', _508 => _508.prev, 'optionalAccess', _509 => _509.text]), () => (""));return this.expression(Ze,{this:i})}return this.parsePlaceholder()}advanceAny(e={}){let{ignoreReserved:t=!1}=e;if(this.curr&&(t||!this._constructor.RESERVED_TOKENS.has(this.curr.tokenType)))return this.advance(),this.prev}parseVarOrString(e={}){let{upper:t=!1}=e;return this.parseString()||this.parseVar({anyToken:!0,upper:t})}parsePrimaryOrVar(){return this.parsePrimary()||this.parseVar({anyToken:!0})}parseNull(){return this.matchSet(new Set(["null","unknown"]))?_optionalChain([this, 'access', _510 => _510._constructor, 'access', _511 => _511.PRIMARY_PARSERS, 'access', _512 => _512.null, 'optionalAccess', _513 => _513.call, 'call', _514 => _514(this,this.prev)]):this.parsePlaceholder()}parseBoolean(){return this.match("true")?_optionalChain([this, 'access', _515 => _515._constructor, 'access', _516 => _516.PRIMARY_PARSERS, 'access', _517 => _517.true, 'optionalAccess', _518 => _518.call, 'call', _519 => _519(this,this.prev)]):this.match("false")?_optionalChain([this, 'access', _520 => _520._constructor, 'access', _521 => _521.PRIMARY_PARSERS, 'access', _522 => _522.false, 'optionalAccess', _523 => _523.call, 'call', _524 => _524(this,this.prev)]):this.parsePlaceholder()}parseString(){return this.matchSet(new Set(Object.keys(this._constructor.STRING_PARSERS)))?_optionalChain([this, 'access', _525 => _525._constructor, 'access', _526 => _526.STRING_PARSERS, 'access', _527 => _527[_nullishCoalesce(_optionalChain([this, 'access', _528 => _528.prev, 'optionalAccess', _529 => _529.tokenType]), () => ("unknown"))], 'optionalAccess', _530 => _530.call, 'call', _531 => _531(this,this.prev)]):this.parsePlaceholder()}parseStringAsIdentifier(){let e=(this.match("string")||void 0)&&_optionalChain([this, 'access', _532 => _532.prev, 'optionalAccess', _533 => _533.text]),t=e===void 0?void 0:K(e,{quoted:!0});return t&&this.prev&&t.updatePositions(this.prev),t}parseNumber(){return this.matchSet(new Set(Object.keys(this._constructor.NUMERIC_PARSERS)))?_optionalChain([this, 'access', _534 => _534._constructor, 'access', _535 => _535.NUMERIC_PARSERS, 'access', _536 => _536[_nullishCoalesce(_optionalChain([this, 'access', _537 => _537.prev, 'optionalAccess', _538 => _538.tokenType]), () => ("unknown"))], 'optionalAccess', _539 => _539.call, 'call', _540 => _540(this,this.prev)]):this.parsePlaceholder()}parseHavingMax(e){if(this.match("having")){this.matchTexts(["MAX","MIN"]);let t=_optionalChain([this, 'access', _541 => _541.prev, 'optionalAccess', _542 => _542.text, 'access', _543 => _543.toUpperCase, 'call', _544 => _544()])!=="MIN";return this.expression(On,{this:e,expression:this.parseColumn(),max:t})}return e}parseWindow(e,t={}){let{alias:s=!1}=t,r=e,i=r instanceof h?r.comments:void 0;if(this.matchTextSeq(["WITHIN","GROUP"])){let x=this.parseWrapped(()=>this.parseOrder());e=this.expression(Cs,{this:e,expression:x})}if(this.matchPair("filter","lParen")&&(this.match("where"),e=this.expression(ti,{this:e,expression:this.parseWhere({skipWhereToken:!0})}),this.matchRParen()),e instanceof q){let x=e.find([dn,Bi]);x&&x!==e&&(x.replace(x.args.this),e=this.expression(x._constructor,{this:e}))}e=this.parseRespectOrIgnoreNulls(e);let a;if(s)a=void 0,this.match("alias");else if(this.matchSet(this._constructor.WINDOW_BEFORE_PAREN_TOKENS))a=_optionalChain([this, 'access', _545 => _545.prev, 'optionalAccess', _546 => _546.text, 'access', _547 => _547.toUpperCase, 'call', _548 => _548()]);else return e;if(i&&r instanceof h&&r.popComments(),!this.match("lParen"))return this.expression(Fe,{comments:i,this:e,alias:this.parseIdVar({anyToken:!1}),over:a});let o=this.parseIdVar({anyToken:!1,tokens:this._constructor.WINDOW_ALIAS_TOKENS}),c=this.match("first")||void 0;this.matchTextSeq("LAST")&&(c=!1);let[p,u]=this.parsePartitionAndOrder(),E=(this.matchSet(new Set(["rows","range"]))||void 0)&&_optionalChain([this, 'access', _549 => _549.prev, 'optionalAccess', _550 => _550.text]),g;if(E){this.match("between");let x=this.parseWindowSpec(),m=this.match("and")?this.parseWindowSpec():{},N=this.matchTextSeq("EXCLUDE")?this.parseVarFromOptions(this._constructor.WINDOW_EXCLUDE_OPTIONS):void 0;g=this.expression(wu,{kind:E,start:x.value,startSide:x.side,end:m.value,endSide:m.side,exclude:N})}else g=void 0;this.matchRParen();let A=this.expression(Fe,{comments:i,this:e,partitionBy:p,order:u,spec:g,alias:o,over:a,first:c});return this.matchSet(this._constructor.WINDOW_BEFORE_PAREN_TOKENS,{advance:!1})?this.parseWindow(A,{alias:s}):A}parsePartitionAndOrder(){return[this.parsePartitionBy(),this.parseOrder()]}parseWindowSpec(){return this.match("between"),{value:this.matchTextSeq("UNBOUNDED")&&"UNBOUNDED"||this.matchTextSeq(["CURRENT","ROW"])&&"CURRENT ROW"||this.parseBitwise()||void 0,side:(this.matchTexts(this._constructor.WINDOW_SIDES)||void 0)&&_optionalChain([this, 'access', _551 => _551.prev, 'optionalAccess', _552 => _552.text])}}parseAlias(e,t={}){let{explicit:s=!1}=t;if(this.canParseLimitOrOffset())return e;let r=this.match("alias"),i=_nullishCoalesce(this.prevComments, () => ([]));if(s&&!r)return e;if(this.match("lParen")){let o=this.expression(Rn,{comments:i,this:e,expressions:this.parseCsv(()=>this.parseIdVar({anyToken:r}))});return this.matchRParen(o),o}let a=this.parseIdVar({anyToken:r,tokens:this._constructor.ALIAS_TOKENS})||this._constructor.STRING_ALIASES&&this.parseStringAsIdentifier();if(a){i.push(...a.popComments()),e=this.expression(Se,{comments:i,this:e,alias:a});let o=e.args.this;(!e.comments||e.comments.length===0)&&o&&o.comments&&0<o.comments.length&&(e.comments=o.popComments())}return e}parseOpenJson(){let e=this.parseBitwise(),t=(this.match("comma")||void 0)&&this.parseString(),s=()=>{let i=this.parseField({anyToken:!0}),a=this.parseTypes(),o=this.parseString(),c=this.matchPair("alias","json")||void 0;return this.expression(Qu,{this:i,kind:a,path:o,asJson:c})},r;return this.matchPair("rParen","with")&&(this.matchLParen(),r=this.parseCsv(s)),this.expression(CO,{this:e,path:t,expressions:r})}parsePosition(e={}){let{haystackFirst:t=!1}=e,s=this.parseCsv(()=>this.parseBitwise());if(this.match("in"))return this.expression(ps,{this:this.parseBitwise(),substr:b(s,0)});let r=t?b(s,0):b(s,1),i=t?b(s,1):b(s,0);return this.expression(ps,{this:r,substr:i,position:b(s,2)})}parseJoinHint(e){let t=this.parseCsv(()=>this.parseTable());return new yi({this:e.toUpperCase(),expressions:t})}parseSubstring(){let e=this.parseCsv(()=>this.parseBitwise()),t,s;for(;this.curr;)if(this.match("from"))t=this.parseBitwise();else if(this.match("for"))t||(t=w.number(1)),s=this.parseBitwise();else break;return t&&e.push(t),s&&e.push(s),this.validateExpression(Ms.fromArgList(e),e)}parseTrim(){let e,t,s;this.matchTexts(this._constructor.TRIM_TYPES)&&(e=_optionalChain([this, 'access', _553 => _553.prev, 'optionalAccess', _554 => _554.text, 'access', _555 => _555.toUpperCase, 'call', _556 => _556()]));let r=this.parseBitwise();if(this.matchSet(new Set(["from","comma"]))){let i=_optionalChain([this, 'access', _557 => _557.prev, 'optionalAccess', _558 => _558.tokenType])==="from"||this._constructor.TRIM_PATTERN_FIRST;s=this.parseBitwise(),i&&([r,s]=[s,r])}return this.match("collate")&&(t=this.parseBitwise()),this.expression(or,{this:r,position:e,expression:s,collation:t})}parseWindowClause(){return(this.match("window")||void 0)&&this.parseCsv(()=>this.parseNamedWindow())}parseNamedWindow(){return this.parseWindow(this.parseIdVar(),{alias:!0})}parseRespectOrIgnoreNulls(e){return this.matchTextSeq(["IGNORE","NULLS"])?this.expression(dn,{this:e}):this.matchTextSeq(["RESPECT","NULLS"])?this.expression(Bi,{this:e}):e}parseJsonObject(e={}){let{agg:t=!1}=e,s=this.parseStar(),r=s?[s]:this.parseCsv(()=>this.parseFormatJson(this.parseJsonKeyValue())),i=this.parseOnHandling("NULL",["NULL","ABSENT"]),a;this.matchTextSeq(["WITH","UNIQUE"])?a=!0:this.matchTextSeq(["WITHOUT","UNIQUE"])&&(a=!1),this.matchTextSeq("KEYS");let o=(this.matchTextSeq("RETURNING")||void 0)&&this.parseFormatJson(this.parseType()),c=(this.matchTextSeq("ENCODING")||void 0)&&this.parseVar();return this.expression(t?_O:pp,{expressions:r,nullHandling:i,uniqueKeys:a,returnType:o,encoding:c})}parseJsonColumnDef(){let e,t,s,r;this.matchTextSeq("NESTED")?(e=void 0,t=void 0,s=void 0,r=!0):(e=this.parseIdVar(),t=this.matchPair("for","ordinality")||void 0,s=this.parseTypes({allowIdentifiers:!1}),r=void 0);let i=(this.matchTextSeq("PATH")||void 0)&&this.parseString(),a=r&&this.parseJsonSchema();return this.expression(Xu,{this:e,kind:s,path:i,nestedSchema:a,ordinality:t})}parseJsonSchema(){return this.matchTextSeq("COLUMNS"),this.expression(zu,{expressions:this.parseWrappedCsv(()=>this.parseJsonColumnDef(),{optional:!0})})}parseJsonTable(){let e=this.parseFormatJson(this.parseBitwise());e||this.raiseError("Expected expression for JSON_TABLE");let t=(this.match("comma")||void 0)&&this.parseString(),s=this.parseOnHandling("ERROR",["ERROR","NULL"]),r=this.parseOnHandling("EMPTY",["ERROR","NULL"]),i=this.parseJsonSchema();return new yO({this:e,schema:i,path:t,errorHandling:s,emptyHandling:r})}parseMatchAgainst(){let e;if(this.matchTextSeq("TABLE")){e=[];let r=this.parseTable();r&&(e=[r])}else e=this.parseCsv(()=>this.parseColumn());this.matchTextSeq([")","AGAINST","("]);let t=this.parseString(),s;return this.matchTextSeq(["IN","NATURAL","LANGUAGE","MODE"])?(s="IN NATURAL LANGUAGE MODE",this.matchTextSeq(["WITH","QUERY","EXPANSION"])&&(s=`${s} WITH QUERY EXPANSION`)):this.matchTextSeq(["IN","BOOLEAN","MODE"])?s="IN BOOLEAN MODE":this.matchTextSeq(["WITH","QUERY","EXPANSION"])?s="WITH QUERY EXPANSION":s=void 0,this.expression(PO,{this:t,expressions:e,modifier:s})}parseJsonKeyValue(){this.matchTextSeq("KEY");let e=this.parseColumn();this.matchSet(this._constructor.JSON_KEY_VALUE_SEPARATOR_TOKENS),this.matchTextSeq("VALUE");let t=this.parseBitwise();if(!(!e&&!t))return this.expression(Ju,{this:e,expression:t})}parseFormatJson(e){return!e||!this.matchTextSeq(["FORMAT","JSON"])?e:this.expression(ju,{this:e})}parseOnCondition(){let e,t;this._dialectConstructor.ON_CONDITION_EMPTY_BEFORE_ERROR?(e=this.parseOnHandling("EMPTY",[...this._constructor.ON_CONDITION_TOKENS]),t=this.parseOnHandling("ERROR",[...this._constructor.ON_CONDITION_TOKENS])):(t=this.parseOnHandling("ERROR",[...this._constructor.ON_CONDITION_TOKENS]),e=this.parseOnHandling("EMPTY",[...this._constructor.ON_CONDITION_TOKENS]));let s=this.parseOnHandling("NULL",[...this._constructor.ON_CONDITION_TOKENS]);if(!(!e&&!t&&!s))return this.expression(hu,{empty:e,error:t,null:s})}parseOnHandling(e,t){for(let r of t)if(this.matchTextSeq([r,"ON",e]))return`${r} ON ${e}`;let s=this.index;if(this.match("default")){let r=this.parseBitwise();if(this.matchTextSeq(["ON",e]))return r;this.retreat(s)}}parseConvert(e){let{safe:t,strict:s}=e,r=this.parseBitwise(),i;return this.match("using")?i=this.expression(Bc,{this:this.parseVar({tokens:new Set(["binary"])})}):this.match("comma")?i=this.parseTypes():i=void 0,this.buildCast({strict:s,this:r,to:i,safe:t})}parseXmlElement(){let e,t;return this.matchTextSeq("EVALNAME")?(e=!0,t=this.parseBitwise()):(e=void 0,this.matchTextSeq("NAME"),t=this.parseIdVar()),this.expression(MO,{this:t,expressions:(this.match("comma")||void 0)&&this.parseCsv(()=>this.parseBitwise()),evalname:e})}parseXmlTable(){let e,t,s;this.matchTextSeq(["XMLNAMESPACES","("])&&(e=this.parseXmlNamespace(),this.match("rParen"),this.match("comma"));let r=this.parseString();this.matchTextSeq("PASSING")&&(this.matchTextSeq(["BY","VALUE"]),t=this.parseCsv(()=>this.parseColumn()));let i=this.matchTextSeq(["RETURNING","SEQUENCE","BY","REF"])||void 0;return this.matchTextSeq("COLUMNS")&&(s=this.parseCsv(()=>this.parseFieldDef())),this.expression(LO,{this:r,namespaces:e,passing:t,columns:s,byRef:i})}parseXmlNamespace(){let e=[];for(;;){let t;if(this.match("default")?t=this.parseString():t=this.parseAlias(this.parseString()),e.push(this.expression(Zu,{this:t})),!this.match("comma"))break}return e}parseDecode(){let e=this.parseCsv(()=>this.parseDisjunction());return e.length<3?this.expression(OE,{this:b(e,0),charset:b(e,1)}):this.expression(bg,{expressions:e})}parseGapFill(){this.match("table");let e=this.parseTable();this.match("comma");let t=[e,...this.parseCsv(()=>this.parseLambda())].filter(r=>r instanceof h),s=NO.fromArgList(t);return this.validateExpression(s,t)}parseChar(){return this.expression(sp,{expressions:this.parseCsv(()=>this.parseAssignment()),charset:(this.match("using")||void 0)&&this.parseVar()})}parseCast(e){let{safe:t,strict:s}=e,r=this.parseDisjunction();if(!this.match("alias")){if(this.match("comma"))return this.expression(OO,{this:r,to:this.parseString()});this.raiseError("Expected AS after CAST")}let i,a=this.parseTypes(),o;if(this.match("default")&&(o=this.parseBitwise(),this.matchTextSeq(["ON","CONVERSION","ERROR"])),this.matchSet(new Set(["format","comma"]))){let c=this.parseString();if(i=this.parseAtTimeZone(c),a||(a=C.build("unknown")),a&&C.TEMPORAL_TYPES.has(a.args.this))return r=this.expression(a.args.this==="date"?ar:Jt,{this:r,format:w.string(_nullishCoalesce(dg(_nullishCoalesce(_optionalChain([c, 'optionalAccess', _559 => _559.args, 'access', _560 => _560.this]), () => ("")),Object.keys(this._dialectConstructor.FORMAT_MAPPING).length?this._dialectConstructor.FORMAT_MAPPING:this._dialectConstructor.TIME_MAPPING,Object.keys(this._dialectConstructor.FORMAT_MAPPING).length?this._dialectConstructor.FORMAT_TRIE:this._dialectConstructor.TIME_TRIE), () => (""))),safe:t}),i instanceof Or&&r instanceof Jt&&r.setArgKey("zone",i.args.zone),r}else a?a instanceof G?a=C.build(a.name,{dialect:this.dialect,udt:!0}):a.args.this==="char"&&this.match("characterSet")&&(a=this.expression(Bc,{this:this.parseVarOrString()})):this.raiseError("Expected TYPE after CAST");return this.buildCast({strict:s,this:r,to:a,format:i,safe:t,action:this.parseVarFromOptions(this._constructor.CAST_ACTIONS,{raiseUnmatched:!1}),default:o})}parseStringAgg(){let e;this.match("distinct")?(e=[this.expression(ct,{expressions:[this.parseDisjunction()]})],this.match("comma")&&e.push(...this.parseCsv(()=>this.parseDisjunction()))):e=this.parseCsv(()=>this.parseDisjunction());let t;this.matchTextSeq(["ON","OVERFLOW"])?this.matchTextSeq("ERROR")?t=Te("ERROR"):(this.matchTextSeq("TRUNCATE"),t=this.expression(Vu,{this:this.parseString(),withCount:this.matchTextSeq(["WITH","COUNT"])||!this.matchTextSeq(["WITHOUT","COUNT"])})):t=void 0;let s=this.index;return!this.match("rParen")&&0<e.length?(e[0]=this.parseLimit(this.parseOrder({thisExpr:e[0]})),this.expression(tr,{this:e[0],separator:b(e,1)})):this.matchTextSeq(["WITHIN","GROUP"])?(this.matchLParen(),this.expression(tr,{this:this.parseOrder({thisExpr:b(e,0)}),separator:b(e,1),onOverflow:t})):(this.retreat(s),this.validateExpression(tr.fromArgList(e.filter(r=>r instanceof h)),e))}parseBracket(e){if(!this.matchSet(new Set(["lBracket","lBrace"])))return e;let t;if(this._constructor.MAP_KEYS_ARE_ARBITRARY_EXPRESSIONS){let i=b(this.tokens,this.index-2);t=i!==void 0&&i.text.toUpperCase()==="MAP"}else t=!1;let s=_optionalChain([this, 'access', _561 => _561.prev, 'optionalAccess', _562 => _562.tokenType]);if(s==="lBrace"&&this.curr&&this.curr.tokenType==="var"&&this._constructor.ODBC_DATETIME_LITERALS[this.curr.text.toLowerCase()])return this.parseOdbcDatetimeLiteral();let r=this.parseCsv(()=>this.parseBracketKeyValue({isMap:s==="lBrace"}));if(s==="lBracket"&&!this.match("rBracket")?this.raiseError("Expected ]"):s==="lBrace"&&!this.match("rBrace")&&this.raiseError("Expected }"),s==="lBrace")e=this.expression(Hs,{expressions:this.kvToPropEq(r,{parseMap:t})});else if(!e&&s)e=eq(Ne,r,s,this.dialect);else if(e&&s){let i=this._constructor.ARRAY_CONSTRUCTORS[_nullishCoalesce(_optionalChain([e, 'optionalAccess', _563 => _563.name, 'access', _564 => _564.toUpperCase, 'call', _565 => _565()]), () => (""))];if(i)return eq(i,r,s,this.dialect);let a=WT(e,r,-this._dialectConstructor.INDEX_OFFSET,{dialect:this.dialect});e=this.expression(fs,{this:e,expressions:a,comments:e.popComments()})}return this.addComments(e),this.parseBracket(e)}parseSlice(e){if(!this.match("colon"))return e;let t;this.matchPair("dash","colon",{advance:!1})?(this.advance(),t=w.number("1").neg()):t=this.parseAssignment();let s=this.match("colon")?this.parseUnary():void 0;return this.expression(Pi,{this:e,expression:t,step:s})}parseCase(){if(this.match("dot",{advance:!1})){this.retreat(this.index-1);return}let e=[],t,s=this.prevComments,r=this.parseDisjunction();for(;this.match("when");){let i=this.parseDisjunction();this.match("then");let a=this.parseDisjunction();e.push(this.expression(He,{this:i,true:a}))}return this.match("else")&&(t=this.parseDisjunction()),this.match("end")||(t instanceof ze&&_optionalChain([(typeof t.args.this=="string"?t.args.this:_optionalChain([t, 'access', _566 => _566.args, 'access', _567 => _567.this, 'optionalAccess', _568 => _568.sql, 'call', _569 => _569()])), 'optionalAccess', _570 => _570.toUpperCase, 'call', _571 => _571()])==="END"?t=Ie({col:"interval"}):this.raiseError("Expected END after CASE",this.prev)),this.expression(Ht,{comments:s,this:r,ifs:e,default:t})}parseIf(){if(this.match("lParen")){let e=this.parseCsv(()=>this.parseAlias(this.parseAssignment(),{explicit:!0})),t=this.validateExpression(He.fromArgList(e),e);return this.matchRParen(),t}else{let e=this.index-1;if(this._constructor.NO_PAREN_IF_COMMANDS&&e===0)return this.parseAsCommand(this.prev);let t=this.parseDisjunction();if(!t){this.retreat(e);return}this.match("then");let s=this.parseDisjunction(),r=this.match("else")?this.parseDisjunction():void 0;return this.match("end"),this.expression(He,{this:t,true:s,false:r})}}parseNextValueFor(){if(!this.matchTextSeq(["VALUE","FOR"])){this.retreat(this.index-1);return}return this.expression(DO,{this:this.parseColumn(),order:(this.match("over")||void 0)&&this.parseWrapped(()=>this.parseOrder())})}parseExtract(){let e=this.parseFunction()||this.parseVarOrString({upper:!0});return this.match("from")?this.expression(Zn,{this:e,expression:this.parseBitwise()}):(this.match("comma")||this.raiseError("Expected FROM or comma after EXTRACT",this.prev),this.expression(Zn,{this:e,expression:this.parseBitwise()}))}parsePrimaryKeyPart(){return this.parseField()}parsePeriodForSystemTime(){if(!this.match("timestampSnapshot")){this.retreat(this.index-1);return}let e=this.parseWrappedIdVars();return this.expression(sE,{this:b(e,0),expression:b(e,1)})}parsePrimaryKey(e={}){let{wrappedOptional:t=!1,inProps:s=!1,namedPrimaryKey:r=!1}=e,i=this.matchSet(new Set(["asc","desc"]))?_optionalChain([this, 'access', _572 => _572.prev, 'optionalAccess', _573 => _573.tokenType])==="desc":void 0,a;if(r&&!((_optionalChain([this, 'access', _574 => _574.curr, 'optionalAccess', _575 => _575.text, 'access', _576 => _576.toUpperCase, 'call', _577 => _577()])||"")in this._constructor.CONSTRAINT_PARSERS)&&this.next&&this.next.tokenType==="lParen"&&(a=this.parseIdVar()),!s&&!this.match("lParen",{advance:!1}))return this.expression(vo,{desc:i,options:this.parseKeyConstraintOptions()});let o=this.parseWrappedCsv(()=>this.parsePrimaryKeyPart(),{optional:t});return this.expression(mo,{this:a,expressions:o,include:this.parseIndexParams(),options:this.parseKeyConstraintOptions()})}parseBracketKeyValue(e={}){return this.parseSlice(this.parseAlias(this.parseDisjunction(),{explicit:!0}))}parseOdbcDatetimeLiteral(){this.match("var");let e=this._constructor.ODBC_DATETIME_LITERALS[_nullishCoalesce(_optionalChain([this, 'access', _578 => _578.prev, 'optionalAccess', _579 => _579.text]), () => ("".toLowerCase()))],t=this.expression(e,{this:this.parseString()});return this.match("rBrace")||this.raiseError("Expected }"),t}parseUniqueKey(){return this.parseIdVar({anyToken:!1})}parseUnique(){return this.matchTexts(["KEY","INDEX"]),this.expression(Fo,{nulls:this.matchTextSeq(["NULLS","NOT","DISTINCT"])||void 0,this:this.parseSchema({this:this.parseUniqueKey()}),indexType:(this.match("using")||void 0)&&this.advanceAny()&&_optionalChain([this, 'access', _580 => _580.prev, 'optionalAccess', _581 => _581.text]),onConflict:this.parseOnConflict(),options:this.parseKeyConstraintOptions()})}parseKeyConstraintOptions(){let e=[];for(;this.curr;)if(this.match("on")){let t,s=this.advanceAny()&&_optionalChain([this, 'access', _582 => _582.prev, 'optionalAccess', _583 => _583.text]);this.matchTextSeq(["NO","ACTION"])?t="NO ACTION":this.matchTextSeq("CASCADE")?t="CASCADE":this.matchTextSeq("RESTRICT")?t="RESTRICT":this.matchPair("set","null")?t="SET NULL":this.matchPair("set","default")?t="SET DEFAULT":this.raiseError("Invalid key constraint"),e.push(`ON ${s} ${t}`)}else{let t=this.parseVarFromOptions(this._constructor.KEY_CONSTRAINT_OPTIONS,{raiseUnmatched:!1});if(!t)break;e.push(t.name)}return e}parseReferences(e={}){let{match:t=!0}=e;if(t&&!this.match("references"))return;let s,r=this.parseTable({schema:!0}),i=this.parseKeyConstraintOptions();return this.expression(Iu,{this:r,expressions:s,options:i})}parseForeignKey(){let e=this.match("references",{advance:!1})?void 0:this.parseWrappedIdVars(),t=this.parseReferences(),s={};for(;this.match("on");){this.matchSet(new Set(["delete","update"]))||this.raiseError("Expected DELETE or UPDATE");let r=(_nullishCoalesce(_optionalChain([this, 'access', _584 => _584.prev, 'optionalAccess', _585 => _585.text]), () => (""))).toLowerCase(),i;this.matchTextSeq(["NO","ACTION"])?i="NO ACTION":this.match("set")?(this.matchSet(new Set(["null","default"])),i="SET "+(_nullishCoalesce(_optionalChain([this, 'access', _586 => _586.prev, 'optionalAccess', _587 => _587.text]), () => (""))).toUpperCase()):(this.advance(),i=(_nullishCoalesce(_optionalChain([this, 'access', _588 => _588.prev, 'optionalAccess', _589 => _589.text]), () => (""))).toUpperCase()),s[r]=i}return this.expression(ou,{expressions:e,reference:t,options:this.parseKeyConstraintOptions(),...s})}parsePrimary(){if(this.matchSet(Object.keys(this._constructor.PRIMARY_PARSERS))){let e=_nullishCoalesce(_optionalChain([this, 'access', _590 => _590.prev, 'optionalAccess', _591 => _591.tokenType]), () => ("unknown")),t=_optionalChain([this, 'access', _592 => _592._constructor, 'access', _593 => _593.PRIMARY_PARSERS, 'access', _594 => _594[e], 'optionalAccess', _595 => _595.call, 'call', _596 => _596(this,this.prev)]);if(e==="string"){let s=[t];for(;this.match("string");)s.push(w.string(_nullishCoalesce(_optionalChain([this, 'access', _597 => _597.prev, 'optionalAccess', _598 => _598.text]), () => (""))));if(1<s.length)return this.expression(Vt,{expressions:s,coalesce:this._dialectConstructor.CONCAT_COALESCE})}return t}return this.matchPair("dot","number")?w.number(`0.${_nullishCoalesce(_optionalChain([this, 'access', _599 => _599.prev, 'optionalAccess', _600 => _600.text]), () => (""))}`):this.parseParen()}parseField(e={}){let{anyToken:t=!1,tokens:s,anonymousFunc:r=!1}=e||{},i;return r?i=this.parseFunction({anonymous:r,anyToken:t})||this.parsePrimary():i=this.parsePrimary()||this.parseFunction({anonymous:r,anyToken:t}),i||this.parseIdVar({anyToken:t,tokens:s})}parseGeneratedAsIdentity(){let e;if(this.matchTextSeq(["BY","DEFAULT"])){let s=this.matchPair("on","null")||void 0;e=this.expression(Ui,{this:!1,onNull:s})}else this.matchTextSeq("ALWAYS"),e=this.expression(Ui,{this:!0});if(this.match("alias"),this.matchTextSeq("ROW")){let s=this.matchTextSeq("START")||void 0;s||this.match("end");let r=this.matchTextSeq("HIDDEN")||void 0;return this.expression(lE,{start:s,hidden:r})}let t=this.matchTextSeq("IDENTITY")||void 0;if(this.match("lParen")){if(this.match("startWith")&&e.setArgKey("start",this.parseBitwise()),this.matchTextSeq(["INCREMENT","BY"])&&e.setArgKey("increment",this.parseBitwise()),this.matchTextSeq("MINVALUE")&&e.setArgKey("minvalue",this.parseBitwise()),this.matchTextSeq("MAXVALUE")&&e.setArgKey("maxvalue",this.parseBitwise()),this.matchTextSeq("CYCLE")?e.setArgKey("cycle",!0):this.matchTextSeq(["NO","CYCLE"])&&e.setArgKey("cycle",!1),!t)e.setArgKey("expression",this.parseRange());else if(!e.args.start&&this.match("number",{advance:!1})){let s=this.parseCsv(this.parseBitwise.bind(this));e.setArgKey("start",b(s,0)),e.setArgKey("increment",b(s,1))}this.matchRParen()}return e}parseInline(){return this.matchTextSeq("LENGTH"),this.expression(uE,{this:this.parseBitwise()})}parseNotConstraint(){if(this.matchTextSeq("NULL"))return this.expression($i);if(this.matchTextSeq("CASESPECIFIC"))return this.expression(Gi,{not:!0});if(this.matchTextSeq(["FOR","REPLICATION"]))return this.expression(si);this.retreat(this.index-1)}parseColumnConstraint(){let e=(this.match("constraint")||void 0)&&this.parseIdVar();if(!((this.match("with",{advance:!1})||void 0)&&this.next&&this.next.text.toUpperCase()in this._constructor.PROCEDURE_OPTIONS)&&this.matchTexts(Object.keys(this._constructor.CONSTRAINT_PARSERS))){let s=_optionalChain([this, 'access', _601 => _601._constructor, 'access', _602 => _602.CONSTRAINT_PARSERS, 'access', _603 => _603[(_nullishCoalesce(_optionalChain([this, 'access', _604 => _604.prev, 'optionalAccess', _605 => _605.text]), () => (""))).toUpperCase()], 'optionalAccess', _606 => _606.call, 'call', _607 => _607(this)]);if(!s){this.retreat(this.index-1);return}return this.expression(ki,{this:e,kind:s})}return e}parseConstraint(){return this.match("constraint")?this.expression(tu,{this:this.parseIdVar(),expressions:this.parseUnnamedConstraints()}):this.parseUnnamedConstraint({constraints:this._constructor.SCHEMA_UNNAMED_CONSTRAINTS})}parseUnnamedConstraints(){let e=[];for(;;){let t=this.parseUnnamedConstraint()||this.parseFunction();if(!t)break;e.push(t)}return e}parseUnnamedConstraint(e={}){let t=this.index,{constraints:s}=e;if(this.match("identifier",{advance:!1})||!this.matchTexts(s||Object.keys(this._constructor.CONSTRAINT_PARSERS)))return;let r=(_nullishCoalesce(_optionalChain([this, 'access', _608 => _608.prev, 'optionalAccess', _609 => _609.text]), () => (""))).toUpperCase();r in this._constructor.CONSTRAINT_PARSERS||this.raiseError(`No parser found for schema constraint ${r}.`);let i=_optionalChain([this, 'access', _610 => _610._constructor, 'access', _611 => _611.CONSTRAINT_PARSERS, 'access', _612 => _612[r], 'optionalAccess', _613 => _613.call, 'call', _614 => _614(this)]);if(!i||Array.isArray(i)){this.retreat(t);return}return i}parseFieldDef(){return this.parseColumnDef(this.parseField({anyToken:!0}))}parseColumnDef(e,t={}){let{computedColumn:s=!0}=t,r=e;r instanceof k&&(r=r.args.this),s||this.match("alias");let i=this.parseTypes({schema:!0});if(this.matchTextSeq(["FOR","ORDINALITY"]))return this.expression(we,{this:r,ordinality:!0});let a=[];if(!i&&this.match("alias")||this.matchTexts(["ALIAS","MATERIALIZED"])){let o=(_nullishCoalesce(_optionalChain([this, 'access', _615 => _615.prev, 'optionalAccess', _616 => _616.text]), () => (""))).toUpperCase()==="MATERIALIZED",c=new An({this:this.parseDisjunction(),persisted:o||this.matchTextSeq("PERSISTED")||void 0,dataType:this.matchTextSeq("AUTO")?new C({this:"AUTO"}):this.parseTypes(),notNull:this.matchPair("not","null")||void 0});a.push(this.expression(ki,{kind:c}))}else if(!i&&this.matchSet(["in","out"],{advance:!1})){let o=this.expression(dE,{input:this.match("in")||void 0,output:this.match("out")||void 0});a.push(o),i=this.parseTypes()}else i&&this.match("alias",{advance:!1})&&(!this._constructor.WRAPPED_TRANSFORM_COLUMN_CONSTRAINT||this.next&&this.next.tokenType==="lParen")&&(this.advance(),a.push(this.expression(ki,{kind:new An({this:this.parseDisjunction(),persisted:(this.matchTexts(["STORED","VIRTUAL"])||void 0)&&(_nullishCoalesce(_optionalChain([this, 'access', _617 => _617.prev, 'optionalAccess', _618 => _618.text]), () => (""))).toUpperCase()==="STORED"})})));for(;;){let o=this.parseColumnConstraint();if(!o)break;a.push(o)}return!i&&a.length===0?r:this.expression(we,{this:r,kind:i,constraints:a})}parseAutoIncrement(){let e,t,s;if(this.match("lParen",{advance:!1})){let r=this.parseWrappedCsv(this.parseBitwise.bind(this));e=b(r,0),t=b(r,1)}else this.matchTextSeq("START")&&(e=this.parseBitwise(),this.matchTextSeq("INCREMENT"),t=this.parseBitwise(),this.matchTextSeq("ORDER")?s=!0:this.matchTextSeq("NOORDER")&&(s=!1));return e&&t?new Ui({start:e,increment:t,this:!1,order:s}):new zT({})}parseCheckConstraint(){if(this.match("lParen",{advance:!1}))return this.expression(Tg,{this:this.parseWrapped(this.parseAssignment.bind(this)),enforced:this.matchTextSeq("ENFORCED")||void 0})}parseAutoProperty(){if(!this.matchTextSeq("REFRESH")){this.retreat(this.index-1);return}return this.expression(Qi,{this:this.parseVar({upper:!0})})}parseCompress(){return this.match("lParen",{advance:!1})?this.expression(kl,{this:this.parseWrappedCsv(this.parseBitwise.bind(this))}):this.expression(kl,{this:this.parseBitwise()})}parseFunction(e={}){let{functions:t,anonymous:s=!1,optionalParens:r=!0,anyToken:i=!1}=e,a=!1;this.match("lBrace",{advance:!1})&&this.next&&this.next.text.toUpperCase()==="FN"&&(this.advance(2),a=!0);let o=this.parseFunctionCall({functions:t,anonymous:s,optionalParens:r,anyToken:i});return a&&this.match("rBrace"),o}parseFunctionArgs(e={}){let{alias:t=!1}=e;return this.parseCsv(()=>this.parseLambda({alias:t}))}parseFunctionCall(e={}){let{functions:t,anonymous:s=!1,optionalParens:r=!0,anyToken:i=!1}=e;if(!this.curr)return;let a=this.curr.comments,o=this.prev,c=this.curr,p=this.curr.tokenType,u=this.curr.text,E=u.toUpperCase(),g=this._constructor.NO_PAREN_FUNCTION_PARSERS[E];if(g&&r&&!this._constructor.INVALID_FUNC_NAME_TOKENS.has(p))return this.advance(),this.parseWindow(g.call(this));if(!this.next||this.next.tokenType!=="lParen"){let x=this._constructor.NO_PAREN_FUNCTIONS[p];return r&&x?(this.advance(),this.expression(x)):void 0}if(i){if(this._constructor.RESERVED_TOKENS.has(p))return}else if(!this._constructor.FUNC_TOKENS.has(p))return;this.advance(2);let A=this._constructor.FUNCTION_PARSERS[E];if(A&&!s){let x=A.call(this);return x instanceof h&&x.addComments(a),this.matchRParen(x),this.parseWindow(x)}else{let x=this._constructor.SUBQUERY_PREDICATES[p];if(x){let B;if(this.curr.tokenType==="select"||this.curr.tokenType==="with"?(B=this.parseSelect(),this.matchRParen()):o&&(o.tokenType==="like"||o.tokenType==="ilike")&&(this.advance(-1),B=this.parseBitwise()),B)return this.expression(x,{comments:a,this:B})}let N=(_nullishCoalesce(t, () => (this._constructor.FUNCTIONS)))[E],R=N&&!s,S=!R||this._constructor.FUNCTIONS_WITH_ALIASED_ARGS.has(E),I=this.parseFunctionArgs({alias:S}),y=_optionalChain([this, 'access', _619 => _619.curr, 'optionalAccess', _620 => _620.comments]),P=R;P&&y&&y.some(B=>B.trimStart().startsWith(qL))&&(P=!1);let v=S&&P?this.kvToPropEq(I):I,H;if(P){let B;1<N.length?B=N(v,{dialect:this.dialect}):B=N(v),B=this.validateExpression(B,v),this._dialectConstructor.PRESERVE_ORIGINAL_NAMES&&(B.meta.name=u),H=B}else{let B=u;p==="identifier"&&(B=new G({this:u,quoted:!0}).updatePositions(c)),H=this.expression(st,{this:B,expressions:I})}return H=H.updatePositions(c),H instanceof h&&H.addComments(a),this.matchRParen(H),this.parseWindow(H)}}toPropEq(e,t){return e}kvToPropEq(e,t={}){let{parseMap:s=!1}=t,r=[];for(let i=0;i<e.length;i++){let a=e[i];if([...this._constructor.KEY_VALUE_DEFINITIONS.keys()].some(o=>a instanceof o)){if(a instanceof Se&&(a=this.expression(At,{this:a.args.alias,expression:a.args.this})),!(a instanceof At)){let o=a.args.this;a=this.expression(At,{this:s?a.args.this:K(o instanceof h?o.name:_optionalChain([o, 'optionalAccess', _621 => _621.toString, 'call', _622 => _622()])),expression:a.args.expression})}a.args.this instanceof k&&a.args.this.replace(a.args.this.args.this)}else a=this.toPropEq(a,i);r.push(a)}return r}parseUserDefinedFunctionExpression(){return this.parseStatement()}parseFunctionParameter(){return this.parseColumnDef(this.parseIdVar(),{computedColumn:!1})}parseUserDefinedFunction(e={}){let t=this.parseTableParts({schema:!0});if(!this.match("lParen"))return t;let s=this.parseCsv(this.parseFunctionParameter.bind(this));return this.matchRParen(),this.expression(Xl,{this:t,expressions:s,wrapped:!0})}parseIntroducer(e){let t=this.parsePrimary();return t?this.expression(gu,{token:e,expression:t}):this.identifierExpression(e)}parseSessionParameter(){let e,t=this.parseIdVar()||this.parsePrimary();return t&&this.match("dot")&&(e=t.name,t=this.parseVar()||this.parsePrimary()),this.expression(Sg,{this:t,kind:e})}parseLambdaArg(){return this.parseIdVar()}parseLambda(e={}){let{alias:t=!1}=e,s=this.index,r;if(this.match("lParen")?(r=this.parseCsv(this.parseLambdaArg.bind(this)),this.match("rParen")||this.retreat(s)):r=[this.parseLambdaArg()],this.matchSet(Object.keys(this._constructor.LAMBDAS))){let a=_optionalChain([this, 'access', _623 => _623.prev, 'optionalAccess', _624 => _624.tokenType]);return a&&_optionalChain([this, 'access', _625 => _625._constructor, 'access', _626 => _626.LAMBDAS, 'access', _627 => _627[a], 'optionalAccess', _628 => _628.call, 'call', _629 => _629(this,r.filter(o=>!!o))])}this.retreat(s);let i;return this.match("distinct")?i=this.expression(ct,{expressions:this.parseCsv(this.parseDisjunction.bind(this))}):i=this.parseSelectOrExpression({alias:t}),this.parseLimit(this.parseOrder({thisExpr:this.parseHavingMax(this.parseRespectOrIgnoreNulls(i))}))}parseSchema(e={}){let{this:t}=e,s=this.index;if(!this.match("lParen"))return t;if(this.matchSet(this._constructor.SELECT_START_TOKENS))return this.retreat(s),t;let r=this.parseCsv(()=>this.parseConstraint()||this.parseFieldDef());return this.matchRParen(),this.expression(Lt,{this:t,expressions:r})}parseAlterTableSet(){let e=this.expression(Ql);if(this.match("lParen",{advance:!1})||this.matchTextSeq(["TABLE","PROPERTIES"]))e.setArgKey("expressions",this.parseWrappedCsv(this.parseAssignment.bind(this)));else if(this.matchTextSeq("FILESTREAM_ON",{advance:!1}))e.setArgKey("expressions",[this.parseAssignment()]);else if(this.matchTexts(["LOGGED","UNLOGGED"]))e.setArgKey("option",Te((_nullishCoalesce(_optionalChain([this, 'access', _630 => _630.prev, 'optionalAccess', _631 => _631.text]), () => (""))).toUpperCase()));else if(this.matchTextSeq("WITHOUT")&&this.matchTexts(["CLUSTER","OIDS"]))e.setArgKey("option",Te(`WITHOUT ${(_nullishCoalesce(_optionalChain([this, 'access', _632 => _632.prev, 'optionalAccess', _633 => _633.text]), () => (""))).toUpperCase()}`));else if(this.matchTextSeq("LOCATION"))e.setArgKey("location",this.parseField());else if(this.matchTextSeq(["ACCESS","METHOD"]))e.setArgKey("accessMethod",this.parseField());else if(this.matchTextSeq("TABLESPACE"))e.setArgKey("tablespace",this.parseField());else if(this.matchTextSeq(["FILE","FORMAT"])||this.matchTextSeq("FILEFORMAT"))e.setArgKey("fileFormat",[this.parseField()]);else if(this.matchTextSeq("STAGE_FILE_FORMAT"))e.setArgKey("fileFormat",this.parseWrappedOptions());else if(this.matchTextSeq("STAGE_COPY_OPTIONS"))e.setArgKey("copyOptions",this.parseWrappedOptions());else if(this.matchTextSeq("TAG")||this.matchTextSeq("TAGS"))e.setArgKey("tag",this.parseCsv(this.parseAssignment.bind(this)));else{this.matchTextSeq("SERDE")&&e.setArgKey("serde",this.parseField());let t=this.parseWrapped(this.parseProperties.bind(this),{optional:!0});e.setArgKey("expressions",t?[t]:[])}return e}parseAlterSession(){if(this.match("set")){let t=this.parseCsv(()=>this.parseSetItemAssignment());return this.expression(Hc,{expressions:t,unset:!1})}this.matchTextSeq("UNSET");let e=this.parseCsv(()=>this.expression(mr,{this:this.parseIdVar({anyToken:!0})}));return this.expression(Hc,{expressions:e,unset:!0})}parseAlter(){let e=this.prev,t=(this.matchSet(this._constructor.ALTERABLES)||void 0)&&this.prev;if(!t)return this.parseAsCommand(e);let s=this.parseExists(),r=this.matchTextSeq("ONLY")||void 0,i,a,o;t.tokenType==="session"?(i=void 0,a=void 0,o=void 0):(i=this.parseTable({schema:!0,parsePartition:this._constructor.ALTER_TABLE_PARTITIONS}),a=this.matchTextSeq(["WITH","CHECK"])||void 0,o=this.match("on")?this.parseOnProperty():void 0,this.next&&this.advance());let c=this.prev?this._constructor.ALTER_PARSERS[this.prev.text.toUpperCase()]:void 0;if(c){let p=pe(c.call(this)),u=this.matchTextSeq(["NOT","VALID"])||void 0,E=this.parseCsv(this.parseProperty.bind(this)),g=this._dialectConstructor.ALTER_TABLE_SUPPORTS_CASCADE&&this.matchTextSeq("CASCADE");if(!this.curr&&p)return this.expression(mn,{this:i,kind:_nullishCoalesce(As(UT,t.text), () => (t.text.toUpperCase())),exists:s,actions:p,only:r,options:E,cluster:o,notValid:u,check:a,cascade:g})}return this.parseAsCommand(e)}parseAnalyze(){let e=this.prev;if(!this.curr)return this.expression(Vc);let t=[];for(;this.matchTexts(this._constructor.ANALYZE_STYLES);)(_nullishCoalesce(_optionalChain([this, 'access', _634 => _634.prev, 'optionalAccess', _635 => _635.text]), () => (""))).toUpperCase()==="BUFFER_USAGE_LIMIT"?t.push(`BUFFER_USAGE_LIMIT ${this.parseNumber()}`):t.push((_nullishCoalesce(_optionalChain([this, 'access', _636 => _636.prev, 'optionalAccess', _637 => _637.text]), () => (""))).toUpperCase());let s,r,i=_optionalChain([this, 'access', _638 => _638.curr, 'optionalAccess', _639 => _639.text, 'access', _640 => _640.toUpperCase, 'call', _641 => _641()]);this.match("table")||this.match("index")?s=this.parseTableParts():this.matchTextSeq("TABLES")?this.matchSet(["from","in"])&&(i=`${i} ${(_nullishCoalesce(_optionalChain([this, 'access', _642 => _642.prev, 'optionalAccess', _643 => _643.text]), () => (""))).toUpperCase()}`,s=this.parseTable({schema:!0,isDbReference:!0})):this.matchTextSeq("DATABASE")?s=this.parseTable({schema:!0,isDbReference:!0}):this.matchTextSeq("CLUSTER")?s=this.parseTable():this.matchTexts(Object.keys(this._constructor.ANALYZE_EXPRESSION_PARSERS))?(i=void 0,r=this._constructor.ANALYZE_EXPRESSION_PARSERS[(_nullishCoalesce(_optionalChain([this, 'access', _644 => _644.prev, 'optionalAccess', _645 => _645.text]), () => (""))).toUpperCase()].call(this)):(i=void 0,s=this.parseTableParts());let a=this.tryParse(this.parsePartition.bind(this));if(!a&&this.matchTexts(this._constructor.PARTITION_KEYWORDS))return this.parseAsCommand(e);let o;this.matchTextSeq(["WITH","SYNC","MODE"])||this.matchTextSeq(["WITH","ASYNC","MODE"])?o=`WITH ${this.tokens[this.index-2].text.toUpperCase()} MODE`:o=void 0,this.matchTexts(Object.keys(this._constructor.ANALYZE_EXPRESSION_PARSERS))&&(r=this._constructor.ANALYZE_EXPRESSION_PARSERS[(_nullishCoalesce(_optionalChain([this, 'access', _646 => _646.prev, 'optionalAccess', _647 => _647.text]), () => (""))).toUpperCase()].call(this));let c=this.parseProperties();return this.expression(Vc,{kind:i,this:s,mode:o,partition:a,properties:c,expression:r,options:t})}parseAnalyzeStatistics(){let e,t=(_nullishCoalesce(_optionalChain([this, 'access', _648 => _648.prev, 'optionalAccess', _649 => _649.text]), () => (""))).toUpperCase(),s=this.matchTextSeq("DELTA")?(_nullishCoalesce(_optionalChain([this, 'access', _650 => _650.prev, 'optionalAccess', _651 => _651.text]), () => (""))).toUpperCase():void 0,r=[];if(this.matchTextSeq("STATISTICS")||this.raiseError("Expecting token STATISTICS"),this.matchTextSeq("NOSCAN"))e="NOSCAN";else if(this.match("for"))this.matchTextSeq(["ALL","COLUMNS"])&&(e="FOR ALL COLUMNS"),this.matchTexts("COLUMNS")&&(e="FOR COLUMNS",r=this.parseCsv(this.parseColumnReference.bind(this)));else if(this.matchTextSeq("SAMPLE")){let i=this.parseNumber();r=[this.expression(qu,{sample:i,kind:this.match("percent")?(_nullishCoalesce(_optionalChain([this, 'access', _652 => _652.prev, 'optionalAccess', _653 => _653.text]), () => (""))).toUpperCase():void 0})]}return this.expression(ku,{kind:t,option:s,this:e,expressions:r})}parseAnalyzeValidate(){let e,t,s;return this.matchTextSeq(["REF","UPDATE"])?(e="REF",t="UPDATE",this.matchTextSeq(["SET","DANGLING","TO","NULL"])&&(t="UPDATE SET DANGLING TO NULL")):this.matchTextSeq("STRUCTURE")&&(e="STRUCTURE",this.matchTextSeq(["CASCADE","FAST"])?t="CASCADE FAST":this.matchTextSeq(["CASCADE","COMPLETE"])&&this.matchTexts(["ONLINE","OFFLINE"])&&(t=`CASCADE COMPLETE ${(_nullishCoalesce(_optionalChain([this, 'access', _654 => _654.prev, 'optionalAccess', _655 => _655.text]), () => (""))).toUpperCase()}`,s=this.parseInto())),this.expression(Bu,{kind:e,this:t,expression:s})}parseAnalyzeColumns(){let e=(_nullishCoalesce(_optionalChain([this, 'access', _656 => _656.prev, 'optionalAccess', _657 => _657.text]), () => (""))).toUpperCase();if(this.matchTextSeq("COLUMNS"))return this.expression(Lo,{this:`${e} ${(_nullishCoalesce(_optionalChain([this, 'access', _658 => _658.prev, 'optionalAccess', _659 => _659.text]), () => (""))).toUpperCase()}`})}parseAnalyzeDelete(){let e=this.matchTextSeq("SYSTEM")?(_nullishCoalesce(_optionalChain([this, 'access', _660 => _660.prev, 'optionalAccess', _661 => _661.text]), () => (""))).toUpperCase():void 0;if(this.matchTextSeq("STATISTICS"))return this.expression(Fu,{kind:e})}parseAnalyzeList(){if(this.matchTextSeq(["CHAINED","ROWS"]))return this.expression(vu,{expression:this.parseInto()})}parseAnalyzeHistogram(){let e=(_nullishCoalesce(_optionalChain([this, 'access', _662 => _662.prev, 'optionalAccess', _663 => _663.text]), () => (""))).toUpperCase(),t,s=[],r;if(this.matchTextSeq(["HISTOGRAM","ON"])){s=this.parseCsv(this.parseColumnReference.bind(this));let i=[];for(;this.match("with");)if(this.matchTexts(["SYNC","ASYNC"]))this.matchTextSeq("MODE",{advance:!1})&&(i.push(`${(_nullishCoalesce(_optionalChain([this, 'access', _664 => _664.prev, 'optionalAccess', _665 => _665.text]), () => (""))).toUpperCase()} MODE`),this.advance());else{let a=this.parseNumber();this.matchTextSeq("BUCKETS")&&i.push(`${a} BUCKETS`)}0<i.length&&(t=this.expression(Mo,{expressions:i})),this.matchTexts(["MANUAL","AUTO"])&&this.match("update",{advance:!1})?(r=(_nullishCoalesce(_optionalChain([this, 'access', _666 => _666.prev, 'optionalAccess', _667 => _667.text]), () => (""))).toUpperCase(),this.advance()):this.matchTextSeq(["USING","DATA"])&&(t=this.expression(Do,{this:this.parseString()}))}return this.expression(Uu,{this:e,expressions:s,expression:t,updateOptions:r})}parseMerge(){this.match("into");let e=this.parseTable();e&&this.match("alias",{advance:!1})&&e.setArgKey("alias",this.parseTableAlias()),this.match("using");let t=this.parseTable();return this.expression(va,{this:e,using:t,on:(this.match("on")||void 0)&&this.parseDisjunction(),usingCond:(this.match("using")||void 0)&&this.parseUsingIdentifiers(),whens:this.parseWhenMatched(),returning:this.parseReturning()})}parseWhenMatched(){let e=[];for(;this.match("when");){let t=!this.match("not");this.matchTextSeq("MATCHED");let s=this.matchTextSeq(["BY","TARGET"])?!1:this.matchTextSeq(["BY","SOURCE"]),r=this.match("and")?this.parseDisjunction():void 0;this.match("then");let i;if(this.match("insert")){let a=this.parseStar();a?i=this.expression(Ss,{this:a}):i=this.expression(Ss,{this:this.matchTextSeq("ROW")?Te("ROW"):this.parseValue({values:!1}),expression:this.matchTextSeq("VALUES")&&this.parseValue()})}else if(this.match("update")){let a=this.parseStar();a?i=this.expression(sr,{expressions:a}):i=this.expression(sr,{expressions:this.match("set")&&this.parseCsv(this.parseEquality.bind(this))})}else this.match("delete")?i=this.expression(Ze,{this:_nullishCoalesce(_optionalChain([this, 'access', _668 => _668.prev, 'optionalAccess', _669 => _669.text]), () => (""))}):i=this.parseVarFromOptions(this._constructor.CONFLICT_ACTIONS);e.push(this.expression(Ji,{matched:t,source:s,condition:r,then:i}))}return this.expression(ko,{expressions:e})}parseShow(){let e=this.findParser(this._constructor.SHOW_PARSERS,this._constructor.SHOW_TRIE);return e?e.call(this):this.parseAsCommand(this.prev)}parseSetItemAssignment(e={}){let{kind:t}=e,s=this.index;if((t==="GLOBAL"||t==="SESSION")&&this.matchTextSeq("TRANSACTION"))return this.parseSetTransaction({global:t==="GLOBAL"});let r=this.parsePrimary()||this.parseColumn(),i=this.matchTexts(this._constructor.SET_ASSIGNMENT_DELIMITERS)||void 0;if(!r||this._constructor.SET_REQUIRES_ASSIGNMENT_DELIMITER&&!i){this.retreat(s);return}let a=this.parseStatement()||this.parseIdVar();(a instanceof k||a instanceof G)&&(a=Te(a.name));let o=this.expression(Ee,{this:r,expression:a});return this.expression(mr,{this:o,kind:t})}parseSetTransaction(e={}){let{global:t=!1}=e;this.matchTextSeq("TRANSACTION");let s=this.parseCsv(()=>this.parseVarFromOptions(this._constructor.TRANSACTION_CHARACTERISTICS));return this.expression(mr,{expressions:s,kind:"TRANSACTION",global:t})}parseSetItem(){let e=this.findParser(this._constructor.SET_PARSERS,this._constructor.SET_TRIE);return e?e.call(this):this.parseSetItemAssignment({kind:void 0})}parseSet(e={}){let{unset:t=!1,tag:s=!1}=e,r=this.index,i=this.expression(fo,{expressions:this.parseCsv(this.parseSetItem.bind(this)),unset:t,tag:s});return this.curr?(this.retreat(r),this.parseAsCommand(this.prev)):i}parseVarFromOptions(e,t={}){let{raiseUnmatched:s=!0}=t,r=this.curr;if(!r)return;let i=r.text.toUpperCase(),a=e[i],o=this.index;this.advance();let c=!1;for(let p of a||[]){let u=typeof p=="string"?[p]:p;if(this.matchTextSeq(u)){i=`${i} ${u.join(" ")}`,c=!0;break}}if(!c&&(a===void 0||0<a.length)){s&&this.raiseError(`Unknown option ${i}`),this.retreat(o);return}return Te(i)}parseCache(){let e=this.matchTextSeq("LAZY")||void 0;this.match("table");let t=this.parseTable({schema:!0}),s=[];if(this.matchTextSeq("OPTIONS")){this.matchLParen();let r=this.parseString();r||this.raiseError("Expected option key"),this.match("eq");let i=this.parseString();i||this.raiseError("Expected option value"),s=[r,i].filter(Boolean),this.matchRParen()}return this.match("alias"),this.expression(Fl,{this:t,lazy:e,options:s,expression:this.parseSelect({nested:!0})})}parsePartition(){if(this.matchTexts(this._constructor.PARTITION_KEYWORDS))return this.expression(Wi,{subpartition:(_nullishCoalesce(_optionalChain([this, 'access', _670 => _670.prev, 'optionalAccess', _671 => _671.text]), () => (""))).toUpperCase()==="SUBPARTITION",expressions:this.parseWrappedCsv(this.parseDisjunction.bind(this))})}parseValue(e){let t=()=>this._dialectConstructor.SUPPORTS_VALUES_DEFAULT&&this.match("default")?Te((_nullishCoalesce(_optionalChain([this, 'access', _672 => _672.prev, 'optionalAccess', _673 => _673.text]), () => (""))).toUpperCase()):this.parseExpression();if(this.match("lParen")){let r=this.parseCsv(t);return this.matchRParen(),this.expression(Mt,{expressions:r})}let s=this.parseExpression();if(s)return this.expression(Mt,{expressions:[s]})}parseProjections(){return this.parseExpressions()}parseWrappedSelect(e={}){let{table:t=!1}=e,s;if(this.matchSet(["pivot","unpivot"]))s=this.parseSimplifiedPivot({isUnpivot:_optionalChain([this, 'access', _674 => _674.prev, 'optionalAccess', _675 => _675.tokenType])==="unpivot"});else if(this.match("from")){let r=this.parseFrom({skipFromToken:!0,consumePipe:!0}),i=this.parseSelect({from:r});i?(i.args.from||i.setArgKey("from",r),s=i):(s=ft("*").from(r),s=this.parseQueryModifiers(this.parseSetOperations(s)))}else{if(s=t?this.parseTable({consumePipe:!0}):this.parseSelect({nested:!0,parseSetOperation:!1}),t&&s instanceof Gs&&s.alias){let r=_optionalChain([s, 'access', _676 => _676.args, 'access', _677 => _677.alias, 'optionalAccess', _678 => _678.pop, 'call', _679 => _679()]);s=new V({this:s,alias:r})}s=this.parseQueryModifiers(this.parseSetOperations(s))}return s}parseCommitOrRollback(){let e,t,s=_optionalChain([this, 'access', _680 => _680.prev, 'optionalAccess', _681 => _681.tokenType])==="rollback";return this.matchTexts(["TRANSACTION","WORK"]),this.matchTextSeq("TO")&&(this.matchTextSeq("SAVEPOINT"),t=this.parseIdVar()),this.match("and")&&(e=!this.matchTextSeq("NO"),this.matchTextSeq("CHAIN")),s?this.expression(_u,{savepoint:t}):this.expression(Du,{chain:e})}parseRefresh(){let e;this.match("table")?e="TABLE":this.matchTextSeq(["MATERIALIZED","VIEW"])?e="MATERIALIZED VIEW":e="";let t=this.parseString()||this.parseTable();return!e&&!(t instanceof w)?this.parseAsCommand(this.prev):this.expression(Gl,{this:t,kind:e})}parseColumnDefWithExists(){let e=this.index;this.match("column");let t=this.parseExists({not:!0}),s=this.parseFieldDef();if(!(s instanceof we)){this.retreat(e);return}return s.setArgKey("exists",t),s}parseAddColumn(){if((_nullishCoalesce(_optionalChain([this, 'access', _682 => _682.prev, 'optionalAccess', _683 => _683.text]), () => (""))).toUpperCase()!=="ADD")return;let e=this.parseColumnDefWithExists();if(e){if(this.matchTexts(["FIRST","AFTER"])){let t=_nullishCoalesce(_optionalChain([this, 'access', _684 => _684.prev, 'optionalAccess', _685 => _685.text]), () => ("")),s=this.expression(Kl,{this:this.parseColumn(),position:t});e.setArgKey("position",s)}return e}}parseDropColumn(){let e=(this.match("drop")||void 0)&&this.parseDrop();return e&&!(e instanceof jn)&&e.setArgKey("kind",e.args.kind||"COLUMN"),e}parseDropPartition(e={}){let{exists:t}=e;return this.expression(Yu,{expressions:this.parseCsv(this.parsePartition.bind(this)),exists:t})}parseAlterTableAdd(){let e=()=>{if(this.matchTextSeq("ADD"),this.matchSet(this._constructor.ADD_CONSTRAINT_TOKENS,{advance:!1}))return this.expression(Gu,{expressions:this.parseCsv(this.parseConstraint.bind(this))});let t=this.parseAddColumn();if(t instanceof we)return t;let s=this.parseExists({not:!0});if(this.matchPair("partition","lParen",{advance:!1}))return this.expression($u,{exists:s,this:this.parseField({anyToken:!0}),location:this.matchTextSeq("LOCATION",{advance:!1})&&this.parseProperty()})};if(!this.matchSet(this._constructor.ADD_CONSTRAINT_TOKENS,{advance:!1})&&(!this._dialectConstructor.ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN||this.matchTextSeq("COLUMNS"))){let t=this.parseSchema();return t?Array.from(pe(t)):this.parseCsv(this.parseColumnDefWithExists.bind(this))}return this.parseCsv(e)}parseAlterTableAlter(){if(this.matchTexts(Object.keys(this._constructor.ALTER_ALTER_PARSERS)))return _optionalChain([this, 'access', _686 => _686._constructor, 'access', _687 => _687.ALTER_ALTER_PARSERS, 'access', _688 => _688[(_nullishCoalesce(_optionalChain([this, 'access', _689 => _689.prev, 'optionalAccess', _690 => _690.text]), () => (""))).toUpperCase()], 'optionalAccess', _691 => _691.call, 'call', _692 => _692(this)]);this.match("column");let e=this.parseField({anyToken:!0});return this.matchPair("drop","default")?this.expression(ws,{this:e,drop:!0}):this.matchPair("set","default")?this.expression(ws,{this:e,default:this.parseDisjunction()}):this.match("comment")?this.expression(ws,{this:e,comment:this.parseString()}):this.matchTextSeq(["DROP","NOT","NULL"])?this.expression(ws,{this:e,drop:!0,allowNull:!0}):this.matchTextSeq(["SET","NOT","NULL"])?this.expression(ws,{this:e,allowNull:!1}):this.matchTextSeq(["SET","VISIBLE"])?this.expression(ws,{this:e,visible:"VISIBLE"}):this.matchTextSeq(["SET","INVISIBLE"])?this.expression(ws,{this:e,visible:"INVISIBLE"}):(this.matchTextSeq(["SET","DATA"]),this.matchTextSeq("TYPE"),this.expression(ws,{this:e,dtype:this.parseTypes(),collate:this.match("collate")&&this.parseTerm(),using:this.match("using")&&this.parseDisjunction()}))}parseAlterDiststyle(){return this.matchTexts(["ALL","EVEN","AUTO"])?this.expression(Gc,{this:Te((_nullishCoalesce(_optionalChain([this, 'access', _693 => _693.prev, 'optionalAccess', _694 => _694.text]), () => (""))).toUpperCase())}):(this.matchTextSeq(["KEY","DISTKEY"]),this.expression(Gc,{this:this.parseColumn()}))}parseAlterSortkey(e={}){let{compound:t}=e;return t&&this.matchTextSeq("SORTKEY"),this.match("lParen",{advance:!1})?this.expression($c,{expressions:this.parseWrappedIdVars(),compound:t}):(this.matchTexts(["AUTO","NONE"]),this.expression($c,{this:Te((_nullishCoalesce(_optionalChain([this, 'access', _695 => _695.prev, 'optionalAccess', _696 => _696.text]), () => (""))).toUpperCase()),compound:t}))}parseAlterTableDrop(){let e=this.index-1,t=this.parseExists();return this.match("partition",{advance:!1})?this.parseCsv(()=>this.parseDropPartition({exists:t})):(this.retreat(e),this.parseCsv(this.parseDropColumn.bind(this)))}parseAlterTableRename(){if(this.match("column")||!this._constructor.ALTER_RENAME_REQUIRES_COLUMN){let e=this.parseExists(),t=this.parseColumn(),s=this.matchTextSeq("TO")||void 0,r=this.parseColumn();return!t||!s||!r?void 0:this.expression(Xc,{this:t,to:r,exists:e})}return this.matchTextSeq("TO"),this.expression(Vi,{this:this.parseTable({schema:!0})})}parseLoad(){if(this.matchTextSeq("DATA")){let e=this.matchTextSeq("LOCAL")||void 0;this.matchTextSeq("INPATH");let t=this.parseString(),s=this.match("overwrite")||void 0;return this.matchPair("into","table"),this.expression(du,{this:this.parseTable({schema:!0}),local:e,overwrite:s,inpath:t,partition:this.parsePartition(),inputFormat:this.matchTextSeq("INPUTFORMAT")&&this.parseString(),serde:this.matchTextSeq("SERDE")&&this.parseString()})}return this.parseAsCommand(this.prev)}parseDelete(){let e;this.match("from",{advance:!1})||(e=this.parseCsv(this.parseTable.bind(this))||void 0);let t=this.parseReturning();return this.expression(Jn,{tables:e,this:this.match("from")&&this.parseTable({joins:!0}),using:this.match("using")&&this.parseCsv(()=>this.parseTable({joins:!0})),cluster:this.match("on")&&this.parseOnProperty(),where:this.parseWhere(),returning:t||this.parseReturning(),order:this.parseOrder(),limit:this.parseLimit()})}parseUpdate(){let e={this:this.parseTable({joins:!0,aliasTokens:this._constructor.UPDATE_ALIAS_TOKENS})};for(;this.curr;)if(this.match("set"))e.expressions=this.parseCsv(this.parseEquality.bind(this));else if(this.match("returning",{advance:!1}))e.returning=this.parseReturning();else if(this.match("from",{advance:!1})){let t=this.parseFrom({joins:!0}),s=_optionalChain([t, 'optionalAccess', _697 => _697.args, 'access', _698 => _698.this]);if(s instanceof ae&&this.match("join",{advance:!1})){let r=this.parseJoins();s.setArgKey("joins",0<r.length?r:void 0)}e.from=t}else if(this.match("where",{advance:!1}))e.where=this.parseWhere();else if(this.match("orderBy",{advance:!1}))e.order=this.parseOrder();else if(this.match("limit",{advance:!1}))e.limit=this.parseLimit();else break;return this.expression(sr,e)}parseUse(){return this.expression(eE,{kind:this.parseVarFromOptions(this._constructor.USABLES,{raiseUnmatched:!1}),this:this.parseTable({schema:!1})})}parseUncache(){return this.match("table")||this.raiseError("Expecting TABLE after UNCACHE"),this.expression(Bl,{exists:this.parseExists(),this:this.parseTable({schema:!0})})}parseAsCommand(e){for(;this.curr;)this.advance();let t=this.findSql(e,this.prev),s=_optionalChain([e, 'optionalAccess', _699 => _699.text, 'access', _700 => _700.length])||0;return this.warnUnsupported(),new jn({this:t.substring(0,s),expression:t.substring(s)})}parseDictProperty(e){let t=[];this.matchLParen();let s=this.parseIdVar();if(this.match("lParen")){for(;;){let r=this.parseIdVar(),i=this.parsePrimary();if(!r&&!i)break;t.push(this.expression(QT,{this:r,value:i}))}this.match("rParen")}return this.matchRParen(),this.expression(zo,{this:e.this,kind:_optionalChain([s, 'optionalAccess', _701 => _701.args, 'access', _702 => _702.this]),settings:t})}parseDictRange(e){this.matchLParen();let t=this.matchTextSeq("MIN")||void 0,s,r;return t?(s=this.parseVar()||this.parsePrimary(),s||this.raiseError("Expected MIN value"),this.matchTextSeq("MAX"),r=this.parseVar()||this.parsePrimary(),r||this.raiseError("Expected MAX value")):(r=this.parseVar()||this.parsePrimary(),r||this.raiseError("Expected MAX value"),s=w.number(0)),this.matchRParen(),this.expression(Ko,{this:e.this,min:s,max:r})}parseComprehension(e){let t=this.index,s=this.parseColumn(),r=(this.match("comma")||void 0)&&this.parseColumn();if(!this.match("in")){this.retreat(t-1);return}let i=this.parseColumn(),a=this.matchTextSeq("IF")?this.parseDisjunction():void 0;return this.expression(eu,{this:e,expression:s,position:r,iterator:i,condition:a})}parseHeredoc(){if(this.match("heredocString"))return this.expression(Fc,{this:_nullishCoalesce(_optionalChain([this, 'access', _703 => _703.prev, 'optionalAccess', _704 => _704.text]), () => (""))});if(!this.matchTextSeq("$"))return;let e=["$"],t;this.isConnected()?(this.advance(),e.push((_nullishCoalesce(_optionalChain([this, 'access', _705 => _705.prev, 'optionalAccess', _706 => _706.text]), () => (""))).toUpperCase())):this.raiseError("No closing $ found"),e[e.length-1]!=="$"&&(this.isConnected()&&this.matchTextSeq("$")?(t=e[e.length-1],e.push("$")):this.raiseError("No closing $ found"));let s=this.curr;for(;this.curr;){if(this.matchTextSeq(e,{advance:!1})){let r=this.findSql(s,this.prev);return this.advance(e.length),this.expression(Fc,{this:r,tag:t})}this.advance()}this.raiseError(`No closing ${e.join("")} found`)}findParser(e,t){if(!this.curr)return;let s=this.index,r=[];for(;;){let i=this.curr.text.toUpperCase(),a=i.split(" ");r.push(i),this.advance();let[o,c]=Il(t,a);if(t=c,o===0)break;if(o===2)return e[r.join(" ")]}this.retreat(s)}parseGroupConcat(){let e=(i,a)=>{if(i instanceof ct&&1<(_nullishCoalesce(_optionalChain([i, 'access', _707 => _707.args, 'access', _708 => _708.expressions, 'optionalAccess', _709 => _709.length]), () => (0)))){let o=[this.expression(Vt,{expressions:i.args.expressions,safe:!0,coalesce:this._dialectConstructor.CONCAT_COALESCE})];return i.setArgKey("expressions",o),i}return a.length===1?a[0]:this.expression(Vt,{expressions:a,safe:!0,coalesce:this._dialectConstructor.CONCAT_COALESCE})},t=this.parseCsv(this.parseLambda.bind(this)),s;if(t){let i=t[t.length-1],a=i instanceof ke?i:void 0;_optionalChain([a, 'optionalAccess', _710 => _710.args, 'access', _711 => _711.this])&&(t[t.length-1]=a.args.this,a.setArgKey("this",e(a.args.this,t))),s=a||e(t[0],t)}else s=void 0;let r=this.match("separator")?this.parseField():void 0;return this.expression(tr,{this:s,separator:r})}parseInitcap(){let e=cp.fromArgList(this.parseFunctionArgs());return e.args.expression||e.setArgKey("expression",w.string(this._dialectConstructor.INITCAP_DEFAULT_DELIMITER_CHARS)),e}parseOperator(e){let t=e;for(;this.match("lParen");){let s="";for(;this.curr&&!this.match("rParen");)s+=this.curr.text,this.advance();if(t=this.expression(ic,{comments:this.prevComments,this:t,operator:s,expression:this.parseBitwise()}),!this.match("operator"))break}return t}buildPipeCte(e){let{query:t,expressions:s,aliasCte:r}=e,i;r?i=r:(this.pipeCteCounter+=1,i=`__tmp${this.pipeCteCounter}`);let o=_optionalChain([t, 'access', _712 => _712.args, 'access', _713 => _713.with, 'optionalAccess', _714 => _714.pop, 'call', _715 => _715()]),c=ft(...s,{copy:!1}).from(i,{copy:!1});return o&&c.setArgKey("with",o),c.with(i,t,{copy:!1})}parsePipeSyntaxSelect(e){let t=this.parseSelect({consumePipe:!1});return t?this.buildPipeCte({query:e.select(t.args.expressions,{append:!1}),expressions:[new ye({})]}):e}parsePipeSyntaxLimit(e){let t=this.parseLimit(),s=this.parseOffset();if(t){let r=e.args.limit||t,i;if(typeof r=="number")i=r;else{ue(r,Ct);let o=r.args.expression;ue(o,h),i=o.toValue()}(_nullishCoalesce(_optionalChain([t, 'access', _716 => _716.args, 'access', _717 => _717.expression, 'optionalAccess', _718 => _718.toValue, 'call', _719 => _719()]), () => (0)))<=i&&e.limit(t,{copy:!1})}if(s){let r=e.args.offset,i;if(r===void 0)i=0;else if(typeof r=="number")i=r;else{ue(r,Fr);let c=r.args.expression;i=typeof c=="number"?c:(ue(c,h),c.toValue())}let a=s.args.expression,o=typeof a=="number"?a:(ue(a,h),a.toValue());e.offset(w.number(i+o))}return e}parsePipeSyntaxAggregateFields(){let e=this.parseDisjunction();return this.matchTextSeq(["GROUP","AND"],{advance:!1})?e:(e=this.parseAlias(e),this.matchSet(["asc","desc"],{advance:!1})?this.parseOrdered(()=>e):e)}parsePipeSyntaxAggregateGroupOrderBy(e,t={}){let{groupByExists:s=!0}=t,r=this.parseCsv(this.parsePipeSyntaxAggregateFields.bind(this)),i=[],a=[];for(let o of r){let c;o instanceof es?(c=o.args.this,c instanceof Se&&o.setArgKey("this",c.args.alias),a.push(o)):c=o,c&&i.push(c)}return s?e.select(i,{copy:!1}).groupBy(...i.map(o=>o.args.alias||o),{copy:!1}):e.select(i,{append:!1,copy:!1}),0<a.length?e.orderBy(...a,{append:!1,copy:!1}):e}parsePipeSyntaxAggregate(e){return this.matchTextSeq("AGGREGATE"),e=this.parsePipeSyntaxAggregateGroupOrderBy(e,{groupByExists:!1}),(this.match("groupBy")||this.matchTextSeq(["GROUP","AND"])&&this.match("orderBy"))&&(e=this.parsePipeSyntaxAggregateGroupOrderBy(e)),this.buildPipeCte({query:e,expressions:[new ye({})]})}parsePipeSyntaxSetOperator(e){if(!e)return;let t=this.parseSetOperation(e);if(!t)return;let s=()=>{let o=this.parseParen();return o?o.assertIs(ae).unnest():void 0};_optionalChain([t, 'access', _720 => _720.args, 'access', _721 => _721.this, 'optionalAccess', _722 => _722.pop, 'call', _723 => _723()]);let r=[_optionalChain([t, 'access', _724 => _724.args, 'access', _725 => _725.expression, 'optionalAccess', _726 => _726.pop, 'call', _727 => _727(), 'access', _728 => _728.assertIs, 'call', _729 => _729(ae), 'access', _730 => _730.unnest, 'call', _731 => _731()]),...this.parseCsv(s)];e=this.buildPipeCte({query:e,expressions:[new ye({})]});let a=_optionalChain([e, 'access', _732 => _732.args, 'access', _733 => _733.with, 'optionalAccess', _734 => _734.pop, 'call', _735 => _735()]);if(t instanceof $r?e=e.union(...r,{copy:!1,...t.args}):t instanceof Yr?e=e.except(...r,{copy:!1,...t.args}):e=e.intersect(...r,{copy:!1,...t.args}),!!e)return e.setArgKey("with",a),this.buildPipeCte({query:e,expressions:[new ye({})]})}parsePipeSyntaxJoin(e){if(!e)return;let t=this.parseJoin();if(t)return e instanceof $?e.join(t,{copy:!1}):e}parsePipeSyntaxPivot(e){let t=this.parsePivots();if(!t)return e;let s=e.args.from;if(s){let r=s.args.this;D(r,h)&&r.setArgKey("pivots",t)}return this.buildPipeCte({query:e,expressions:[new ye({})]})}parsePipeSyntaxExtend(e){return this.matchTextSeq("EXTEND"),e.select([new ye({}),...this.parseExpressions()],{append:!1,copy:!1}),this.buildPipeCte({query:e,expressions:[new ye({})]})}parsePipeSyntaxTablesample(e){let t=this.parseTableSample(),s=e.args.with;if(s){let r=_optionalChain([s, 'access', _736 => _736.args, 'access', _737 => _737.expressions, 'optionalAccess', _738 => _738[s.args.expressions.length-1]]);r instanceof h&&r.args.this instanceof h&&r.args.this.setArgKey("sample",t)}else e.setArgKey("sample",t);return e}parsePipeSyntaxQuery(e){let t=e;for(t instanceof ae&&(t=ft("*").from(t,{copy:!1})),t.args.from||(t=ft("*").from(t.subquery(void 0,{copy:!1}),{copy:!1}));this.match("pipeGt");){let s=this.curr,r=s?this.tokens.indexOf(s):-1,i=this._constructor.PIPE_SYNTAX_TRANSFORM_PARSERS[_nullishCoalesce(_optionalChain([this, 'access', _739 => _739.curr, 'optionalAccess', _740 => _740.text, 'access', _741 => _741.toUpperCase, 'call', _742 => _742()]), () => (""))];if(i)t=i.call(this,t);else{let a=this.parsePipeSyntaxSetOperator(t);if(a=a||this.parsePipeSyntaxJoin(t),!a&&0<=r){this.retreat(r),this.raiseError(`Unsupported pipe syntax operator: '${_optionalChain([s, 'optionalAccess', _743 => _743.text, 'access', _744 => _744.toUpperCase, 'call', _745 => _745()])}'.`);break}t=a}}return t}parseDeclareitem(){let e=this.parseCsv(this.parseIdVar.bind(this));if(e)return this.expression(Jl,{this:e,kind:this.parseTypes(),default:this.match("default")&&this.parseBitwise()})}parseDeclare(){let e=this.prev,t=this.tryParse(()=>this.parseCsv(this.parseDeclareitem.bind(this)));return!t||this.curr?this.parseAsCommand(e):this.expression(jl,{expressions:t})}buildCast(e){let{strict:t}=e,s=t?Z:Ft,r={...e};return delete r.strict,s===Ft&&(r.requiresString=this._dialectConstructor.TRY_CAST_REQUIRES_STRING),this.expression(s,r)}parseJsonValue(){let e=this.parseBitwise();this.match("comma");let t=this.parseBitwise(),s=(this.match("returning")||void 0)&&this.parseType();return this.expression(Ku,{this:e,path:this.dialect.toJsonPath(t),returning:s,onCondition:this.parseOnCondition()})}validateExpression(e,t){if(this.errorLevel!==0)for(let s of e.errorMessages(t))this.raiseError(s);return e}get _constructor(){return this.constructor}get _dialectConstructor(){return this.dialect._constructor}};J=re(null),T(J,10,"FUNCTIONS",Nv,M),T(J,10,"NO_PAREN_FUNCTIONS",Ov,M),T(J,10,"STRUCT_TYPE_TOKENS",Rv,M),T(J,10,"NESTED_TYPE_TOKENS",mv,M),T(J,10,"ENUM_TYPE_TOKENS",Sv,M),T(J,10,"AGGREGATE_TYPE_TOKENS",Tv,M),T(J,10,"TYPE_TOKENS",xv,M),T(J,10,"SIGNED_TO_UNSIGNED_TYPE_TOKEN",fv,M),T(J,10,"SUBQUERY_PREDICATES",Av,M),T(J,10,"RESERVED_TOKENS",dv,M),T(J,10,"DB_CREATABLES",gv,M),T(J,10,"CREATABLES",hv,M),T(J,10,"ALTERABLES",Ev,M),T(J,10,"ID_VAR_TOKENS",uv,M),T(J,10,"TABLE_ALIAS_TOKENS",lv,M),T(J,10,"ALIAS_TOKENS",pv,M),T(J,10,"COLON_PLACEHOLDER_TOKENS",cv,M),T(J,10,"ARRAY_CONSTRUCTORS",ov,M),T(J,10,"COMMENT_TABLE_ALIAS_TOKENS",av,M),T(J,10,"UPDATE_ALIAS_TOKENS",iv,M),T(J,10,"TRIM_TYPES",nv,M),T(J,10,"FUNC_TOKENS",rv,M),T(J,10,"CONJUNCTION",sv,M),T(J,10,"ASSIGNMENT",tv,M),T(J,10,"DISJUNCTION",ev,M),T(J,10,"EQUALITY",Zq,M),T(J,10,"COMPARISON",Qq,M),T(J,10,"BITWISE",Kq,M),T(J,10,"TERM",zq,M),T(J,10,"FACTOR",Xq,M),T(J,10,"EXPONENT",Jq,M),T(J,10,"TIMES",jq,M),T(J,10,"TIMESTAMPS",Wq,M),T(J,10,"SET_OPERATIONS",Vq,M),T(J,10,"JOIN_METHODS",Hq,M),T(J,10,"JOIN_SIDES",Yq,M),T(J,10,"JOIN_KINDS",$q,M),T(J,10,"LAMBDAS",Gq,M),T(J,10,"COLUMN_OPERATORS",Bq,M),T(J,10,"CAST_COLUMN_OPERATORS",Fq,M),T(J,10,"EXPRESSION_PARSERS",vq,M),T(J,10,"STATEMENT_PARSERS",qq,M),T(J,10,"UNARY_PARSERS",Uq,M),T(J,10,"STRING_PARSERS",kq,M),T(J,10,"NUMERIC_PARSERS",_q,M),T(J,10,"PRIMARY_PARSERS",Dq,M),T(J,10,"PLACEHOLDER_PARSERS",Lq,M),T(J,10,"RANGE_PARSERS",Mq,M),T(J,10,"PIPE_SYNTAX_TRANSFORM_PARSERS",wq,M),T(J,10,"PROPERTY_PARSERS",Pq,M),T(J,10,"CONSTRAINT_PARSERS",bq,M),T(J,10,"ALTER_PARSERS",Cq,M),T(J,10,"NO_PAREN_FUNCTION_PARSERS",yq,M),T(J,10,"INVALID_FUNC_NAME_TOKENS",Iq,M),T(J,10,"KEY_VALUE_DEFINITIONS",Nq,M),T(J,10,"FUNCTION_PARSERS",Oq,M),T(J,10,"QUERY_MODIFIER_PARSERS",Rq,M),T(J,10,"QUERY_MODIFIER_TOKENS",mq,M),T(J,10,"TYPE_LITERAL_PARSERS",Sq,M),T(J,10,"TYPE_CONVERTERS",Tq,M),T(J,10,"DDL_SELECT_TOKENS",xq,M),T(J,10,"PRE_VOLATILE_TOKENS",fq,M),T(J,10,"OPTYPE_FOLLOW_TOKENS",Aq,M),T(J,10,"TABLE_INDEX_HINT_TOKENS",dq,M),T(J,10,"WINDOW_ALIAS_TOKENS",gq,M),T(J,10,"WINDOW_BEFORE_PAREN_TOKENS",hq,M),T(J,10,"JSON_KEY_VALUE_SEPARATOR_TOKENS",Eq,M),T(J,10,"FETCH_TOKENS",uq,M),T(J,10,"ADD_CONSTRAINT_TOKENS",lq,M),T(J,10,"DISTINCT_TOKENS",pq,M),T(J,10,"UNNEST_OFFSET_ALIAS_TOKENS",cq,M),T(J,10,"SELECT_START_TOKENS",oq,M),T(J,10,"PRIVILEGE_FOLLOW_TOKENS",aq,M),T(J,10,"AMBIGUOUS_ALIAS_TOKENS",iq,M),T(J,10,"MODIFIABLES",nq,M),te(J,M),se(J,3,M),M._showTrie=void 0,M._setTrie=void 0,M.JOIN_HINTS=new Set,M.ALTER_ALTER_PARSERS={DISTKEY:function(){return this.parseAlterDiststyle()},DISTSTYLE:function(){return this.parseAlterDiststyle()},SORTKEY:function(){return this.parseAlterSortkey()},COMPOUND:function(){return this.parseAlterSortkey({compound:!0})}},M.SCHEMA_UNNAMED_CONSTRAINTS=new Set(["CHECK","EXCLUDE","FOREIGN KEY","LIKE","PERIOD","PRIMARY KEY","UNIQUE","BUCKET","TRUNCATE"]),M.FUNCTIONS_WITH_ALIASED_ARGS=new Set(["STRUCT"]),M.SET_PARSERS={GLOBAL:function(){return this.parseSetItemAssignment({kind:"GLOBAL"})},LOCAL:function(){return this.parseSetItemAssignment({kind:"LOCAL"})},SESSION:function(){return this.parseSetItemAssignment({kind:"SESSION"})},TRANSACTION:function(){return this.parseSetTransaction()}},M.SHOW_PARSERS={},M.TRANSACTION_KIND=new Set(["DEFERRED","IMMEDIATE","EXCLUSIVE"]),M.TRANSACTION_CHARACTERISTICS={ISOLATION:[["LEVEL","REPEATABLE","READ"],["LEVEL","READ","COMMITTED"],["LEVEL","READ","UNCOMITTED"],["LEVEL","SERIALIZABLE"]],READ:["WRITE","ONLY"]},M.CONFLICT_ACTIONS={...Object.fromEntries(["ABORT","FAIL","IGNORE","REPLACE","ROLLBACK","UPDATE"].map(e=>[e,[]])),DO:["NOTHING","UPDATE"]},M.CREATE_SEQUENCE={SCALE:["EXTEND","NOEXTEND"],ShaRD:["EXTEND","NOEXTEND"],NO:["CYCLE","CACHE","MAXVALUE","MINVALUE"],...Object.fromEntries(["SESSION","GLOBAL","KEEP","NOKEEP","ORDER","NOORDER","NOCACHE","CYCLE","NOCYCLE","NOMINVALUE","NOMAXVALUE","NOSCALE","NOSHARD"].map(e=>[e,[]]))},M.ISOLATED_LOADING_OPTIONS={FOR:["ALL","INSERT","NONE"]},M.USABLES=Object.fromEntries(["ROLE","WAREHOUSE","DATABASE","SCHEMA","CATALOG"].map(e=>[e,[]])),M.CAST_ACTIONS=Object.fromEntries(["RENAME","ADD"].map(e=>[e,["FIELDS"]])),M.SCHEMA_BINDING_OPTIONS={TYPE:["EVOLUTION"],...Object.fromEntries(["BINDING","COMPENSATION","EVOLUTION"].map(e=>[e,[]]))},M.PROCEDURE_OPTIONS={},M.EXECUTE_AS_OPTIONS=Object.fromEntries(["CALLER","SELF","OWNER"].map(e=>[e,[]])),M.KEY_CONSTRAINT_OPTIONS={NOT:["ENFORCED"],MATCH:["FULL","PARTIAL","SIMPLE"],INITIALLY:["DEFERRED","IMMEDIATE"],USING:["BTREE","HASH"],...Object.fromEntries(["DEFERRABLE","NORELY","RELY"].map(e=>[e,[]]))},M.WINDOW_EXCLUDE_OPTIONS={NO:["OTHERS"],CURRENT:["ROW"],...Object.fromEntries(["GROUP","TIES"].map(e=>[e,[]]))},M.INSERT_ALTERNATIVES=new Set(["ABORT","FAIL","IGNORE","REPLACE","ROLLBACK"]),M.CLONE_KEYWORDS=new Set(["CLONE","COPY"]),M.HISTORICAL_DATA_PREFIX=new Set(["AT","BEFORE","END"]),M.HISTORICAL_DATA_KIND=new Set(["OFFSET","STATEMENT","STREAM","TIMESTAMP","VERSION"]),M.OPCLASS_FOLLOW_KEYWORDS=new Set(["ASC","DESC","NULLS","WITH"]),M.VIEW_ATTRIBUTES=new Set(["ENCRYPTION","SCHEMABINDING","VIEW_METADATA"]),M.WINDOW_SIDES=new Set(["FOLLOWING","PRECEDING"]),M.COPY_INTO_VARLEN_OPTIONS=new Set(["FILE_FORMAT","COPY_OPTIONS","FORMAT_OPTIONS","CREDENTIAL"]),M.IS_JSON_PREDICATE_KIND=new Set(["VALUE","SCALAR","ARRAY","OBJECT"]),M.ODBC_DATETIME_LITERALS={},M.ON_CONDITION_TOKENS=new Set(["ERROR","NULL","TRUE","FALSE","EMPTY"]),M.DESCRIBE_STYLES=new Set(["ANALYZE","EXTENDED","FORMATTED","HISTORY"]),M.SET_ASSIGNMENT_DELIMITERS=new Set(["=",":=","TO"]),M.ANALYZE_STYLES=new Set(["BUFFER_USAGE_LIMIT","FULL","LOCAL","NO_WRITE_TO_BINLOG","SAMPLE","SKIP_LOCKED","VERBOSE"]),M.ANALYZE_EXPRESSION_PARSERS={ALL:function(){return this.parseAnalyzeColumns()},COMPUTE:function(){return this.parseAnalyzeStatistics()},DELETE:function(){return this.parseAnalyzeDelete()},DROP:function(){return this.parseAnalyzeHistogram()},ESTIMATE:function(){return this.parseAnalyzeStatistics()},LIST:function(){return this.parseAnalyzeList()},PREDICATE:function(){return this.parseAnalyzeColumns()},UPDATE:function(){return this.parseAnalyzeHistogram()},VALIDATE:function(){return this.parseAnalyzeValidate()}},M.PARTITION_KEYWORDS=new Set(["PARTITION","SUBPARTITION"]),M.OPERATION_MODIFIERS=new Set,M.RECURSIVE_CTE_SEARCH_KIND=new Set(["BREADTH","DEPTH","CYCLE"]),M.STRICT_CAST=!0,M.PREFIXED_PIVOT_COLUMNS=!1,M.IDENTIFY_PIVOT_STRINGS=!1,M.LOG_DEFAULTS_TO_LN=!1,M.TABLESAMPLE_CSV=!1,M.DEFAULT_SAMPLING_METHOD=void 0,M.SET_REQUIRES_ASSIGNMENT_DELIMITER=!0,M.TRIM_PATTERN_FIRST=!1,M.STRING_ALIASES=!1,M.MODIFIERS_ATTACHED_TO_SET_OP=!0,M.SET_OP_MODIFIERS=new Set(["order","limit","offset"]),M.NO_PAREN_IF_COMMANDS=!0,M.JSON_ARROWS_REQUIRE_JSON_TYPE=!1,M.COLON_IS_VARIANT_EXTRACT=!1,M.VALUES_FOLLOWED_BY_PAREN=!0,M.SUPPORTS_IMPLICIT_UNNEST=!1,M.INTERVAL_SPANS=!0,M.SUPPORTS_PARTITION_SELECTION=!1,M.WRAPPED_TRANSFORM_COLUMN_CONSTRAINT=!0,M.OPTIONAL_ALIAS_TOKEN_CTE=!0,M.ALTER_RENAME_REQUIRES_COLUMN=!0,M.ALTER_TABLE_PARTITIONS=!1,M.JOINS_HAVE_EQUAL_PRECEDENCE=!1,M.ZONE_AWARE_TIMESTAMP_CONSTRUCTOR=!1,M.MAP_KEYS_ARE_ARBITRARY_EXPRESSIONS=!1,M.JSON_EXTRACT_REQUIRES_JSON_EXPRESSION=!1,M.ADD_JOIN_ON_TRUE=!1,M.SUPPORTS_OMITTED_INTERVAL_SPAN_UNIT=!1;var he=M;var bv="i",Pv="k",wv="a",BL="c",kO="t",GL="o",$L="m",kw="v",Mv="DataType.Type";function Uw(n){let e=0,t=[],s=[[n,void 0,void 0,!1]];for(;0<s.length;){let[r,i,a,o]=s.pop(),c={};if(i!==void 0&&(c[bv]=i),a!==void 0&&(c[Pv]=a),o&&(c[wv]=o),t.push(c),r instanceof h){if(c[BL]=r.constructor.name,r.type&&(typeof r=="string"?c[kO]=[r]:typeof r.type=="string"?c[kO]=[r.type]:c[kO]=Uw(r.type)),r.comments&&0<r.comments.length&&(c[GL]=r.comments),r.meta&&(c[$L]=r.meta),r.args){let p=Object.entries(r.args).reverse();for(let[u,E]of p)if(Array.isArray(E))for(let g=E.length-1;0<=g;g--)s.push([E[g],e,u,!0]);else E!==void 0&&s.push([E,e,u,!1])}}else r&&typeof r=="object"&&"value"in r?(c[BL]=Mv,c[kw]=r.value):c[kw]=r;e++}return t}function qw(n,e){let t={...YL,...e};if(!n||n.length===0)return;let[s,...r]=n,i=Cv(s,t);if(!(i instanceof h))return;let a=[i];for(let o of r){let c=Cv(o,t);a.push(c);let p=a[o[bv]],u=o[Pv];o[wv]?p.append(u,c):p.setArgKey(u,c)}return i}function Cv(n,e){let t=n[BL];if(!t)return n[kw];if(t===Mv)return As(Be,n[kw]);let s=e[t];if(!s)throw new Error(`Expression class does not exist: ${t}`);let r=new s({});return n[kO]&&(r.type=qw(n[kO])),n[GL]&&(r.comments=n[GL]),n[$L]&&(r.meta=n[$L]),r}var Dv="sqlglot.meta",qL="sqlglot.anonymous",TL=["this","db","catalog"],_v=["this","table","db","catalog"],kv=["line","col","start","end"];function xV(n){if(typeof n=="boolean")return n;if(typeof n=="string"){let e=n.toLowerCase().trim();return e==="true"||e==="1"||e==="yes"}return!!n}var Xt=class Xt{constructor(e={}){this.args={};this.meta={};this.args=e;for(let[t,s]of Object.entries(e))this.setParent(t,s);Object.defineProperty(this,"meta",{value:{},writable:!0,configurable:!0,enumerable:!1}),Object.defineProperty(this,"comments",{value:void 0,writable:!0,configurable:!0,enumerable:!1})}*[Symbol.iterator](){if(this.constructor.availableArgs.has("expressions")){if(Array.isArray(this.args.expressions))for(let e of this.args.expressions)yield e;return}}text(e){let t=this.getArgKey(e);return typeof t=="string"?t:t instanceof G||t instanceof w||t instanceof Ze?_nullishCoalesce(_optionalChain([t, 'access', _746 => _746.args, 'access', _747 => _747.this, 'optionalAccess', _748 => _748.toString, 'call', _749 => _749()]), () => ("")):t instanceof ye||t instanceof Qt?t.name:""}get isString(){return this instanceof w&&this.args.isString===!0}get isNumber(){return this instanceof w&&!this.args.isString||this instanceof Ps&&this.args.this.isNumber}toValue(){if(this instanceof w){let e=this.args.this;return this.isString?e:typeof e=="string"?Number(e):e}if(this instanceof Ps){let e=this.args.this.toValue();return typeof e=="number"?-e:e!==void 0?-Number(e):void 0}throw new Error(`${this.constructor.name} cannot be converted to a JavaScript value.`)}get isInteger(){if(!this.isNumber)return!1;if(this instanceof w){let e=String(this.args.this);return!e.includes(".")&&!e.toLowerCase().includes("e")}try{return this.args.this.isInteger}catch (e8){return!1}}get isStar(){return this instanceof ye||this instanceof k&&this.args.this instanceof ye}get alias(){return this.args.alias instanceof ie?this.args.alias.name:this.text("alias")}get aliasColumnNames(){let e=this.args.alias;if(!(e instanceof ie))return[];let t=e.args.columns;return Array.isArray(t)?t.map(s=>s instanceof Xt?s.name:""):[]}get name(){return this.text("this")}get aliasOrName(){return this.alias||this.name}get sqlKey(){return this.sql()}get outputName(){return""}get type(){return this instanceof Z?this._type||this.args.to:this._type}set type(e){e!==void 0&&!(e instanceof C)&&(e=C.build(e)),this._type=e}isType(e,t){return this._type?this._type.isType(pe(e)):!1}get isLeaf(){return!Object.values(this.args).some(e=>(e instanceof Xt||Array.isArray(e))&&e)}copy(){let e=new this.constructor,t=[[this,e]];for(;0<t.length;){let[s,r]=t.pop();s.comments&&(r.comments=[...s.comments]),s._type&&(r._type=s._type.copy()),s.meta&&(r.meta={...s.meta}),s._hash&&(r._hash=s._hash);for(let[i,a]of Object.entries(s.args))if(a instanceof Xt){let o=new a.constructor;t.push([a,o]),r.setArgKey(i,o)}else if(Array.isArray(a)){r.args[i]=[];for(let o of a)if(o instanceof Xt){let c=new o.constructor;t.push([o,c]),r.append(i,c)}else r.append(i,o)}else r.args[i]=a}return e}addComments(e,t={}){let{prepend:s=!1}=t;if(this.comments||(this.comments=[]),e){for(let r of e){let[i,...a]=r.split(Dv);if(0<a.length)for(let o of a.join("").split(",")){let[c,...p]=o.split("="),u=0<p.length?p[0].trim():void 0,E=WU(c.trim());u===void 0?this.meta[E]=!0:/^(true|false|1|0)$/i.test(u)?this.meta[E]=xV(u):this.meta[E]=u}s||this.comments.push(r)}s&&(this.comments=[...e,...this.comments])}}popComments(){let e=this.comments||[];return this.comments=void 0,e}append(e,t){let s=this.args;Array.isArray(s[e])||(s[e]=[]),this.setParent(e,t);let r=s[e];t instanceof Xt&&(t.index=r.length),r.push(t)}setArgKey(e,t,s,r){let i=_nullishCoalesce(_optionalChain([r, 'optionalAccess', _750 => _750.overwrite]), () => (!0)),a=this;for(;a&&a._hash!==void 0;)a._hash=void 0,a=a.parent;let o=this.args;if(s!==void 0){let c=o[e]||[];if(c[s]===void 0)return;if(t===void 0){c.splice(s,1);for(let p=s;p<c.length;p++){let u=c[p];u instanceof Xt&&u.index!==void 0&&(u.index=u.index-1)}return}Array.isArray(t)?(c.splice(s,1),c.splice(s,0,...t)):i?c[s]=t:c.splice(s,0,t),t=c}else if(t===void 0){delete o[e];return}o[e]=t,this.setParent(e,t,s)}getArgKey(e){if(e!==void 0)return _nullishCoalesce(this.args[e], () => (void 0))}setParent(e,t,s){t instanceof Xt?(t.parent=this,t.argKey=e,t.index=s):Array.isArray(t)&&t.forEach((r,i)=>{r instanceof Xt&&(r.parent=this,r.argKey=e,r.index=i)})}get depth(){let e=0,t=this.parent;for(;t;)e++,t=t.parent;return e}*iterExpressions(e){let t=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _751 => _751.reverse]), () => (!1)),s=t?Object.values(this.args).reverse():Object.values(this.args);for(let r of s)if(r instanceof Xt)yield r;else if(Array.isArray(r)){let i=t?[...r].reverse():r;for(let a of i)a instanceof Xt&&(yield a)}}find(e,t){for(let s of this.findAll(e,t))return s}*findAll(e,t){let s=Array.from(pe(e)),r=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _752 => _752.bfs]), () => (!0));for(let i of this.walk({bfs:r}))s.some(a=>i instanceof a)&&(yield i)}findAncestor(...e){let t=this.parent;for(;t;){if(e.some(s=>t instanceof s))return t;t=t.parent}}get parentSelect(){return this.findAncestor($)}get sameParent(){return _optionalChain([this, 'access', _753 => _753.parent, 'optionalAccess', _754 => _754.constructor])===this.constructor}sameParentAs(e){return this.parent===e.parent}root(){let e=this;for(;e.parent;)e=e.parent;return e}*walk(e){let t=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _755 => _755.bfs]), () => (!0)),s=_optionalChain([e, 'optionalAccess', _756 => _756.prune]);t?yield*this.bfs({prune:s}):yield*this.dfs({prune:s})}*dfs(e){let t=_optionalChain([e, 'optionalAccess', _757 => _757.prune]),s=[this];for(;0<s.length;){let r=s.pop();if(yield r,!_optionalChain([t, 'optionalCall', _758 => _758(r)]))for(let i of r.iterExpressions({reverse:!0}))s.push(i)}}*bfs(e){let t=_optionalChain([e, 'optionalAccess', _759 => _759.prune]),s=[this];for(;0<s.length;){let r=s.shift();if(yield r,!_optionalChain([t, 'optionalCall', _760 => _760(r)]))for(let i of r.iterExpressions())s.push(i)}}unnest(){let e=this;for(;e instanceof Ye;){let t=e.args.this;if(t instanceof Xt)e=t;else break}return e}unalias(){if(this instanceof Se){let e=this.args.this;if(e instanceof Xt)return e}return this}unnestOperands(){return Array.from(this.iterExpressions()).map(e=>e.unnest())}*flatten(e){let t=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _761 => _761.unnest]), () => (!0));for(let s of this.dfs({prune:r=>r.parent!==void 0&&r.constructor!==this.constructor}))s.constructor!==this.constructor&&(t&&!(s instanceof ae)?yield s.unnest():yield s)}sql(e={}){let{dialect:t,...s}=e;return W.getOrRaise(t).generate(this,s)}transform(e,t={}){let{copy:s=!0,...r}=t,i,a,o=s?this.copy():this;for(let c of o.dfs({prune:p=>p!==a})){let p=c.parent,u=c.argKey,E=c.index;a=e(c,{...r,copy:s}),i?p&&u&&a!==c&&p.setArgKey(u,a,E):i=a}if(!i)throw new Error("Transform failed: no root node");if(!(i instanceof Xt))throw new Error("Expected final root to be an Expression");return i}replace(e){let t=this.parent;if(!t||t===e)return e;let s=this.argKey;if(!s)return e;let r=t.getArgKey(s);return Array.isArray(e)&&r instanceof Xt?_optionalChain([r, 'access', _762 => _762.parent, 'optionalAccess', _763 => _763.replace, 'call', _764 => _764(e)]):t.setArgKey(s,e,this.index),e!==this&&(this.parent=void 0,this.argKey=void 0,this.index=void 0),e}pop(){return this.replace(void 0),this}assertIs(e){if(!(this instanceof e))throw new Error(`${this.constructor.name} is not ${e.name}.`);return this}errorMessages(e){let t=[],s=this._constructor;for(let r of s.requiredArgs){let i=this.getArgKey(r);(i===void 0||Array.isArray(i)&&i.length===0)&&t.push(`Required keyword: '${r}' missing for ${this.constructor.name}`)}if(e&&this instanceof d){let r=s.availableArgs.size,i=s.isVarLenArgs||!1;r<e.length&&!i&&t.push(`The number of provided arguments (${e.length}) is greater than the maximum number of supported arguments (${r})`)}return t}dump(){return Uw(this)}static load(e){return qw(e)}and(e,t={}){let{copy:s=!0,wrap:r=!0,...i}=t,a=Array.from(pe(e));return nt([this,...a],{...i,copy:s,wrap:r})}or(e,t={}){let{copy:s=!0,wrap:r=!0,...i}=t,a=Array.from(pe(e));return bs([this,...a],{...i,copy:s,wrap:r})}not(e={}){let{copy:t=!0,...s}=e;return Hn(this,{...s,copy:t})}updatePositions(e,t){if(!e)this.meta.line=_optionalChain([t, 'optionalAccess', _765 => _765.line]),this.meta.col=_optionalChain([t, 'optionalAccess', _766 => _766.col]),this.meta.start=_optionalChain([t, 'optionalAccess', _767 => _767.start]),this.meta.end=_optionalChain([t, 'optionalAccess', _768 => _768.end]);else if(e instanceof Xt)for(let s of kv)this.meta[s]=e.meta[s];else this.meta.line=e.line,this.meta.col=e.col,this.meta.start=e.start,this.meta.end=e.end;return this}as(e,t={}){let{copy:s=!0,...r}=t,i=e instanceof Xt?e.name:e.toString();return oe(this,i,{...r,copy:s})}binop(e,t,s){let r=_nullishCoalesce(_optionalChain([s, 'optionalAccess', _769 => _769.reverse]), () => (!1)),i=this.copy(),a=ts(t,{copy:!0});if(!(i instanceof e)&&!(t instanceof e)){let o=xc(i,Y),c=xc(a,Y);o&&(i=o),c&&(a=c)}return r?new e({this:a,expression:i}):new e({this:i,expression:a})}resetHash(){this._hash=void 0}computeHash(){return this.hash()}hash(){if(this._hash!==void 0)return this._hash;let e=[],t=[this];for(;0<t.length;){let s=t.shift();e.push(s);for(let r of s.iterExpressions())r._hash===void 0&&t.push(r)}for(let s=e.length-1;0<=s;s--){let r=e[s],i=this.hashString(r._constructor.key);if(r instanceof w||r instanceof G){let a=Object.entries(r.args).sort();for(let[o,c]of a)c&&(i=this.hashString(i+o+c.toString()))}else{let a=Object.entries(r.args);for(let[o,c]of a)if(Array.isArray(c))for(let p of c)if(p!==void 0&&p!==!1){let u=typeof p=="string"?p.toLowerCase():p;i=this.hashString(i+o+u)}else i=this.hashString(i+o);else if(c!==void 0&&c!==!1){let p=typeof c=="string"?c.toLowerCase():c;i=this.hashString(i+o+p)}}r._hash=i}return this._hash||""}equals(e){return this===e?!0:!(e instanceof Xt)||this.constructor!==e.constructor?!1:this.hash()===e.hash()}hashString(e){return e.split("").reduce((t,s)=>(t=(t<<5)-t+s.charCodeAt(0),t&t),0).toString()}toString(){return this.sql()}in(e,t,s={}){let{copy:r=!0,unnest:i,...a}=s,o=t?ne(t):void 0;return!(o instanceof ae)&&o instanceof ce&&(o=o.subquery(void 0,{copy:!1})),new it({this:bt(this,r),expressions:_optionalChain([e, 'optionalAccess', _770 => _770.map, 'call', _771 => _771(c=>ts(c,{copy:r}))]),query:o,unnest:i?new Pe({expressions:Array.from(pe(i)).map(c=>ne(c,{...a,copy:r}))}):void 0})}between(e,t,s={}){let{copy:r=!0,symmetric:i}=s,a=new Fs({this:bt(this,r),low:ts(e,{copy:r}),high:ts(t,{copy:r})});return i!==void 0&&a.setArgKey("symmetric",i),a}is(e){return this.binop(Ut,e)}like(e){return this.binop(Ws,e)}ilike(e){return this.binop(ms,e)}eq(e){return this.binop(Ee,e)}neq(e){return this.binop(vt,e)}rlike(e){return this.binop(lc,e)}div(e,t){let s=this.binop(jt,e);return s.setArgKey("typed",_nullishCoalesce(_optionalChain([t, 'optionalAccess', _772 => _772.typed]), () => (!1))),s.setArgKey("safe",_nullishCoalesce(_optionalChain([t, 'optionalAccess', _773 => _773.safe]), () => (!1))),s}asc(e={}){let{nullsFirst:t=!0}=e;return new es({this:this.copy(),nullsFirst:t?ts(t):void 0})}desc(e={}){let{nullsFirst:t=!1}=e;return new es({this:this.copy(),desc:ts(!0),nullsFirst:t?ts(t):void 0})}lt(e){return this.binop(Tt,e)}lte(e){return this.binop(yt,e)}gt(e){return this.binop(It,e)}gte(e){return this.binop(xt,e)}add(e){return this.binop(lt,e)}radd(e){return this.binop(lt,e,{reverse:!0})}sub(e){return this.binop(dt,e)}rsub(e){return this.binop(dt,e,{reverse:!0})}mul(e){return this.binop(Ts,e)}rmul(e){return this.binop(Ts,e,{reverse:!0})}truediv(e){return this.binop(jt,e)}rtruediv(e){return this.binop(jt,e,{reverse:!0})}floorDiv(e){return this.binop(Hi,e)}rfloorDiv(e){return this.binop(Hi,e,{reverse:!0})}mod(e){return this.binop(Hr,e)}rmod(e){return this.binop(Hr,e,{reverse:!0})}pow(e){return this.binop(zp,e)}rpow(e){return this.binop(zp,e,{reverse:!0})}neg(){return new Ps({this:xc(this.copy(),Y)})}invert(){return Hn(this.copy())}getItem(...e){return new fs({this:this.copy(),expressions:(Array.isArray(e)?e:[e]).map(t=>ts(t,{copy:!0}))})}get _constructor(){return this.constructor}};Xt.key="expression",Xt.requiredArgs=new Set(["this"]),Xt.availableArgs=new Set(["this"]);var h=Xt,Qe=class extends h{constructor(e={}){super(e)}};Qe.key="condition";var Ve=class extends Qe{constructor(e={}){super(e)}};Ve.key="predicate",Ve.requiredArgs=new Set(["this"]),Ve.availableArgs=new Set(["this"]);var bi=class extends h{constructor(e={}){super(e)}get selects(){return this.args.this instanceof ce?this.args.this.selects:[]}get namedSelects(){return this.selects.map(e=>e.outputName)}};bi.key="derivedTable",bi.requiredArgs=new Set(["this"]),bi.availableArgs=new Set(["this"]);var ce=class extends h{constructor(e={}){super(e)}subquery(e,t={}){let{copy:s=!0}=t,r=bt(this,s),i;return e instanceof ie?i=e:e&&(i=new ie({this:K(e)})),new ae({this:r,alias:i})}limit(e,t={}){let{copy:s=!0,...r}=t;return OT(e,{instance:this,arg:"limit",into:Ct,prefix:"LIMIT",intoArg:"expression",...r,copy:s})}offset(e,t={}){let{copy:s=!0,...r}=t;return OT(e,{instance:this,arg:"offset",into:Fr,prefix:"OFFSET",intoArg:"expression",...r,copy:s})}orderBy(e,t={}){let{append:s=!0,copy:r=!0,...i}=t,a=Array.from(pe(e));return _S(a,{instance:this,arg:"order",prefix:"ORDER BY",into:ke,...i,append:s,copy:r})}get ctes(){let e=this.args.with;return Xe(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _774 => _774.args, 'access', _775 => _775.expressions]), () => ([])),h)}get selects(){throw new Error("Query objects must implement `selects`")}get namedSelects(){throw new Error("Query objects must implement `namedSelects`")}select(e,t={}){throw new Error("Query objects must implement `select`")}where(e,t={}){let{append:s=!0,copy:r=!0,dialect:i,...a}=t;return MR(pe(e).map(o=>o instanceof at?o.args.this:o),{instance:this,arg:"where",into:at,append:s,copy:r,dialect:i,...a})}with(e,t,s={}){let{recursive:r=!1,append:i=!0,copy:a=!0,...o}=s;return vD({instance:this,alias:e,as:t,...o,recursive:r,append:i,copy:a})}union(e,t={}){return NT([this,...e!==void 0?pe(e):[]],{...t,distinct:_nullishCoalesce(t.distinct, () => (!0))})}intersect(e,t={}){return UD([this,...pe(e)],{...t,distinct:_nullishCoalesce(t.distinct, () => (!0))})}except(e,t={}){return qD([this,...e!==void 0?Array.from(pe(e)):[]],{...t,distinct:_nullishCoalesce(t.distinct, () => (!0))})}};ce.key="query",ce.requiredArgs=new Set(["this"]),ce.availableArgs=new Set(["this"]);var as=class extends bi{constructor(e={}){super(e)}get selects(){let e=this.args.alias;return D(e,ie)?e.columns:[]}};as.key="udtf";var Fl=class extends h{constructor(e={}){super(e)}};Fl.key="cache",Fl.requiredArgs=new Set(["this"]),Fl.availableArgs=new Set(["this","lazy","options","expression"]);var Bl=class extends h{constructor(e={}){super(e)}};Bl.key="uncache",Bl.requiredArgs=new Set(["this"]),Bl.availableArgs=new Set(["this","exists"]);var Gl=class extends h{constructor(e={}){super(e)}};Gl.key="refresh",Gl.requiredArgs=new Set(["this","kind"]),Gl.availableArgs=new Set(["this","kind"]);var ln=class extends h{constructor(e={}){super(e)}get ctes(){let e=this.args.with;return Xe(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _776 => _776.args, 'access', _777 => _777.expressions]), () => ([])),h)}get selects(){let e=this.args.expression;return e instanceof ce?e.selects:[]}get namedSelects(){let e=this.args.expression;return e instanceof ce?e.namedSelects:[]}};ln.key="ddl",ln.requiredArgs=new Set(["this"]),ln.availableArgs=new Set(["this"]);var nS=class extends h{constructor(e={}){super(e)}};nS.key="lockingStatement",nS.requiredArgs=new Set(["this","expression"]),nS.availableArgs=new Set(["this","expression"]);var Lr=class extends h{constructor(e={}){super(e)}returning(e,t={}){let{copy:s=!0,...r}=t;return OT(e,{instance:this,arg:"returning",prefix:"RETURNING",into:zc,...r,copy:s})}};Lr.key="dml",Lr.requiredArgs=new Set(["this"]),Lr.availableArgs=new Set(["this"]);var us=class extends ln{constructor(e={}){super(e)}get kind(){return this.args.kind}};us.key="create",us.requiredArgs=new Set(["this","kind"]),us.availableArgs=new Set(["with","this","kind","expression","exists","properties","replace","refresh","unique","indexes","noSchemaBinding","begin","clone","concurrently","clustered"]);var Wn=class extends h{constructor(e={}){super(e)}};Wn.key="sequenceProperties",Wn.requiredArgs=new Set,Wn.availableArgs=new Set(["increment","minvalue","maxvalue","cache","start","owned","options"]);var $l=class extends h{constructor(e={}){super(e)}};$l.key="truncateTable",$l.requiredArgs=new Set(["expressions"]),$l.availableArgs=new Set(["expressions","isDatabase","exists","only","cluster","identity","option","partition"]);var Yl=class extends h{constructor(e={}){super(e)}};Yl.key="clone",Yl.requiredArgs=new Set(["this"]),Yl.availableArgs=new Set(["this","shallow","copy"]);var ei=class extends h{constructor(e={}){super(e)}};ei.key="describe",ei.requiredArgs=new Set(["this"]),ei.availableArgs=new Set(["this","style","kind","expressions","partition","format","asJson"]);var iS=class extends h{constructor(e={}){super(e)}};iS.key="attach",iS.requiredArgs=new Set(["this"]),iS.availableArgs=new Set(["this","exists","expressions"]);var aS=class extends h{constructor(e={}){super(e)}};aS.key="detach",aS.requiredArgs=new Set(["this"]),aS.availableArgs=new Set(["this","exists"]);var oS=class extends h{constructor(e={}){super(e)}};oS.key="install",oS.requiredArgs=new Set(["this"]),oS.availableArgs=new Set(["this","from","force"]);var Hl=class extends h{constructor(e={}){super(e)}};Hl.key="summarize",Hl.requiredArgs=new Set(["this"]),Hl.availableArgs=new Set(["this","table"]);var Vl=class extends h{constructor(e={}){super(e)}};Vl.key="kill",Vl.requiredArgs=new Set(["this"]),Vl.availableArgs=new Set(["this","kind"]);var Wl=class extends h{constructor(e={}){super(e)}};Wl.key="pragma",Wl.requiredArgs=new Set(["this"]),Wl.availableArgs=new Set(["this"]);var jl=class extends h{constructor(e={}){super(e)}};jl.key="declare",jl.requiredArgs=new Set(["expressions"]),jl.availableArgs=new Set(["expressions"]);var Jl=class extends h{constructor(e={}){super(e)}};Jl.key="declareItem",Jl.requiredArgs=new Set(["this"]),Jl.availableArgs=new Set(["this","kind","default"]);var fo=class extends h{constructor(e={}){super(e)}};fo.key="set",fo.requiredArgs=new Set,fo.availableArgs=new Set(["expressions","unset","tag"]);var Fc=class extends h{constructor(e={}){super(e)}};Fc.key="heredoc",Fc.requiredArgs=new Set(["this"]),Fc.availableArgs=new Set(["this","tag"]);var mr=class extends h{constructor(e={}){super(e)}};mr.key="setItem",mr.requiredArgs=new Set,mr.availableArgs=new Set(["this","expressions","kind","collate","global"]);var cS=class extends h{constructor(e={}){super(e)}};cS.key="queryBand",cS.requiredArgs=new Set(["this"]),cS.availableArgs=new Set(["this","scope","update"]);var gc=class extends h{constructor(e={}){super(e)}};gc.key="show",gc.requiredArgs=new Set(["this"]),gc.availableArgs=new Set(["this","history","terse","target","offset","startsWith","limit","from","like","where","db","scope","scopeKind","full","mutex","query","channel","global","log","position","types","privileges","forTable","forGroup","forUser","forRole","intoOutfile","json"]);var Xl=class extends h{constructor(e={}){super(e)}};Xl.key="userDefinedFunction",Xl.requiredArgs=new Set(["this"]),Xl.availableArgs=new Set(["this","expressions","wrapped"]);var Bc=class extends h{constructor(e={}){super(e)}};Bc.key="characterSet",Bc.requiredArgs=new Set(["this"]),Bc.availableArgs=new Set(["this","default"]);var zl=class extends h{constructor(e={}){super(e)}};zl.key="recursiveWithSearch",zl.requiredArgs=new Set(["kind","this","expression"]),zl.availableArgs=new Set(["kind","this","expression","using"]);var ve=class extends h{constructor(e={}){super(e)}get recursive(){return this.args.recursive}};ve.key="with",ve.requiredArgs=new Set(["expressions"]),ve.availableArgs=new Set(["expressions","recursive","search"]);var Cs=class extends h{constructor(e={}){super(e)}};Cs.key="withinGroup",Cs.requiredArgs=new Set(["this"]),Cs.availableArgs=new Set(["this","expression"]);var pS=class extends h{constructor(e={}){super(e)}};pS.key="projectionDef",pS.requiredArgs=new Set(["this","expression"]),pS.availableArgs=new Set(["this","expression"]);var ie=class extends h{constructor(e={}){super(e)}get columns(){return this.args.columns||[]}};ie.key="tableAlias",ie.requiredArgs=new Set,ie.availableArgs=new Set(["this","columns"]);var Kl=class extends h{constructor(e={}){super(e)}};Kl.key="columnPosition",Kl.requiredArgs=new Set(["position"]),Kl.availableArgs=new Set(["this","position"]);var we=class extends h{constructor(e={}){super(e)}get kind(){return this.args.kind}get constraints(){return this.args.constraints||[]}};we.key="columnDef",we.requiredArgs=new Set(["this"]),we.availableArgs=new Set(["this","kind","constraints","exists","position","default","output"]);var ws=class extends h{constructor(e={}){super(e)}};ws.key="alterColumn",ws.requiredArgs=new Set(["this"]),ws.availableArgs=new Set(["this","dtype","collate","using","default","drop","comment","allowNull","visible","renameTo"]);var Oh=class extends h{constructor(e={}){super(e)}};Oh.key="alterIndex",Oh.requiredArgs=new Set(["this","visible"]),Oh.availableArgs=new Set(["this","visible"]);var Gc=class extends h{constructor(e={}){super(e)}};Gc.key="alterDistStyle",Gc.requiredArgs=new Set(["this"]),Gc.availableArgs=new Set(["this"]);var $c=class extends h{constructor(e={}){super(e)}};$c.key="alterSortKey",$c.requiredArgs=new Set,$c.availableArgs=new Set(["this","expressions","compound"]);var Ql=class extends h{constructor(e={}){super(e)}};Ql.key="alterSet",Ql.requiredArgs=new Set,Ql.availableArgs=new Set(["expressions","option","tablespace","accessMethod","fileFormat","copyOptions","tag","location","serde"]);var Xc=class extends h{constructor(e={}){super(e)}};Xc.key="renameColumn",Xc.requiredArgs=new Set(["this","to"]),Xc.availableArgs=new Set(["this","to","exists"]);var Vi=class extends h{constructor(e={}){super(e)}};Vi.key="alterRename",Vi.requiredArgs=new Set(["this"]),Vi.availableArgs=new Set(["this"]);var xo=class extends h{constructor(e={}){super(e)}};xo.key="swapTable",xo.requiredArgs=new Set(["this"]),xo.availableArgs=new Set(["this"]);var Zl=class extends h{constructor(e={}){super(e)}};Zl.key="comment",Zl.requiredArgs=new Set(["this","kind","expression"]),Zl.availableArgs=new Set(["this","kind","expression","exists","materialized"]);var eu=class extends h{constructor(e={}){super(e)}};eu.key="comprehension",eu.requiredArgs=new Set(["this","expression","iterator"]),eu.availableArgs=new Set(["this","expression","position","iterator","condition"]);var _i=class extends h{constructor(e={}){super(e)}};_i.key="mergeTreeTtlAction",_i.requiredArgs=new Set(["this"]),_i.availableArgs=new Set(["this","delete","recompress","toDisk","toVolume"]);var vi=class extends h{constructor(e={}){super(e)}};vi.key="mergeTreeTtl",vi.requiredArgs=new Set(["expressions"]),vi.availableArgs=new Set(["expressions","where","group","aggregates"]);var yr=class extends h{constructor(e={}){super(e)}};yr.key="indexConstraintOption",yr.requiredArgs=new Set,yr.availableArgs=new Set(["keyBlockSize","using","parser","comment","visible","engineAttr","secondaryEngineAttr"]);var ki=class extends h{constructor(e={}){super(e)}get kind(){return this.args.kind}};ki.key="columnConstraint",ki.requiredArgs=new Set(["kind"]),ki.availableArgs=new Set(["this","kind"]);var qe=class extends h{constructor(e={}){super(e)}};qe.key="columnConstraintKind",qe.requiredArgs=new Set(["this"]),qe.availableArgs=new Set(["this"]);var To=class extends h{constructor(e={}){super(e)}};To.key="withOperator",To.requiredArgs=new Set(["this","op"]),To.availableArgs=new Set(["this","op"]);var lS=class extends h{constructor(e={}){super(e)}};lS.key="watermarkColumnConstraint",lS.requiredArgs=new Set(["this","expression"]),lS.availableArgs=new Set(["this","expression"]);var tu=class extends h{constructor(e={}){super(e)}};tu.key="constraint",tu.requiredArgs=new Set(["this","expressions"]),tu.availableArgs=new Set(["this","expressions"]);var Jn=class extends Lr{constructor(e={}){super(e)}delete(e,t={}){let{copy:s=!0,...r}=t;return OT(e,{instance:this,arg:"this",into:V,...r,copy:s})}where(e,t={}){let{append:s=!0,copy:r=!0,...i}=t;return MR(Array.from(pe(e)),{instance:this,arg:"where",into:at,...i,append:s,copy:r})}};Jn.key="delete",Jn.requiredArgs=new Set,Jn.availableArgs=new Set(["with","this","using","where","returning","order","limit","tables","cluster"]);var Tn=class extends h{constructor(e={}){super(e)}get kind(){return this.args.kind}};Tn.key="drop",Tn.requiredArgs=new Set,Tn.availableArgs=new Set(["this","kind","expressions","exists","temporary","materialized","cascade","constraints","purge","cluster","concurrently"]);var uS=class extends h{constructor(e={}){super(e)}};uS.key="export",uS.requiredArgs=new Set(["this","options"]),uS.availableArgs=new Set(["this","connection","options"]);var ti=class extends h{constructor(e={}){super(e)}};ti.key="filter",ti.requiredArgs=new Set(["this","expression"]),ti.availableArgs=new Set(["this","expression"]);var ES=class extends h{constructor(e={}){super(e)}};ES.key="check",ES.requiredArgs=new Set(["this"]),ES.availableArgs=new Set(["this"]);var su=class extends h{constructor(e={}){super(e)}};su.key="changes",su.requiredArgs=new Set(["information"]),su.availableArgs=new Set(["information","atBefore","end"]);var ru=class extends h{constructor(e={}){super(e)}};ru.key="connect",ru.requiredArgs=new Set(["connect"]),ru.availableArgs=new Set(["start","connect","nocycle"]);var nu=class extends h{constructor(e={}){super(e)}};nu.key="copyParameter",nu.requiredArgs=new Set(["this"]),nu.availableArgs=new Set(["this","expression","expressions"]);var iu=class extends h{constructor(e={}){super(e)}};iu.key="credentials",iu.requiredArgs=new Set,iu.availableArgs=new Set(["credentials","encryption","storage","iamRole","region"]);var au=class extends h{constructor(e={}){super(e)}};au.key="prior",au.requiredArgs=new Set(["this"]),au.availableArgs=new Set(["this"]);var So=class extends h{constructor(e={}){super(e)}};So.key="directory",So.requiredArgs=new Set(["this"]),So.availableArgs=new Set(["this","local","rowFormat"]);var hS=class extends h{constructor(e={}){super(e)}};hS.key="directoryStage",hS.requiredArgs=new Set(["this"]),hS.availableArgs=new Set(["this"]);var ou=class extends h{constructor(e={}){super(e)}};ou.key="foreignKey",ou.requiredArgs=new Set,ou.availableArgs=new Set(["expressions","reference","delete","update","options"]);var Nh=class extends h{constructor(e={}){super(e)}};Nh.key="columnPrefix",Nh.requiredArgs=new Set(["this","expression"]),Nh.availableArgs=new Set(["this","expression"]);var mo=class extends h{constructor(e={}){super(e)}};mo.key="primaryKey",mo.requiredArgs=new Set(["expressions"]),mo.availableArgs=new Set(["this","expressions","options","include"]);var Ro=class extends h{constructor(e={}){super(e)}};Ro.key="into",Ro.requiredArgs=new Set,Ro.availableArgs=new Set(["this","temporary","unlogged","bulkCollect","expressions"]);var Ge=class extends h{constructor(e={}){super(e)}get name(){return _optionalChain([this, 'access', _778 => _778.args, 'access', _779 => _779.this, 'optionalAccess', _780 => _780.name])||""}get aliasOrName(){return _nullishCoalesce(_optionalChain([this, 'access', _781 => _781.args, 'access', _782 => _782.this, 'optionalAccess', _783 => _783.aliasOrName]), () => (""))}};Ge.key="from",Ge.requiredArgs=new Set(["this"]),Ge.availableArgs=new Set(["this"]);var $t=class extends h{constructor(e={}){super(e)}};$t.key="having",$t.requiredArgs=new Set(["this"]),$t.availableArgs=new Set(["this"]);var Dr=class extends h{constructor(e={}){super(e)}};Dr.key="hint",Dr.requiredArgs=new Set(["expressions"]),Dr.availableArgs=new Set(["expressions"]);var yi=class extends h{constructor(e={}){super(e)}};yi.key="joinHint",yi.requiredArgs=new Set(["this","expressions"]),yi.availableArgs=new Set(["this","expressions"]);var G=class extends h{constructor(e={}){super(e)}get outputName(){return this.name}get quoted(){return!!this.args.quoted}};G.key="identifier",G.requiredArgs=new Set(["this"]),G.availableArgs=new Set(["this","quoted","global","temporary"]);var cu=class extends h{constructor(e={}){super(e)}};cu.key="opclass",cu.requiredArgs=new Set(["this","expression"]),cu.availableArgs=new Set(["this","expression"]);var pu=class extends h{constructor(e={}){super(e)}};pu.key="index",pu.requiredArgs=new Set,pu.availableArgs=new Set(["this","table","unique","primary","amp","params"]);var lu=class extends h{constructor(e={}){super(e)}};lu.key="indexParameters",lu.requiredArgs=new Set,lu.availableArgs=new Set(["using","include","columns","withStorage","partitionBy","tablespace","where","on"]);var uu=class extends h{constructor(e={}){super(e)}};uu.key="conditionalInsert",uu.requiredArgs=new Set(["this"]),uu.availableArgs=new Set(["this","expression","else"]);var Oo=class extends h{constructor(e={}){super(e)}};Oo.key="multitableInserts",Oo.requiredArgs=new Set(["expressions","kind","source"]),Oo.availableArgs=new Set(["expressions","kind","source"]);var Eu=class extends h{constructor(e={}){super(e)}};Eu.key="onConflict",Eu.requiredArgs=new Set,Eu.availableArgs=new Set(["duplicate","expressions","action","conflictKeys","indexPredicate","constraint","where"]);var hu=class extends h{constructor(e={}){super(e)}};hu.key="onCondition",hu.requiredArgs=new Set,hu.availableArgs=new Set(["error","empty","null"]);var zc=class extends h{constructor(e={}){super(e)}};zc.key="returning",zc.requiredArgs=new Set(["expressions"]),zc.availableArgs=new Set(["expressions","into"]);var gu=class extends h{constructor(e={}){super(e)}};gu.key="introducer",gu.requiredArgs=new Set(["this","expression"]),gu.availableArgs=new Set(["this","expression"]);var No=class extends h{constructor(e={}){super(e)}};No.key="national",No.requiredArgs=new Set(["this"]),No.availableArgs=new Set(["this"]);var du=class extends h{constructor(e={}){super(e)}};du.key="loadData",du.requiredArgs=new Set(["this","inpath"]),du.availableArgs=new Set(["this","local","overwrite","inpath","partition","inputFormat","serde"]);var Wi=class extends h{constructor(e={}){super(e)}};Wi.key="partition",Wi.requiredArgs=new Set(["expressions"]),Wi.availableArgs=new Set(["expressions","subpartition"]);var Ih=class extends h{constructor(e={}){super(e)}};Ih.key="partitionRange",Ih.requiredArgs=new Set(["this"]),Ih.availableArgs=new Set(["this","expression","expressions"]);var gS=class extends h{constructor(e={}){super(e)}};gS.key="partitionId",gS.requiredArgs=new Set(["this"]),gS.availableArgs=new Set(["this"]);var Sn=class extends h{constructor(e={}){super(e)}};Sn.key="fetch",Sn.requiredArgs=new Set,Sn.availableArgs=new Set(["direction","count","limitOptions"]);var Au=class extends h{constructor(e={}){super(e)}};Au.key="grant",Au.requiredArgs=new Set(["privileges","securable","principals"]),Au.availableArgs=new Set(["privileges","kind","securable","principals","grantOption"]);var fu=class extends h{constructor(e={}){super(e)}};fu.key="revoke",fu.requiredArgs=new Set(["privileges","securable","principals"]),fu.availableArgs=new Set(["privileges","kind","securable","principals","grantOption","cascade"]);var Ys=class extends h{constructor(e={}){super(e)}};Ys.key="group",Ys.requiredArgs=new Set,Ys.availableArgs=new Set(["expressions","groupingSets","cube","rollup","totals","all"]);var xu=class extends h{constructor(e={}){super(e)}};xu.key="cube",xu.requiredArgs=new Set,xu.availableArgs=new Set(["expressions"]);var Yc=class extends h{constructor(e={}){super(e)}};Yc.key="rollup",Yc.requiredArgs=new Set,Yc.availableArgs=new Set(["expressions"]);var Tu=class extends h{constructor(e={}){super(e)}};Tu.key="groupingSets",Tu.requiredArgs=new Set(["expressions"]),Tu.availableArgs=new Set(["expressions"]);var vs=class extends h{constructor(e={}){super(e)}};vs.key="lambda",vs.requiredArgs=new Set(["this","expressions"]),vs.availableArgs=new Set(["this","expressions","colon"]);var Ct=class extends h{constructor(e={}){super(e)}};Ct.key="limit",Ct.requiredArgs=new Set(["expression"]),Ct.availableArgs=new Set(["this","expression","offset","limitOptions","expressions"]);var Su=class extends h{constructor(e={}){super(e)}};Su.key="limitOptions",Su.requiredArgs=new Set,Su.availableArgs=new Set(["percent","rows","withTies"]);var z=class extends h{constructor(e={}){super(e)}on(e,t={}){let{append:s,dialect:r,copy:i,...a}=t,o=Array.from(pe(e)),c=MR(o,{instance:this,arg:"on",append:s,dialect:r,copy:i,...a});return c.args.kind==="cross"&&c.setArgKey("kind",void 0),c}using(e,t={}){let{append:s,dialect:r,copy:i,...a}=t,o=Array.from(pe(e)),c=Dg(o,{instance:this,arg:"using",append:s,dialect:r,copy:i,...a});return c.args.kind==="cross"&&c.setArgKey("kind",void 0),c}get method(){return this.text("method").toUpperCase()}get kind(){return this.text("kind").toUpperCase()}get side(){return this.text("side").toUpperCase()}get hint(){return this.text("hint").toUpperCase()}get aliasOrName(){return _nullishCoalesce(_optionalChain([this, 'access', _784 => _784.args, 'access', _785 => _785.this, 'optionalAccess', _786 => _786.aliasOrName]), () => (""))}get isSemiOrAntiJoin(){return this.args.kind!==void 0&&["semi","anti"].includes(this.args.kind)}};z.key="join",z.requiredArgs=new Set(["this"]),z.availableArgs=new Set(["this","on","side","kind","using","method","global","hint","matchCondition","directed","expressions","pivots"]);var mu=class extends h{constructor(e={}){super(e)}};mu.key="matchRecognizeMeasure",mu.requiredArgs=new Set(["this"]),mu.availableArgs=new Set(["this","windowFrame"]);var Io=class extends h{constructor(e={}){super(e)}};Io.key="matchRecognize",Io.requiredArgs=new Set,Io.availableArgs=new Set(["partitionBy","order","measures","rows","after","pattern","define","alias"]);var wl=class extends h{constructor(e={}){super(e)}};wl.key="final",wl.requiredArgs=new Set(["this"]),wl.availableArgs=new Set(["this"]);var Fr=class extends h{constructor(e={}){super(e)}};Fr.key="offset",Fr.requiredArgs=new Set(["expression"]),Fr.availableArgs=new Set(["this","expression","expressions"]);var ke=class extends h{constructor(e={}){super(e)}};ke.key="order",ke.requiredArgs=new Set(["expressions"]),ke.availableArgs=new Set(["this","expressions","siblings"]);var Ru=class extends h{constructor(e={}){super(e)}};Ru.key="withFill",Ru.requiredArgs=new Set,Ru.availableArgs=new Set(["from","to","step","interpolate"]);var es=class extends h{constructor(e={}){super(e)}get name(){return _optionalChain([this, 'access', _787 => _787.args, 'access', _788 => _788.this, 'optionalAccess', _789 => _789.name])||""}};es.key="ordered",es.requiredArgs=new Set(["this","nullsFirst"]),es.availableArgs=new Set(["this","desc","nullsFirst","withFill"]);var U=class extends h{constructor(e={}){super(e)}};U.key="property",U.requiredArgs=new Set(["this","value"]),U.availableArgs=new Set(["this","value"]);var Ou=class extends h{constructor(e={}){super(e)}};Ou.key="grantPrivilege",Ou.requiredArgs=new Set(["this"]),Ou.availableArgs=new Set(["this","expressions"]);var Nu=class extends h{constructor(e={}){super(e)}};Nu.key="grantPrincipal",Nu.requiredArgs=new Set(["this"]),Nu.availableArgs=new Set(["this","kind"]);var ji=class extends h{constructor(e={}){super(e)}};ji.key="allowedValuesProperty",ji.requiredArgs=new Set(["expressions"]),ji.availableArgs=new Set(["expressions"]);var dS=class extends h{constructor(e={}){super(e)}};dS.key="partitionByRangePropertyDynamic",dS.requiredArgs=new Set(["start","end","every"]),dS.availableArgs=new Set(["this","start","end","every"]);var AS=class extends h{constructor(e={}){super(e)}};AS.key="rollupIndex",AS.requiredArgs=new Set(["this","expressions"]),AS.availableArgs=new Set(["this","expressions","fromIndex","properties"]);var yh=class extends h{constructor(e={}){super(e)}};yh.key="partitionList",yh.requiredArgs=new Set(["this","expressions"]),yh.availableArgs=new Set(["this","expressions"]);var yo=class extends h{constructor(e={}){super(e)}};yo.key="partitionBoundSpec",yo.requiredArgs=new Set,yo.availableArgs=new Set(["this","expression","fromExpressions","toExpressions"]);var pr=class extends h{constructor(e={}){super(e)}};pr.key="queryTransform",pr.requiredArgs=new Set(["expressions","commandScript"]),pr.availableArgs=new Set(["expressions","commandScript","schema","rowFormatBefore","recordWriter","rowFormatAfter","recordReader"]);var fS=class extends h{constructor(e={}){super(e)}};fS.key="semanticView",fS.requiredArgs=new Set(["this"]),fS.availableArgs=new Set(["this","metrics","dimensions","facts","where"]);var xS=class extends h{constructor(e={}){super(e)}};xS.key="location",xS.requiredArgs=new Set,xS.availableArgs=new Set;var un=class extends h{constructor(e={}){super(e)}};un.key="qualify",un.requiredArgs=new Set(["this"]),un.availableArgs=new Set(["this"]);var Co=class extends h{constructor(e={}){super(e)}};Co.key="inputOutputFormat",Co.requiredArgs=new Set,Co.availableArgs=new Set(["inputFormat","outputFormat"]);var bo=class extends h{constructor(e={}){super(e)}};bo.key="return",bo.requiredArgs=new Set(["this"]),bo.availableArgs=new Set(["this"]);var Iu=class extends h{constructor(e={}){super(e)}};Iu.key="reference",Iu.requiredArgs=new Set(["this"]),Iu.availableArgs=new Set(["this","expressions","options"]);var Mt=class extends h{constructor(e={}){super(e)}in(e,t,s={}){let{copy:r=!0,unnest:i,...a}=s;return new it({this:bt(this,r),expressions:_optionalChain([e, 'optionalAccess', _790 => _790.map, 'call', _791 => _791(o=>ts(o,{copy:r}))]),query:t?ne(t,{...a,copy:r}):void 0,unnest:i?new Pe({expressions:Array.from(pe(i)).map(o=>ne(o,{...a,copy:r}))}):void 0})}};Mt.key="tuple",Mt.requiredArgs=new Set,Mt.availableArgs=new Set(["expressions"]);var TV={match:!1,laterals:!1,joins:!1,connect:!1,pivots:!1,prewhere:!1,where:!1,group:!1,having:!1,qualify:!1,windows:!1,distribute:!1,sort:!1,cluster:!1,order:!1,limit:!1,offset:!1,locks:!1,sample:!1,settings:!1,format:!1,options:!1},TS=class extends h{constructor(e={}){super(e)}};TS.key="queryOption",TS.requiredArgs=new Set(["this"]),TS.availableArgs=new Set(["this","expression"]);var Po=class extends h{constructor(e={}){super(e)}};Po.key="withTableHint",Po.requiredArgs=new Set(["expressions"]),Po.availableArgs=new Set(["expressions"]);var yu=class extends h{constructor(e={}){super(e)}};yu.key="indexTableHint",yu.requiredArgs=new Set(["this"]),yu.availableArgs=new Set(["this","expressions","target"]);var Cu=class extends h{constructor(e={}){super(e)}};Cu.key="historicalData",Cu.requiredArgs=new Set(["this","kind","expression"]),Cu.availableArgs=new Set(["this","kind","expression"]);var Rp=class extends h{constructor(e={}){super(e)}};Rp.key="put",Rp.requiredArgs=new Set(["this","target"]),Rp.availableArgs=new Set(["this","target","properties"]);var Ch=class extends h{constructor(e={}){super(e)}};Ch.key="get",Ch.requiredArgs=new Set(["this","target"]),Ch.availableArgs=new Set(["this","target","properties"]);var V=class extends h{constructor(e={}){super(e)}get name(){let e=this.args.this;return!e||e instanceof d?"":e instanceof h?e.name||"":e.toString()}get db(){return this.text("db")}get catalog(){return this.text("catalog")}get selects(){return[]}get namedSelects(){return[]}get parts(){let e=[];for(let t of["catalog","db","this"]){let s=this.args[t];s instanceof me?e.push(...s.flatten()):s instanceof h&&e.push(s)}return e}toColumn(e={}){let{copy:t=!0}=e,s=this.parts,r=s[s.length-1],i;if(r instanceof G){let o=s.slice(0,4).reverse(),c=s.slice(4);i=Ie({col:o[0],table:o[1],db:o[2],catalog:o[3]},{fields:c,copy:t})}else i=r;let a=this.args.alias;if(a){let o=a.args.this,c=typeof o=="string"||D(o,G)?o:void 0;i=oe(i,c,{copy:t})}return i}};V.key="table",V.requiredArgs=new Set,V.availableArgs=new Set(["this","alias","db","catalog","laterals","joins","pivots","hints","systemTime","version","format","pattern","ordinality","when","only","partition","changes","rowsFrom","sample","indexed"]);var Ze=class extends h{constructor(e={}){super(e)}};Ze.key="var",Ze.requiredArgs=new Set(["this"]),Ze.availableArgs=new Set(["this"]);var bu=class extends h{constructor(e={}){super(e)}};bu.key="version",bu.requiredArgs=new Set(["this","kind"]),bu.availableArgs=new Set(["this","kind","expression"]);var Lt=class extends h{constructor(e={}){super(e)}};Lt.key="schema",Lt.requiredArgs=new Set,Lt.availableArgs=new Set(["this","expressions"]);var Kc=class extends h{constructor(e={}){super(e)}};Kc.key="lock",Kc.requiredArgs=new Set(["update"]),Kc.availableArgs=new Set(["update","expressions","wait","key"]);var wo=class extends h{constructor(e={}){super(e)}};wo.key="tableSample",wo.requiredArgs=new Set,wo.availableArgs=new Set(["expressions","method","bucketNumerator","bucketDenominator","bucketField","percent","rows","size","seed"]);var yx=class extends h{constructor(e={}){super(e)}get this(){return this.args.this}};yx.key="tag",yx.availableArgs=new Set(["this","prefix","postfix"]);var ls=class extends h{constructor(e={}){super(e)}get unpivot(){return!!this.args.unpivot}get fields(){return this.args.fields||[]}};ls.key="pivot",ls.requiredArgs=new Set([]),ls.availableArgs=new Set(["this","alias","expressions","fields","unpivot","using","group","columns","includeNulls","defaultOnNull","into","with"]);var Pu=class extends h{constructor(e={}){super(e)}};Pu.key="unpivotColumns",Pu.requiredArgs=new Set(["this","expressions"]),Pu.availableArgs=new Set(["this","expressions"]);var wu=class extends h{constructor(e={}){super(e)}};wu.key="windowSpec",wu.requiredArgs=new Set,wu.availableArgs=new Set(["kind","start","startSide","end","endSide","exclude"]);var Mu=class extends h{constructor(e={}){super(e)}};Mu.key="preWhere",Mu.requiredArgs=new Set(["this"]),Mu.availableArgs=new Set(["this"]);var at=class extends h{constructor(e={}){super(e)}};at.key="where",at.requiredArgs=new Set(["this"]),at.availableArgs=new Set(["this"]);var ye=class extends h{constructor(e={}){super(e)}get name(){return"*"}get outputName(){return this.name}};ye.key="star",ye.requiredArgs=new Set,ye.availableArgs=new Set(["except","replace","rename"]);var Jr=class extends h{constructor(e={}){super(e)}get name(){return _nullishCoalesce(_optionalChain([this, 'access', _792 => _792.args, 'access', _793 => _793.this, 'optionalAccess', _794 => _794.name]), () => (""))}};Jr.key="dataTypeParam",Jr.requiredArgs=new Set(["this"]),Jr.availableArgs=new Set(["this","expression"]);var ot=class ot extends h{constructor(e={}){super(e)}static build(e,t={}){let{udt:s=!1,copy:r=!0,dialect:i,...a}=t,o;if(typeof e=="string"){if(e==="unknown")return new ot({...a,this:"unknown"});if(Object.values(Be).includes(e))return new ot({...a,this:e});try{o=_w(e,{read:i,into:ot,errorLevel:0})}catch(u){if(u instanceof ns){if(s)return new ot({this:"user-defined",kind:e,...a});throw u}else throw u}}else{if((e instanceof G||e instanceof me)&&s)return new ot({...a,this:"user-defined",kind:e});if(e instanceof ot)return bt(e,r);throw new Error(`Invalid data type: ${typeof e}. Expected string, DataTypeExprKind, or DataTypeExpr`)}for(let[c,p]of Object.entries(a))_optionalChain([o, 'optionalAccess', _795 => _795.setArgKey, 'call', _796 => _796(c,p)]);return o}toString(){let e=this.args.this;return e===void 0?super.toString():e instanceof h?e.toString():String(e)}isType(e,t){let s=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _797 => _797.checkNullable]), () => (!1)),r=this.args.nullable;for(let i of pe(e)){let a=ot.build(i,{copy:!1,udt:!0}),o=_optionalChain([a, 'optionalAccess', _798 => _798.args, 'access', _799 => _799.nullable]),c;if(_optionalChain([a, 'optionalAccess', _800 => _800.args, 'access', _801 => _801.expressions])||s&&(r||o)||this.args.this==="user-defined"||_optionalChain([a, 'optionalAccess', _802 => _802.args, 'access', _803 => _803.this])==="user-defined"?c=this.equals(a):c=this.args.this===_optionalChain([a, 'optionalAccess', _804 => _804.args, 'access', _805 => _805.this]),c)return!0}return!1}};ot.key="dataType",ot.requiredArgs=new Set(["this"]),ot.availableArgs=new Set(["this","expressions","nested","values","prefix","kind","nullable"]),ot.STRUCT_TYPES=new Set(["file","nested","object","struct","union"]),ot.ARRAY_TYPES=new Set(["array","list"]),ot.NESTED_TYPES=new Set([...ot.STRUCT_TYPES,...ot.ARRAY_TYPES,"map"]),ot.TEXT_TYPES=new Set(["char","nchar","nvarchar","text","varchar","name"]),ot.SIGNED_INTEGER_TYPES=new Set(["bigint","int","int128","int256","mediumint","smallint","tinyint"]),ot.UNSIGNED_INTEGER_TYPES=new Set(["ubigint","uint","uint128","uint256","umediumint","usmallint","utinyint"]),ot.INTEGER_TYPES=new Set([...ot.SIGNED_INTEGER_TYPES,...ot.UNSIGNED_INTEGER_TYPES,"bit"]),ot.FLOAT_TYPES=new Set(["double","float"]),ot.REAL_TYPES=new Set([...ot.FLOAT_TYPES,"bigdecimal","decimal","decimal32","decimal64","decimal128","decimal256","decfloat","money","smallmoney","udecimal","udouble"]),ot.NUMERIC_TYPES=new Set([...ot.INTEGER_TYPES,...ot.REAL_TYPES]),ot.TEMPORAL_TYPES=new Set(["date","date32","datetime","datetime2","datetime64","smalldatetime","time","timestamp","timestampntz","timestampltz","timestamptz","timestampMs","timestampNs","timestampS","timetz"]);var C=ot,SS=class extends h{constructor(e={}){super(e)}};SS.key="type",SS.requiredArgs=new Set,SS.availableArgs=new Set;var jn=class extends h{constructor(e={}){super(e)}};jn.key="command",jn.requiredArgs=new Set(["this"]),jn.availableArgs=new Set(["this","expression"]);var Lu=class extends h{constructor(e={}){super(e)}};Lu.key="transaction",Lu.requiredArgs=new Set,Lu.availableArgs=new Set(["this","modes","mark"]);var Du=class extends h{constructor(e={}){super(e)}};Du.key="commit",Du.requiredArgs=new Set,Du.availableArgs=new Set(["chain","this","durability"]);var _u=class extends h{constructor(e={}){super(e)}};_u.key="rollback",_u.requiredArgs=new Set,_u.availableArgs=new Set(["savepoint","this"]);var mn=class extends h{constructor(e={}){super(e)}get kind(){let e=this.args.kind;return e?e.toUpperCase():void 0}get actions(){return this.args.actions||[]}};mn.key="alter",mn.requiredArgs=new Set(["kind","actions"]),mn.availableArgs=new Set(["this","kind","actions","exists","only","options","cluster","notValid","check","cascade"]);var Hc=class extends h{constructor(e={}){super(e)}};Hc.key="alterSession",Hc.requiredArgs=new Set(["expressions"]),Hc.availableArgs=new Set(["expressions","unset"]);var Vc=class extends h{constructor(e={}){super(e)}};Vc.key="analyze",Vc.requiredArgs=new Set,Vc.availableArgs=new Set(["kind","this","options","mode","partition","expression","properties"]);var ku=class extends h{constructor(e={}){super(e)}};ku.key="analyzeStatistics",ku.requiredArgs=new Set(["kind"]),ku.availableArgs=new Set(["kind","option","this","expressions"]);var Uu=class extends h{constructor(e={}){super(e)}};Uu.key="analyzeHistogram",Uu.requiredArgs=new Set(["this","expressions"]),Uu.availableArgs=new Set(["this","expressions","expression","updateOptions"]);var qu=class extends h{constructor(e={}){super(e)}};qu.key="analyzeSample",qu.requiredArgs=new Set(["kind","sample"]),qu.availableArgs=new Set(["kind","sample"]);var vu=class extends h{constructor(e={}){super(e)}};vu.key="analyzeListChainedRows",vu.requiredArgs=new Set,vu.availableArgs=new Set(["expression"]);var Fu=class extends h{constructor(e={}){super(e)}};Fu.key="analyzeDelete",Fu.requiredArgs=new Set,Fu.availableArgs=new Set(["kind"]);var Mo=class extends h{constructor(e={}){super(e)}};Mo.key="analyzeWith",Mo.requiredArgs=new Set(["expressions"]),Mo.availableArgs=new Set(["expressions"]);var Bu=class extends h{constructor(e={}){super(e)}};Bu.key="analyzeValidate",Bu.requiredArgs=new Set(["kind"]),Bu.availableArgs=new Set(["kind","this","expression"]);var Lo=class extends h{constructor(e={}){super(e)}};Lo.key="analyzeColumns",Lo.requiredArgs=new Set(["this"]),Lo.availableArgs=new Set(["this"]);var Do=class extends h{constructor(e={}){super(e)}};Do.key="usingData",Do.requiredArgs=new Set(["this"]),Do.availableArgs=new Set(["this"]);var Gu=class extends h{constructor(e={}){super(e)}};Gu.key="addConstraint",Gu.requiredArgs=new Set(["expressions"]),Gu.availableArgs=new Set(["expressions"]);var $u=class extends h{constructor(e={}){super(e)}};$u.key="addPartition",$u.requiredArgs=new Set(["this"]),$u.availableArgs=new Set(["this","exists","location"]);var mS=class extends h{constructor(e={}){super(e)}};mS.key="attachOption",mS.requiredArgs=new Set(["this"]),mS.availableArgs=new Set(["this","expression"]);var Yu=class extends h{constructor(e={}){super(e)}};Yu.key="dropPartition",Yu.requiredArgs=new Set(["expressions"]),Yu.availableArgs=new Set(["expressions","exists"]);var RS=class extends h{constructor(e={}){super(e)}};RS.key="replacePartition",RS.requiredArgs=new Set(["expression","source"]),RS.availableArgs=new Set(["expression","source"]);var Se=class extends h{constructor(e={}){super(e)}get outputName(){return typeof this.args.alias=="string"?this.args.alias:_nullishCoalesce(_optionalChain([this, 'access', _806 => _806.args, 'access', _807 => _807.alias, 'optionalAccess', _808 => _808.name]), () => (""))}};Se.key="alias",Se.requiredArgs=new Set(["this"]),Se.availableArgs=new Set(["this","alias"]);var Fi=class extends h{constructor(e={}){super(e)}};Fi.key="pivotAny",Fi.requiredArgs=new Set,Fi.availableArgs=new Set(["this"]);var Rn=class extends h{constructor(e={}){super(e)}get aliases(){return _nullishCoalesce(this.args.expressions, () => ([]))}};Rn.key="aliases",Rn.requiredArgs=new Set(["this","expressions"]),Rn.availableArgs=new Set(["this","expressions"]);var Hu=class extends h{constructor(e={}){super(e)}};Hu.key="atIndex",Hu.requiredArgs=new Set(["this","expression"]),Hu.availableArgs=new Set(["this","expression"]);var Or=class extends h{constructor(e={}){super(e)}};Or.key="atTimeZone",Or.requiredArgs=new Set(["this","zone"]),Or.availableArgs=new Set(["this","zone"]);var bh=class extends h{constructor(e={}){super(e)}};bh.key="fromTimeZone",bh.requiredArgs=new Set(["this","zone"]),bh.availableArgs=new Set(["this","zone"]);var OS=class extends h{constructor(e={}){super(e)}};OS.key="formatPhrase",OS.requiredArgs=new Set(["this","format"]),OS.availableArgs=new Set(["this","format"]);var ct=class extends h{constructor(e={}){super(e)}};ct.key="distinct",ct.requiredArgs=new Set,ct.availableArgs=new Set(["expressions","on"]);var NS=class extends h{constructor(e={}){super(e)}};NS.key="forIn",NS.requiredArgs=new Set(["this","expression"]),NS.availableArgs=new Set(["this","expression"]);var IE=class IE extends h{static isVarLike(e){return e instanceof Ze||e instanceof k||e instanceof w}static initTimeArgs(e){let t=e.unit;if(t&&IE.isVarLike(t)&&!(t instanceof k&&t.parts.length!==1))e.unit=new Ze({this:(IE.UNABBREVIATED_UNIT_NAME[t.name]||t.name).toUpperCase()});else if(t instanceof Un){let s=t.args.this;s&&t.setArgKey("this",new Ze({this:s.name.toUpperCase()}))}return e}constructor(e={}){super(IE.initTimeArgs(e))}get unit(){return this.args.unit}};IE.key="timeUnit",IE.availableArgs=new Set(["unit"]),IE.UNABBREVIATED_UNIT_NAME={D:"DAY",H:"HOUR",M:"MINUTE",MS:"MILLISECOND",NS:"NANOSECOND",Q:"QUARTER",S:"SECOND",US:"MICROSECOND",W:"WEEK",Y:"YEAR"};var Re=IE,dn=class extends h{constructor(e={}){super(e)}};dn.key="ignoreNulls",dn.requiredArgs=new Set(["this"]),dn.availableArgs=new Set(["this"]);var Bi=class extends h{constructor(e={}){super(e)}};Bi.key="respectNulls",Bi.requiredArgs=new Set(["this"]),Bi.availableArgs=new Set(["this"]);var On=class extends h{constructor(e={}){super(e)}};On.key="havingMax",On.requiredArgs=new Set(["this","expression","max"]),On.availableArgs=new Set(["this","expression","max"]);var IS=class extends h{constructor(e={}){super(e)}};IS.key="translateCharacters",IS.requiredArgs=new Set(["this","expression"]),IS.availableArgs=new Set(["this","expression","withError"]);var Ph=class extends h{constructor(e={}){super(e)}};Ph.key="positionalColumn",Ph.requiredArgs=new Set(["this"]),Ph.availableArgs=new Set(["this"]);var Vu=class extends h{constructor(e={}){super(e)}};Vu.key="overflowTruncateBehavior",Vu.requiredArgs=new Set(["withCount"]),Vu.availableArgs=new Set(["this","withCount"]);var Wu=class extends h{constructor(e={}){super(e)}};Wu.key="json",Wu.requiredArgs=new Set,Wu.availableArgs=new Set(["this","with","unique"]);var Ya=class extends h{constructor(e={}){super(e)}get outputName(){let t=_optionalChain([this, 'access', _809 => _809.args, 'access', _810 => _810.expressions, 'optionalAccess', _811 => _811[this.args.expressions.length-1], 'optionalAccess', _812 => _812.args, 'access', _813 => _813.this]);return typeof t=="string"?t:""}};Ya.key="jsonPath",Ya.requiredArgs=new Set(["expressions"]),Ya.availableArgs=new Set(["expressions","escape"]);var Rs=class extends h{constructor(e={}){super(e)}};Rs.key="jsonPathPart",Rs.requiredArgs=new Set,Rs.availableArgs=new Set;var ju=class extends h{constructor(e={}){super(e)}};ju.key="formatJson",ju.requiredArgs=new Set(["this"]),ju.availableArgs=new Set(["this"]);var Ju=class extends h{constructor(e={}){super(e)}};Ju.key="jsonKeyValue",Ju.requiredArgs=new Set(["this","expression"]),Ju.availableArgs=new Set(["this","expression"]);var Xu=class extends h{constructor(e={}){super(e)}};Xu.key="jsonColumnDef",Xu.requiredArgs=new Set,Xu.availableArgs=new Set(["this","kind","path","nestedSchema","ordinality"]);var zu=class extends h{constructor(e={}){super(e)}};zu.key="jsonSchema",zu.requiredArgs=new Set(["expressions"]),zu.availableArgs=new Set(["expressions"]);var Ku=class extends h{constructor(e={}){super(e)}};Ku.key="jsonValue",Ku.requiredArgs=new Set(["this","path"]),Ku.availableArgs=new Set(["this","path","returning","onCondition"]);var Qu=class extends h{constructor(e={}){super(e)}};Qu.key="openJsonColumnDef",Qu.requiredArgs=new Set(["this","kind"]),Qu.availableArgs=new Set(["this","kind","path","asJson"]);var wh=class extends h{constructor(e={}){super(e)}};wh.key="jsonExtractQuote",wh.requiredArgs=new Set(["option"]),wh.availableArgs=new Set(["option","scalar"]);var Wc=class extends h{constructor(e={}){super(e)}};Wc.key="scopeResolution",Wc.requiredArgs=new Set(["expression"]),Wc.availableArgs=new Set(["this","expression"]);var Pi=class extends h{constructor(e={}){super(e)}};Pi.key="slice",Pi.requiredArgs=new Set,Pi.availableArgs=new Set(["this","expression","step"]);var _o=class extends h{constructor(e={}){super(e)}};_o.key="stream",_o.requiredArgs=new Set(["this"]),_o.availableArgs=new Set(["this"]);var yS=class extends h{constructor(e={}){super(e)}};yS.key="modelAttribute",yS.requiredArgs=new Set(["this","expression"]),yS.availableArgs=new Set(["this","expression"]);var CS=class extends h{constructor(e={}){super(e)}};CS.key="weekStart",CS.requiredArgs=new Set(["this"]),CS.availableArgs=new Set(["this"]);var Zu=class extends h{constructor(e={}){super(e)}};Zu.key="xmlNamespace",Zu.requiredArgs=new Set(["this"]),Zu.availableArgs=new Set(["this"]);var bS=class extends h{constructor(e={}){super(e)}};bS.key="xmlKeyValueOption",bS.requiredArgs=new Set(["this"]),bS.availableArgs=new Set(["this","expression"]);var eE=class extends h{constructor(e={}){super(e)}};eE.key="use",eE.requiredArgs=new Set,eE.availableArgs=new Set(["this","expressions","kind"]);var Ji=class extends h{constructor(e={}){super(e)}};Ji.key="when",Ji.requiredArgs=new Set(["matched","then"]),Ji.availableArgs=new Set(["matched","source","condition","then"]);var ko=class extends h{constructor(e={}){super(e)}};ko.key="whens",ko.requiredArgs=new Set(["expressions"]),ko.availableArgs=new Set(["expressions"]);var tE=class extends h{constructor(e={}){super(e)}};tE.key="semicolon",tE.requiredArgs=new Set,tE.availableArgs=new Set;var Gn=class extends h{constructor(e={}){super(e)}};Gn.key="tableColumn",Gn.requiredArgs=new Set(["this"]),Gn.availableArgs=new Set(["this"]);var Mh=class extends h{constructor(e={}){super(e)}};Mh.key="variadic",Mh.requiredArgs=new Set(["this"]),Mh.availableArgs=new Set(["this"]);var Yt=class extends bi{constructor(e={}){super(e)}};Yt.key="cte",Yt.requiredArgs=new Set(["this","alias"]),Yt.availableArgs=new Set(["this","alias","scalar","materialized","keyExpressions"]);var XT=class extends Qe{constructor(e={}){super(e)}};XT.key="bitString";var Xi=class extends Qe{constructor(e={}){super(e)}};Xi.key="hexString",Xi.availableArgs=new Set(["this","isInteger"]);var Qc=class extends Qe{constructor(e={}){super(e)}};Qc.key="byteString",Qc.availableArgs=new Set(["this","isBytes"]);var jc=class extends Qe{constructor(e={}){super(e)}};jc.key="rawString";var xg=class extends Qe{constructor(e={}){super(e)}};xg.key="unicodeString",xg.availableArgs=new Set(["this","escape"]);var k=class extends Qe{constructor(e={}){super(e)}get table(){return this.text("table")}get db(){return this.text("db")}get catalog(){return this.text("catalog")}get outputName(){return this.name}get parts(){let e=[];for(let t of["catalog","db","table","this"]){let s=this.args[t];s&&e.push(s)}return e}toDot(e={}){let{includeDots:t=!0}=e,s=this.parts,r=this.parent;if(t)for(;r instanceof me&&r.args.expression!==void 0;)s.push(r.args.expression),r=r.parent;return 1<s.length?me.build(s.map(i=>i.copy())):s[0]}};k.key="column",k.requiredArgs=new Set(["this"]),k.availableArgs=new Set(["this","table","db","catalog","joinMark"]);var Ml=class extends k{constructor(e={}){super(e)}};Ml.key="pseudocolumn";var zT=class extends qe{constructor(e={}){super(e)}};zT.key="autoIncrementColumnConstraint";var dc=class extends ki{constructor(e={}){super(e)}};dc.key="zeroFillColumnConstraint",dc.requiredArgs=new Set,dc.availableArgs=new Set;var sE=class extends qe{constructor(e={}){super(e)}};sE.key="periodForSystemTimeConstraint",sE.requiredArgs=new Set(["this","expression"]),sE.availableArgs=new Set(["this","expression"]);var Gi=class extends qe{constructor(e={}){super(e)}};Gi.key="caseSpecificColumnConstraint",Gi.requiredArgs=new Set(["not"]),Gi.availableArgs=new Set(["not"]);var rE=class extends qe{constructor(e={}){super(e)}};rE.key="characterSetColumnConstraint";var Tg=class extends qe{constructor(e={}){super(e)}};Tg.key="checkColumnConstraint",Tg.availableArgs=new Set(["this","enforced"]);var Uo=class extends qe{constructor(e={}){super(e)}};Uo.key="clusteredColumnConstraint";var nE=class extends qe{constructor(e={}){super(e)}};nE.key="collateColumnConstraint";var iE=class extends qe{constructor(e={}){super(e)}};iE.key="commentColumnConstraint";var kl=class extends qe{constructor(e={}){super(e)}};kl.key="compressColumnConstraint",kl.requiredArgs=new Set;var aE=class extends qe{constructor(e={}){super(e)}};aE.key="dateFormatColumnConstraint";var oE=class extends qe{constructor(e={}){super(e)}};oE.key="defaultColumnConstraint";var cE=class extends qe{constructor(e={}){super(e)}};cE.key="encodeColumnConstraint";var pE=class extends qe{constructor(e={}){super(e)}};pE.key="excludeColumnConstraint";var Zc=class extends qe{constructor(e={}){super(e)}};Zc.key="ephemeralColumnConstraint",Zc.requiredArgs=new Set;var Ui=class extends qe{constructor(e={}){super(e)}};Ui.key="generatedAsIdentityColumnConstraint",Ui.availableArgs=new Set(["this","expression","onNull","start","increment","minvalue","maxvalue","cycle","order"]);var lE=class extends qe{constructor(e={}){super(e)}};lE.key="generatedAsRowColumnConstraint",lE.requiredArgs=new Set,lE.availableArgs=new Set(["start","hidden"]);var Lh=class extends qe{constructor(e={}){super(e)}};Lh.key="indexColumnConstraint",Lh.requiredArgs=new Set,Lh.availableArgs=new Set(["this","expressions","kind","indexType","options","expression","granularity"]);var uE=class extends qe{constructor(e={}){super(e)}};uE.key="inlineLengthColumnConstraint";var qo=class extends qe{constructor(e={}){super(e)}};qo.key="nonClusteredColumnConstraint";var si=class extends qe{constructor(e={}){super(e)}};si.key="notForReplicationColumnConstraint",si.requiredArgs=new Set,si.availableArgs=new Set;var UO=class extends qe{constructor(e={}){super(e)}};UO.key="maskingPolicyColumnConstraint",UO.availableArgs=new Set(["this","expressions"]);var $i=class extends qe{constructor(e={}){super(e)}};$i.key="notNullColumnConstraint",$i.requiredArgs=new Set,$i.availableArgs=new Set(["allowNull"]);var EE=class extends qe{constructor(e={}){super(e)}};EE.key="onUpdateColumnConstraint";var vo=class extends qe{constructor(e={}){super(e)}};vo.key="primaryKeyColumnConstraint",vo.requiredArgs=new Set,vo.availableArgs=new Set(["desc","options"]);var hE=class extends qe{constructor(e={}){super(e)}};hE.key="titleColumnConstraint";var Fo=class extends qe{constructor(e={}){super(e)}};Fo.key="uniqueColumnConstraint",Fo.requiredArgs=new Set,Fo.availableArgs=new Set(["this","indexType","onConflict","nulls","options"]);var Bo=class extends qe{constructor(e={}){super(e)}};Bo.key="uppercaseColumnConstraint",Bo.requiredArgs=new Set,Bo.availableArgs=new Set;var gE=class extends qe{constructor(e={}){super(e)}};gE.key="pathColumnConstraint";var CR=class extends qe{constructor(e={}){super(e)}};CR.key="projectionPolicyColumnConstraint";var An=class extends qe{constructor(e={}){super(e)}};An.key="computedColumnConstraint",An.availableArgs=new Set(["this","persisted","notNull","dataType"]);var dE=class extends qe{constructor(e={}){super(e)}};dE.key="inOutColumnConstraint",dE.requiredArgs=new Set,dE.availableArgs=new Set(["input","output","variadic"]);var AE=class extends Lr{constructor(e={}){super(e)}};AE.key="copy",AE.requiredArgs=new Set(["this","kind"]),AE.availableArgs=new Set(["this","kind","files","credentials","format","params"]);var Ss=class extends Q(ln,Lr,h){constructor(e={}){super(e)}with(e,t,s={}){let{recursive:r,materialized:i,append:a,dialect:o,copy:c,...p}=s;return vD({instance:this,alias:e,as:t,recursive:r,materialized:i,append:a,dialect:o,copy:c,...p})}};Ss.key="insert",Ss.requiredArgs=new Set,Ss.availableArgs=new Set(["hint","with","isFunction","this","expression","conflict","returning","overwrite","exists","alternative","where","ignore","byName","stored","partition","settings","source","default"]);var yE=class yE extends Qe{static number(e){let t=new yE({this:String(e),isString:!1}),s=typeof e=="number"?e:parseFloat(String(e));return!isNaN(s)&&s<0&&(t=new yE({this:String(Math.abs(s)),isString:!1}),t=new Ps({this:t})),t}static string(e){return new yE({this:String(e),isString:!0})}constructor(e={}){super(e)}get outputName(){return this.name}toValue(){if(this.isNumber){let e=parseFloat(this.args.this);if(!isNaN(e))return e}return this.args.this}};yE.key="literal",yE.requiredArgs=new Set(["this","isString"]),yE.availableArgs=new Set(["this","isString"]);var w=yE,qi=class extends ke{constructor(e={}){super(e)}};qi.key="cluster";var KT=class extends ke{constructor(e={}){super(e)}};KT.key="distribute";var Ul=class extends ke{constructor(e={}){super(e)}};Ul.key="sort";var zi=class extends U{constructor(e={}){super(e)}};zi.key="algorithmProperty",zi.requiredArgs=new Set(["this"]),zi.availableArgs=new Set(["this"]);var Ki=class extends U{constructor(e={}){super(e)}};Ki.key="autoIncrementProperty",Ki.requiredArgs=new Set(["this"]),Ki.availableArgs=new Set(["this"]);var Qi=class extends U{constructor(e={}){super(e)}};Qi.key="autoRefreshProperty",Qi.requiredArgs=new Set(["this"]),Qi.availableArgs=new Set(["this"]);var Zi=class extends U{constructor(e={}){super(e)}};Zi.key="backupProperty",Zi.requiredArgs=new Set(["this"]),Zi.availableArgs=new Set(["this"]);var PS=class extends U{constructor(e={}){super(e)}};PS.key="buildProperty",PS.requiredArgs=new Set(["this"]),PS.availableArgs=new Set(["this"]);var Go=class extends U{constructor(e={}){super(e)}};Go.key="blockCompressionProperty",Go.requiredArgs=new Set,Go.availableArgs=new Set(["autotemp","always","default","manual","never"]);var ri=class extends U{constructor(e={}){super(e)}get value(){return this.args.value}};ri.key="characterSetProperty",ri.requiredArgs=new Set(["this","default"]),ri.availableArgs=new Set(["this","default"]);var $o=class extends U{constructor(e={}){super(e)}};$o.key="checksumProperty",$o.requiredArgs=new Set,$o.availableArgs=new Set(["on","default"]);var ea=class extends U{constructor(e={}){super(e)}get value(){return this.args.value}};ea.key="collateProperty",ea.requiredArgs=new Set(["this"]),ea.availableArgs=new Set(["this","default"]);var ta=class extends U{constructor(e={}){super(e)}};ta.key="copyGrantsProperty",ta.requiredArgs=new Set,ta.availableArgs=new Set;var Yo=class extends U{constructor(e={}){super(e)}};Yo.key="dataBlocksizeProperty",Yo.requiredArgs=new Set,Yo.availableArgs=new Set(["size","units","minimum","maximum","default"]);var Ho=class extends U{constructor(e={}){super(e)}};Ho.key="dataDeletionProperty",Ho.requiredArgs=new Set(["on"]),Ho.availableArgs=new Set(["on","filterColumn","retentionPeriod"]);var sa=class extends U{constructor(e={}){super(e)}};sa.key="definerProperty",sa.requiredArgs=new Set(["this"]),sa.availableArgs=new Set(["this"]);var ra=class extends U{constructor(e={}){super(e)}};ra.key="distKeyProperty",ra.requiredArgs=new Set(["this"]),ra.availableArgs=new Set(["this"]);var na=class extends U{constructor(e={}){super(e)}get value(){return this.args.value}};na.key="distributedByProperty",na.requiredArgs=new Set(["kind"]),na.availableArgs=new Set(["expressions","kind","buckets","order"]);var ia=class extends U{constructor(e={}){super(e)}};ia.key="distStyleProperty",ia.requiredArgs=new Set(["this"]),ia.availableArgs=new Set(["this"]);var Vo=class extends U{constructor(e={}){super(e)}};Vo.key="duplicateKeyProperty",Vo.requiredArgs=new Set(["expressions"]),Vo.availableArgs=new Set(["expressions"]);var aa=class extends U{constructor(e={}){super(e)}};aa.key="engineProperty",aa.requiredArgs=new Set(["this"]),aa.availableArgs=new Set(["this"]);var oa=class extends U{constructor(e={}){super(e)}};oa.key="heapProperty",oa.requiredArgs=new Set,oa.availableArgs=new Set;var ca=class extends U{constructor(e={}){super(e)}};ca.key="toTableProperty",ca.requiredArgs=new Set(["this"]),ca.availableArgs=new Set(["this"]);var fn=class extends U{constructor(e={}){super(e)}};fn.key="executeAsProperty",fn.requiredArgs=new Set(["this"]),fn.availableArgs=new Set(["this"]);var Nn=class extends U{constructor(e={}){super(e)}};Nn.key="externalProperty",Nn.requiredArgs=new Set,Nn.availableArgs=new Set(["this"]);var Wo=class extends U{constructor(e={}){super(e)}};Wo.key="fallbackProperty",Wo.requiredArgs=new Set(["no"]),Wo.availableArgs=new Set(["no","protection"]);var $s=class extends U{constructor(e={}){super(e)}get value(){return this.args.value}};$s.key="fileFormatProperty",$s.requiredArgs=new Set,$s.availableArgs=new Set(["this","expressions","hiveFormat"]);var Op=class extends U{constructor(e={}){super(e)}};Op.key="credentialsProperty",Op.requiredArgs=new Set(["expressions"]),Op.availableArgs=new Set(["expressions"]);var jo=class extends U{constructor(e={}){super(e)}};jo.key="freespaceProperty",jo.requiredArgs=new Set(["this"]),jo.availableArgs=new Set(["this","percent"]);var pa=class extends U{constructor(e={}){super(e)}};pa.key="globalProperty",pa.requiredArgs=new Set,pa.availableArgs=new Set;var la=class extends U{constructor(e={}){super(e)}};la.key="icebergProperty",la.requiredArgs=new Set,la.availableArgs=new Set;var ua=class extends U{constructor(e={}){super(e)}};ua.key="inheritsProperty",ua.requiredArgs=new Set(["expressions"]),ua.availableArgs=new Set(["expressions"]);var Ea=class extends U{constructor(e={}){super(e)}};Ea.key="inputModelProperty",Ea.requiredArgs=new Set(["this"]),Ea.availableArgs=new Set(["this"]);var ha=class extends U{constructor(e={}){super(e)}};ha.key="outputModelProperty",ha.requiredArgs=new Set(["this"]),ha.availableArgs=new Set(["this"]);var Jo=class extends U{constructor(e={}){super(e)}};Jo.key="isolatedLoadingProperty",Jo.requiredArgs=new Set,Jo.availableArgs=new Set(["no","concurrent","target"]);var Xo=class extends U{constructor(e={}){super(e)}};Xo.key="journalProperty",Xo.requiredArgs=new Set,Xo.availableArgs=new Set(["no","dual","before","local","after"]);var ni=class extends U{constructor(e={}){super(e)}};ni.key="languageProperty",ni.requiredArgs=new Set(["this"]),ni.availableArgs=new Set(["this"]);var ga=class extends U{constructor(e={}){super(e)}};ga.key="enviromentProperty",ga.requiredArgs=new Set(["expressions"]),ga.availableArgs=new Set(["expressions"]);var da=class extends U{constructor(e={}){super(e)}};da.key="clusteredByProperty",da.requiredArgs=new Set(["expressions","buckets"]),da.availableArgs=new Set(["expressions","sortedBy","buckets"]);var zo=class extends U{constructor(e={}){super(e)}};zo.key="dictProperty",zo.requiredArgs=new Set(["this","kind"]),zo.availableArgs=new Set(["this","kind","settings"]);var QT=class extends U{constructor(e={}){super(e)}};QT.key="dictSubProperty";var Ko=class extends U{constructor(e={}){super(e)}};Ko.key="dictRange",Ko.requiredArgs=new Set(["this","min","max"]),Ko.availableArgs=new Set(["this","min","max"]);var Aa=class extends U{constructor(e={}){super(e)}};Aa.key="dynamicProperty",Aa.requiredArgs=new Set,Aa.availableArgs=new Set;var wS=class extends U{constructor(e={}){super(e)}};wS.key="onCluster",wS.requiredArgs=new Set(["this"]),wS.availableArgs=new Set(["this"]);var fa=class extends U{constructor(e={}){super(e)}};fa.key="emptyProperty",fa.requiredArgs=new Set,fa.availableArgs=new Set;var Qo=class extends U{constructor(e={}){super(e)}};Qo.key="likeProperty",Qo.requiredArgs=new Set(["this"]),Qo.availableArgs=new Set(["this","expressions"]);var Es=class extends U{constructor(e={}){super(e)}};Es.key="locationProperty",Es.requiredArgs=new Set(["this"]),Es.availableArgs=new Set(["this"]);var Ha=class extends U{constructor(e={}){super(e)}};Ha.key="lockProperty",Ha.requiredArgs=new Set(["this"]),Ha.availableArgs=new Set(["this"]);var Zo=class extends U{constructor(e={}){super(e)}get value(){return this.args.value}};Zo.key="lockingProperty",Zo.requiredArgs=new Set(["kind","lockType"]),Zo.availableArgs=new Set(["this","kind","forOrIn","lockType","override"]);var xa=class extends U{constructor(e={}){super(e)}};xa.key="logProperty",xa.requiredArgs=new Set(["no"]),xa.availableArgs=new Set(["no"]);var Ta=class extends U{constructor(e={}){super(e)}};Ta.key="materializedProperty",Ta.requiredArgs=new Set,Ta.availableArgs=new Set(["this"]);var Yi=class extends U{constructor(e={}){super(e)}get value(){return this.args.value}};Yi.key="mergeBlockRatioProperty",Yi.requiredArgs=new Set,Yi.availableArgs=new Set(["this","no","default","percent"]);var Sa=class extends U{constructor(e={}){super(e)}};Sa.key="noPrimaryIndexProperty",Sa.requiredArgs=new Set,Sa.availableArgs=new Set;var Br=class extends U{constructor(e={}){super(e)}};Br.key="onProperty",Br.requiredArgs=new Set(["this"]),Br.availableArgs=new Set(["this"]);var Xn=class extends U{constructor(e={}){super(e)}};Xn.key="onCommitProperty",Xn.requiredArgs=new Set,Xn.availableArgs=new Set(["delete"]);var Bt=class extends U{constructor(e={}){super(e)}};Bt.key="partitionedByProperty",Bt.requiredArgs=new Set(["this"]),Bt.availableArgs=new Set(["this"]);var ii=class extends U{constructor(e={}){super(e)}};ii.key="partitionedByBucket",ii.requiredArgs=new Set(["this","expression"]),ii.availableArgs=new Set(["this","expression"]);var ai=class extends U{constructor(e={}){super(e)}};ai.key="partitionByTruncate",ai.requiredArgs=new Set(["this","expression"]),ai.availableArgs=new Set(["this","expression"]);var Ac=class extends U{constructor(e={}){super(e)}};Ac.key="partitionByRangeProperty",Ac.requiredArgs=new Set(["partitionExpressions","createExpressions"]),Ac.availableArgs=new Set(["partitionExpressions","createExpressions"]);var Dh=class extends U{constructor(e={}){super(e)}};Dh.key="rollupProperty",Dh.requiredArgs=new Set(["expressions"]),Dh.availableArgs=new Set(["expressions"]);var fc=class extends U{constructor(e={}){super(e)}};fc.key="partitionByListProperty",fc.requiredArgs=new Set(["partitionExpressions","createExpressions"]),fc.availableArgs=new Set(["partitionExpressions","createExpressions"]);var _h=class extends U{constructor(e={}){super(e)}};_h.key="refreshTriggerProperty",_h.requiredArgs=new Set,_h.availableArgs=new Set(["method","kind","every","unit","starts"]);var MS=class extends U{constructor(e={}){super(e)}};MS.key="uniqueKeyProperty",MS.requiredArgs=new Set(["expressions"]),MS.availableArgs=new Set(["expressions"]);var ec=class extends U{constructor(e={}){super(e)}};ec.key="partitionedOfProperty",ec.requiredArgs=new Set(["this","expression"]),ec.availableArgs=new Set(["this","expression"]);var ma=class extends U{constructor(e={}){super(e)}};ma.key="streamingTableProperty",ma.requiredArgs=new Set,ma.availableArgs=new Set;var Ra=class extends U{constructor(e={}){super(e)}};Ra.key="remoteWithConnectionModelProperty",Ra.requiredArgs=new Set(["this"]),Ra.availableArgs=new Set(["this"]);var oi=class extends U{constructor(e={}){super(e)}};oi.key="returnsProperty",oi.requiredArgs=new Set,oi.availableArgs=new Set(["this","isTable","table","null"]);var Oa=class extends U{constructor(e={}){super(e)}};Oa.key="strictProperty",Oa.requiredArgs=new Set,Oa.availableArgs=new Set;var Na=class extends U{constructor(e={}){super(e)}};Na.key="rowFormatProperty",Na.requiredArgs=new Set(["this"]),Na.availableArgs=new Set(["this"]);var tc=class extends U{constructor(e={}){super(e)}};tc.key="rowFormatDelimitedProperty",tc.requiredArgs=new Set,tc.availableArgs=new Set(["fields","escaped","collectionItems","mapKeys","lines","null","serde"]);var sc=class extends U{constructor(e={}){super(e)}};sc.key="rowFormatSerdeProperty",sc.requiredArgs=new Set(["this"]),sc.availableArgs=new Set(["this","serdeProperties"]);var Ia=class extends U{constructor(e={}){super(e)}};Ia.key="sampleProperty",Ia.requiredArgs=new Set(["this"]),Ia.availableArgs=new Set(["this"]);var ya=class extends U{constructor(e={}){super(e)}};ya.key="securityProperty",ya.requiredArgs=new Set(["this"]),ya.availableArgs=new Set(["this"]);var Nr=class extends U{constructor(e={}){super(e)}};Nr.key="schemaCommentProperty",Nr.requiredArgs=new Set(["this"]),Nr.availableArgs=new Set(["this"]);var ci=class extends U{constructor(e={}){super(e)}};ci.key="serdeProperties",ci.requiredArgs=new Set(["expressions"]),ci.availableArgs=new Set(["expressions","with"]);var zn=class extends U{constructor(e={}){super(e)}};zn.key="setProperty",zn.requiredArgs=new Set(["multi"]),zn.availableArgs=new Set(["multi"]);var Ca=class extends U{constructor(e={}){super(e)}};Ca.key="sharingProperty",Ca.requiredArgs=new Set,Ca.availableArgs=new Set(["this"]);var Np=class extends U{constructor(e={}){super(e)}};Np.key="setConfigProperty",Np.requiredArgs=new Set(["this"]),Np.availableArgs=new Set(["this"]);var ba=class extends U{constructor(e={}){super(e)}};ba.key="settingsProperty",ba.requiredArgs=new Set(["expressions"]),ba.availableArgs=new Set(["expressions"]);var Pa=class extends U{constructor(e={}){super(e)}};Pa.key="sortKeyProperty",Pa.requiredArgs=new Set(["this"]),Pa.availableArgs=new Set(["this","compound"]);var qr=class extends U{constructor(e={}){super(e)}};qr.key="sqlReadWriteProperty",qr.requiredArgs=new Set(["this"]),qr.availableArgs=new Set(["this"]);var wa=class extends U{constructor(e={}){super(e)}};wa.key="sqlSecurityProperty",wa.requiredArgs=new Set(["this"]),wa.availableArgs=new Set(["this"]);var vr=class extends U{constructor(e={}){super(e)}};vr.key="stabilityProperty",vr.requiredArgs=new Set(["this"]),vr.availableArgs=new Set(["this"]);var pi=class extends U{constructor(e={}){super(e)}};pi.key="storageHandlerProperty",pi.requiredArgs=new Set(["this"]),pi.availableArgs=new Set(["this"]);var Gr=class extends U{constructor(e={}){super(e)}};Gr.key="temporaryProperty",Gr.requiredArgs=new Set,Gr.availableArgs=new Set(["this"]);var Ma=class extends U{constructor(e={}){super(e)}};Ma.key="secureProperty",Ma.requiredArgs=new Set,Ma.availableArgs=new Set;var Ip=class extends Q(qe,U){constructor(e={}){super(e)}};Ip.key="tags",Ip.requiredArgs=new Set(["expressions"]),Ip.availableArgs=new Set(["expressions"]);var La=class extends U{constructor(e={}){super(e)}};La.key="transformModelProperty",La.requiredArgs=new Set(["expressions"]),La.availableArgs=new Set(["expressions"]);var In=class extends U{constructor(e={}){super(e)}};In.key="transientProperty",In.requiredArgs=new Set,In.availableArgs=new Set(["this"]);var Da=class extends U{constructor(e={}){super(e)}};Da.key="unloggedProperty",Da.requiredArgs=new Set,Da.availableArgs=new Set;var yp=class extends U{constructor(e={}){super(e)}};yp.key="usingTemplateProperty",yp.requiredArgs=new Set(["this"]),yp.availableArgs=new Set(["this"]);var _a=class extends U{constructor(e={}){super(e)}};_a.key="viewAttributeProperty",_a.requiredArgs=new Set(["this"]),_a.availableArgs=new Set(["this"]);var Vs=class extends U{constructor(e={}){super(e)}};Vs.key="volatileProperty",Vs.requiredArgs=new Set,Vs.availableArgs=new Set(["this"]);var li=class extends U{constructor(e={}){super(e)}};li.key="withDataProperty",li.requiredArgs=new Set(["no"]),li.availableArgs=new Set(["no","statistics"]);var ka=class extends U{constructor(e={}){super(e)}};ka.key="withJournalTableProperty",ka.requiredArgs=new Set(["this"]),ka.availableArgs=new Set(["this"]);var Ua=class extends U{constructor(e={}){super(e)}};Ua.key="withSchemaBindingProperty",Ua.requiredArgs=new Set(["this"]),Ua.availableArgs=new Set(["this"]);var rc=class extends U{constructor(e={}){super(e)}};rc.key="withSystemVersioningProperty",rc.requiredArgs=new Set(["with"]),rc.availableArgs=new Set(["on","this","dataConsistency","retentionPeriod","with"]);var qa=class extends U{constructor(e={}){super(e)}};qa.key="withProcedureOptions",qa.requiredArgs=new Set(["expressions"]),qa.availableArgs=new Set(["expressions"]);var Cp=class extends U{constructor(e={}){super(e)}};Cp.key="encodeProperty",Cp.requiredArgs=new Set(["this"]),Cp.availableArgs=new Set(["this","properties","key"]);var bp=class extends U{constructor(e={}){super(e)}};bp.key="includeProperty",bp.requiredArgs=new Set(["this"]),bp.availableArgs=new Set(["this","alias","columnDef"]);var Pp=class extends U{constructor(e={}){super(e)}};Pp.key="forceProperty",Pp.requiredArgs=new Set,Pp.availableArgs=new Set;var hc=class hc extends h{constructor(e={}){super(e)}static fromDict(e){let t=[];for(let[s,r]of Object.entries(e)){let i=hc.NAME_TO_PROPERTY[s.toUpperCase()];i?t.push(new i({this:ts(r)})):t.push(new U({this:w.string(s),value:ts(r)}))}return new hc({expressions:t})}};hc.key="properties",hc.requiredArgs=new Set(["expressions"]),hc.availableArgs=new Set(["expressions"]),hc.NAME_TO_PROPERTY={ALGORITHM:zi,AUTO_INCREMENT:Ki,"CHARACTER SET":ri,CLUSTERED_BY:da,COLLATE:ea,COMMENT:Nr,CREDENTIALS:Op,DEFINER:sa,DISTKEY:ra,DISTRIBUTED_BY:na,DISTSTYLE:ia,ENGINE:aa,"EXECUTE AS":fn,FORMAT:$s,LANGUAGE:ni,LOCATION:Es,LOCK:Ha,PARTITIONED_BY:Bt,RETURNS:oi,ROW_FORMAT:Na,SORTKEY:Pa,ENCODE:Cp,INCLUDE:bp},hc.PROPERTY_TO_NAME=Object.fromEntries(Object.entries(hc.NAME_TO_PROPERTY).map(([e,t])=>[t.key,e]));var mt=hc,_g=class _g extends ce{constructor(e={}){super(e)}select(e,t={}){let{copy:s=!0,...r}=t,i=Array.from(pe(e)),a=bt(this,s),o=a.args.this;ue(o,ce),_optionalChain([Pt, 'call', _814 => _814(o.unnest(),ce), 'optionalAccess', _815 => _815.select, 'call', _816 => _816(i,{...r,copy:!1})]);let c=a.args.expression;return ue(c,ce),_optionalChain([Pt, 'call', _817 => _817(c.unnest(),ce), 'optionalAccess', _818 => _818.select, 'call', _819 => _819(i,{...r,copy:!1,append:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _820 => _820.append]), () => (!0))})]),a}get namedSelects(){let e=this;for(;e instanceof _g;){let t=_optionalChain([e, 'access', _821 => _821.args, 'access', _822 => _822.this, 'optionalAccess', _823 => _823.unnest, 'call', _824 => _824()]);ue(t,ce),e=t}return e.namedSelects}get isStar(){let e=_optionalChain([this, 'access', _825 => _825.args, 'access', _826 => _826.this, 'optionalAccess', _827 => _827.isStar]),t=_optionalChain([this, 'access', _828 => _828.args, 'access', _829 => _829.expression, 'optionalAccess', _830 => _830.isStar]);return e||t||!1}get selects(){let e=this;for(;e instanceof _g;){let t=_optionalChain([e, 'access', _831 => _831.args, 'access', _832 => _832.this, 'optionalAccess', _833 => _833.unnest, 'call', _834 => _834()]);ue(t,ce),e=t}return e.selects}get left(){return this.args.this}get right(){return this.args.expression}get kind(){return this.args.kind}get side(){return this.text("side").toUpperCase()}};_g.key="setOperation",_g.requiredArgs=new Set(["this","expression"]),_g.availableArgs=new Set(["with","this","expression","distinct","byName","side","kind","on","match","laterals","joins","connect","pivots","prewhere","where","group","having","qualify","windows","distribute","sort","cluster","order","limit","offset","locks","sample","settings","format","options"]);var be=_g,sr=class extends Lr{constructor(e={}){super(e)}table(e,t={}){let{dialect:s,copy:r=!0}=t;return OT(e,{instance:this,arg:"this",into:V,prefix:void 0,dialect:s,copy:r})}set(e,t={}){let{append:s=!0,dialect:r,copy:i=!0}=t,a=Array.from(pe(e));return Dg(a,{instance:this,arg:"expressions",append:s,into:h,prefix:void 0,dialect:r,copy:i})}where(e,t={}){let{append:s=!0,dialect:r,copy:i=!0}=t;return MR(e,{instance:this,arg:"where",append:s,into:at,dialect:r,copy:i})}from(e,t={}){let{dialect:s,copy:r=!0}=t;return e?OT(e,{instance:this,arg:"from",into:Ge,prefix:"FROM",dialect:s,copy:r}):this}with(e,t,s={}){let{recursive:r=!1,append:i=!0,copy:a=!0,...o}=s;return vD({instance:this,alias:e,as:t,...o,recursive:r,append:i,copy:a})}};sr.key="update",sr.requiredArgs=new Set,sr.availableArgs=new Set(["with","this","expressions","from","where","returning","order","limit","options"]);var kS=class kS extends ce{constructor(e={}){super(e)}get namedSelects(){let e=[];for(let t of this.args.expressions||[])t.aliasOrName?e.push(t.outputName):t instanceof Rn&&e.push(...t.aliases.map(s=>s.name));return e}get isStar(){return _nullishCoalesce(_optionalChain([this, 'access', _835 => _835.args, 'access', _836 => _836.expressions, 'optionalAccess', _837 => _837.some, 'call', _838 => _838(e=>typeof e=="object"&&"isStar"in e&&e.isStar)]), () => (!1))}get selects(){return this.args.expressions||[]}from(e,t={}){let{dialect:s,copy:r=!0,...i}=t;return OT(e,{...i,instance:this,arg:"from",into:Ge,prefix:"FROM",dialect:s,copy:r})}groupBy(e,t={}){let{append:s=!0,dialect:r,copy:i=!0,...a}=t,o=Array.from(pe(e));return o.length===0?i?this.copy():this:_S(o,{...a,instance:this,arg:"group",append:s,copy:i,prefix:"GROUP BY",into:Ys,dialect:r})}sortBy(e,t={}){let{append:s=!0,dialect:r,copy:i=!0,...a}=t;return _S(e,{...a,instance:this,arg:"sort",append:s,copy:i,prefix:"SORT BY",into:Ul,dialect:r})}clusterBy(e,t={}){let{append:s=!0,dialect:r,copy:i=!0,...a}=t;return _S(e,{...a,instance:this,arg:"cluster",append:s,copy:i,prefix:"CLUSTER BY",into:qi,dialect:r})}having(e,t={}){let{append:s=!0,dialect:r=void 0,copy:i=!0,...a}=t;return MR(e,{instance:this,arg:"having",append:s,into:$t,dialect:r,copy:i,...a})}orderBy(e,t={}){let{append:s=!0,dialect:r=void 0,copy:i=!0,...a}=t;return _S(e,{instance:this,arg:"order",append:s,copy:i,prefix:"ORDER BY",into:ke,dialect:r,...a})}select(e,t={}){let{append:s=!0,dialect:r,copy:i=!0,...a}=t;return Dg(e,{instance:this,arg:"expressions",append:s,dialect:r,into:h,copy:i,...a})}lateral(e,t={}){let{append:s=!0,dialect:r,copy:i=!0,...a}=t;return Dg(e,{...a,instance:this,arg:"laterals",append:s,into:kt,prefix:"LATERAL VIEW",dialect:r,copy:i})}join(e,t={}){let{on:s,using:r,append:i=!0,joinType:a,joinAlias:o,dialect:c,copy:p=!0,...u}=t,E={dialect:c},g;try{g=ne(e,{...E,into:z,prefix:"JOIN"})}catch (e9){try{g=ne(e,{...E,into:z})}catch (e10){g=ne(e,{...E})}}let A=g instanceof z?g:new z({this:g});A.args.this instanceof kS&&_optionalChain([A, 'access', _839 => _839.args, 'access', _840 => _840.this, 'optionalAccess', _841 => _841.replace, 'call', _842 => _842(_optionalChain([A, 'access', _843 => _843.args, 'access', _844 => _844.this, 'optionalAccess', _845 => _845.subquery, 'call', _846 => _846()]))]);let x={left:"left",right:"right",full:"full"};if(a){let m=_nullishCoalesce(x[a], () => (a)),N=ne(m,{...E,into:"JOIN_TYPE"});N.args.method&&A.setArgKey("method",N.args.method),N.args.side&&A.setArgKey("side",N.args.side),N.args.kind&&A.setArgKey("kind",N.args.kind)}if(s){let m=nt(Array.from(pe(s)),{dialect:c,copy:p});A.setArgKey("on",m)}return r&&(A=Dg(Array.from(pe(r)),{instance:A,arg:"using",append:i,copy:p,into:G})),o&&A.setArgKey("this",oe(A.args.this,o,{table:!0})),Dg([A],{instance:this,arg:"joins",append:i,copy:p})}window(e,t={}){let{append:s=!0,dialect:r,copy:i=!0,...a}=t;return Dg(e,{...a,instance:this,arg:"windows",append:s,into:Fe,dialect:r,copy:i})}qualify(e,t={}){let{append:s=!0,dialect:r,copy:i=!0,...a}=t;return MR(e,{...a,instance:this,arg:"qualify",append:s,into:un,dialect:r,copy:i})}distinct(e,t={}){let{distinct:s=!0,copy:r=!0,...i}=t,a=bt(this,r),c=(e?e.some(u=>u===!1):!1)?!1:s,p=e?e.filter(u=>u!==void 0&&u!==!1&&u!==!0):[];if(0<p.length){let u=p.map(g=>ne(g,{copy:r,into:h})),E=new Mt({expressions:u});a.setArgKey("distinct",c?new ct({on:E}):void 0)}else a.setArgKey("distinct",c?new ct({}):void 0);return a}ctas(e,t={}){let{properties:s,dialect:r,copy:i=!0}=t,a=bt(this,i),o=ne((e instanceof h,e),{dialect:r,into:V}),c;return s&&(c=mt.fromDict(s)),new us({this:o,kind:"table",expression:a,properties:c})}lock(e={}){let{update:t=!0,copy:s=!0}=e,r=bt(this,s);return r.setArgKey("locks",[new Kc({update:new w({this:String(Number(t)),isString:!1})})]),r}hint(e,t={}){let{dialect:s,copy:r=!0}=t,a=(e!==void 0?Array.from(pe(e)):[]).map(c=>ne(c,{dialect:s,into:h})),o=bt(this,r);return o.setArgKey("hint",new Dr({expressions:a})),o}};kS.key="select",kS.requiredArgs=new Set,kS.availableArgs=new Set(["with","kind","expressions","hint","distinct","into","from","operationModifiers","exclude","match","laterals","joins","connect","pivots","prewhere","where","group","having","qualify","windows","distribute","sort","cluster","order","limit","offset","locks","sample","settings","format","options","for"]);var $=kS,kg=class kg extends Q(bi,ce){constructor(e={}){super(e)}unnest(){let e=this;for(;e instanceof kg;){let t=e.args.this;if(!t||(e=t,e===this))break}return e}unwrap(){let e=this;for(;e.sameParent&&e.isWrapper;){let t=e.parent;if(!(t instanceof kg))break;e=t}return e}select(e,t={}){let{copy:s=!0,...r}=t,i=bt(this,s),a=_optionalChain([i, 'optionalAccess', _847 => _847.unnest, 'call', _848 => _848()]);return a instanceof $&&a.select(e,{...r,copy:!1}),i}get isWrapper(){return Object.entries(this.args).every(([e,t])=>e==="this"||t===void 0)}get isStar(){let e=this.args.this;return e?e.isStar:!1}get outputName(){return this.alias}};kg.key="subquery",kg.requiredArgs=new Set(["this"]),kg.availableArgs=new Set(["this","alias","with","match","laterals","joins","connect","pivots","prewhere","where","group","having","qualify","windows","distribute","sort","cluster","order","limit","offset","locks","sample","settings","format","options"]);var ae=kg,Fe=class extends Qe{constructor(e={}){super(e)}};Fe.key="window",Fe.requiredArgs=new Set(["this"]),Fe.availableArgs=new Set(["this","partitionBy","order","spec","alias","over","first"]);var ep=class extends Qe{constructor(e={}){super(e)}};ep.key="parameter",ep.availableArgs=new Set(["this","expression"]);var Sg=class extends Qe{constructor(e={}){super(e)}};Sg.key="sessionParameter",Sg.availableArgs=new Set(["this","kind"]);var rr=class extends Qe{constructor(e={}){super(e)}get name(){return(this.args.this instanceof h?this.args.this.name:this.args.this)||"?"}};rr.key="placeholder",rr.requiredArgs=new Set,rr.availableArgs=new Set(["this","kind","widget","jdbc"]);var Qt=class extends Qe{constructor(e={}){super(e)}get name(){return"NULL"}toValue(){}};Qt.key="null",Qt.requiredArgs=new Set,Qt.availableArgs=new Set;var Et=class extends Qe{constructor(e={}){super(e)}toValue(){return!!this.args.this}};Et.key="boolean";var mg=class extends C{constructor(e={}){super(e)}};mg.key="pseudoType",mg.availableArgs=new Set(["this"]);var Rg=class extends C{constructor(e={}){super(e)}};Rg.key="objectIdentifier",Rg.availableArgs=new Set(["this"]);var Y=class extends Qe{constructor(e={}){super(e)}get left(){return this.args.this}get right(){return this.args.expression}};Y.key="binary",Y.requiredArgs=new Set(["this","expression"]),Y.availableArgs=new Set(["this","expression"]);var Zs=class extends Qe{constructor(e={}){super(e)}};Zs.key="unary",Zs.requiredArgs=new Set(["this"]),Zs.availableArgs=new Set(["this"]);var ZT=class extends Se{constructor(e={}){super(e)}};ZT.key="pivotAlias";var fs=class extends Qe{constructor(e={}){super(e)}get outputName(){return _optionalChain([this, 'access', _849 => _849.args, 'access', _850 => _850.expressions, 'optionalAccess', _851 => _851.length])===1?this.args.expressions[0].outputName:super.outputName}};fs.key="bracket",fs.requiredArgs=new Set,fs.availableArgs=new Set(["this","expressions","offset","safe","returnsListForMaps"]);var gn=class extends Re{constructor(e={}){super(e)}interval(){return new ze({this:_optionalChain([this, 'access', _852 => _852.args, 'access', _853 => _853.expression, 'optionalAccess', _854 => _854.copy, 'call', _855 => _855()]),unit:_optionalChain([this, 'access', _856 => _856.unit, 'optionalAccess', _857 => _857.copy, 'call', _858 => _858()])})}};gn.key="intervalOp",gn.requiredArgs=new Set(["expression"]),gn.availableArgs=new Set(["unit","expression"]);var Kn=class extends h{constructor(e={}){super(e)}};Kn.key="intervalSpan",Kn.requiredArgs=new Set(["this","expression"]),Kn.availableArgs=new Set(["this","expression"]);var ze=class extends Re{constructor(e={}){super(e)}};ze.key="interval",ze.requiredArgs=new Set,ze.availableArgs=new Set(["this","unit"]);var hp=class hp extends Qe{constructor(e={}){super(e)}static fromArgList(e){let t=this.argOrder;if(t.length===0&&(t=Array.from(this.availableArgs)),this.isVarLenArgs){let s=t.slice(0,-1),r=s.length,i={};for(let a=0;a<s.length;a++)i[s[a]]=e[a];return i[t[t.length-1]]=e.slice(r),new this(i)}else{let s={};for(let r=0;r<t.length;r++)s[t[r]]=e[r];return new this(s)}}static sqlNames(){if(this===hp)throw new Error("SQL name is only supported by concrete function implementations");if(!Object.hasOwn(this,"_sqlNames")){let t=this.name.replace(/Expr$/,"").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toUpperCase();this._sqlNames=[t]}return this._sqlNames}static sqlName(){let e=this.sqlNames();if(!e.length)throw new Error(`Expected non-empty 'sql_names' for Func: ${this.name}.`);return e[0]}static defaultParserMappings(){let e={};for(let t of this.sqlNames())e[t]=this.fromArgList.bind(this);return e}static register(){this===hp||this===q||QU(this)}};hp.key="func",hp.requiredArgs=new Set,hp.isVarLenArgs=!1,hp.argOrder=[],hp._sqlNames=[];var d=hp,q=class extends d{constructor(e={}){super(e)}};q.key="aggFunc",q.argOrder=["this"];var Xr=class extends Rs{constructor(e={}){super(e)}};Xr.key="jsonPathFilter",Xr.requiredArgs=new Set(["this"]),Xr.availableArgs=new Set(["this"]);var Gt=class extends Rs{constructor(e={}){super(e)}};Gt.key="jsonPathKey",Gt.requiredArgs=new Set(["this"]),Gt.availableArgs=new Set(["this"]);var Ai=class extends Rs{constructor(e={}){super(e)}};Ai.key="jsonPathRecursive",Ai.availableArgs=new Set(["this"]);var Ls=class extends Rs{constructor(e={}){super(e)}};Ls.key="jsonPathRoot",Ls.requiredArgs=new Set,Ls.availableArgs=new Set;var zr=class extends Rs{constructor(e={}){super(e)}};zr.key="jsonPathScript",zr.requiredArgs=new Set(["this"]),zr.availableArgs=new Set(["this"]);var fi=class extends Rs{constructor(e={}){super(e)}};fi.key="jsonPathSlice",fi.availableArgs=new Set(["start","end","step"]);var di=class extends Rs{constructor(e={}){super(e)}};di.key="jsonPathSelector",di.requiredArgs=new Set(["this"]),di.availableArgs=new Set(["this"]);var Ds=class extends Rs{constructor(e={}){super(e)}};Ds.key="jsonPathSubscript",Ds.requiredArgs=new Set(["this"]),Ds.availableArgs=new Set(["this"]);var Ln=class extends Rs{constructor(e={}){super(e)}};Ln.key="jsonPathUnion",Ln.requiredArgs=new Set(["expressions"]),Ln.availableArgs=new Set(["expressions"]);var hs=class extends Rs{constructor(e={}){super(e)}};hs.key="jsonPathWildcard",hs.requiredArgs=new Set,hs.availableArgs=new Set;var va=class extends Lr{constructor(e={}){super(e)}};va.key="merge",va.requiredArgs=new Set(["this","using","whens"]),va.availableArgs=new Set(["this","using","on","usingCond","whens","with","returning"]);var kt=class extends as{constructor(e={}){super(e)}};kt.key="lateral",kt.availableArgs=new Set(["this","view","outer","alias","crossApply","ordinality"]);var _c=class extends as{constructor(e={}){super(e)}};_c.key="tableFromRows",_c.availableArgs=new Set(["this","alias","joins","pivots","sample"]);var $r=class extends be{constructor(e={}){super(e)}};$r.key="union";var Yr=class extends be{constructor(e={}){super(e)}};Yr.key="except";var yn=class extends be{constructor(e={}){super(e)}};yn.key="intersect";var Gs=class extends as{constructor(e={}){super(e)}};Gs.key="values",Gs.requiredArgs=new Set(["expressions"]),Gs.availableArgs=new Set(["expressions","alias","order","limit","offset"]);var Vn=class extends Ve{constructor(e={}){super(e)}};Vn.key="subqueryPredicate";var lt=class extends Y{constructor(e={}){super(e)}};lt.key="add";var We=class extends Y{constructor(e={}){super(e)}};We.key="connector";var Cn=class extends Y{constructor(e={}){super(e)}};Cn.key="bitwiseAnd",Cn.availableArgs=new Set(["this","expression","padside"]);var tp=class extends Y{constructor(e={}){super(e)}};tp.key="bitwiseLeftShift",tp.availableArgs=new Set(["this","expression","requiresInt128"]);var ui=class extends Y{constructor(e={}){super(e)}};ui.key="bitwiseOr",ui.availableArgs=new Set(["this","expression","padside"]);var nc=class extends Y{constructor(e={}){super(e)}};nc.key="bitwiseRightShift",nc.availableArgs=new Set(["this","expression","requiresInt128"]);var Ei=class extends Y{constructor(e={}){super(e)}};Ei.key="bitwiseXor",Ei.availableArgs=new Set(["this","expression","padside"]);var jt=class extends Y{constructor(e={}){super(e)}get left(){return this.args.this}get right(){return this.args.expression}};jt.key="div",jt.availableArgs=new Set(["this","expression","typed","safe"]);var eS=class extends Y{constructor(e={}){super(e)}};eS.key="overlaps";var fE=class extends Y{constructor(e={}){super(e)}};fE.key="extendsLeft";var xE=class extends Y{constructor(e={}){super(e)}};xE.key="extendsRight";var Gw=class Gw extends Y{constructor(e={}){super(e)}get isStar(){return _nullishCoalesce(_optionalChain([this, 'access', _859 => _859.args, 'access', _860 => _860.expression, 'optionalAccess', _861 => _861.isStar]), () => (!1))}get name(){return _nullishCoalesce(_optionalChain([this, 'access', _862 => _862.args, 'access', _863 => _863.expression, 'optionalAccess', _864 => _864.name]), () => (""))}get outputName(){return this.name}static build(e){if(e.length<2)throw new Error("Dot requires >= 2 expressions.");return e.reduce((t,s)=>new Gw({this:t,expression:s}))}get parts(){let[e,...t]=this.flatten(),s=[...t];s.reverse();for(let r of _v){let i=e.args[r];i instanceof h&&s.push(i)}return s.reverse(),s}};Gw.key="dot";var me=Gw,Ar=class extends Y{constructor(e={}){super(e)}};Ar.key="dPipe",Ar.availableArgs=new Set(["this","expression","safe"]);var Ee=class extends Q(Y,Ve){constructor(e={}){super(e)}};Ee.key="eq",Ee.requiredArgs=new Set(["this","expression"]),Ee.availableArgs=new Set(["this","expression"]);var fr=class extends Q(Y,Ve){constructor(e={}){super(e)}};fr.key="nullSafeEq",fr.requiredArgs=new Set(["this","expression"]),fr.availableArgs=new Set(["this","expression"]);var kr=class extends Q(Y,Ve){constructor(e={}){super(e)}};kr.key="nullSafeNeq",kr.requiredArgs=new Set(["this","expression"]),kr.availableArgs=new Set(["this","expression"]);var At=class extends Y{constructor(e={}){super(e)}};At.key="propertyEq";var tS=class extends Y{constructor(e={}){super(e)}};tS.key="distance";var TE=class extends Y{constructor(e={}){super(e)}};TE.key="escape";var Jc=class extends Q(Y,Ve){constructor(e={}){super(e)}};Jc.key="glob",Jc.requiredArgs=new Set(["this","expression"]),Jc.availableArgs=new Set(["this","expression"]);var It=class extends Q(Y,Ve){constructor(e={}){super(e)}};It.key="gt",It.requiredArgs=new Set(["this","expression"]),It.availableArgs=new Set(["this","expression"]);var xt=class extends Q(Y,Ve){constructor(e={}){super(e)}};xt.key="gte",xt.requiredArgs=new Set(["this","expression"]),xt.availableArgs=new Set(["this","expression"]);var ms=class extends Q(Y,Ve){constructor(e={}){super(e)}};ms.key="iLike",ms.requiredArgs=new Set(["this","expression"]),ms.availableArgs=new Set(["this","expression"]);var Hi=class extends Y{constructor(e={}){super(e)}};Hi.key="intDiv";var Ut=class extends Q(Y,Ve){constructor(e={}){super(e)}};Ut.key="is",Ut.requiredArgs=new Set(["this","expression"]),Ut.availableArgs=new Set(["this","expression"]);var Og=class extends Y{constructor(e={}){super(e)}};Og.key="kwarg";var Ws=class extends Q(Y,Ve){constructor(e={}){super(e)}};Ws.key="like",Ws.requiredArgs=new Set(["this","expression"]),Ws.availableArgs=new Set(["this","expression"]);var LS=class extends Q(Y,Ve){constructor(e={}){super(e)}};LS.key="match",LS.requiredArgs=new Set(["this","expression"]),LS.availableArgs=new Set(["this","expression"]);var Tt=class extends Q(Y,Ve){constructor(e={}){super(e)}};Tt.key="lt",Tt.requiredArgs=new Set(["this","expression"]),Tt.availableArgs=new Set(["this","expression"]);var yt=class extends Q(Y,Ve){constructor(e={}){super(e)}};yt.key="lte",yt.requiredArgs=new Set(["this","expression"]),yt.availableArgs=new Set(["this","expression"]);var Hr=class extends Y{constructor(e={}){super(e)}};Hr.key="mod";var Ts=class extends Y{constructor(e={}){super(e)}};Ts.key="mul";var vt=class extends Q(Y,Ve){constructor(e={}){super(e)}};vt.key="neq",vt.requiredArgs=new Set(["this","expression"]),vt.availableArgs=new Set(["this","expression"]);var ic=class extends Y{constructor(e={}){super(e)}};ic.key="operator",ic.requiredArgs=new Set(["this","operator","expression"]),ic.availableArgs=new Set(["this","operator","expression"]);var SE=class extends Q(Y,Ve){constructor(e={}){super(e)}};SE.key="similarTo",SE.requiredArgs=new Set(["this","expression"]),SE.availableArgs=new Set(["this","expression"]);var dt=class extends Y{constructor(e={}){super(e)}};dt.key="sub";var mE=class extends Y{constructor(e={}){super(e)}};mE.key="adjacent";var bn=class extends Zs{constructor(e={}){super(e)}};bn.key="bitwiseNot";var rt=class extends Zs{constructor(e={}){super(e)}};rt.key="not";var Ye=class extends Zs{constructor(e={}){super(e)}get outputName(){return _nullishCoalesce(_optionalChain([this, 'access', _865 => _865.args, 'access', _866 => _866.this, 'optionalAccess', _867 => _867.name]), () => (""))}};Ye.key="paren";var Ps=class extends Zs{constructor(e={}){super(e)}toValue(){return this.isNumber?(_nullishCoalesce(_optionalChain([this, 'access', _868 => _868.args, 'access', _869 => _869.this, 'optionalAccess', _870 => _870.toValue, 'call', _871 => _871()]), () => (0)))*-1:super.toValue()}};Ps.key="neg";var Fs=class extends Ve{constructor(e={}){super(e)}};Fs.key="between",Fs.requiredArgs=new Set(["this","low","high"]),Fs.availableArgs=new Set(["this","low","high","symmetric"]);var it=class extends Ve{constructor(e={}){super(e)}};it.key="in",it.availableArgs=new Set(["this","expressions","query","unnest","field","isGlobal"]);var qO=class qO extends d{constructor(e={}){super(e)}};qO.key="safeFunc",qO.argOrder=["this"],qO.register();var bx=qO,vO=class vO extends d{constructor(e={}){super(e)}};vO.key="typeof",vO.argOrder=["this"],vO.register();var HL=vO,FO=class FO extends d{constructor(e={}){super(e)}};FO.key="acos",FO.argOrder=["this"],FO.register();var wp=FO,BO=class BO extends d{constructor(e={}){super(e)}};BO.key="acosh",BO.argOrder=["this"],BO.register();var ty=BO,GO=class GO extends d{constructor(e={}){super(e)}};GO.key="asin",GO.argOrder=["this"],GO.register();var Mp=GO,$O=class $O extends d{constructor(e={}){super(e)}};$O.key="asinh",$O.argOrder=["this"],$O.register();var sy=$O,US=class US extends d{constructor(e={}){super(e)}};US.key="atan",US.availableArgs=new Set(["this","expression"]),US.argOrder=["this","expression"],US.register();var Lp=US,YO=class YO extends d{constructor(e={}){super(e)}};YO.key="atanh",YO.argOrder=["this"],YO.register();var ry=YO,Ug=class Ug extends d{constructor(e={}){super(e)}};Ug.key="atan2",Ug.requiredArgs=new Set(["this","expression"]),Ug.availableArgs=new Set(["this","expression"]),Ug.argOrder=["this","expression"],Ug.register();var Cr=Ug,HO=class HO extends d{constructor(e={}){super(e)}};HO.key="cot",HO.argOrder=["this"],HO.register();var Dp=HO,VO=class VO extends d{constructor(e={}){super(e)}};VO.key="coth",VO.argOrder=["this"],VO.register();var ny=VO,WO=class WO extends d{constructor(e={}){super(e)}};WO.key="cos",WO.argOrder=["this"],WO.register();var _p=WO,jO=class jO extends d{constructor(e={}){super(e)}};jO.key="csc",jO.argOrder=["this"],jO.register();var iy=jO,JO=class JO extends d{constructor(e={}){super(e)}};JO.key="csch",JO.argOrder=["this"],JO.register();var ay=JO,XO=class XO extends d{constructor(e={}){super(e)}};XO.key="sec",XO.argOrder=["this"],XO.register();var Px=XO,zO=class zO extends d{constructor(e={}){super(e)}};zO.key="sech",zO.argOrder=["this"],zO.register();var oy=zO,KO=class KO extends d{constructor(e={}){super(e)}};KO.key="sin",KO.argOrder=["this"],KO.register();var kp=KO,QO=class QO extends d{constructor(e={}){super(e)}};QO.key="sinh",QO.argOrder=["this"],QO.register();var cy=QO,ZO=class ZO extends d{constructor(e={}){super(e)}};ZO.key="tan",ZO.argOrder=["this"],ZO.register();var Up=ZO,eN=class eN extends d{constructor(e={}){super(e)}};eN.key="tanh",eN.argOrder=["this"],eN.register();var wx=eN,tN=class tN extends d{constructor(e={}){super(e)}};tN.key="degrees",tN.argOrder=["this"],tN.register();var Mx=tN,sN=class sN extends d{constructor(e={}){super(e)}};sN.key="cosh",sN.argOrder=["this"],sN.register();var py=sN,qg=class qg extends d{constructor(e={}){super(e)}};qg.key="cosineDistance",qg.requiredArgs=new Set(["this","expression"]),qg.availableArgs=new Set(["this","expression"]),qg.argOrder=["this","expression"],qg.register();var Lx=qg,vg=class vg extends d{constructor(e={}){super(e)}};vg.key="dotProduct",vg.requiredArgs=new Set(["this","expression"]),vg.availableArgs=new Set(["this","expression"]),vg.argOrder=["this","expression"],vg.register();var ly=vg,Fg=class Fg extends d{constructor(e={}){super(e)}};Fg.key="euclideanDistance",Fg.requiredArgs=new Set(["this","expression"]),Fg.availableArgs=new Set(["this","expression"]),Fg.argOrder=["this","expression"],Fg.register();var Dx=Fg,Bg=class Bg extends d{constructor(e={}){super(e)}};Bg.key="manhattanDistance",Bg.requiredArgs=new Set(["this","expression"]),Bg.availableArgs=new Set(["this","expression"]),Bg.argOrder=["this","expression"],Bg.register();var uy=Bg,Gg=class Gg extends d{constructor(e={}){super(e)}};Gg.key="jarowinklerSimilarity",Gg.requiredArgs=new Set(["this","expression"]),Gg.availableArgs=new Set(["this","expression","caseInsensitive"]),Gg.argOrder=["this","expression"],Gg.register();var _x=Gg,rN=class rN extends d{constructor(e={}){super(e)}};rN.key="bitwiseCount",rN.argOrder=["this"],rN.register();var kh=rN,nN=class nN extends d{constructor(e={}){super(e)}};nN.key="bitmapBucketNumber",nN.argOrder=["this"],nN.register();var Ey=nN,iN=class iN extends d{constructor(e={}){super(e)}};iN.key="bitmapCount",iN.argOrder=["this"],iN.register();var kx=iN,aN=class aN extends d{constructor(e={}){super(e)}};aN.key="bitmapBitPosition",aN.argOrder=["this"],aN.register();var hy=aN,oN=class oN extends d{constructor(e={}){super(e)}};oN.key="byteLength",oN.argOrder=["this"],oN.register();var Ux=oN,qS=class qS extends d{constructor(e={}){super(e)}};qS.key="boolnot",qS.availableArgs=new Set(["this","roundInput"]),qS.argOrder=["this","roundInput"],qS.register();var gy=qS,$g=class $g extends d{constructor(e={}){super(e)}};$g.key="booland",$g.requiredArgs=new Set(["this","expression"]),$g.availableArgs=new Set(["this","expression","roundInput"]),$g.argOrder=["this","expression","roundInput"],$g.register();var dy=$g,Yg=class Yg extends d{constructor(e={}){super(e)}};Yg.key="boolor",Yg.requiredArgs=new Set(["this","expression"]),Yg.availableArgs=new Set(["this","expression","roundInput"]),Yg.argOrder=["this","expression","roundInput"],Yg.register();var Ay=Yg,cN=class cN extends d{constructor(e={}){super(e)}};cN.key="jsonBool",cN.argOrder=["this"],cN.register();var fy=cN,Hg=class Hg extends d{constructor(e={}){super(e)}};Hg.key="arrayRemove",Hg.requiredArgs=new Set(["this","expression"]),Hg.availableArgs=new Set(["this","expression","nullPropagation"]),Hg.argOrder=["this","expression","nullPropagation"],Hg.register();var RE=Hg,pN=class pN extends d{constructor(e={}){super(e)}};pN.key="abs",pN.argOrder=["this"],pN.register();var xy=pN,vS=class vS extends d{constructor(e={}){super(e)}};vS.key="approxTopKEstimate",vS.availableArgs=new Set(["this","expression"]),vS.argOrder=["this","expression"],vS.register();var Ty=vS,gp=class gp extends d{constructor(e={}){super(e)}};gp.key="farmFingerprint",gp.isVarLenArgs=!0,gp._sqlNames=["FARM_FINGERPRINT","FARMFINGERPRINT64"],gp.requiredArgs=new Set(["expressions"]),gp.availableArgs=new Set(["expressions"]),gp.argOrder=["expressions"],gp.register();var Sy=gp,lN=class lN extends d{constructor(e={}){super(e)}};lN.key="flatten",lN.argOrder=["this"],lN.register();var VL=lN,FS=class FS extends d{constructor(e={}){super(e)}};FS.key="float64",FS.availableArgs=new Set(["this","expression"]),FS.argOrder=["this","expression"],FS.register();var my=FS,Vg=class Vg extends d{constructor(e={}){super(e)}};Vg.key="transform",Vg.requiredArgs=new Set(["this","expression"]),Vg.availableArgs=new Set(["this","expression"]),Vg.argOrder=["this","expression"],Vg.register();var Ry=Vg,Wg=class Wg extends d{constructor(e={}){super(e)}};Wg.key="translate",Wg.requiredArgs=new Set(["this","from","to"]),Wg.availableArgs=new Set(["this","from","to"]),Wg.argOrder=["this","from","to"],Wg.register();var qx=Wg,jg=class jg extends d{constructor(e={}){super(e)}get name(){let e=this.args.this;return e===void 0?"":e instanceof h?e.name:e.toString()}};jg.key="anonymous",jg.isVarLenArgs=!0,jg.availableArgs=new Set(["this","expressions"]),jg.argOrder=["this","expressions"],jg.register();var st=jg,Jg=class Jg extends d{constructor(e={}){super(e)}};Jg.key="apply",Jg.requiredArgs=new Set(["this","expression"]),Jg.availableArgs=new Set(["this","expression"]),Jg.argOrder=["this","expression"],Jg.register();var WL=Jg,CE=class CE extends d{constructor(e={}){super(e)}};CE.key="array",CE.isVarLenArgs=!0,CE.requiredArgs=new Set,CE.availableArgs=new Set(["expressions","bracketNotation","structNameInheritance"]),CE.argOrder=["expressions","bracketNotation","structNameInheritance"],CE.register();var Ne=CE,uN=class uN extends d{constructor(e={}){super(e)}};uN.key="ascii",uN.argOrder=["this"],uN.register();var Oy=uN,EN=class EN extends d{constructor(e={}){super(e)}};EN.key="toArray",EN.argOrder=["this"],EN.register();var jL=EN,BS=class BS extends d{constructor(e={}){super(e)}};BS.key="toBoolean",BS.availableArgs=new Set(["this","safe"]),BS.argOrder=["this","safe"],BS.register();var Ny=BS,bE=class bE extends d{constructor(e={}){super(e)}};bE.key="list",bE.requiredArgs=new Set,bE.isVarLenArgs=!0,bE.availableArgs=new Set(["expressions"]),bE.argOrder=["expressions"],bE.register();var mO=bE,Xg=class Xg extends d{constructor(e={}){super(e)}};Xg.key="pad",Xg.requiredArgs=new Set(["this","expression","isLeft"]),Xg.availableArgs=new Set(["this","expression","fillPattern","isLeft"]),Xg.argOrder=["this","expression","fillPattern","isLeft"],Xg.register();var Fa=Xg,GS=class GS extends d{constructor(e={}){super(e)}};GS.key="toChar",GS.availableArgs=new Set(["this","format","nlsparam","isNumeric"]),GS.argOrder=["this","format","nlsparam","isNumeric"],GS.register();var bR=GS,hN=class hN extends d{constructor(e={}){super(e)}};hN.key="toCodePoints",hN.argOrder=["this"],hN.register();var Iy=hN,$S=class $S extends d{constructor(e={}){super(e)}};$S.key="toNumber",$S.availableArgs=new Set(["this","format","nlsparam","precision","scale","safe","safeName"]),$S.argOrder=["this","format","nlsparam","precision","scale","safe","safeName"],$S.register();var yy=$S,YS=class YS extends d{constructor(e={}){super(e)}};YS.key="toDouble",YS.availableArgs=new Set(["this","format","safe"]),YS.argOrder=["this","format","safe"],YS.register();var Cy=YS,HS=class HS extends d{constructor(e={}){super(e)}};HS.key="toDecfloat",HS.availableArgs=new Set(["this","format"]),HS.argOrder=["this","format"],HS.register();var by=HS,VS=class VS extends d{constructor(e={}){super(e)}};VS.key="tryToDecfloat",VS.availableArgs=new Set(["this","format"]),VS.argOrder=["this","format"],VS.register();var Py=VS,WS=class WS extends d{constructor(e={}){super(e)}};WS.key="toFile",WS.availableArgs=new Set(["this","path","safe"]),WS.argOrder=["this","path","safe"],WS.register();var wy=WS,gN=class gN extends d{constructor(e={}){super(e)}};gN.key="codePointsToBytes",gN.argOrder=["this"],gN.register();var My=gN,jS=class jS extends d{constructor(e={}){super(e)}};jS.key="columns",jS.availableArgs=new Set(["this","unpack"]),jS.argOrder=["this","unpack"],jS.register();var RO=jS,zg=class zg extends d{constructor(e={}){super(e)}};zg.key="convert",zg.requiredArgs=new Set(["this","expression"]),zg.availableArgs=new Set(["this","expression","style","safe"]),zg.argOrder=["this","expression","style","safe"],zg.register();var JL=zg,Kg=class Kg extends d{constructor(e={}){super(e)}};Kg.key="convertToCharset",Kg.requiredArgs=new Set(["this","dest"]),Kg.availableArgs=new Set(["this","dest","source"]),Kg.argOrder=["this","dest","source"],Kg.register();var Ly=Kg,Qg=class Qg extends d{constructor(e={}){super(e)}};Qg.key="convertTimezone",Qg.requiredArgs=new Set(["targetTz","timestamp"]),Qg.availableArgs=new Set(["sourceTz","targetTz","timestamp","options"]),Qg.argOrder=["sourceTz","targetTz","timestamp","options"],Qg.register();var Qn=Qg,dN=class dN extends d{constructor(e={}){super(e)}};dN.key="codePointsToString",dN.argOrder=["this"],dN.register();var Dy=dN,Zg=class Zg extends d{constructor(e={}){super(e)}};Zg.key="generateSeries",Zg.requiredArgs=new Set(["start","end"]),Zg.availableArgs=new Set(["start","end","step","isEndExclusive"]),Zg.argOrder=["start","end","step","isEndExclusive"],Zg.register();var Os=Zg,ed=class ed extends Q(d,as){constructor(e={}){super(e)}};ed.key="generator",ed.argOrder=["rowcount","timelimit"],ed.requiredArgs=new Set,ed.availableArgs=new Set(["rowcount","timelimit"]),ed.register();var XL=ed,PE=class PE extends d{constructor(e={}){super(e)}};PE.key="aiClassify",PE._sqlNames=["AI_CLASSIFY"],PE.requiredArgs=new Set(["this","categories"]),PE.availableArgs=new Set(["this","categories","config"]),PE.argOrder=["this","categories","config"],PE.register();var _y=PE,td=class td extends d{constructor(e={}){super(e)}};td.key="arrayAll",td.requiredArgs=new Set(["this","expression"]),td.availableArgs=new Set(["this","expression"]),td.argOrder=["this","expression"],td.register();var zL=td,sd=class sd extends d{constructor(e={}){super(e)}};sd.key="arrayAny",sd.requiredArgs=new Set(["this","expression"]),sd.availableArgs=new Set(["this","expression"]),sd.argOrder=["this","expression"],sd.register();var ky=sd,rd=class rd extends d{constructor(e={}){super(e)}};rd.key="arrayAppend",rd.requiredArgs=new Set(["this","expression"]),rd.availableArgs=new Set(["this","expression","nullPropagation"]),rd.argOrder=["this","expression","nullPropagation"],rd.register();var Ng=rd,nd=class nd extends d{constructor(e={}){super(e)}};nd.key="arrayPrepend",nd.requiredArgs=new Set(["this","expression"]),nd.availableArgs=new Set(["this","expression","nullPropagation"]),nd.argOrder=["this","expression","nullPropagation"],nd.register();var Ig=nd,wE=class wE extends d{constructor(e={}){super(e)}};wE.key="arrayConcat",wE._sqlNames=["ARRAY_CONCAT","ARRAY_CAT"],wE.isVarLenArgs=!0,wE.availableArgs=new Set(["this","expressions","nullPropagation"]),wE.argOrder=["this","expressions","nullPropagation"],wE.register();var Pn=wE,AN=class AN extends d{constructor(e={}){super(e)}};AN.key="arrayCompact",AN.argOrder=["this"],AN.register();var Uy=AN,id=class id extends d{constructor(e={}){super(e)}};id.key="arrayInsert",id.requiredArgs=new Set(["this","position","expression"]),id.availableArgs=new Set(["this","position","expression","offset"]),id.argOrder=["this","position","expression","offset"],id.register();var KL=id,ad=class ad extends d{constructor(e={}){super(e)}};ad.key="arrayRemoveAt",ad.requiredArgs=new Set(["this","position"]),ad.availableArgs=new Set(["this","position"]),ad.argOrder=["this","position"],ad.register();var QL=ad,ME=class ME extends d{constructor(e={}){super(e)}};ME.key="arrayConstructCompact",ME.requiredArgs=new Set,ME.isVarLenArgs=!0,ME.availableArgs=new Set(["expressions"]),ME.argOrder=["expressions"],ME.register();var qy=ME,LE=class LE extends Q(Y,d){constructor(e={}){super(e)}};LE.key="arrayContains",LE._sqlNames=["ARRAY_CONTAINS","ARRAY_HAS"],LE.argOrder=["this","expression"],LE.requiredArgs=new Set(["this","expression"]),LE.availableArgs=new Set(["this","expression","ensureVariant","checkNull"]),LE.register();var PR=LE,od=class od extends Q(Y,d){constructor(e={}){super(e)}};od.key="arrayContainsAll",od._sqlNames=["ARRAY_CONTAINS_ALL","ARRAY_HAS_ALL"],od.requiredArgs=new Set(["this","expression"]),od.availableArgs=new Set(["this","expression"]),od.register();var ql=od,DE=class DE extends d{constructor(e={}){super(e)}};DE.key="arrayFilter",DE._sqlNames=["FILTER","ARRAY_FILTER"],DE.requiredArgs=new Set(["this","expression"]),DE.availableArgs=new Set(["this","expression"]),DE.argOrder=["this","expression"],DE.register();var wR=DE,fN=class fN extends d{constructor(e={}){super(e)}};fN.key="arrayFirst",fN.argOrder=["this"],fN.register();var vy=fN,xN=class xN extends d{constructor(e={}){super(e)}};xN.key="arrayLast",xN.argOrder=["this"],xN.register();var Fy=xN,TN=class TN extends d{constructor(e={}){super(e)}};TN.key="arrayReverse",TN.argOrder=["this"],TN.register();var By=TN,cd=class cd extends d{constructor(e={}){super(e)}};cd.key="arraySlice",cd.requiredArgs=new Set(["this","start"]),cd.availableArgs=new Set(["this","start","end","step"]),cd.argOrder=["this","start","end","step"],cd.register();var Uh=cd,_E=class _E extends d{constructor(e={}){super(e)}};_E.key="arrayToString",_E._sqlNames=["ARRAY_TO_STRING","ARRAY_JOIN"],_E.requiredArgs=new Set(["this","expression"]),_E.availableArgs=new Set(["this","expression","null"]),_E.argOrder=["this","expression","null"],_E.register();var qp=_E,dp=class dp extends d{constructor(e={}){super(e)}};dp.key="arrayIntersect",dp.isVarLenArgs=!0,dp._sqlNames=["ARRAY_INTERSECT","ARRAY_INTERSECTION"],dp.requiredArgs=new Set(["expressions"]),dp.availableArgs=new Set(["expressions"]),dp.argOrder=["expressions"],dp.register();var ZL=dp,kE=class kE extends d{constructor(e={}){super(e)}};kE.key="stPoint",kE._sqlNames=["ST_POINT","ST_MAKEPOINT"],kE.requiredArgs=new Set(["this","expression"]),kE.availableArgs=new Set(["this","expression","null"]),kE.argOrder=["this","expression","null"],kE.register();var eD=kE,pd=class pd extends d{constructor(e={}){super(e)}};pd.key="stDistance",pd.requiredArgs=new Set(["this","expression"]),pd.availableArgs=new Set(["this","expression","useSpheroid"]),pd.argOrder=["this","expression","useSpheroid"],pd.register();var tD=pd,JS=class JS extends d{constructor(e={}){super(e)}};JS.key="string",JS.availableArgs=new Set(["this","zone"]),JS.argOrder=["this","zone"],JS.register();var Gy=JS,ld=class ld extends d{constructor(e={}){super(e)}};ld.key="stringToArray",ld._sqlNames=["STRING_TO_ARRAY","SPLIT_BY_STRING","STRTOK_TO_ARRAY"],ld.availableArgs=new Set(["this","expression","null"]),ld.argOrder=["this","expression","null"],ld.register();var $y=ld,XS=class XS extends Q(Y,d){constructor(e={}){super(e)}};XS.key="arrayOverlaps",XS.requiredArgs=new Set(["this","expression"]),XS.availableArgs=new Set(["this","expression"]),XS.register();var Yy=XS,ud=class ud extends d{constructor(e={}){super(e)}};ud.key="arraySize",ud._sqlNames=["ARRAY_SIZE","ARRAY_LENGTH"],ud.availableArgs=new Set(["this","expression"]),ud.argOrder=["this","expression"],ud.register();var lr=ud,zS=class zS extends d{constructor(e={}){super(e)}};zS.key="arraySort",zS.availableArgs=new Set(["this","expression"]),zS.argOrder=["this","expression"],zS.register();var Hy=zS,KS=class KS extends d{constructor(e={}){super(e)}};KS.key="arraySum",KS.availableArgs=new Set(["this","expression"]),KS.argOrder=["this","expression"],KS.register();var Vy=KS,UE=class UE extends d{constructor(e={}){super(e)}};UE.key="arraysZip",UE.requiredArgs=new Set,UE.isVarLenArgs=!0,UE.availableArgs=new Set(["expressions"]),UE.argOrder=["expressions"],UE.register();var Wy=UE,Ed=class Ed extends d{constructor(e={}){super(e)}when(e,t,s={}){let{copy:r=!0}=s,i=bt(this,r);return i.append("ifs",new He({this:ne(e,s),true:ne(t,s)})),i}else(e,t={}){let{copy:s=!0}=t,r=bt(this,s);return r.setArgKey("default",ne(e,t)),r}};Ed.key="case",Ed.requiredArgs=new Set(["ifs"]),Ed.availableArgs=new Set(["this","ifs","default"]),Ed.argOrder=["this","ifs","default"],Ed.register();var Ht=Ed,hd=class hd extends d{constructor(e={}){super(e)}get name(){return this.args.this.name||""}get to(){return this.args.to}get outputName(){return this.name}isType(e,t={}){let s=this.args.to;return s&&s instanceof C?s.isType(e):!1}};hd.key="cast",hd.requiredArgs=new Set(["this","to"]),hd.availableArgs=new Set(["this","to","format","safe","action","default"]),hd.argOrder=["this","to","format","safe","action","default"],hd.register();var Z=hd,SN=class SN extends d{constructor(e={}){super(e)}};SN.key="justifyDays",SN.argOrder=["this"],SN.register();var jy=SN,mN=class mN extends d{constructor(e={}){super(e)}};mN.key="justifyHours",mN.argOrder=["this"],mN.register();var Jy=mN,RN=class RN extends d{constructor(e={}){super(e)}};RN.key="justifyInterval",RN.argOrder=["this"],RN.register();var Xy=RN,ON=class ON extends d{constructor(e={}){super(e)}};ON.key="try",ON.argOrder=["this"],ON.register();var sD=ON,gd=class gd extends d{constructor(e={}){super(e)}};gd.key="castToStrType",gd.requiredArgs=new Set(["this","to"]),gd.availableArgs=new Set(["this","to"]),gd.argOrder=["this","to"],gd.register();var OO=gd,NN=class NN extends d{constructor(e={}){super(e)}};NN.key="checkJson",NN.argOrder=["this"],NN.register();var zy=NN,QS=class QS extends d{constructor(e={}){super(e)}};QS.key="checkXml",QS.availableArgs=new Set(["this","disableAutoConvert"]),QS.argOrder=["this","disableAutoConvert"],QS.register();var Ky=QS,ZS=class ZS extends Q(Y,d){constructor(e={}){super(e)}};ZS.key="collate",ZS.requiredArgs=new Set(["this","expression"]),ZS.availableArgs=new Set(["this","expression"]),ZS.register();var vl=ZS,IN=class IN extends d{constructor(e={}){super(e)}};IN.key="collation",IN.argOrder=["this"],IN.register();var vx=IN,dd=class dd extends d{constructor(e={}){super(e)}};dd.key="ceil",dd._sqlNames=["CEIL","CEILING"],dd.availableArgs=new Set(["this","decimals","to"]),dd.argOrder=["this","decimals","to"],dd.register();var Ir=dd,qE=class qE extends d{constructor(e={}){super(e)}};qE.key="coalesce",qE._sqlNames=["COALESCE","IFNULL","NVL"],qE.isVarLenArgs=!0,qE.availableArgs=new Set(["this","expressions","isNvl","isNull"]),qE.argOrder=["this","expressions","isNvl","isNull"],qE.register();var St=qE,Ap=class Ap extends d{constructor(e={}){super(e)}};Ap.key="chr",Ap._sqlNames=["CHR","CHAR"],Ap.isVarLenArgs=!0,Ap.requiredArgs=new Set(["expressions"]),Ap.availableArgs=new Set(["expressions","charset"]),Ap.argOrder=["expressions","charset"],Ap.register();var sp=Ap,vE=class vE extends d{constructor(e={}){super(e)}};vE.key="concat",vE.isVarLenArgs=!0,vE.requiredArgs=new Set(["expressions"]),vE.availableArgs=new Set(["expressions","safe","coalesce"]),vE.argOrder=["expressions","safe","coalesce"],vE.register();var Vt=vE,Ad=class Ad extends d{constructor(e={}){super(e)}};Ad.key="contains",Ad.requiredArgs=new Set(["this","expression"]),Ad.availableArgs=new Set(["this","expression","jsonScope"]),Ad.argOrder=["this","expression","jsonScope"],Ad.register();var Qy=Ad,yN=class yN extends d{constructor(e={}){super(e)}};yN.key="connectByRoot",yN.argOrder=["this"],yN.register();var yg=yN,CN=class CN extends d{constructor(e={}){super(e)}};CN.key="cbrt",CN.argOrder=["this"],CN.register();var rp=CN,fd=class fd extends d{constructor(e={}){super(e)}};fd.key="currentAccount",fd.requiredArgs=new Set,fd.availableArgs=new Set,fd.argOrder=["this"],fd.register();var Zy=fd,xd=class xd extends d{constructor(e={}){super(e)}};xd.key="currentAccountName",xd.requiredArgs=new Set,xd.availableArgs=new Set,xd.argOrder=["this"],xd.register();var eC=xd,Td=class Td extends d{constructor(e={}){super(e)}};Td.key="currentAvailableRoles",Td.requiredArgs=new Set,Td.availableArgs=new Set,Td.argOrder=["this"],Td.register();var tC=Td,Sd=class Sd extends d{constructor(e={}){super(e)}};Sd.key="currentClient",Sd.requiredArgs=new Set,Sd.availableArgs=new Set,Sd.argOrder=["this"],Sd.register();var sC=Sd,md=class md extends d{constructor(e={}){super(e)}};md.key="currentIpAddress",md.requiredArgs=new Set,md.availableArgs=new Set,md.argOrder=["this"],md.register();var rC=md,Rd=class Rd extends d{constructor(e={}){super(e)}};Rd.key="currentDatabase",Rd.requiredArgs=new Set,Rd.availableArgs=new Set,Rd.argOrder=["this"],Rd.register();var Fx=Rd,em=class em extends d{constructor(e={}){super(e)}};em.key="currentSchemas",em.requiredArgs=new Set,em.argOrder=["this"],em.register();var nC=em,Od=class Od extends d{constructor(e={}){super(e)}};Od.key="currentSecondaryRoles",Od.requiredArgs=new Set,Od.availableArgs=new Set,Od.argOrder=["this"],Od.register();var iC=Od,Nd=class Nd extends d{constructor(e={}){super(e)}};Nd.key="currentSession",Nd.requiredArgs=new Set,Nd.availableArgs=new Set,Nd.argOrder=["this"],Nd.register();var aC=Nd,Id=class Id extends d{constructor(e={}){super(e)}};Id.key="currentStatement",Id.requiredArgs=new Set,Id.availableArgs=new Set,Id.argOrder=["this"],Id.register();var oC=Id,yd=class yd extends d{constructor(e={}){super(e)}};yd.key="currentVersion",yd.requiredArgs=new Set,yd.availableArgs=new Set,yd.argOrder=["this"],yd.register();var Dn=yd,Cd=class Cd extends d{constructor(e={}){super(e)}};Cd.key="currentTransaction",Cd.requiredArgs=new Set,Cd.availableArgs=new Set,Cd.argOrder=["this"],Cd.register();var cC=Cd,bd=class bd extends d{constructor(e={}){super(e)}};bd.key="currentWarehouse",bd.requiredArgs=new Set,bd.availableArgs=new Set,bd.argOrder=["this"],bd.register();var pC=bd,tm=class tm extends d{constructor(e={}){super(e)}};tm.key="currentDate",tm.requiredArgs=new Set,tm.argOrder=["this"],tm.register();var xn=tm,sm=class sm extends d{constructor(e={}){super(e)}};sm.key="currentDatetime",sm.requiredArgs=new Set,sm.argOrder=["this"],sm.register();var lC=sm,rm=class rm extends d{constructor(e={}){super(e)}};rm.key="currentTime",rm.requiredArgs=new Set,rm.argOrder=["this"],rm.register();var Ba=rm,nm=class nm extends d{constructor(e={}){super(e)}};nm.key="localtime",nm.requiredArgs=new Set,nm.argOrder=["this"],nm.register();var np=nm,im=class im extends d{constructor(e={}){super(e)}};im.key="localtimestamp",im.requiredArgs=new Set,im.argOrder=["this"],im.register();var ip=im,am=class am extends d{constructor(e={}){super(e)}};am.key="systimestamp",am.requiredArgs=new Set,am.argOrder=["this"],am.register();var rD=am,FE=class FE extends d{constructor(e={}){super(e)}};FE.key="currentTimestamp",FE._sqlNames=["CURRENT_TIMESTAMP"],FE.requiredArgs=new Set,FE.availableArgs=new Set(["this","sysdate"]),FE.argOrder=["this","sysdate"],FE.register();var ir=FE,Pd=class Pd extends d{constructor(e={}){super(e)}};Pd.key="currentTimestampLtz",Pd.requiredArgs=new Set,Pd.availableArgs=new Set,Pd.argOrder=["this"],Pd.register();var uC=Pd,wd=class wd extends d{constructor(e={}){super(e)}};wd.key="currentTimezone",wd.requiredArgs=new Set,wd.availableArgs=new Set,wd.argOrder=["this"],wd.register();var Bx=wd,Md=class Md extends d{constructor(e={}){super(e)}};Md.key="currentOrganizationName",Md.requiredArgs=new Set,Md.availableArgs=new Set,Md.argOrder=["this"],Md.register();var EC=Md,om=class om extends d{constructor(e={}){super(e)}};om.key="currentSchema",om.requiredArgs=new Set,om.argOrder=["this"],om.register();var qh=om,cm=class cm extends d{constructor(e={}){super(e)}};cm.key="currentUser",cm.requiredArgs=new Set,cm.argOrder=["this"],cm.register();var ap=cm,Ld=class Ld extends d{constructor(e={}){super(e)}};Ld.key="currentCatalog",Ld.requiredArgs=new Set,Ld.availableArgs=new Set,Ld.argOrder=["this"],Ld.register();var vp=Ld,Dd=class Dd extends d{constructor(e={}){super(e)}};Dd.key="currentRegion",Dd.requiredArgs=new Set,Dd.availableArgs=new Set,Dd.argOrder=["this"],Dd.register();var hC=Dd,_d=class _d extends d{constructor(e={}){super(e)}};_d.key="currentRole",_d.requiredArgs=new Set,_d.availableArgs=new Set,_d.argOrder=["this"],_d.register();var Cg=_d,kd=class kd extends d{constructor(e={}){super(e)}};kd.key="currentRoleType",kd.requiredArgs=new Set,kd.availableArgs=new Set,kd.argOrder=["this"],kd.register();var gC=kd,Ud=class Ud extends d{constructor(e={}){super(e)}};Ud.key="currentOrganizationUser",Ud.requiredArgs=new Set,Ud.availableArgs=new Set,Ud.argOrder=["this"],Ud.register();var dC=Ud,qd=class qd extends d{constructor(e={}){super(e)}};qd.key="sessionUser",qd.requiredArgs=new Set,qd.availableArgs=new Set,qd.argOrder=["this"],qd.register();var Fp=qd,vd=class vd extends d{constructor(e={}){super(e)}};vd.key="utcDate",vd.requiredArgs=new Set,vd.availableArgs=new Set,vd.argOrder=["this"],vd.register();var AC=vd,pm=class pm extends d{constructor(e={}){super(e)}};pm.key="utcTime",pm.requiredArgs=new Set,pm.argOrder=["this"],pm.register();var Gx=pm,lm=class lm extends d{constructor(e={}){super(e)}};lm.key="utcTimestamp",lm.requiredArgs=new Set,lm.argOrder=["this"],lm.register();var $x=lm,Fd=class Fd extends Q(d,gn){constructor(e={}){super(Re.initTimeArgs(e))}};Fd.key="dateAdd",Fd.argOrder=["this","expression","unit"],Fd.requiredArgs=new Set(["this","expression"]),Fd.availableArgs=new Set(["this","expression","unit"]),Fd.register();var ut=Fd,Bd=class Bd extends Q(d,gn){constructor(e={}){super(Re.initTimeArgs(e))}};Bd.key="dateBin",Bd.argOrder=["this","expression","unit","zone","origin"],Bd.requiredArgs=new Set(["this","expression"]),Bd.availableArgs=new Set(["this","expression","unit","zone","origin"]),Bd.register();var nD=Bd,Gd=class Gd extends Q(d,gn){constructor(e={}){super(Re.initTimeArgs(e))}};Gd.key="dateSub",Gd.argOrder=["this","expression","unit"],Gd.requiredArgs=new Set(["this","expression"]),Gd.availableArgs=new Set(["this","expression","unit"]),Gd.register();var Wt=Gd,BE=class BE extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};BE.key="dateDiff",BE.argOrder=["this","expression","unit","zone","bigInt","datePartBoundary"],BE._sqlNames=["DATEDIFF","DATE_DIFF"],BE.requiredArgs=new Set(["this","expression"]),BE.availableArgs=new Set(["this","expression","unit","zone","bigInt","datePartBoundary"]),BE.register();var ks=BE,GE=class GE extends d{constructor(e={}){let t=_nullishCoalesce(e.unabbreviate, () => (!0)),s=e.unit;if(Re.isVarLike(s)&&!(s instanceof k&&s.parts.length!==1)){let r=s.name.toUpperCase();t&&r in Re.UNABBREVIATED_UNIT_NAME&&(r=Re.UNABBREVIATED_UNIT_NAME[r]),e.unit=w.string(r)}delete e.unabbreviate,super(e)}get unit(){return this.args.unit}};GE.key="dateTrunc",GE._sqlNames=["DATE_TRUNC"],GE.requiredArgs=new Set(["unit","this"]),GE.availableArgs=new Set(["unit","this","zone","inputTypePreserved"]),GE.argOrder=["unit","this","zone","inputTypePreserved"],GE.register();var Bs=GE,um=class um extends d{constructor(e={}){super(e)}};um.key="datetime",um.availableArgs=new Set(["this","expression"]),um.argOrder=["this","expression"],um.register();var fC=um,$d=class $d extends Q(d,gn){constructor(e={}){super(Re.initTimeArgs(e))}};$d.key="datetimeAdd",$d.argOrder=["this","expression","unit"],$d.requiredArgs=new Set(["this","expression"]),$d.availableArgs=new Set(["this","expression","unit"]),$d.register();var Uc=$d,Yd=class Yd extends Q(d,gn){constructor(e={}){super(Re.initTimeArgs(e))}};Yd.key="datetimeSub",Yd.argOrder=["this","expression","unit"],Yd.requiredArgs=new Set(["this","expression"]),Yd.availableArgs=new Set(["this","expression","unit"]),Yd.register();var qc=Yd,Hd=class Hd extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};Hd.key="datetimeDiff",Hd.argOrder=["this","expression","unit"],Hd.requiredArgs=new Set(["this","expression"]),Hd.availableArgs=new Set(["this","expression","unit"]),Hd.register();var xC=Hd,Vd=class Vd extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};Vd.key="datetimeTrunc",Vd.argOrder=["this","unit","zone"],Vd.requiredArgs=new Set(["this","unit"]),Vd.availableArgs=new Set(["this","unit","zone"]),Vd.register();var TC=Vd,bN=class bN extends d{constructor(e={}){super(e)}};bN.key="dateFromUnixDate",bN.argOrder=["this"],bN.register();var Yx=bN,Em=class Em extends d{constructor(e={}){super(e)}};Em.key="dayOfWeek",Em._sqlNames=["DAY_OF_WEEK","DAYOFWEEK"],Em.argOrder=["this"],Em.register();var ur=Em,PN=class PN extends d{constructor(e={}){super(e)}};PN.key="dayOfWeekIso",PN.argOrder=["this"],PN.register();var Bp=PN,hm=class hm extends d{constructor(e={}){super(e)}};hm.key="dayOfMonth",hm.argOrder=["this"],hm._sqlNames=["DAY_OF_MONTH","DAYOFMONTH"],hm.register();var Kr=hm,gm=class gm extends d{constructor(e={}){super(e)}};gm.key="dayOfYear",gm.argOrder=["this"],gm._sqlNames=["DAY_OF_YEAR","DAYOFYEAR"],gm.register();var Qr=gm,dm=class dm extends d{constructor(e={}){super(e)}};dm.key="dayname",dm.availableArgs=new Set(["this","abbreviated"]),dm.argOrder=["this","abbreviated"],dm.register();var SC=dm,wN=class wN extends d{constructor(e={}){super(e)}};wN.key="toDays",wN.argOrder=["this"],wN.register();var mC=wN,MN=class MN extends d{constructor(e={}){super(e)}};MN.key="weekOfYear",MN.argOrder=["this"],MN.register();var xi=MN,Am=class Am extends d{constructor(e={}){super(e)}};Am.key="yearOfWeek",Am.argOrder=["this"],Am._sqlNames=["YEAR_OF_WEEK","YEAROFWEEK"],Am.register();var RC=Am,fm=class fm extends d{constructor(e={}){super(e)}};fm.key="yearOfWeekIso",fm.argOrder=["this"],fm._sqlNames=["YEAR_OF_WEEK_ISO","YEAROFWEEKISO"],fm.register();var OC=fm,Wd=class Wd extends d{constructor(e={}){super(e)}};Wd.key="monthsBetween",Wd.requiredArgs=new Set(["this","expression"]),Wd.availableArgs=new Set(["this","expression","roundoff"]),Wd.argOrder=["this","expression","roundoff"],Wd.register();var Gp=Wd,jd=class jd extends d{constructor(e={}){super(e)}};jd.key="makeInterval",jd.requiredArgs=new Set,jd.availableArgs=new Set(["year","month","week","day","hour","minute","second"]),jd.argOrder=["year","month","week","day","hour","minute","second"],jd.register();var NC=jd,$E=class $E extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};$E.key="lastDay",$E._sqlNames=["LAST_DAY","LAST_DAY_OF_MONTH"],$E.argOrder=["this","unit"],$E.requiredArgs=new Set(["this"]),$E.availableArgs=new Set(["this","unit"]),$E.register();var vh=$E,Jd=class Jd extends d{constructor(e={}){super(e)}};Jd.key="previousDay",Jd.requiredArgs=new Set(["this","expression"]),Jd.availableArgs=new Set(["this","expression"]),Jd.argOrder=["this","expression"],Jd.register();var IC=Jd,LN=class LN extends d{constructor(e={}){super(e)}};LN.key="laxBool",LN.argOrder=["this"],LN.register();var yC=LN,DN=class DN extends d{constructor(e={}){super(e)}};DN.key="laxFloat64",DN.argOrder=["this"],DN.register();var CC=DN,_N=class _N extends d{constructor(e={}){super(e)}};_N.key="laxInt64",_N.argOrder=["this"],_N.register();var bC=_N,kN=class kN extends d{constructor(e={}){super(e)}};kN.key="laxString",kN.argOrder=["this"],kN.register();var PC=kN,Xd=class Xd extends d{constructor(e={}){super(e)}};Xd.key="extract",Xd.requiredArgs=new Set(["this","expression"]),Xd.availableArgs=new Set(["this","expression"]),Xd.argOrder=["this","expression"],Xd.register();var Zn=Xd,zd=class zd extends Q(d,Vn){constructor(e={}){super(e)}};zd.key="exists",zd.argOrder=["this","expression"],zd.requiredArgs=new Set(["this"]),zd.availableArgs=new Set(["this","expression"]),zd.register();var js=zd,YE=class YE extends d{constructor(e={}){super(e)}};YE.key="elt",YE.isVarLenArgs=!0,YE.requiredArgs=new Set(["this","expressions"]),YE.availableArgs=new Set(["this","expressions"]),YE.argOrder=["this","expressions"],YE.register();var wC=YE,Kd=class Kd extends d{constructor(e={}){super(e)}};Kd.key="timestamp",Kd.requiredArgs=new Set,Kd.availableArgs=new Set(["this","zone","withTz"]),Kd.argOrder=["this","zone","withTz"],Kd.register();var $p=Kd,Qd=class Qd extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};Qd.key="timestampAdd",Qd.argOrder=["this","expression","unit"],Qd.requiredArgs=new Set(["this","expression"]),Qd.availableArgs=new Set(["this","expression","unit"]),Qd.register();var Tc=Qd,Zd=class Zd extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};Zd.key="timestampSub",Zd.argOrder=["this","expression","unit"],Zd.requiredArgs=new Set(["this","expression"]),Zd.availableArgs=new Set(["this","expression","unit"]),Zd.register();var Hx=Zd,eA=class eA extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};eA.key="timestampDiff",eA.argOrder=["this","expression","unit"],eA.requiredArgs=new Set(["this","expression"]),eA.availableArgs=new Set(["this","expression","unit"]),eA.register();var Va=eA,tA=class tA extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};tA.key="timestampTrunc",tA.argOrder=["this","unit","zone","inputTypePreserved"],tA.requiredArgs=new Set(["this","unit"]),tA.availableArgs=new Set(["this","unit","zone","inputTypePreserved"]),tA.register();var er=tA,sA=class sA extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};sA.key="timeSlice",sA.argOrder=["this","expression","unit","kind"],sA.requiredArgs=new Set(["this","expression","unit"]),sA.availableArgs=new Set(["this","expression","unit","kind"]),sA.register();var MC=sA,rA=class rA extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};rA.key="timeAdd",rA.argOrder=["this","expression","unit"],rA.requiredArgs=new Set(["this","expression"]),rA.availableArgs=new Set(["this","expression","unit"]),rA.register();var Fh=rA,nA=class nA extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};nA.key="timeSub",nA.argOrder=["this","expression","unit"],nA.requiredArgs=new Set(["this","expression"]),nA.availableArgs=new Set(["this","expression","unit"]),nA.register();var LC=nA,iA=class iA extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};iA.key="timeDiff",iA.argOrder=["this","expression","unit"],iA.requiredArgs=new Set(["this","expression"]),iA.availableArgs=new Set(["this","expression","unit"]),iA.register();var DC=iA,aA=class aA extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};aA.key="timeTrunc",aA.argOrder=["this","unit","zone"],aA.requiredArgs=new Set(["this","unit"]),aA.availableArgs=new Set(["this","unit","zone"]),aA.register();var _C=aA,HE=class HE extends d{constructor(e={}){super(e)}};HE.key="dateFromParts",HE._sqlNames=["DATE_FROM_PARTS","DATEFROMPARTS"],HE.requiredArgs=new Set(["year"]),HE.availableArgs=new Set(["year","month","day","allowOverflow"]),HE.argOrder=["year","month","day","allowOverflow"],HE.register();var kC=HE,oA=class oA extends d{constructor(e={}){super(e)}};oA.key="timeFromParts",oA.requiredArgs=new Set(["hour","min","sec"]),oA.availableArgs=new Set(["hour","min","sec","nano","fractions","precision","overflow"]),oA.argOrder=["hour","min","sec","nano","fractions","precision","overflow"],oA.register();var Ti=oA,UN=class UN extends d{constructor(e={}){super(e)}};UN.key="dateStrToDate",UN.argOrder=["this"],UN.register();var Wa=UN,qN=class qN extends d{constructor(e={}){super(e)}};qN.key="dateToDateStr",qN.argOrder=["this"],qN.register();var UC=qN,vN=class vN extends d{constructor(e={}){super(e)}};vN.key="dateToDi",vN.argOrder=["this"],vN.register();var Yp=vN,VE=class VE extends d{constructor(e={}){super(e)}};VE.key="date",VE.requiredArgs=new Set,VE.isVarLenArgs=!0,VE.availableArgs=new Set(["this","zone","expressions"]),VE.argOrder=["this","zone","expressions"],VE.register();var Hp=VE,FN=class FN extends d{constructor(e={}){super(e)}};FN.key="day",FN.argOrder=["this"],FN.register();var Zr=FN,cA=class cA extends d{constructor(e={}){super(e)}};cA.key="decode",cA.requiredArgs=new Set(["this","charset"]),cA.availableArgs=new Set(["this","charset","replace"]),cA.argOrder=["this","charset","replace"],cA.register();var OE=cA,WE=class WE extends d{constructor(e={}){super(e)}};WE.key="decodeCase",WE.isVarLenArgs=!0,WE.requiredArgs=new Set(["expressions"]),WE.availableArgs=new Set(["expressions"]),WE.argOrder=["expressions"],WE.register();var bg=WE,pA=class pA extends d{constructor(e={}){super(e)}};pA.key="decrypt",pA.requiredArgs=new Set(["this","passphrase"]),pA.availableArgs=new Set(["this","passphrase","aad","encryptionMethod","safe"]),pA.argOrder=["this","passphrase","aad","encryptionMethod","safe"],pA.register();var qC=pA,lA=class lA extends d{constructor(e={}){super(e)}};lA.key="decryptRaw",lA.requiredArgs=new Set(["this","key","iv"]),lA.availableArgs=new Set(["this","key","iv","aad","encryptionMethod","aead","safe"]),lA.argOrder=["this","key","iv","aad","encryptionMethod","aead","safe"],lA.register();var vC=lA,BN=class BN extends d{constructor(e={}){super(e)}};BN.key="diToDate",BN.argOrder=["this"],BN.register();var Vp=BN,uA=class uA extends d{constructor(e={}){super(e)}};uA.key="encode",uA.requiredArgs=new Set(["this","charset"]),uA.availableArgs=new Set(["this","charset"]),uA.argOrder=["this","charset"],uA.register();var Wp=uA,EA=class EA extends d{constructor(e={}){super(e)}};EA.key="encrypt",EA.requiredArgs=new Set(["this","passphrase"]),EA.availableArgs=new Set(["this","passphrase","aad","encryptionMethod"]),EA.argOrder=["this","passphrase","aad","encryptionMethod"],EA.register();var FC=EA,hA=class hA extends d{constructor(e={}){super(e)}};hA.key="encryptRaw",hA.requiredArgs=new Set(["this","key","iv"]),hA.availableArgs=new Set(["this","key","iv","aad","encryptionMethod"]),hA.argOrder=["this","key","iv","aad","encryptionMethod"],hA.register();var BC=hA,gA=class gA extends d{constructor(e={}){super(e)}};gA.key="equalNull",gA.requiredArgs=new Set(["this","expression"]),gA.availableArgs=new Set(["this","expression"]),gA.argOrder=["this","expression"],gA.register();var GC=gA,GN=class GN extends d{constructor(e={}){super(e)}};GN.key="exp",GN.argOrder=["this"],GN.register();var jp=GN,$N=class $N extends d{constructor(e={}){super(e)}};$N.key="factorial",$N.argOrder=["this"],$N.register();var Jp=$N,jE=class jE extends Q(d,as){constructor(e={}){super(e)}};jE.key="explode",jE.argOrder=["this","expressions"],jE.isVarLenArgs=!0,jE.requiredArgs=new Set(["this"]),jE.availableArgs=new Set(["this","expressions"]),jE.register();var qt=jE,YN=class YN extends d{constructor(e={}){super(e)}};YN.key="inline",YN.argOrder=["this"],YN.register();var Vx=YN,dA=class dA extends Q(d,as){constructor(e={}){super(e)}get selects(){let e=super.selects,t=this.args.offset;if(t){let s=t===!0?K("offset"):t;return[...e,s]}return e}};dA.key="unnest",dA.argOrder=["expressions","alias","offset","explodeArray"],dA.requiredArgs=new Set(["expressions"]),dA.availableArgs=new Set(["expressions","alias","offset","explodeArray"]),dA.register();var Pe=dA,xm=class xm extends d{constructor(e={}){super(e)}};xm.key="floor",xm.availableArgs=new Set(["this","decimals","to"]),xm.argOrder=["this","decimals","to"],xm.register();var wn=xm,HN=class HN extends d{constructor(e={}){super(e)}};HN.key="fromBase32",HN.argOrder=["this"],HN.register();var $C=HN,VN=class VN extends d{constructor(e={}){super(e)}};VN.key="fromBase64",VN.argOrder=["this"],VN.register();var Bh=VN,WN=class WN extends d{constructor(e={}){super(e)}};WN.key="toBase32",WN.argOrder=["this"],WN.register();var YC=WN,jN=class jN extends d{constructor(e={}){super(e)}};jN.key="toBase64",jN.argOrder=["this"],jN.register();var Gh=jN,Tm=class Tm extends d{constructor(e={}){super(e)}};Tm.key="toBinary",Tm.availableArgs=new Set(["this","format","safe"]),Tm.argOrder=["this","format","safe"],Tm.register();var Wx=Tm,Sm=class Sm extends d{constructor(e={}){super(e)}};Sm.key="base64DecodeBinary",Sm.availableArgs=new Set(["this","alphabet"]),Sm.argOrder=["this","alphabet"],Sm.register();var HC=Sm,mm=class mm extends d{constructor(e={}){super(e)}};mm.key="base64DecodeString",mm.availableArgs=new Set(["this","alphabet"]),mm.argOrder=["this","alphabet"],mm.register();var VC=mm,Rm=class Rm extends d{constructor(e={}){super(e)}};Rm.key="base64Encode",Rm.availableArgs=new Set(["this","maxLineLength","alphabet"]),Rm.argOrder=["this","maxLineLength","alphabet"],Rm.register();var WC=Rm,Om=class Om extends d{constructor(e={}){super(e)}};Om.key="tryBase64DecodeBinary",Om.availableArgs=new Set(["this","alphabet"]),Om.argOrder=["this","alphabet"],Om.register();var jC=Om,Nm=class Nm extends d{constructor(e={}){super(e)}};Nm.key="tryBase64DecodeString",Nm.availableArgs=new Set(["this","alphabet"]),Nm.argOrder=["this","alphabet"],Nm.register();var JC=Nm,JN=class JN extends d{constructor(e={}){super(e)}};JN.key="tryHexDecodeBinary",JN.argOrder=["this"],JN.register();var XC=JN,XN=class XN extends d{constructor(e={}){super(e)}};XN.key="tryHexDecodeString",XN.argOrder=["this"],XN.register();var zC=XN,Im=class Im extends d{constructor(e={}){super(e)}};Im.key="fromIso8601Timestamp",Im.argOrder=["this"],Im._sqlNames=["FROM_ISO8601_TIMESTAMP"],Im.register();var iD=Im,AA=class AA extends d{constructor(e={}){super(e)}};AA.key="gapFill",AA.requiredArgs=new Set(["this","tsColumn","bucketWidth"]),AA.availableArgs=new Set(["this","tsColumn","bucketWidth","partitioningColumns","valueColumns","origin","ignoreNulls"]),AA.argOrder=["tsColumn","bucketWidth","partitioningColumns","valueColumns","origin","ignoreNulls"],AA.register();var NO=AA,fA=class fA extends d{constructor(e={}){super(e)}};fA.key="generateDateArray",fA.requiredArgs=new Set(["start","end"]),fA.availableArgs=new Set(["start","end","step"]),fA.argOrder=["start","end","step"],fA.register();var Mn=fA,xA=class xA extends d{constructor(e={}){super(e)}};xA.key="generateTimestampArray",xA.requiredArgs=new Set(["start","end","step"]),xA.availableArgs=new Set(["start","end","step"]),xA.argOrder=["start","end","step"],xA.register();var jx=xA,TA=class TA extends d{constructor(e={}){super(e)}};TA.key="getExtract",TA.requiredArgs=new Set(["this","expression"]),TA.availableArgs=new Set(["this","expression"]),TA.argOrder=["this","expression"],TA.register();var aD=TA,SA=class SA extends d{constructor(e={}){super(e)}};SA.key="getbit",SA.requiredArgs=new Set(["this","expression"]),SA.availableArgs=new Set(["this","expression","zeroIsMsb"]),SA.argOrder=["this","expression","zeroIsMsb"],SA.register();var KC=SA,JE=class JE extends d{constructor(e={}){super(e)}};JE.key="greatest",JE.isVarLenArgs=!0,JE.requiredArgs=new Set(["this","ignoreNulls"]),JE.availableArgs=new Set(["this","expressions","ignoreNulls"]),JE.argOrder=["this","expressions","ignoreNulls"],JE.register();var op=JE,zN=class zN extends d{constructor(e={}){super(e)}};zN.key="hex",zN.argOrder=["this"],zN.register();var ac=zN,KN=class KN extends d{constructor(e={}){super(e)}};KN.key="hexDecodeString",KN.argOrder=["this"],KN.register();var QC=KN,ym=class ym extends d{constructor(e={}){super(e)}};ym.key="hexEncode",ym.availableArgs=new Set(["this","case"]),ym.argOrder=["this","case"],ym.register();var ZC=ym,QN=class QN extends d{constructor(e={}){super(e)}};QN.key="hour",QN.argOrder=["this"],QN.register();var Jx=QN,ZN=class ZN extends d{constructor(e={}){super(e)}};ZN.key="minute",ZN.argOrder=["this"],ZN.register();var Xx=ZN,eI=class eI extends d{constructor(e={}){super(e)}};eI.key="second",eI.argOrder=["this"],eI.register();var ja=eI,Cm=class Cm extends d{constructor(e={}){super(e)}};Cm.key="compress",Cm.availableArgs=new Set(["this","method"]),Cm.argOrder=["this","method"],Cm.register();var eb=Cm,mA=class mA extends d{constructor(e={}){super(e)}};mA.key="decompressBinary",mA.requiredArgs=new Set(["this","method"]),mA.availableArgs=new Set(["this","method"]),mA.argOrder=["this","method"],mA.register();var tb=mA,RA=class RA extends d{constructor(e={}){super(e)}};RA.key="decompressString",RA.requiredArgs=new Set(["this","method"]),RA.availableArgs=new Set(["this","method"]),RA.argOrder=["this","method"],RA.register();var sb=RA,XE=class XE extends d{constructor(e={}){super(e)}};XE.key="if",XE._sqlNames=["IF","IIF"],XE.requiredArgs=new Set(["this","true"]),XE.availableArgs=new Set(["this","true","false"]),XE.argOrder=["this","true","false"],XE.register();var He=XE,OA=class OA extends d{constructor(e={}){super(e)}};OA.key="nullif",OA.requiredArgs=new Set(["this","expression"]),OA.availableArgs=new Set(["this","expression"]),OA.argOrder=["this","expression"],OA.register();var zx=OA,bm=class bm extends d{constructor(e={}){super(e)}};bm.key="initcap",bm.availableArgs=new Set(["this","expression"]),bm.argOrder=["this","expression"],bm.register();var cp=bm,tI=class tI extends d{constructor(e={}){super(e)}};tI.key="isAscii",tI.argOrder=["this"],tI.register();var oD=tI,Pm=class Pm extends d{constructor(e={}){super(e)}};Pm.key="isNan",Pm.argOrder=["this"],Pm._sqlNames=["IS_NAN","ISNAN"],Pm.register();var Kx=Pm,sI=class sI extends d{constructor(e={}){super(e)}};sI.key="int64",sI.argOrder=["this"],sI.register();var Qx=sI,wm=class wm extends d{constructor(e={}){super(e)}};wm.key="isInf",wm.argOrder=["this"],wm._sqlNames=["IS_INF","ISINF"],wm.register();var rb=wm,rI=class rI extends d{constructor(e={}){super(e)}};rI.key="isNullValue",rI.argOrder=["this"],rI.register();var nb=rI,nI=class nI extends d{constructor(e={}){super(e)}};nI.key="isArray",nI.argOrder=["this"],nI.register();var cD=nI,NA=class NA extends d{constructor(e={}){super(e)}};NA.key="format",NA.isVarLenArgs=!0,NA.availableArgs=new Set(["this","expressions"]),NA.argOrder=["this","expressions"],NA.register();var Zx=NA,IA=class IA extends d{constructor(e={}){super(e)}};IA.key="jsonKeys",IA.isVarLenArgs=!0,IA.availableArgs=new Set(["this","expression","expressions"]),IA.argOrder=["this","expression","expressions"],IA.register();var IO=IA,Mm=class Mm extends d{constructor(e={}){super(e)}};Mm.key="jsonKeysAtDepth",Mm.availableArgs=new Set(["this","expression","mode"]),Mm.argOrder=["this","expression","mode"],Mm.register();var ib=Mm,Lm=class Lm extends d{constructor(e={}){super(e)}};Lm.key="jsonObject",Lm.availableArgs=new Set(["expressions","nullHandling","uniqueKeys","returnType","encoding"]),Lm.argOrder=["nullHandling","uniqueKeys","returnType","encoding"],Lm.register();var pp=Lm,Dm=class Dm extends d{constructor(e={}){super(e)}};Dm.key="jsonArray",Dm.availableArgs=new Set(["expressions","nullHandling","returnType","strict"]),Dm.argOrder=["nullHandling","returnType","strict"],Dm.register();var ab=Dm,yA=class yA extends d{constructor(e={}){super(e)}};yA.key="jsonExists",yA.requiredArgs=new Set(["this","path"]),yA.availableArgs=new Set(["this","path","passing","onCondition","fromDcolonqmark"]),yA.argOrder=["path","passing","onCondition","fromDcolonqmark"],yA.register();var pD=yA,fp=class fp extends d{constructor(e={}){super(e)}};fp.key="jsonSet",fp.isVarLenArgs=!0,fp._sqlNames=["JSON_SET"],fp.requiredArgs=new Set(["this","expressions"]),fp.availableArgs=new Set(["this","expressions"]),fp.argOrder=["this","expressions"],fp.register();var ob=fp,CA=class CA extends d{constructor(e={}){super(e)}};CA.key="jsonStripNulls",CA._sqlNames=["JSON_STRIP_NULLS"],CA.availableArgs=new Set(["this","expression","includeArrays","removeEmpty"]),CA.argOrder=["this","expression","includeArrays","removeEmpty"],CA.register();var cb=CA,_m=class _m extends d{constructor(e={}){super(e)}};_m.key="jsonValueArray",_m.availableArgs=new Set(["this","expression"]),_m.argOrder=["this","expression"],_m.register();var pb=_m,xp=class xp extends d{constructor(e={}){super(e)}};xp.key="jsonRemove",xp.isVarLenArgs=!0,xp._sqlNames=["JSON_REMOVE"],xp.requiredArgs=new Set(["this","expressions"]),xp.availableArgs=new Set(["this","expressions"]),xp.argOrder=["this","expressions"],xp.register();var lb=xp,bA=class bA extends d{constructor(e={}){super(e)}};bA.key="jsonTable",bA.requiredArgs=new Set(["this","schema"]),bA.availableArgs=new Set(["this","schema","path","errorHandling","emptyHandling"]),bA.argOrder=["this","schema","path","errorHandling","emptyHandling"],bA.register();var yO=bA,PA=class PA extends d{constructor(e={}){super(e)}};PA.key="jsontype",PA._sqlNames=["JSON_TYPE"],PA.availableArgs=new Set(["this","expression"]),PA.argOrder=["this","expression"],PA.register();var ub=PA,wA=class wA extends d{constructor(e={}){super(e)}};wA.key="objectInsert",wA.requiredArgs=new Set(["this","key","value"]),wA.availableArgs=new Set(["this","key","value","updateFlag"]),wA.argOrder=["this","key","value","updateFlag"],wA.register();var lD=wA,km=class km extends d{constructor(e={}){super(e)}};km.key="openJson",km.availableArgs=new Set(["this","path","expressions"]),km.argOrder=["this","path","expressions"],km.register();var CO=km,lp=class extends Q(Y,d){constructor(e={}){super(e)}};lp.key="jsonbContains",lp._sqlNames=["JSONB_CONTAINS"],lp.requiredArgs=new Set(["this","expression"]),lp.availableArgs=new Set(["this","expression"]);var oc=class extends Q(Y,d){constructor(e={}){super(e)}};oc.key="jsonbContainsAnyTopKeys",oc.requiredArgs=new Set(["this","expression"]),oc.availableArgs=new Set(["this","expression"]);var cc=class extends Q(Y,d){constructor(e={}){super(e)}};cc.key="jsonbContainsAllTopKeys",cc.requiredArgs=new Set(["this","expression"]),cc.availableArgs=new Set(["this","expression"]);var zE=class zE extends d{constructor(e={}){super(e)}};zE.key="jsonbExists",zE._sqlNames=["JSONB_EXISTS"],zE.requiredArgs=new Set(["this","path"]),zE.availableArgs=new Set(["this","path"]),zE.argOrder=["this","path"],zE.register();var uD=zE,pc=class extends Q(Y,d){constructor(e={}){super(e)}};pc.key="jsonbDeleteAtPath",pc.requiredArgs=new Set(["this","expression"]),pc.availableArgs=new Set(["this","expression"]);var KE=class KE extends Q(Y,d){constructor(e={}){super(e)}get outputName(){return this.args.expressions?"":_nullishCoalesce(_optionalChain([this, 'access', _872 => _872.args, 'access', _873 => _873.expression, 'optionalAccess', _874 => _874.outputName]), () => (""))}};KE.key="jsonExtract",KE.isVarLenArgs=!0,KE._sqlNames=["JSON_EXTRACT"],KE.requiredArgs=new Set(["this","expression"]),KE.availableArgs=new Set(["this","expression","onlyJsonTypes","expressions","variantExtract","jsonQuery","option","quote","onCondition","requiresJson"]),KE.register();var Zt=KE,MA=class MA extends d{constructor(e={}){super(e)}};MA.key="jsonExtractArray",MA._sqlNames=["JSON_EXTRACT_ARRAY"],MA.availableArgs=new Set(["this","expression"]),MA.argOrder=["this","expression"],MA.register();var Eb=MA,QE=class QE extends Q(Y,d){constructor(e={}){super(e)}get outputName(){return _nullishCoalesce(_optionalChain([this, 'access', _875 => _875.args, 'access', _876 => _876.expression, 'optionalAccess', _877 => _877.outputName]), () => (""))}};QE.key="jsonExtractScalar",QE.isVarLenArgs=!0,QE._sqlNames=["JSON_EXTRACT_SCALAR"],QE.requiredArgs=new Set(["this","expression"]),QE.availableArgs=new Set(["this","expression","onlyJsonTypes","expressions","jsonType","scalarOnly"]),QE.register();var Rr=QE,LA=class LA extends Q(Y,d){constructor(e={}){super(e)}};LA.key="jsonbExtract",LA._sqlNames=["JSONB_EXTRACT"],LA.requiredArgs=new Set(["this","expression"]),LA.availableArgs=new Set(["this","expression"]),LA.register();var sS=LA,DA=class DA extends Q(Y,d){constructor(e={}){super(e)}};DA.key="jsonbExtractScalar",DA._sqlNames=["JSONB_EXTRACT_SCALAR"],DA.requiredArgs=new Set(["this","expression"]),DA.availableArgs=new Set(["this","expression","jsonType"]),DA.register();var bO=DA,_A=class _A extends d{constructor(e={}){super(e)}};_A.key="jsonFormat",_A._sqlNames=["JSON_FORMAT"],_A.availableArgs=new Set(["this","options","isJson","toJson"]),_A.argOrder=["this","options","isJson","toJson"],_A.register();var Sc=_A,Tp=class Tp extends d{constructor(e={}){super(e)}};Tp.key="jsonArrayAppend",Tp.isVarLenArgs=!0,Tp._sqlNames=["JSON_ARRAY_APPEND"],Tp.requiredArgs=new Set(["this","expressions"]),Tp.availableArgs=new Set(["this","expressions"]),Tp.argOrder=["this","expressions"],Tp.register();var hb=Tp,mp=class extends Q(Y,Ve,d){constructor(e={}){super(e)}};mp.key="jsonArrayContains",mp._sqlNames=["JSON_ARRAY_CONTAINS"],mp.requiredArgs=new Set(["this","expression"]),mp.availableArgs=new Set(["this","expression","jsonType"]);var Sp=class Sp extends d{constructor(e={}){super(e)}};Sp.key="jsonArrayInsert",Sp.isVarLenArgs=!0,Sp._sqlNames=["JSON_ARRAY_INSERT"],Sp.requiredArgs=new Set(["this","expressions"]),Sp.availableArgs=new Set(["this","expressions"]),Sp.argOrder=["this","expressions"],Sp.register();var gb=Sp,iI=class iI extends d{constructor(e={}){super(e)}};iI.key="parseBignumeric",iI.argOrder=["this"],iI.register();var db=iI,aI=class aI extends d{constructor(e={}){super(e)}};aI.key="parseNumeric",aI.argOrder=["this"],aI.register();var Ab=aI,kA=class kA extends d{constructor(e={}){super(e)}};kA.key="parseJson",kA._sqlNames=["PARSE_JSON","JSON_PARSE"],kA.availableArgs=new Set(["this","expression","safe"]),kA.argOrder=["this","expression","safe"],kA.register();var up=kA,Um=class Um extends d{constructor(e={}){super(e)}};Um.key="parseUrl",Um.availableArgs=new Set(["this","partToExtract","key","permissive"]),Um.argOrder=["this","partToExtract","key","permissive"],Um.register();var fb=Um,UA=class UA extends d{constructor(e={}){super(e)}};UA.key="parseIp",UA.requiredArgs=new Set(["this","type"]),UA.availableArgs=new Set(["this","type","permissive"]),UA.argOrder=["this","type","permissive"],UA.register();var xb=UA,qA=class qA extends d{constructor(e={}){super(e)}};qA.key="parseTime",qA.requiredArgs=new Set(["this","format"]),qA.availableArgs=new Set(["this","format"]),qA.argOrder=["this","format"],qA.register();var Tb=qA,qm=class qm extends d{constructor(e={}){super(e)}};qm.key="parseDatetime",qm.availableArgs=new Set(["this","format","zone"]),qm.argOrder=["this","format","zone"],qm.register();var Sb=qm,ZE=class ZE extends d{constructor(e={}){super(e)}};ZE.key="least",ZE.isVarLenArgs=!0,ZE.requiredArgs=new Set(["this","ignoreNulls"]),ZE.availableArgs=new Set(["this","expressions","ignoreNulls"]),ZE.argOrder=["this","expressions","ignoreNulls"],ZE.register();var Pg=ZE,vA=class vA extends d{constructor(e={}){super(e)}};vA.key="left",vA.requiredArgs=new Set(["this","expression"]),vA.availableArgs=new Set(["this","expression"]),vA.argOrder=["this","expression"],vA.register();var Ja=vA,FA=class FA extends d{constructor(e={}){super(e)}};FA.key="right",FA.requiredArgs=new Set(["this","expression"]),FA.availableArgs=new Set(["this","expression"]),FA.argOrder=["this","expression"],FA.register();var _n=FA,oI=class oI extends d{constructor(e={}){super(e)}};oI.key="reverse",oI.argOrder=["this"],oI.register();var Xp=oI,BA=class BA extends d{constructor(e={}){super(e)}};BA.key="length",BA._sqlNames=["LENGTH","LEN","CHAR_LENGTH","CHARACTER_LENGTH"],BA.availableArgs=new Set(["this","binary","encoding"]),BA.argOrder=["this","binary","encoding"],BA.register();var Er=BA,cI=class cI extends d{constructor(e={}){super(e)}};cI.key="rtrimmedLength",cI.argOrder=["this"],cI.register();var mb=cI,pI=class pI extends d{constructor(e={}){super(e)}};pI.key="bitLength",pI.argOrder=["this"],pI.register();var eT=pI,vm=class vm extends d{constructor(e={}){super(e)}};vm.key="levenshtein",vm.availableArgs=new Set(["this","expression","insCost","delCost","subCost","maxDist"]),vm.argOrder=["this","expression","insCost","delCost","subCost","maxDist"],vm.register();var Si=vm,lI=class lI extends d{constructor(e={}){super(e)}};lI.key="ln",lI.argOrder=["this"],lI.register();var Ga=lI,Fm=class Fm extends d{constructor(e={}){super(e)}};Fm.key="log",Fm.availableArgs=new Set(["this","expression"]),Fm.argOrder=["this","expression"],Fm.register();var Vr=Fm,Bm=class Bm extends d{constructor(e={}){super(e)}};Bm.key="lower",Bm.argOrder=["this"],Bm._sqlNames=["LOWER","LCASE"],Bm.register();var hi=Bm,GA=class GA extends d{constructor(e={}){super(e)}get keys(){return _optionalChain([this, 'access', _878 => _878.args, 'access', _879 => _879.keys, 'optionalAccess', _880 => _880.args, 'optionalAccess', _881 => _881.expressions])||[]}get values(){return _optionalChain([this, 'access', _882 => _882.args, 'access', _883 => _883.values, 'optionalAccess', _884 => _884.args, 'optionalAccess', _885 => _885.expressions])||[]}};GA.key="map",GA.requiredArgs=new Set,GA.availableArgs=new Set(["keys","values"]),GA.argOrder=["keys","values"],GA.register();var Eo=GA,uI=class uI extends d{constructor(e={}){super(e)}};uI.key="toMap",uI.argOrder=["this"],uI.register();var tT=uI,EI=class EI extends d{constructor(e={}){super(e)}};EI.key="mapFromEntries",EI.argOrder=["this"],EI.register();var ED=EI,$A=class $A extends d{constructor(e={}){super(e)}};$A.key="mapCat",$A.requiredArgs=new Set(["this","expression"]),$A.availableArgs=new Set(["this","expression"]),$A.argOrder=["this","expression"],$A.register();var Rb=$A,YA=class YA extends d{constructor(e={}){super(e)}};YA.key="mapContainsKey",YA.requiredArgs=new Set(["this","key"]),YA.availableArgs=new Set(["this","key"]),YA.argOrder=["this","key"],YA.register();var Ob=YA,eh=class eh extends d{constructor(e={}){super(e)}};eh.key="mapDelete",eh.isVarLenArgs=!0,eh.requiredArgs=new Set(["this","expressions"]),eh.availableArgs=new Set(["this","expressions"]),eh.argOrder=["this","expressions"],eh.register();var Nb=eh,HA=class HA extends d{constructor(e={}){super(e)}};HA.key="mapInsert",HA.requiredArgs=new Set(["this","value"]),HA.availableArgs=new Set(["this","key","value","updateFlag"]),HA.argOrder=["this","key","value","updateFlag"],HA.register();var Ib=HA,hI=class hI extends d{constructor(e={}){super(e)}};hI.key="mapkeys",hI.argOrder=["this"],hI.register();var yb=hI,th=class th extends d{constructor(e={}){super(e)}};th.key="mapPick",th.isVarLenArgs=!0,th.requiredArgs=new Set(["this","expressions"]),th.availableArgs=new Set(["this","expressions"]),th.argOrder=["this","expressions"],th.register();var Cb=th,gI=class gI extends d{constructor(e={}){super(e)}};gI.key="mapSize",gI.argOrder=["this"],gI.register();var bb=gI,dI=class dI extends d{constructor(e={}){super(e)}};dI.key="starMap",dI.argOrder=["this"],dI.register();var NE=dI,sh=class sh extends d{constructor(e={}){super(e)}get keys(){return _nullishCoalesce(_optionalChain([this, 'access', _886 => _886.args, 'access', _887 => _887.keys, 'optionalAccess', _888 => _888.args, 'access', _889 => _889.expressions]), () => ([]))}get values(){return _nullishCoalesce(_optionalChain([this, 'access', _890 => _890.args, 'access', _891 => _891.values, 'optionalAccess', _892 => _892.args, 'access', _893 => _893.expressions]), () => ([]))}};sh.key="varMap",sh.isVarLenArgs=!0,sh.requiredArgs=new Set(["keys","values"]),sh.availableArgs=new Set(["keys","values"]),sh.argOrder=["keys","values"],sh.register();var gr=sh,VA=class VA extends d{constructor(e={}){super(e)}};VA.key="matchAgainst",VA.requiredArgs=new Set(["this","expressions"]),VA.availableArgs=new Set(["this","expressions","modifier"]),VA.argOrder=["this","expressions","modifier"],VA.register();var PO=VA,Gm=class Gm extends d{constructor(e={}){super(e)}};Gm.key="md5",Gm._sqlNames=["MD5"],Gm.argOrder=["this"],Gm.register();var Pb=Gm,rh=class rh extends d{constructor(e={}){super(e)}};rh.key="md5Digest",rh.isVarLenArgs=!0,rh._sqlNames=["MD5_DIGEST"],rh.availableArgs=new Set(["this","expressions"]),rh.argOrder=["this","expressions"],rh.register();var en=rh,AI=class AI extends d{constructor(e={}){super(e)}};AI.key="md5NumberLower64",AI.argOrder=["this"],AI.register();var wb=AI,fI=class fI extends d{constructor(e={}){super(e)}};fI.key="md5NumberUpper64",fI.argOrder=["this"],fI.register();var Mb=fI,xI=class xI extends d{constructor(e={}){super(e)}};xI.key="month",xI.argOrder=["this"],xI.register();var Js=xI,$m=class $m extends d{constructor(e={}){super(e)}};$m.key="monthname",$m.availableArgs=new Set(["this","abbreviated"]),$m.argOrder=["this","abbreviated"],$m.register();var sT=$m,WA=class WA extends d{constructor(e={}){super(e)}};WA.key="addMonths",WA.requiredArgs=new Set(["this","expression"]),WA.availableArgs=new Set(["this","expression","preserveEndOfMonth"]),WA.argOrder=["this","expression","preserveEndOfMonth"],WA.register();var Lb=WA,jA=class jA extends d{constructor(e={}){super(e)}};jA.key="nvl2",jA.requiredArgs=new Set(["this","true"]),jA.availableArgs=new Set(["this","true","false"]),jA.argOrder=["this","true","false"],jA.register();var hD=jA,Ym=class Ym extends d{constructor(e={}){super(e)}};Ym.key="normalize",Ym.availableArgs=new Set(["this","form","isCasefold"]),Ym.argOrder=["this","form","isCasefold"],Ym.register();var wg=Ym,JA=class JA extends d{constructor(e={}){super(e)}};JA.key="normal",JA.requiredArgs=new Set(["this","stddev","gen"]),JA.availableArgs=new Set(["this","stddev","gen"]),JA.argOrder=["this","stddev","gen"],JA.register();var Db=JA,TI=class TI extends d{constructor(e={}){super(e)}};TI.key="netFunc",TI.argOrder=["this"],TI.register();var rT=TI,SI=class SI extends d{constructor(e={}){super(e)}};SI.key="host",SI.argOrder=["this"],SI.register();var _b=SI,mI=class mI extends d{constructor(e={}){super(e)}};mI.key="regDomain",mI.argOrder=["this"],mI.register();var kb=mI,XA=class XA extends d{constructor(e={}){super(e)}};XA.key="overlay",XA.requiredArgs=new Set(["this","expression","from"]),XA.availableArgs=new Set(["this","expression","from","for"]),XA.argOrder=["this","expression","from","for"],XA.register();var Mg=XA,zA=class zA extends d{constructor(e={}){super(e)}};zA.key="predict",zA.requiredArgs=new Set(["this","expression"]),zA.availableArgs=new Set(["this","expression","paramsStruct"]),zA.argOrder=["this","expression","paramsStruct"],zA.register();var gD=zA,KA=class KA extends d{constructor(e={}){super(e)}};KA.key="mlTranslate",KA.requiredArgs=new Set(["this","expression","paramsStruct"]),KA.availableArgs=new Set(["this","expression","paramsStruct"]),KA.argOrder=["this","expression","paramsStruct"],KA.register();var dD=KA,Hm=class Hm extends d{constructor(e={}){super(e)}};Hm.key="featuresAtTime",Hm.availableArgs=new Set(["this","time","numRows","ignoreFeatureNulls"]),Hm.argOrder=["this","time","numRows","ignoreFeatureNulls"],Hm.register();var AD=Hm,QA=class QA extends d{constructor(e={}){super(e)}};QA.key="generateEmbedding",QA.requiredArgs=new Set(["this","expression"]),QA.availableArgs=new Set(["this","expression","paramsStruct","isText"]),QA.argOrder=["this","expression","paramsStruct","isText"],QA.register();var fD=QA,Vm=class Vm extends d{constructor(e={}){super(e)}};Vm.key="mlForecast",Vm.availableArgs=new Set(["this","expression","paramsStruct"]),Vm.argOrder=["this","expression","paramsStruct"],Vm.register();var xD=Vm,ZA=class ZA extends d{constructor(e={}){super(e)}};ZA.key="vectorSearch",ZA.requiredArgs=new Set(["this","columnToSearch","queryTable"]),ZA.availableArgs=new Set(["this","columnToSearch","queryTable","queryColumnToSearch","topK","distanceType","options"]),ZA.argOrder=["columnToSearch","queryTable","queryColumnToSearch","topK","distanceType","options"],ZA.register();var TD=ZA,ef=class ef extends d{constructor(e={}){super(e)}};ef.key="pi",ef.requiredArgs=new Set,ef.availableArgs=new Set,ef.argOrder=["this"],ef.register();var Ub=ef,nh=class nh extends Q(Y,d){constructor(e={}){super(e)}};nh.key="pow",nh._sqlNames=["POWER","POW"],nh.argOrder=["this","expression"],nh.requiredArgs=new Set(["this","expression"]),nh.availableArgs=new Set(["this","expression"]),nh.register();var zp=nh,tf=class tf extends d{constructor(e={}){super(e)}};tf.key="approxPercentileEstimate",tf.requiredArgs=new Set(["this","percentile"]),tf.availableArgs=new Set(["this","percentile"]),tf.argOrder=["this","percentile"],tf.register();var qb=tf,RI=class RI extends d{constructor(e={}){super(e)}};RI.key="quarter",RI.argOrder=["this"],RI.register();var Kp=RI,sf=class sf extends d{constructor(e={}){super(e)}};sf.key="rand",sf._sqlNames=["RAND","RANDOM"],sf.availableArgs=new Set(["this","lower","upper"]),sf.argOrder=["this","lower","upper"],sf.register();var xr=sf,Wm=class Wm extends d{constructor(e={}){super(e)}};Wm.key="randn",Wm.requiredArgs=new Set,Wm.argOrder=["this"],Wm.register();var Eg=Wm,jm=class jm extends d{constructor(e={}){super(e)}};jm.key="randstr",jm.availableArgs=new Set(["this","generator"]),jm.argOrder=["this","generator"],jm.register();var nT=jm,rf=class rf extends d{constructor(e={}){super(e)}};rf.key="rangeN",rf.requiredArgs=new Set(["this","expressions"]),rf.availableArgs=new Set(["this","expressions","each"]),rf.argOrder=["this","expressions","each"],rf.register();var SD=rf,nf=class nf extends d{constructor(e={}){super(e)}};nf.key="rangeBucket",nf.requiredArgs=new Set(["this","expression"]),nf.availableArgs=new Set(["this","expression"]),nf.argOrder=["this","expression"],nf.register();var vb=nf,ih=class ih extends d{constructor(e={}){super(e)}};ih.key="readCsv",ih.isVarLenArgs=!0,ih._sqlNames=["READ_CSV"],ih.availableArgs=new Set(["this","expressions"]),ih.argOrder=["this","expressions"],ih.register();var mD=ih,ah=class ah extends d{constructor(e={}){super(e)}};ah.key="readParquet",ah.isVarLenArgs=!0,ah.requiredArgs=new Set(["expressions"]),ah.availableArgs=new Set(["expressions"]),ah.argOrder=["expressions"],ah.register();var RD=ah,af=class af extends d{constructor(e={}){super(e)}};af.key="reduce",af.requiredArgs=new Set(["this","initial","merge"]),af.availableArgs=new Set(["this","initial","merge","finish"]),af.argOrder=["this","initial","merge","finish"],af.register();var OD=af,of=class of extends d{constructor(e={}){super(e)}};of.key="regexpExtract",of.requiredArgs=new Set(["this","expression"]),of.availableArgs=new Set(["this","expression","position","occurrence","parameters","group","nullIfPosOverflow"]),of.argOrder=["this","expression","position","occurrence","parameters","group","nullIfPosOverflow"],of.register();var br=of,cf=class cf extends d{constructor(e={}){super(e)}};cf.key="regexpExtractAll",cf.requiredArgs=new Set(["this","expression"]),cf.availableArgs=new Set(["this","expression","group","parameters","position","occurrence"]),cf.argOrder=["group","parameters","position","occurrence"],cf.register();var kn=cf,pf=class pf extends d{constructor(e={}){super(e)}};pf.key="regexpReplace",pf.requiredArgs=new Set(["this","expression"]),pf.availableArgs=new Set(["this","expression","replacement","position","occurrence","modifiers","singleReplace"]),pf.argOrder=["this","expression","replacement","position","occurrence","modifiers","singleReplace"],pf.register();var Xa=pf,lf=class lf extends Q(Y,d){constructor(e={}){super(e)}};lf.key="regexpLike",lf.argOrder=["this","expression"],lf.requiredArgs=new Set(["this","expression"]),lf.availableArgs=new Set(["this","expression","flag","fullMatch"]),lf.register();var lc=lf,uf=class uf extends Q(Y,d){constructor(e={}){super(e)}};uf.key="regexpIlike",uf.argOrder=["this","expression"],uf.requiredArgs=new Set(["this","expression"]),uf.availableArgs=new Set(["this","expression","flag"]),uf.register();var wO=uf,Ef=class Ef extends Q(Y,d){constructor(e={}){super(e)}};Ef.key="regexpFullMatch",Ef.argOrder=["this","expression","options"],Ef.requiredArgs=new Set(["this","expression"]),Ef.availableArgs=new Set(["this","expression","options"]),Ef.register();var ND=Ef,hf=class hf extends d{constructor(e={}){super(e)}};hf.key="regexpInstr",hf.requiredArgs=new Set(["this","expression"]),hf.availableArgs=new Set(["this","expression","position","occurrence","option","parameters","group"]),hf.argOrder=["this","expression","position","occurrence","option","parameters","group"],hf.register();var iT=hf,gf=class gf extends d{constructor(e={}){super(e)}};gf.key="regexpSplit",gf.requiredArgs=new Set(["this","expression"]),gf.availableArgs=new Set(["this","expression","limit"]),gf.argOrder=["this","expression","limit"],gf.register();var $h=gf,df=class df extends d{constructor(e={}){super(e)}};df.key="regexpCount",df.requiredArgs=new Set(["this","expression"]),df.availableArgs=new Set(["this","expression","position","parameters"]),df.argOrder=["this","expression","position","parameters"],df.register();var Fb=df,Af=class Af extends d{constructor(e={}){super(e)}};Af.key="repeat",Af.requiredArgs=new Set(["this","times"]),Af.availableArgs=new Set(["this","times"]),Af.argOrder=["this","times"],Af.register();var Qp=Af,ff=class ff extends d{constructor(e={}){super(e)}};ff.key="replace",ff.requiredArgs=new Set(["this","expression"]),ff.availableArgs=new Set(["this","expression","replacement"]),ff.argOrder=["this","expression","replacement"],ff.register();var za=ff,OI=class OI extends d{constructor(e={}){super(e)}};OI.key="radians",OI.argOrder=["this"],OI.register();var Zp=OI,Jm=class Jm extends d{constructor(e={}){super(e)}};Jm.key="round",Jm.availableArgs=new Set(["this","decimals","truncate","castsNonIntegerDecimals"]),Jm.argOrder=["this","decimals","truncate","castsNonIntegerDecimals"],Jm.register();var Ka=Jm,xf=class xf extends d{constructor(e={}){super(e)}};xf.key="trunc",xf._sqlNames=["TRUNC","TRUNCATE"],xf.availableArgs=new Set(["this","decimals"]),xf.argOrder=["this","decimals"],xf.register();var Yh=xf,Tf=class Tf extends d{constructor(e={}){super(e)}};Tf.key="rowNumber",Tf.argOrder=["this"],Tf.requiredArgs=new Set,Tf.availableArgs=new Set(["this"]),Tf.register();var aT=Tf,Sf=class Sf extends d{constructor(e={}){super(e)}};Sf.key="seq1",Sf.argOrder=["this"],Sf.requiredArgs=new Set,Sf.availableArgs=new Set(["this"]),Sf.register();var Bb=Sf,mf=class mf extends d{constructor(e={}){super(e)}};mf.key="seq2",mf.argOrder=["this"],mf.requiredArgs=new Set,mf.availableArgs=new Set(["this"]),mf.register();var Gb=mf,Rf=class Rf extends d{constructor(e={}){super(e)}};Rf.key="seq4",Rf.argOrder=["this"],Rf.requiredArgs=new Set,Rf.availableArgs=new Set(["this"]),Rf.register();var $b=Rf,Of=class Of extends d{constructor(e={}){super(e)}};Of.key="seq8",Of.argOrder=["this"],Of.requiredArgs=new Set,Of.availableArgs=new Set(["this"]),Of.register();var Yb=Of,Nf=class Nf extends d{constructor(e={}){super(e)}};Nf.key="safeAdd",Nf.requiredArgs=new Set(["this","expression"]),Nf.availableArgs=new Set(["this","expression"]),Nf.argOrder=["this","expression"],Nf.register();var Hb=Nf,If=class If extends d{constructor(e={}){super(e)}};If.key="safeDivide",If.requiredArgs=new Set(["this","expression"]),If.availableArgs=new Set(["this","expression"]),If.argOrder=["this","expression"],If.register();var Hh=If,yf=class yf extends d{constructor(e={}){super(e)}};yf.key="safeMultiply",yf.requiredArgs=new Set(["this","expression"]),yf.availableArgs=new Set(["this","expression"]),yf.argOrder=["this","expression"],yf.register();var Vb=yf,NI=class NI extends d{constructor(e={}){super(e)}};NI.key="safeNegate",NI.argOrder=["this"],NI.register();var Wb=NI,Cf=class Cf extends d{constructor(e={}){super(e)}};Cf.key="safeSubtract",Cf.requiredArgs=new Set(["this","expression"]),Cf.availableArgs=new Set(["this","expression"]),Cf.argOrder=["this","expression"],Cf.register();var jb=Cf,II=class II extends d{constructor(e={}){super(e)}};II.key="safeConvertBytesToString",II.argOrder=["this"],II.register();var Jb=II,Xm=class Xm extends d{constructor(e={}){super(e)}};Xm.key="sha",Xm.argOrder=["this"],Xm._sqlNames=["SHA","Sha1"],Xm.register();var el=Xm,bf=class bf extends d{constructor(e={}){super(e)}};bf.key="sha2",bf._sqlNames=["Sha2"],bf.availableArgs=new Set(["this","length"]),bf.argOrder=["this","length"],bf.register();var Qa=bf,yI=class yI extends d{constructor(e={}){super(e)}};yI.key="sha1Digest",yI.argOrder=["this"],yI.register();var tl=yI,zm=class zm extends d{constructor(e={}){super(e)}};zm.key="sha2Digest",zm.availableArgs=new Set(["this","length"]),zm.argOrder=["this","length"],zm.register();var sl=zm,Km=class Km extends d{constructor(e={}){super(e)}};Km.key="sign",Km.argOrder=["this"],Km._sqlNames=["SIGN","SIGNUM"],Km.register();var rl=Km,Qm=class Qm extends d{constructor(e={}){super(e)}};Qm.key="sortArray",Qm.availableArgs=new Set(["this","asc","nullsFirst"]),Qm.argOrder=["this","asc","nullsFirst"],Qm.register();var oT=Qm,CI=class CI extends d{constructor(e={}){super(e)}};CI.key="soundex",CI.argOrder=["this"],CI.register();var tn=CI,bI=class bI extends d{constructor(e={}){super(e)}};bI.key="soundexP123",bI.argOrder=["this"],bI.register();var Xb=bI,Pf=class Pf extends d{constructor(e={}){super(e)}};Pf.key="split",Pf.requiredArgs=new Set(["this","expression"]),Pf.availableArgs=new Set(["this","expression","limit"]),Pf.argOrder=["this","expression","limit"],Pf.register();var nl=Pf,Zm=class Zm extends d{constructor(e={}){super(e)}};Zm.key="splitPart",Zm.availableArgs=new Set(["this","delimiter","partIndex"]),Zm.argOrder=["this","delimiter","partIndex"],Zm.register();var zb=Zm,wf=class wf extends d{constructor(e={}){super(e)}};wf.key="substring",wf._sqlNames=["SUBSTRING","SUBSTR"],wf.availableArgs=new Set(["this","start","length"]),wf.argOrder=["this","start","length"],wf.register();var Ms=wf,Mf=class Mf extends d{constructor(e={}){super(e)}};Mf.key="substringIndex",Mf.requiredArgs=new Set(["this","delimiter","count"]),Mf.availableArgs=new Set(["this","delimiter","count"]),Mf.argOrder=["this","delimiter","count"],Mf.register();var ID=Mf,eR=class eR extends d{constructor(e={}){super(e)}};eR.key="standardHash",eR.availableArgs=new Set(["this","expression"]),eR.argOrder=["this","expression"],eR.register();var yD=eR,oh=class oh extends d{constructor(e={}){super(e)}};oh.key="startswith",oh._sqlNames=["STARTS_WITH","STARTSWITH"],oh.requiredArgs=new Set(["this","expression"]),oh.availableArgs=new Set(["this","expression"]),oh.argOrder=["this","expression"],oh.register();var hg=oh,ch=class ch extends d{constructor(e={}){super(e)}};ch.key="endsWith",ch._sqlNames=["ENDS_WITH","ENDSWITH"],ch.requiredArgs=new Set(["this","expression"]),ch.availableArgs=new Set(["this","expression"]),ch.argOrder=["this","expression"],ch.register();var Kb=ch,Lf=class Lf extends d{constructor(e={}){super(e)}};Lf.key="strPosition",Lf.requiredArgs=new Set(["this","substr"]),Lf.availableArgs=new Set(["this","substr","position","occurrence"]),Lf.argOrder=["this","substr","position","occurrence"],Lf.register();var ps=Lf,Df=class Df extends d{constructor(e={}){super(e)}};Df.key="search",Df.requiredArgs=new Set(["this","expression"]),Df.availableArgs=new Set(["this","expression","jsonScope","analyzer","analyzerOptions","searchMode"]),Df.argOrder=["this","expression","jsonScope","analyzer","analyzerOptions","searchMode"],Df.register();var Qb=Df,_f=class _f extends d{constructor(e={}){super(e)}};_f.key="searchIp",_f.requiredArgs=new Set(["this","expression"]),_f.availableArgs=new Set(["this","expression"]),_f.argOrder=["this","expression"],_f.register();var Zb=_f,tR=class tR extends d{constructor(e={}){super(e)}};tR.key="strToDate",tR.availableArgs=new Set(["this","format","safe"]),tR.argOrder=["this","format","safe"],tR.register();var ar=tR,kf=class kf extends d{constructor(e={}){super(e)}};kf.key="strToTime",kf.requiredArgs=new Set(["this","format"]),kf.availableArgs=new Set(["this","format","zone","safe","targetType"]),kf.argOrder=["this","format","zone","safe","targetType"],kf.register();var Jt=kf,Uf=class Uf extends d{constructor(e={}){super(e)}};Uf.key="strToUnix",Uf.requiredArgs=new Set,Uf.availableArgs=new Set(["this","format"]),Uf.argOrder=["format","this"],Uf.register();var Vh=Uf,sR=class sR extends d{constructor(e={}){super(e)}};sR.key="strToMap",sR.availableArgs=new Set(["this","pairDelim","keyValueDelim","duplicateResolutionCallback"]),sR.argOrder=["this","pairDelim","keyValueDelim","duplicateResolutionCallback"],sR.register();var Wh=sR,qf=class qf extends d{constructor(e={}){super(e)}};qf.key="numberToStr",qf.requiredArgs=new Set(["this","format"]),qf.availableArgs=new Set(["this","format","culture"]),qf.argOrder=["this","format","culture"],qf.register();var jh=qf,vf=class vf extends d{constructor(e={}){super(e)}};vf.key="fromBase",vf.requiredArgs=new Set(["this","expression"]),vf.availableArgs=new Set(["this","expression"]),vf.argOrder=["this","expression"],vf.register();var CD=vf,PI=class PI extends d{constructor(e={}){super(e)}};PI.key="space",PI.argOrder=["this"],PI.register();var eP=PI,ph=class ph extends d{constructor(e={}){super(e)}};ph.key="struct",ph.isVarLenArgs=!0,ph.requiredArgs=new Set([]),ph.availableArgs=new Set(["expressions"]),ph.argOrder=["expressions"],ph.register();var Hs=ph,Ff=class Ff extends d{constructor(e={}){super(e)}};Ff.key="structExtract",Ff.requiredArgs=new Set(["this","expression"]),Ff.availableArgs=new Set(["this","expression"]),Ff.argOrder=["this","expression"],Ff.register();var cT=Ff,lh=class lh extends d{constructor(e={}){super(e)}};lh.key="stuff",lh._sqlNames=["STUFF","INSERT"],lh.requiredArgs=new Set(["this","start","length","expression"]),lh.availableArgs=new Set(["this","start","length","expression"]),lh.argOrder=["this","start","length","expression"],lh.register();var il=lh,wI=class wI extends d{constructor(e={}){super(e)}};wI.key="sqrt",wI.argOrder=["this"],wI.register();var $a=wI,Bf=class Bf extends d{constructor(e={}){super(e)}};Bf.key="time",Bf.requiredArgs=new Set,Bf.availableArgs=new Set(["this","zone"]),Bf.argOrder=["zone","this"],Bf.register();var tP=Bf,Gf=class Gf extends d{constructor(e={}){super(e)}};Gf.key="timeToStr",Gf.requiredArgs=new Set(["this","format"]),Gf.availableArgs=new Set(["this","format","culture","zone"]),Gf.argOrder=["this","format","culture","zone"],Gf.register();var Ns=Gf,MI=class MI extends d{constructor(e={}){super(e)}};MI.key="timeToTimeStr",MI.argOrder=["this"],MI.register();var sP=MI,LI=class LI extends d{constructor(e={}){super(e)}};LI.key="timeToUnix",LI.argOrder=["this"],LI.register();var Za=LI,DI=class DI extends d{constructor(e={}){super(e)}};DI.key="timeStrToDate",DI.argOrder=["this"],DI.register();var al=DI,rR=class rR extends d{constructor(e={}){super(e)}};rR.key="timeStrToTime",rR.availableArgs=new Set(["this","zone"]),rR.argOrder=["zone","this"],rR.register();var Xs=rR,_I=class _I extends d{constructor(e={}){super(e)}};_I.key="timeStrToUnix",_I.argOrder=["this"],_I.register();var ol=_I,nR=class nR extends d{constructor(e={}){super(e)}};nR.key="trim",nR.availableArgs=new Set(["this","expression","position","collation"]),nR.argOrder=["this","expression","position","collation"],nR.register();var or=nR,$f=class $f extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}get returnType(){let e=this.args.returnType;return e instanceof C?e:C.build("date")}};$f.key="tsOrDsAdd",$f.argOrder=["this","expression","unit","returnType"],$f.requiredArgs=new Set(["this","expression"]),$f.availableArgs=new Set(["this","expression","unit","returnType"]),$f.register();var sn=$f,Yf=class Yf extends Q(d,Re){constructor(e={}){super(Re.initTimeArgs(e))}};Yf.key="tsOrDsDiff",Yf.argOrder=["this","expression","unit"],Yf.requiredArgs=new Set(["this","expression"]),Yf.availableArgs=new Set(["this","expression","unit"]),Yf.register();var cl=Yf,kI=class kI extends d{constructor(e={}){super(e)}};kI.key="tsOrDsToDateStr",kI.argOrder=["this"],kI.register();var rP=kI,iR=class iR extends d{constructor(e={}){super(e)}};iR.key="tsOrDsToDate",iR.availableArgs=new Set(["this","format","safe"]),iR.argOrder=["this","format","safe"],iR.register();var Ue=iR,UI=class UI extends d{constructor(e={}){super(e)}};UI.key="tsOrDsToDatetime",UI.argOrder=["this"],UI.register();var nP=UI,aR=class aR extends d{constructor(e={}){super(e)}};aR.key="tsOrDsToTime",aR.availableArgs=new Set(["this","format","safe"]),aR.argOrder=["format","safe","this"],aR.register();var pl=aR,qI=class qI extends d{constructor(e={}){super(e)}};qI.key="tsOrDsToTimestamp",qI.argOrder=["this"],qI.register();var iP=qI,vI=class vI extends d{constructor(e={}){super(e)}};vI.key="tsOrDiToDi",vI.argOrder=["this"],vI.register();var ll=vI,oR=class oR extends d{constructor(e={}){super(e)}};oR.key="unhex",oR.availableArgs=new Set(["this","expression"]),oR.argOrder=["this","expression"],oR.register();var mi=oR,FI=class FI extends d{constructor(e={}){super(e)}};FI.key="unicode",FI.argOrder=["this"],FI.register();var ul=FI,Hf=class Hf extends d{constructor(e={}){super(e)}};Hf.key="uniform",Hf.requiredArgs=new Set(["this","expression"]),Hf.availableArgs=new Set(["this","expression","gen","seed"]),Hf.argOrder=["this","expression","gen","seed"],Hf.register();var bD=Hf,BI=class BI extends d{constructor(e={}){super(e)}};BI.key="unixDate",BI.argOrder=["this"],BI.register();var aP=BI,cR=class cR extends d{constructor(e={}){super(e)}};cR.key="unixToStr",cR.availableArgs=new Set(["this","format"]),cR.argOrder=["format","this"],cR.register();var mc=cR,cr=class cr extends d{constructor(e={}){super(e)}};cr.key="unixToTime",cr.availableArgs=new Set(["this","scale","zone","hours","minutes","format","targetType"]),cr.argOrder=["this","scale","zone","hours","minutes","format","targetType"],cr.SECONDS=w.number(0),cr.DECIS=w.number(1),cr.CENTIS=w.number(2),cr.MILLIS=w.number(3),cr.DECIMILLIS=w.number(4),cr.CENTIMILLIS=w.number(5),cr.MICROS=w.number(6),cr.DECIMICROS=w.number(7),cr.CENTIMICROS=w.number(8),cr.NANOS=w.number(9),cr.register();var Us=cr,GI=class GI extends d{constructor(e={}){super(e)}};GI.key="unixToTimeStr",GI.argOrder=["this"],GI.register();var El=GI,$I=class $I extends d{constructor(e={}){super(e)}};$I.key="unixSeconds",$I.argOrder=["this"],$I.register();var oP=$I,YI=class YI extends d{constructor(e={}){super(e)}};YI.key="unixMicros",YI.argOrder=["this"],YI.register();var cP=YI,HI=class HI extends d{constructor(e={}){super(e)}};HI.key="unixMillis",HI.argOrder=["this"],HI.register();var pP=HI,Vf=class Vf extends d{constructor(e={}){super(e)}};Vf.key="uuid",Vf._sqlNames=["UUID","GEN_RANDOM_UUID","GENERATE_UUID","UUID_STRING"],Vf.availableArgs=new Set(["this","name","isString"]),Vf.argOrder=["name","isString","this"],Vf.register();var Ao=Vf,SV={year:!1,month:!1,day:!1,hour:!1,min:!1,sec:!1,nano:!1},uh=class uh extends d{constructor(e={}){super(e)}};uh.key="timestampFromParts",uh._sqlNames=["TIMESTAMP_FROM_PARTS","TIMESTAMPFROMPARTS"],uh.requiredArgs=new Set,uh.availableArgs=new Set(["year","month","day","hour","min","sec","nano","zone","milli","this","expression"]),uh.argOrder=["year","month","day","hour","min","sec","nano","zone","milli","this","expression"],uh.register();var Jh=uh,Wf=class Wf extends d{constructor(e={}){super(e)}};Wf.key="timestampLtzFromParts",Wf.argOrder=["year","month","day","hour","min","sec","nano"],Wf._sqlNames=["TIMESTAMP_LTZ_FROM_PARTS","TIMESTAMPLTZFROMPARTS"],Wf.availableArgs=new Set(["year","month","day","hour","min","sec","nano"]),Wf.register();var lP=Wf,jf=class jf extends d{constructor(e={}){super(e)}};jf.key="timestampTzFromParts",jf._sqlNames=["TIMESTAMP_TZ_FROM_PARTS","TIMESTAMPTZFROMPARTS"],jf.availableArgs=new Set(["year","month","day","hour","min","sec","nano","zone"]),jf.argOrder=["zone"],jf.register();var uP=jf,pR=class pR extends d{constructor(e={}){super(e)}};pR.key="upper",pR.argOrder=["this"],pR._sqlNames=["UPPER","UCASE"],pR.register();var Ep=pR,Jf=class Jf extends Q(Y,q){constructor(e={}){super(e)}};Jf.key="corr",Jf.requiredArgs=new Set(["this","expression"]),Jf.availableArgs=new Set(["this","expression","nullOnZeroVariance"]),Jf.argOrder=["this","expression","nullOnZeroVariance"],Jf.register();var pT=Jf,lR=class lR extends d{constructor(e={}){super(e)}};lR.key="widthBucket",lR.availableArgs=new Set(["this","minValue","maxValue","numBuckets","threshold"]),lR.argOrder=["this","minValue","maxValue","numBuckets","threshold"],lR.register();var lT=lR,Xf=class Xf extends d{constructor(e={}){super(e)}};Xf.key="week",Xf.requiredArgs=new Set,Xf.availableArgs=new Set(["this","mode"]),Xf.argOrder=["this","mode"],Xf.register();var Un=Xf,zf=class zf extends d{constructor(e={}){super(e)}};zf.key="nextDay",zf.requiredArgs=new Set(["this","expression"]),zf.availableArgs=new Set(["this","expression"]),zf.argOrder=["this","expression"],zf.register();var EP=zf,Kf=class Kf extends d{constructor(e={}){super(e)}};Kf.key="xmlElement",Kf._sqlNames=["XmlELEMENT"],Kf.availableArgs=new Set(["this","expressions","evalname"]),Kf.argOrder=["evalname","this","expressions"],Kf.register();var MO=Kf,Eh=class Eh extends d{constructor(e={}){super(e)}};Eh.key="xmlGet",Eh._sqlNames=["XmlGET"],Eh.requiredArgs=new Set(["this","expression"]),Eh.availableArgs=new Set(["this","expression","instance"]),Eh.argOrder=["this","expression","instance"],Eh.register();var hP=Eh,uR=class uR extends d{constructor(e={}){super(e)}};uR.key="xmlTable",uR.availableArgs=new Set(["this","namespaces","passing","columns","byRef"]),uR.argOrder=["this","namespaces","passing","columns","byRef"],uR.register();var LO=uR,VI=class VI extends d{constructor(e={}){super(e)}};VI.key="year",VI.argOrder=["this"],VI.register();var qn=VI,Qf=class Qf extends d{constructor(e={}){super(e)}};Qf.key="zipf",Qf.requiredArgs=new Set(["this","elementcount","gen"]),Qf.availableArgs=new Set(["this","elementcount","gen"]),Qf.argOrder=["elementcount","gen","this"],Qf.register();var gP=Qf,ER=class ER extends d{constructor(e={}){super(e)}};ER.key="nextValueFor",ER.availableArgs=new Set(["this","order"]),ER.argOrder=["order","this"],ER.register();var DO=ER,qs=class extends Vn{constructor(e={}){super(e)}};qs.key="all";var wt=class extends Vn{constructor(e={}){super(e)}};wt.key="any";var $w=class $w extends q{constructor(e={}){super(e)}};$w.key="bitwiseAndAgg",$w.register();var Rc=$w,Yw=class Yw extends q{constructor(e={}){super(e)}};Yw.key="bitwiseOrAgg",Yw.register();var Oc=Yw,Hw=class Hw extends q{constructor(e={}){super(e)}};Hw.key="bitwiseXorAgg",Hw.register();var Nc=Hw,Vw=class Vw extends q{constructor(e={}){super(e)}};Vw.key="boolxorAgg",Vw.register();var dP=Vw,Ww=class Ww extends q{constructor(e={}){super(e)}};Ww.key="bitmapConstructAgg",Ww.register();var AP=Ww,jw=class jw extends q{constructor(e={}){super(e)}};jw.key="bitmapOrAgg",jw.register();var fP=jw,Zf=class Zf extends q{constructor(e={}){super(e)}};Zf.key="parameterizedAgg",Zf.argOrder=["this","expressions","params"],Zf.requiredArgs=new Set(["this","expressions","params"]),Zf.availableArgs=new Set(["this","expressions","params"]),Zf.register();var vw=Zf,hh=class hh extends q{constructor(e={}){super(e)}};hh.key="argMax",hh.argOrder=["this","expression","count"],hh._sqlNames=["ARG_MAX","ARGMAX","MAX_BY"],hh.requiredArgs=new Set(["this","expression"]),hh.availableArgs=new Set(["this","expression","count"]),hh.register();var Wr=hh,gh=class gh extends q{constructor(e={}){super(e)}};gh.key="argMin",gh.argOrder=["this","expression","count"],gh._sqlNames=["ARG_MIN","ARGMIN","MIN_BY"],gh.requiredArgs=new Set(["this","expression"]),gh.availableArgs=new Set(["this","expression","count"]),gh.register();var jr=gh,hR=class hR extends q{constructor(e={}){super(e)}};hR.key="approxTopK",hR.argOrder=["this","expression","counters"],hR.availableArgs=new Set(["this","expression","counters"]),hR.register();var uT=hR,gR=class gR extends q{constructor(e={}){super(e)}};gR.key="approxTopKAccumulate",gR.argOrder=["this","expression"],gR.availableArgs=new Set(["this","expression"]),gR.register();var xP=gR,dR=class dR extends q{constructor(e={}){super(e)}};dR.key="approxTopKCombine",dR.argOrder=["this","expression"],dR.availableArgs=new Set(["this","expression"]),dR.register();var TP=dR,ex=class ex extends q{constructor(e={}){super(e)}};ex.key="approxTopSum",ex.argOrder=["this","expression","count"],ex.requiredArgs=new Set(["this","expression","count"]),ex.availableArgs=new Set(["this","expression","count"]),ex.register();var SP=ex,AR=class AR extends q{constructor(e={}){super(e)}};AR.key="approxQuantiles",AR.argOrder=["this","expression"],AR.availableArgs=new Set(["this","expression"]),AR.register();var mP=AR,Jw=class Jw extends q{constructor(e={}){super(e)}};Jw.key="approxPercentileCombine",Jw.register();var RP=Jw,dh=class dh extends q{constructor(e={}){super(e)}};dh.key="minhash",dh.argOrder=["this","expressions"],dh.isVarLenArgs=!0,dh.requiredArgs=new Set(["this","expressions"]),dh.availableArgs=new Set(["this","expressions"]),dh.register();var OP=dh,Xw=class Xw extends q{constructor(e={}){super(e)}};Xw.key="minhashCombine",Xw.register();var NP=Xw,WI=class WI extends q{constructor(e={}){super(e)}};WI.key="approximateSimilarity",WI._sqlNames=["APPROXIMATE_SIMILARITY","APPROXIMATE_JACCARD_INDEX"],WI.register();var IP=WI,Ah=class Ah extends q{constructor(e={}){super(e)}};Ah.key="grouping",Ah.isVarLenArgs=!0,Ah.argOrder=["expressions"],Ah.requiredArgs=new Set(["expressions"]),Ah.availableArgs=new Set(["expressions"]),Ah.register();var ET=Ah,tx=class tx extends q{constructor(e={}){super(e)}};tx.key="groupingId",tx.requiredArgs=new Set,tx.isVarLenArgs=!0,tx.availableArgs=new Set(["expressions"]),tx.register();var yP=tx,sx=class sx extends q{constructor(e={}){super(e)}};sx.key="anonymousAggFunc",sx.argOrder=["this","expressions"],sx.isVarLenArgs=!0,sx.availableArgs=new Set(["this","expressions"]),sx.register();var Fw=sx,rx=class rx extends q{constructor(e={}){super(e)}};rx.key="hashAgg",rx.argOrder=["this","expressions"],rx.isVarLenArgs=!0,rx.availableArgs=new Set(["this","expressions"]),rx.register();var CP=rx,nx=class nx extends q{constructor(e={}){super(e)}};nx.key="hll",nx.argOrder=["this","expressions"],nx.isVarLenArgs=!0,nx.availableArgs=new Set(["this","expressions"]),nx.register();var PD=nx,ix=class ix extends q{constructor(e={}){super(e)}};ix.key="approxDistinct",ix.argOrder=["this","accuracy"],ix._sqlNames=["APPROX_DISTINCT","APPROX_COUNT_DISTINCT"],ix.availableArgs=new Set(["this","accuracy"]),ix.register();var hl=ix,zw=class zw extends Os{};zw.key="explodingGenerateSeries",zw.register();var wD=zw,fR=class fR extends q{constructor(e={}){super(e)}};fR.key="arrayAgg",fR.argOrder=["this","nullsExcluded"],fR.availableArgs=new Set(["this","nullsExcluded"]),fR.register();var nr=fR,Kw=class Kw extends q{constructor(e={}){super(e)}};Kw.key="arrayUniqueAgg",Kw.register();var vn=Kw,fh=class fh extends q{constructor(e={}){super(e)}};fh.key="aiAgg",fh.argOrder=["this","expression"],fh._sqlNames=["AI_AGG"],fh.requiredArgs=new Set(["this","expression"]),fh.availableArgs=new Set(["this","expression"]),fh.register();var bP=fh,jI=class jI extends q{constructor(e={}){super(e)}};jI.key="aiSummarizeAgg",jI._sqlNames=["AI_SUMMARIZE_AGG"],jI.register();var PP=jI,Qw=class Qw extends q{constructor(e={}){super(e)}};Qw.key="arrayConcatAgg",Qw.register();var wP=Qw,Zw=class Zw extends q{constructor(e={}){super(e)}};Zw.key="arrayUnionAgg",Zw.register();var MP=Zw,eM=class eM extends q{constructor(e={}){super(e)}};eM.key="avg",eM.register();var hT=eM,tM=class tM extends q{constructor(e={}){super(e)}};tM.key="anyValue",tM.register();var Ic=tM,xR=class xR extends q{constructor(e={}){super(e)}};xR.key="lag",xR.argOrder=["this","offset","default"],xR.availableArgs=new Set(["this","offset","default"]),xR.register();var LP=xR,TR=class TR extends q{constructor(e={}){super(e)}};TR.key="lead",TR.argOrder=["this","offset","default"],TR.availableArgs=new Set(["this","offset","default"]),TR.register();var DP=TR,SR=class SR extends q{constructor(e={}){super(e)}};SR.key="first",SR.argOrder=["this","expression"],SR.availableArgs=new Set(["this","expression"]),SR.register();var gT=SR,mR=class mR extends q{constructor(e={}){super(e)}};mR.key="last",mR.argOrder=["this","expression"],mR.availableArgs=new Set(["this","expression"]),mR.register();var dT=mR,sM=class sM extends q{constructor(e={}){super(e)}};sM.key="firstValue",sM.register();var AT=sM,rM=class rM extends q{constructor(e={}){super(e)}};rM.key="lastValue",rM.register();var fT=rM,ax=class ax extends q{constructor(e={}){super(e)}};ax.key="nthValue",ax.argOrder=["this","offset","fromFirst"],ax.requiredArgs=new Set(["this","offset"]),ax.availableArgs=new Set(["this","offset","fromFirst"]),ax.register();var _P=ax,ox=class ox extends q{constructor(e={}){super(e)}};ox.key="objectAgg",ox.argOrder=["this","expression"],ox.requiredArgs=new Set(["this","expression"]),ox.availableArgs=new Set(["this","expression"]),ox.register();var kP=ox,Ft=class extends Z{constructor(e={}){super(e)}};Ft.key="tryCast",Ft.requiredArgs=new Set,Ft.availableArgs=new Set(["this","to","format","safe","action","default","requiresString"]);var rS=class extends Z{constructor(e={}){super(e)}};rS.key="jsonCast";var xs=class extends Vt{constructor(e={}){super(e)}};xs.key="concatWs",xs._sqlNames=["CONCAT_WS"];var xh=class xh extends q{constructor(e={}){super(e)}};xh.key="count",xh.argOrder=["this","expressions","bigInt"],xh.requiredArgs=new Set,xh.isVarLenArgs=!0,xh.availableArgs=new Set(["this","expressions","bigInt"]),xh.register();var uc=xh,JI=class JI extends q{constructor(e={}){super(e)}};JI.key="countIf",JI._sqlNames=["COUNT_IF","COUNTIF"],JI.register();var UP=JI,Th=class Th extends q{constructor(e={}){super(e)}};Th.key="denseRank",Th.argOrder=[],Th.requiredArgs=new Set,Th.isVarLenArgs=!0,Th.availableArgs=new Set(["expressions"]),Th.register();var qP=Th,Cx=class extends qt{constructor(e={}){super(e)}};Cx.key="explodeOuter";var nM=class nM extends qt{constructor(e={}){super(e)}};nM.key="posexplode",nM.register();var gl=nM,RR=class RR extends q{constructor(e={}){super(e)}};RR.key="groupConcat",RR.argOrder=["this","separator","onOverflow"],RR.availableArgs=new Set(["this","separator","onOverflow"]),RR.register();var tr=RR,Ec=class extends ac{constructor(e={}){super(e)}};Ec.key="lowerHex";var Oe=class extends Q(We,d){constructor(e={}){super(e)}};Oe.key="and",Oe.requiredArgs=new Set(["this","expression"]),Oe.availableArgs=new Set(["this","expression"]);var pt=class extends Q(We,d){constructor(e={}){super(e)}};pt.key="or",pt.requiredArgs=new Set(["this","expression"]),pt.availableArgs=new Set(["this","expression"]);var Ur=class extends Q(We,d){constructor(e={}){super(e)}};Ur.key="xor",Ur.requiredArgs=new Set,Ur.isVarLenArgs=!0,Ur.availableArgs=new Set(["this","expression","expressions","roundInput"]);var OR=class OR extends q{constructor(e={}){super(e)}};OR.key="jsonObjectAgg",OR.argOrder=["expressions","nullHandling","uniqueKeys","returnType","encoding"],OR.availableArgs=new Set(["expressions","nullHandling","uniqueKeys","returnType","encoding"]),OR.register();var _O=OR,cx=class cx extends q{constructor(e={}){super(e)}};cx.key="jsonbObjectAgg",cx.argOrder=["this","expression"],cx.requiredArgs=new Set(["this","expression"]),cx.availableArgs=new Set(["this","expression"]),cx.register();var MD=cx,NR=class NR extends q{constructor(e={}){super(e)}};NR.key="jsonArrayAgg",NR.argOrder=["this","order","nullHandling","returnType","strict"],NR.availableArgs=new Set(["this","order","nullHandling","returnType","strict"]),NR.register();var LD=NR,XI=class XI extends q{constructor(e={}){super(e)}};XI.key="logicalOr",XI._sqlNames=["LOGICAL_OR","BOOL_OR","BOOLOR_AGG"],XI.register();var dl=XI,zI=class zI extends q{constructor(e={}){super(e)}};zI.key="logicalAnd",zI._sqlNames=["LOGICAL_AND","BOOL_AND","BOOLAND_AGG"],zI.register();var Al=zI,px=class px extends q{constructor(e={}){super(e)}};px.key="max",px.argOrder=["this","expressions"],px.isVarLenArgs=!0,px.availableArgs=new Set(["this","expressions"]),px.register();var rn=px,iM=class iM extends q{constructor(e={}){super(e)}};iM.key="median",iM.register();var vP=iM,lx=class lx extends q{constructor(e={}){super(e)}};lx.key="mode",lx.argOrder=["this","deterministic"],lx.requiredArgs=new Set,lx.availableArgs=new Set(["this","deterministic"]),lx.register();var FP=lx,ux=class ux extends q{constructor(e={}){super(e)}};ux.key="min",ux.argOrder=["this","expressions"],ux.isVarLenArgs=!0,ux.availableArgs=new Set(["this","expressions"]),ux.register();var fl=ux,KI=class KI extends q{constructor(e={}){super(e)}};KI.key="ntile",KI.requiredArgs=new Set,KI.register();var BP=KI,IR=class IR extends q{constructor(e={}){super(e)}};IR.key="percentileCont",IR.argOrder=["this","expression"],IR.availableArgs=new Set(["this","expression"]),IR.register();var yc=IR,yR=class yR extends q{constructor(e={}){super(e)}};yR.key="percentileDisc",yR.argOrder=["this","expression"],yR.availableArgs=new Set(["this","expression"]),yR.register();var Xh=yR,Sh=class Sh extends q{constructor(e={}){super(e)}};Sh.key="percentRank",Sh.argOrder=[],Sh.requiredArgs=new Set,Sh.isVarLenArgs=!0,Sh.availableArgs=new Set(["expressions"]),Sh.register();var GP=Sh,Ex=class Ex extends q{constructor(e={}){super(e)}};Ex.key="quantile",Ex.argOrder=["this","quantile"],Ex.requiredArgs=new Set(["this","quantile"]),Ex.availableArgs=new Set(["this","quantile"]),Ex.register();var eo=Ex,aM=class aM extends q{constructor(e={}){super(e)}};aM.key="approxPercentileAccumulate",aM.register();var $P=aM,mh=class mh extends q{constructor(e={}){super(e)}};mh.key="rank",mh.argOrder=[],mh.requiredArgs=new Set,mh.isVarLenArgs=!0,mh.availableArgs=new Set(["expressions"]),mh.register();var YP=mh,hx=class hx extends q{constructor(e={}){super(e)}};hx.key="regrValx",hx.argOrder=["this","expression"],hx.requiredArgs=new Set(["this","expression"]),hx.availableArgs=new Set(["this","expression"]),hx.register();var HP=hx,gx=class gx extends q{constructor(e={}){super(e)}};gx.key="regrValy",gx.argOrder=["this","expression"],gx.requiredArgs=new Set(["this","expression"]),gx.availableArgs=new Set(["this","expression"]),gx.register();var VP=gx,dx=class dx extends q{constructor(e={}){super(e)}};dx.key="regrAvgy",dx.argOrder=["this","expression"],dx.requiredArgs=new Set(["this","expression"]),dx.availableArgs=new Set(["this","expression"]),dx.register();var WP=dx,Ax=class Ax extends q{constructor(e={}){super(e)}};Ax.key="regrAvgx",Ax.argOrder=["this","expression"],Ax.requiredArgs=new Set(["this","expression"]),Ax.availableArgs=new Set(["this","expression"]),Ax.register();var jP=Ax,fx=class fx extends q{constructor(e={}){super(e)}};fx.key="regrCount",fx.argOrder=["this","expression"],fx.requiredArgs=new Set(["this","expression"]),fx.availableArgs=new Set(["this","expression"]),fx.register();var JP=fx,xx=class xx extends q{constructor(e={}){super(e)}};xx.key="regrIntercept",xx.argOrder=["this","expression"],xx.requiredArgs=new Set(["this","expression"]),xx.availableArgs=new Set(["this","expression"]),xx.register();var XP=xx,Tx=class Tx extends q{constructor(e={}){super(e)}};Tx.key="regrR2",Tx.argOrder=["this","expression"],Tx.requiredArgs=new Set(["this","expression"]),Tx.availableArgs=new Set(["this","expression"]),Tx.register();var zP=Tx,Sx=class Sx extends q{constructor(e={}){super(e)}};Sx.key="regrSxx",Sx.argOrder=["this","expression"],Sx.requiredArgs=new Set(["this","expression"]),Sx.availableArgs=new Set(["this","expression"]),Sx.register();var KP=Sx,mx=class mx extends q{constructor(e={}){super(e)}};mx.key="regrSxy",mx.argOrder=["this","expression"],mx.requiredArgs=new Set(["this","expression"]),mx.availableArgs=new Set(["this","expression"]),mx.register();var QP=mx,Rx=class Rx extends q{constructor(e={}){super(e)}};Rx.key="regrSyy",Rx.argOrder=["this","expression"],Rx.requiredArgs=new Set(["this","expression"]),Rx.availableArgs=new Set(["this","expression"]),Rx.register();var ZP=Rx,Ox=class Ox extends q{constructor(e={}){super(e)}};Ox.key="regrSlope",Ox.argOrder=["this","expression"],Ox.requiredArgs=new Set(["this","expression"]),Ox.availableArgs=new Set(["this","expression"]),Ox.register();var ew=Ox,oM=class oM extends q{constructor(e={}){super(e)}};oM.key="sum",oM.register();var tw=oM,QI=class QI extends q{constructor(e={}){super(e)}};QI.key="stddev",QI._sqlNames=["STDDEV","STDEV"],QI.register();var sw=QI,cM=class cM extends q{constructor(e={}){super(e)}};cM.key="stddevPop",cM.register();var rw=cM,pM=class pM extends q{constructor(e={}){super(e)}};pM.key="stddevSamp",pM.register();var nw=pM,Rh=class Rh extends q{constructor(e={}){super(e)}};Rh.key="cumeDist",Rh.argOrder=[],Rh.requiredArgs=new Set,Rh.isVarLenArgs=!0,Rh.availableArgs=new Set(["expressions"]),Rh.register();var iw=Rh,ZI=class ZI extends q{constructor(e={}){super(e)}};ZI.key="variance",ZI._sqlNames=["VARIANCE","VARIANCE_SAMP","VAR_SAMP"],ZI.register();var xT=ZI,ey=class ey extends q{constructor(e={}){super(e)}};ey.key="variancePop",ey._sqlNames=["VARIANCE_POP","VAR_POP"],ey.register();var xl=ey,lM=class lM extends q{constructor(e={}){super(e)}};lM.key="kurtosis",lM.register();var TT=lM,uM=class uM extends q{constructor(e={}){super(e)}};uM.key="skewness",uM.register();var aw=uM,Nx=class Nx extends q{constructor(e={}){super(e)}};Nx.key="covarSamp",Nx.argOrder=["this","expression"],Nx.requiredArgs=new Set(["this","expression"]),Nx.availableArgs=new Set(["this","expression"]),Nx.register();var ST=Nx,Ix=class Ix extends q{constructor(e={}){super(e)}};Ix.key="covarPop",Ix.argOrder=["this","expression"],Ix.requiredArgs=new Set(["this","expression"]),Ix.availableArgs=new Set(["this","expression"]),Ix.register();var mT=Ix,EM=class EM extends Fw{constructor(e={}){super(e)}};EM.key="combinedAggFunc",EM.register();var DD=EM,hM=class hM extends vw{constructor(e={}){super(e)}};hM.key="combinedParameterizedAgg",hM.register();var _D=hM,DS=class extends Q(gl,Cx){constructor(e={}){super(e)}};DS.key="posexplodeOuter",DS.requiredArgs=new Set(["this"]),DS.availableArgs=new Set(["this","expressions"]);var _s=class extends eo{constructor(e={}){super(e)}};_s.key="approxQuantile",_s.argOrder=["this","quantile","accuracy","weight","errorTolerance"],_s.availableArgs=new Set(["this","quantile","accuracy","weight","errorTolerance"]);function Ie(n,e={}){let{col:t,table:s,db:r,catalog:i}=n,{fields:a,quoted:o,copy:c=!0}=e,p;t instanceof ye?p=t:p=K(t,{quoted:o,copy:c});let u=new k({this:p,table:s!==void 0?K(s,{quoted:o,copy:c}):void 0,db:r!==void 0?K(r,{quoted:o,copy:c}):void 0,catalog:i!==void 0?K(i,{quoted:o,copy:c}):void 0});if(a&&0<a.length){let E=a.map(g=>K(g,{quoted:o,copy:c})).filter(g=>g!==void 0);return me.build([u,...E])}return u}function mV(n,e={}){let{db:t,catalog:s,quoted:r,alias:i}=e;return new V({this:n?K(n,{quoted:r}):void 0,db:t?K(t,{quoted:r}):void 0,catalog:s?K(s,{quoted:r}):void 0,alias:i?new ie({this:K(i)}):void 0})}function LR(n,e,t){let s={this:new G({this:n})};return e&&(s.db=new G({this:e})),t&&(s.catalog=new G({this:t})),new V(s)}function nt(n,e={}){let{dialect:t,copy:s=!0,wrap:r=!0,...i}=e;return _R(n,Oe,{dialect:t,copy:s,wrap:r,...i})}function bs(n,e={}){let{dialect:t,copy:s=!0,wrap:r=!0,...i}=e;return _R(n,pt,{dialect:t,copy:s,wrap:r,...i})}function LL(n,e={}){let{dialect:t,copy:s=!0,wrap:r=!0,...i}=e;return _R(n,Ur,{dialect:t,copy:s,wrap:r,...i})}function Hn(n,e={}){let t=pw(n,e);return new rt({this:xc(t,We)||t})}function _r(n,e={}){let{copy:t=!0,...s}=e;return new Ye({this:ne(n,{copy:t,...s})})}var cw=/^[_a-zA-Z][\w]*$/;function K(n,e={}){let{quoted:t,copy:s=!0}=e;if(n!==void 0)return n instanceof G?bt(n,s):new G({this:n,quoted:t!==void 0?t:!cw.test(n.toString())})}function Cl(n,e={}){let{dialect:t,...s}=e;try{return ne(n,{dialect:t,into:G,...s})}catch (e11){return K(n)}}var vL=/\s*(-?[0-9]+(?:\.[0-9]+)?)\s*([a-zA-Z]+)\s*/,FL=/\s*-?\s*\d+(?:\.\d+)?\s+(?:-?(?:\d+:)?\d+:\d+(?:\.\d+)?|-?(?:\d+:){1,2}|:)\s*/;function RV(n){let e;if(n instanceof w){if(!n.args.isString)throw new Error("Invalid interval string.");e=n.args.this}else e=n;let t=ne(`INTERVAL ${e}`);if(!(t instanceof ze))throw new Error("Failed to parse interval expression");return t}function oe(n,e,t={}){let{table:s,quoted:r,dialect:i,copy:a=!0,...o}=t,c=ne(n,{dialect:i,copy:a,...o}),p=e!==void 0?K(e instanceof G?e:e.toString(),{quoted:r}):void 0;if(s){let u=new ie({this:p});if(c.setArgKey("alias",u),Array.isArray(s))for(let E of s){let g=K(E,{quoted:r});g&&u.append("columns",g)}return c}return c._constructor.availableArgs.has("alias")&&!(c instanceof Fe)?(p&&c.setArgKey("alias",p),c):new Se({this:c,alias:p})}function gM(n,e,t={}){let{dialect:s,...r}=t,i=ne(n,{dialect:s,...r});if(!(i instanceof ce))throw new Error("The input sql is not a QueryExpr");let a=i.subquery(e,r);return new $({}).from(a,{dialect:s,...r})}function ft(n,e={}){return new $().select(n,e)}function Uv(n,e={}){return new $({}).from(n,e)}function dM(n,e={}){let t;return n!==void 0&&(t=ne(n,e)),new Ht({this:t,ifs:[]})}function Le(n,e,t={}){let{copy:s=!0,dialect:r,...i}=t,a=ne(n,{copy:s,dialect:r,...i}),o=C.build(e,{copy:s,dialect:r,...i});if(a instanceof Z){let u=W.getOrRaise(r)._constructor.generatorClass.TYPE_MAPPING,E=_optionalChain([a, 'access', _894 => _894.args, 'access', _895 => _895.to, 'optionalAccess', _896 => _896.args, 'access', _897 => _897.this]),g=_optionalChain([o, 'optionalAccess', _898 => _898.args, 'access', _899 => _899.this]),A=E!=null&&(u.get(E.toString())||E)===(u.get(_nullishCoalesce(_optionalChain([g, 'optionalAccess', _900 => _900.toString, 'call', _901 => _901()]), () => ("")))||g);if(o!==void 0&&a.isType([o])||A)return a}let c=new Z({this:a,to:o});return c.type=o,c}function OV(n,e={}){let{alias:t,columns:s}=e;if(s&&!t)throw new Error("Alias is required when providing columns");let r=n.map(a=>new Mt({expressions:a.map(o=>ts(o))})),i;return s?i=new ie({this:t!==void 0?K(t):void 0,columns:s.map(a=>K(a)).filter(a=>a!==void 0)}):t&&(i=new ie({this:K(t)})),new Gs({expressions:r,alias:i})}function DR(n,...e){let t=e.map(r=>typeof r=="string"?ne(r):ts(r)),s=Ag.get(n.toUpperCase());return s?s.fromArgList(t):new st({this:n,expressions:t})}function kD(n,e,t={}){let{distinct:s=!0,dialect:r,copy:i=!0,...a}=t;return _optionalChain([n, 'optionalAccess', _902 => _902.map, 'call', _903 => _903(c=>ne(c,{dialect:r,copy:i,...a})), 'optionalAccess', _904 => _904.reduce, 'call', _905 => _905((c,p)=>new e({this:c,expression:p,distinct:s,...a}))])}function NT(n,e={}){let t=Array.from(pe(n)).filter(s=>s!==void 0);if(t.length<2)throw new Error("At least two expressions are required by `union`.");return kD(t,$r,e)}function UD(n,e={}){let t=Array.from(pe(n)).filter(s=>s!==void 0);if(t.length<2)throw new Error("At least two expressions are required by `intersect`.");return kD(t,yn,e)}function qD(n,e={}){let t=Array.from(pe(n)).filter(s=>s!==void 0);if(t.length<2)throw new Error("At least two expressions are required by `except`.");return kD(t,Yr,e)}function qv(n,e,t={}){let{columns:s,overwrite:r,returning:i,dialect:a,copy:o=!0,...c}=t,p=ne(n,{dialect:a,copy:o,...c}),u=ne(e,{into:V,dialect:a,copy:o,...c});s&&(u=new Lt({this:u,expressions:s.map(g=>typeof g=="string"?K(g):g)}));let E=new Ss({this:u,expression:p,overwrite:r});return i&&(E=E.returning(i,{dialect:a,copy:!1,...c})),E}function vv(n,e={}){let{where:t,returning:s,dialect:r,...i}=e,a=new Jn({}).delete(n,{dialect:r,copy:!1,...i});return t&&(a=a.where(t,{dialect:r,copy:!1,...i})),s&&(a=a.returning(s,{dialect:r,copy:!1,...i})),a}function NV(n,e,t={}){let{where:s,from:r,with:i,dialect:a,...o}=t,c=new sr({this:ne(n,{into:V,dialect:a})});if(e&&c.setArgKey("expressions",Object.entries(e).map(([p,u])=>new Ee({this:ne(p,{dialect:a,...o}),expression:ts(u)}))),r&&c.setArgKey("from",ne(r,{into:Ge,dialect:a,prefix:"FROM",...o})),s){let p=s;s instanceof Qe&&(p=new at({this:s})),c.setArgKey("where",ne(p,{into:at,dialect:a,prefix:"WHERE",...o}))}if(i){let p=Object.entries(i).map(([u,E])=>oe(new Yt({this:ne(E,{dialect:a,...o})}),u,{table:!0}));c.setArgKey("with",new ve({expressions:p}))}return c}function Fv(n,e={}){let{into:t,using:s,on:r,returning:i,dialect:a,copy:o=!0,...c}=e,p=n!==void 0?Array.from(pe(n)):[],u=[];for(let A of p){let x=ne(A,{dialect:a,copy:o,into:ko,...c});x instanceof Ji?u.push(x):u.push(...x.args.expressions)}let E=new va({this:ne(t,{dialect:a,copy:o,...c}),using:ne(s,{dialect:a,copy:o,...c}),on:ne(r,{dialect:a,copy:o,...c}),whens:new ko({expressions:u})});i&&(E=E.returning(i,{dialect:a,copy:!1,...c}));let g=E.args.using;if(g instanceof Se){let A=g.args.alias,x=typeof A=="string"||D(A,G)?A:void 0;g.replace(oe(g.args.this,x,{table:!0}))}return E}function pw(n,e={}){return ne(n,{into:Qe,...e})}function ne(n,e){if(n instanceof h)return _optionalChain([e, 'optionalAccess', _906 => _906.copy])?n.copy():n;if(n===void 0)throw new ns("SQL cannot be null or undefined");let t=String(n);_optionalChain([e, 'optionalAccess', _907 => _907.prefix])&&(t=`${e.prefix} ${t}`);let{dialect:s,...r}=e||{};return _w(t,{...r,read:s||r.read})}function RT(n,e={}){let{dialect:t,copy:s=!0,...r}=e;if(n instanceof V)return bt(n,s);try{let i=ne(n,{into:V,dialect:t,...r});for(let[a,o]of Object.entries(r))i.setArgKey(a,o);return i}catch (e12){let[i,a,o]=JU(n,".",3);if(!o)throw new Error(`Invalid table path: ${n}`);let c=LR(o,a,i);for(let[p,u]of Object.entries(r))c.setArgKey(p,u);return c}}function Bw(n,e={}){let{quoted:t,dialect:s,copy:r=!0,...i}=e;if(n instanceof k)return bt(n,r);try{let a=ne(n,{into:k,dialect:s,...i});for(let[o,c]of Object.entries(i))a.setArgKey(o,c);if(t)for(let o of a.findAll(G))o.setArgKey("quoted",!0);return a}catch (e13){let a=n.split(".").reverse(),[o,c]=a,p={this:K(o,{quoted:t})};c&&(p.table=K(c,{quoted:t}));let u=new k(p);for(let[E,g]of Object.entries(i))u.setArgKey(E,g);return u}}function Bv(n){let e=new Set;for(let t of _t(n))for(let s of t.tables)s.name&&!t.cteSources.has(s.name)&&e.add(s);return e}function bt(n,e=!0){return e&&n?n.copy():n}function Gv(n,e){return n instanceof h&&!(n instanceof e)}function OT(n,e){let{instance:t,arg:s,copy:r=!0,prefix:i,into:a,dialect:o,intoArg:c="this",...p}=e;a&&Gv(n,a)&&(n=new a({[c]:n}));let u=bt(t,r),E=ne(n,{prefix:i,into:a,dialect:o,...p});return s!==void 0&&u.setArgKey(s,E),u}function _S(n,e={}){let{instance:t,arg:s,append:r=!0,copy:i=!0,prefix:a,into:o,dialect:c,properties:p,...u}=e,E=bt(t,i),g=[],A=p||{},x=pe(n);for(let S of x){if(S===void 0)continue;let I=S;o&&Gv(I,o)&&(I=new o({expressions:[I]}));let y=ne(I,{into:o,dialect:c,prefix:a,...u});for(let[P,v]of Object.entries(y.args))P==="expressions"?g.push(...v):A[P]=v}let m=E.getArgKey(s),N=g;r&&m&&m.args.expressions&&(N=[...m.args.expressions,...g]);let R=o?new o({expressions:N}):new h({expressions:N});for(let[S,I]of Object.entries(A))R.setArgKey(S,I);return s!==void 0&&E.setArgKey(s,R),E}function Dg(n,e){let{instance:t,arg:s,append:r=!0,copy:i=!0,prefix:a,into:o,dialect:c,...p}=e,u=bt(t,i),g=pe(n).filter(x=>x!==void 0).map(x=>ne(x,{into:o,prefix:a,dialect:c,...p})),A=_optionalChain([u, 'optionalAccess', _908 => _908.getArgKey, 'call', _909 => _909(s)]);return s!==void 0&&(r&&A?_optionalChain([u, 'optionalAccess', _910 => _910.setArgKey, 'call', _911 => _911(s,[...A,...g])]):_optionalChain([u, 'optionalAccess', _912 => _912.setArgKey, 'call', _913 => _913(s,g)])),u}function MR(n,e={}){let{instance:t,arg:s,into:r,append:i=!0,copy:a=!0,dialect:o,...c}=e,u=Array.from(pe(n)).filter(R=>R!==void 0&&R!=="");if(u.length===0)return t;let E=bt(t,a),g=E.getArgKey(s),A=[...u];i&&g instanceof h&&(A=[r&&"this"in g.args?g.args.this:g,...u]);let x=R=>R instanceof We?new Ye({this:R}):R,m;if(0<A.length){let R=A.map(P=>ne(P,{dialect:o,copy:a,...c})),[S,...I]=R,y=S;0<I.length&&(y=x(S)),m=I.reduce((P,v)=>new Oe({this:P,expression:x(v)}),y)}let N=r&&m?new r({this:m}):m;return N&&s!==void 0&&E.setArgKey(s,N),E}function vD(n){let{instance:e,alias:t,as:s,recursive:r,materialized:i,append:a=!0,dialect:o,copy:c=!0,scalar:p,...u}=n,E=ne(t,{dialect:o,into:ie,...u}),g=ne(s,{dialect:o,copy:c,...u});p&&!(g instanceof ae)&&(g=new ae({this:g}));let A=new Yt({this:g,alias:E,materialized:i,scalar:p});return _S([A],{instance:e,arg:"with",append:a,copy:c,into:ve,properties:r?{recursive:r}:{}})}function _R(n,e,t={}){let{dialect:s,copy:r=!0,wrap:i=!0,...a}=t,c=Array.from(pe(n)).filter(g=>g!==void 0&&g!=="").map(g=>ne(g,{dialect:s,copy:r,...a})),[p,...u]=c,E=p;0<u.length&&i&&(E=xc(E,We)||E);for(let g of u)E=new e({this:E,expression:i&&xc(g,We)||g});return E}function xc(n,e){return n instanceof e?new Ye({this:n}):n}function gg(n){return typeof n=="string"?w.string(n):typeof n=="number"?w.number(n):w.string(String(n))}function Ke(){return new Qt({})}function $e(){return new Et({this:!0})}function cs(){return new Et({this:!1})}function ts(n,e={}){let{copy:t=!1}=e;if(n instanceof h){let s=bt(n,t);if(s)return s}if(typeof n=="string")return w.string(n);if(typeof n=="boolean")return new Et({this:n});if(n===void 0||typeof n=="number"&&isNaN(n))return Ke();if(typeof n=="number")return w.number(n);if(_luxon.DateTime.isDateTime(n)){let s=n.toFormat("yyyy-MM-dd HH:mm:ss"),r=w.string(s),i;return n.zoneName&&n.zoneName!=="UTC"&&(i=w.string(n.zoneName)),new Xs({this:r,zone:i})}if(n instanceof Date){let r=_luxon.DateTime.fromJSDate(n).toFormat("yyyy-MM-dd HH:mm:ss"),i=w.string(r);return new Xs({this:i,zone:void 0})}if(Array.isArray(n))return new Ne({expressions:n.map(s=>ts(s,{copy:t}))});if(n!==null&&typeof n=="object"){let s=Object.entries(n);return new Eo({keys:new Ne({expressions:s.map(([r])=>w.string(r))}),values:new Ne({expressions:s.map(([,r])=>ts(r,{copy:t}))})})}throw new Error(`Cannot convert ${n}`)}function Te(n){if(!n)throw new Error("Cannot convert empty name into var.");return n instanceof h&&(n=n.name),new Ze({this:n})}function jT(n,e={}){let{copy:t=!0,dialect:s,...r}=e,i=Array.from(pe(n));return new Ne({expressions:i.map(a=>ne(a,{copy:t,dialect:s,...r}))})}function IV(n,e={}){let{copy:t=!0,dialect:s,...r}=e,i=Array.from(pe(n));return new Mt({expressions:i.map(a=>ne(a,{copy:t,dialect:s,...r}))})}function yV(n,e,t={}){let{dialect:s}=t,r=RT(n,{dialect:s}),i=RT(e,{dialect:s});return new mn({this:r,kind:"table",actions:[new Vi({this:i})]})}function CV(n,e,t,s={}){let{exists:r,dialect:i}=s,a=RT(n,{dialect:i}),o=Bw(e,{dialect:i}),c=Bw(t,{dialect:i});return new mn({this:a,kind:"table",actions:[new Xc({this:o,to:c,exists:r})]})}function to(n,e={}){let{exclude:t=""}=e,s=new Set;for(let r of n.findAll(k)){let i=r.table;i&&i!==t&&s.add(i)}return s}function bV(n,e={}){let{dialect:t,identify:s=!1}=e,r=ne(n,{into:V,dialect:t});if(!r)throw new Error(`Cannot parse ${n}`);return r.parts.map(i=>s||!cw.test(i.name)?i.sql({dialect:t,identify:!0,copy:!1,comments:!1}):i.name).join(".")}function Cw(n,e,...t){for(let[s,r]of Object.entries(n.args)){let i=Array.isArray(r),a=i?r:[r],o=[];for(let c of a)if(c instanceof h){let p=e(c,...t),u=Array.isArray(p)?p:[p];o.push(...u)}else o.push(c);i?n.setArgKey(s,o):n.setArgKey(s,o[0])}}function PV(n,e,t){let s=Array.from(n.dfs({prune:t})),r=n;for(;0<s.length;){let i=s.pop();r=e(i),r!==i&&(i.replace(r),r instanceof h&&s.push(r))}return r}function ow(n,e={}){let{dialect:t,copy:s=!0}=e;return Tr(RT(n,{dialect:t,copy:s}),{dialect:t}).parts.map(r=>r.name).join(".")}function wV(n,e,t={}){let{dialect:s,copy:r=!0}=t,i={};for(let[o,c]of Object.entries(e))i[ow(o,{dialect:s})]=c;function a(o){if(o instanceof V&&o.meta.replace!==!1){let c=ow(o,{dialect:s}),p=i[c];if(p){let u=RT(p,{dialect:s});for(let[E,g]of Object.entries(o.args))["this","db","catalog"].includes(E)||u.setArgKey(E,g);return u.addComments([c]),u}}return o}return n.transform(a,{copy:r})}function MV(n,e=[],t={}){let s=0;function r(i){if(i instanceof rr){if(typeof i.args.this=="string"){let a=t[i.args.this];if(a!==void 0)return ts(a)}else if(s<e.length)return ts(e[s++])}return i}return n.transform(r)}function FD(n,e,t={}){let{dialect:s,copy:r=!0}=t,i={};for(let[o,c]of Object.entries(e))i[ow(o,{dialect:s})]=c;function a(o){if(o instanceof V){let c=ow(o,{dialect:s}),p=i[c];if(p){let u=typeof p=="function"?p():p,E=o.alias||c,g=u.subquery(E);return g.comments=[`source: ${c}`],g.transform(a,{copy:!1})}}return o}return n.transform(a,{copy:r})}var En=[$,be],BD=[yc,Xh],DL=[w,Et],TO=[w,Et,Qt],LV=new Set([Xr,Gt,Ai,Ls,zr,fi,Ds,Ln,hs]);function wi(n,e){if(!D(n,"string",h)||n===void 0)return!1;if(n instanceof h)return n.isType(e);let t=typeof e!="string"&&cO(e)?e:[e];for(let r of t)if(r.toLowerCase()===n.toLowerCase())return!0;let s=As(Be,n.toString());if(s===void 0)return!1;for(let r of t)if(r===s)return!0;return!1}var $v,Yv,GD,zs=class extends(Yv=Dt,$v=[O],Yv){static get KEYWORDS(){return{"..":"dot"}}};GD=re(Yv),T(GD,10,"KEYWORDS",$v,zs),te(GD,zs),se(GD,3,zs),zs.SINGLE_TOKENS={"(":"lParen",")":"rParen","[":"lBracket","]":"rBracket",":":"colon",",":"comma","-":"dash",".":"dot","?":"placeholder","@":"parameter","'":"quote",'"':"quote",$:"dollar","*":"star"},zs.IDENTIFIER_ESCAPES=["\\"],zs.STRING_ESCAPES=["\\"],zs.VAR_TOKENS=new Set(["var"]);var DV={jsonPathFilter:(n,e)=>`?${e.args.this}`,jsonPathKey:(n,e)=>n.jsonPathKeySql(e),jsonPathRecursive:(n,e)=>`..${e.args.this||""}`,jsonPathRoot:(n,e)=>"$",jsonPathScript:(n,e)=>`(${e.args.this}`,jsonPathSelector:(n,e)=>`[${n.jsonPathPart(e.args.this)}]`,jsonPathSlice:(n,e)=>[e.args.start,e.args.end,e.args.step].filter(s=>s!==void 0).map(s=>s===void 0?"":n.jsonPathPart(s)).join(":"),jsonPathSubscript:(n,e)=>n.jsonPathSubscriptSql(e),jsonPathUnion:(n,e)=>`[${(_nullishCoalesce(e.args.expressions, () => ([]))).map(t=>n.jsonPathPart(t)).join(",")}]`,jsonPathWildcard:(n,e)=>"*"},AM=new Set([Xr,Gt,Ai,Ls,zr,di,fi,Ds,Ln,hs]);function $D(n,e){let s=W.getOrRaise(_optionalChain([e, 'optionalAccess', _914 => _914.dialect])).jsonpathTokenizer().tokenize(n),r=s.length,i=0;function a(){return i<r?s[i].tokenType:void 0}function o(){return s[i-1]}function c(){return i+=1,o()}function p(R){return`${R} at index ${i}: ${n}`}function u(R,S={}){let{raiseUnmatched:I=!1}=S;if(a()===R)return c();if(I)throw new ns(p(`Expected ${R}`))}function E(R){let S=a();if(S!==void 0)return R.has(S)?c():void 0}function g(){let R=u("string")||u("identifier");if(R)return R.text;if(u("star"))return new hs({});if(u("placeholder")||u("lParen")){let y=o().text==="(",P=i;for(;;){u("lBracket")&&x();let fe=a();if(fe==="rBracket"||fe===void 0)break;c()}let v=y?zr:Xr,H=_nullishCoalesce(s[P].start, () => (0)),B=i<r?_nullishCoalesce(s[i].end, () => (n.length)):n.length;return new v({this:n.slice(H,B)})}let S=u("dash")?"-":"",I=u("number");return I&&(S+=I.text),S?parseInt(S,10):!1}function A(){let R=g(),S=!!u("colon"),I=S?g():void 0,y=!!u("colon"),P=y?g():void 0;return!S&&!y?R:new fi({start:R,end:I,step:P})}function x(){let R=A();if(typeof R=="string"||R!==!1){let S=[R];for(;u("comma");){let y=A();y!==!1&&S.push(y)}let I;return S.length===1?typeof R=="string"?I=new Gt({this:S[0]}):R instanceof zr||R instanceof Xr?I=new di({this:S[0]}):I=new Ds({this:S[0]}):I=new Ln({expressions:S}),u("rBracket",{raiseUnmatched:!0}),I}else throw new ns(p("Cannot have empty segment"))}function m(){let R=i-2;for(;E(zs.VAR_TOKENS););let S=R<0?0:(_nullishCoalesce(s[R].end, () => (0)))+1,I;return s.length<=i?I=n.slice(S):I=n.slice(S,_nullishCoalesce(s[i].start, () => (n.length))),I}u("dollar");let N=[new Ls({})];for(;a();)if(u("dot")||u("colon")){let R=o().text==="..",S;if(E(zs.VAR_TOKENS)?S=m():u("identifier")?S=o().text:u("star")?S=new hs({}):S=void 0,R)N.push(new Ai({this:S}));else if(S)N.push(new Gt({this:S}));else throw new ns(p("Expected key name or * after DOT"))}else if(u("lBracket"))N.push(x());else if(E(zs.VAR_TOKENS))N.push(new Gt({this:m()}));else if(u("identifier"))N.push(new Gt({this:o().text}));else if(u("star"))N.push(new hs({}));else throw new ns(p(`Unexpected ${s[i].tokenType}`));return new Ya({expressions:N})}function VD(n,e={}){let{dialect:t}=e,s=W.getOrRaise(t);function r(i){return i=_V(i),i=kV(i,s),i=qV(i,{promoteToInferredDatetimeType:s._constructor.PROMOTE_TO_INFERRED_DATETIME_TYPE}),i=vV(i),i=WD(i,HD),i=FV(i),i}return n.transform(r,{copy:!1})}function _V(n){if(n instanceof lt&&n.type instanceof h&&n.type.args.this&&C.TEXT_TYPES.has(n.type.args.this)){let e=n.args.this,t=n.args.expression;return!e||!t?n:new Vt({expressions:[e,t],coalesce:!1})}return n}function kV(n,e){if(n instanceof Hp||n instanceof Ue){let t=n.args.expressions,s=n instanceof Hp?n.args.zone:void 0,r=n.args.this;if(!(t&&Array.isArray(t)&&0<t.length)&&!s&&r){let a=r;if(a.isString&&vT(a.name))return new Z({this:r,to:new C({this:"date"})})}}if(n instanceof $p&&!n.args.zone){let r=n;n.type||(r=os(n,{dialect:e}));let i=r.args.this;if(!i)return n;let a=r.type||new C({this:"timestamp"});return a instanceof C?new Z({this:i,to:a}):n}return n}var UV=[lt,dt,Ee,vt,It,xt,Tt,yt,fr,kr];function qV(n,e={}){let{promoteToInferredDatetimeType:t=!1}=e;if(UV.some(r=>n instanceof r)){let r=n.args.this,i=n.args.expression;r&&i&&Hv(r,i,{promoteToInferredDatetimeType:t})}else if(n instanceof Fs){let r=n.args.this,i=n.args.low;r&&i&&Hv(r,i,{promoteToInferredDatetimeType:t})}else if(n instanceof Zn){let r=n.args.expression;if(r){let i=r;i.type instanceof h&&i.type.args.this&&C.TEMPORAL_TYPES.has(i.type.args.this)||YD(i,"datetime")}}else if(n instanceof ut||n instanceof Wt||n instanceof Bs){let r=n.args.this,i=n.args.unit;r&&Vv(r,i)}else n instanceof ks&&BV(n);return n}function vV(n){if(n instanceof Z){let e=n.args.this,t=n.args.to;if(e&&t){let s=e,r=t;if(s.type&&r.equals(s.type))return s}}if(n instanceof Hp||n instanceof Ue){let e=n.args.this;if(e){let t=e;if(t.type instanceof h&&t.type.args.this==="date"){let s=t.type.args.expressions;if(!(s&&Array.isArray(s)&&0<s.length))return t}}}return n}function WD(n,e){if(n instanceof We){let t=n.args.this,s=n.args.expression;t&&e(t),s&&e(s)}else if(n instanceof rt){let t=n.args.this;t&&e(t)}else if(n instanceof He){let t=n.parent;if(!(t instanceof Ht&&t.args.this)){let r=n.args.this;r&&e(r)}}else if(n instanceof at||n instanceof $t){let t=n.args.this;t&&e(t)}return n}function FV(n){if(n instanceof es){let e=n.args;e.desc===!1&&(e.desc=void 0)}return n}function Hv(n,e,t){let{promoteToInferredDatetimeType:s}=t;for(let[r,i]of[[n,e],[e,n]]){if(i instanceof ze){let u=i.args.unit;Vv(r,u)}let a=r.type;if(!a||!(a instanceof h)||!a.args.this||!C.TEMPORAL_TYPES.has(a.args.this))continue;let o=a,c=i.type;if(!c||!(c instanceof h)||!c.args.this||!C.TEXT_TYPES.has(c.args.this))continue;let p;if(s){let u;if(i.isString){let g=i.name;vT(g)?u="date":AO(g)?u="datetime":u=o.args.this}else u="datetime";let E=$n.COERCES_TO.get(o.args.this);p=E&&E.has(u)?u:o.args.this}else p=o.args.this;p!==o.args.this&&YD(r,p),YD(i,p)}}function Vv(n,e){if(!n.type)return n;if(n.type instanceof h&&n.type.args.this&&C.TEXT_TYPES.has(n.type.args.this)){let t=n.name,s=vT(t);if(s&&FT(e))return n.replace(new Z({this:n.copy(),to:new C({this:"date"})}));if(s||AO(t))return n.replace(new Z({this:n.copy(),to:new C({this:"datetime"})}))}else if(n.type instanceof h&&n.type.args.this==="date"&&!FT(e))return n.replace(new Z({this:n.copy(),to:new C({this:"datetime"})}));return n}function BV(n){let e=n.args.this,t=n.args.expression;for(let s of[e,t])if(s){let r=s;r.type instanceof h&&r.type.args.this&&!C.TEMPORAL_TYPES.has(r.type.args.this)&&r.replace(new Z({this:r.copy(),to:new C({this:"datetime"})}))}}function YD(n,e){n.replace(new Z({this:n.copy(),to:new C({this:e})}))}function HD(n){if(n instanceof St){let e=n.args.this;e instanceof h&&HD(e);let t=n.args.expressions;if(t)for(let s of t)s instanceof h&&HD(s)}else n.type instanceof h&&n.type.args.this&&C.INTEGER_TYPES.has(n.type.args.this)&&n.replace(n.neq(0))}var GV=["on","side","kind","using","method"];function jD(n){for(let e of n.findAll($)){let t=Xe(_nullishCoalesce(e.args.joins, () => ([])),z);if(!XD(t))continue;let s={},r=[];for(let i of t){let a=fM(i);if(0<a.size)for(let o of a)s[o]||(s[o]=[]),s[o].push(i);else r.push([i.aliasOrName,i])}for(let[i,a]of r)for(let o of _nullishCoalesce(s[i], () => ([]))){let c=o.args.on;if(c instanceof We){if(fM(o).size<2)continue;let p=c.constructor;for(let u of c.flatten())if(to(u).has(i)){u.replace($e());let E=_R([a.args.on,u],p,{copy:!1});a.on(E,{append:!1,copy:!1})}}}}return n=Wv(n),n=JD(n),n}function Wv(n){for(let e of n.findAll(Ge)){let t=e.parent;if(!t)continue;let s=Xe(_nullishCoalesce(t.args.joins, () => ([])),z);if(!XD(s))continue;let r=new Map;for(let p of s)r.set(p.aliasOrName,p);let i=new Map;for(let[p,u]of r)i.set(p,fM(u));let a=jU(i),o=e.aliasOrName,c=a.filter(p=>p!==o&&r.has(p)).map(p=>r.get(p));t.setArgKey("joins",c)}return n}function JD(n){for(let e of n.findAll(z)){let t=GV.some(r=>e.args[r]!=null),s=e.args;t||(s.kind="cross"),s.kind==="cross"?s.on=void 0:((s.kind==="inner"||s.kind==="outer")&&(s.kind=void 0),!s.on&&!s.using&&(s.on=$e()))}return n}function fM(n){let e=n.args.on;return e?to(e,{exclude:n.aliasOrName}):new Set}function XD(n){for(let e of n)if(e.args.side)return!1;return!0}function Ks(n,e){return function(t){let s=t,r=s.constructor;try{for(let o of n)s=o(s)}catch(o){if(o instanceof uo)this.unsupported(o.message);else throw o}if(e)return e.call(this,s);let i=this[`${s._constructor.key}Sql`];if(i instanceof Function)return i.call(this,s);let a=this._constructor.TRANSFORMS.get(s._constructor);if(a){if(r===s.constructor){if(s instanceof d)return this.functionFallbackSql(s);throw new Error(`Expression type ${s.constructor.name} requires a _sql method to be transformed.`)}return a.call(this,s)}throw new Error(`Unsupported expression type ${s.constructor.name}.`)}}function jv(n){if(n instanceof $){let e=0,t=[];for(let s of n.findAll(Pe)){let r=s.parent;if(!(r instanceof Ge||r instanceof z)||_optionalChain([s, 'access', _915 => _915.args, 'access', _916 => _916.expressions, 'optionalAccess', _917 => _917.length])!==1||!(s.args.expressions[0]instanceof Mn))continue;let i=s.args.expressions[0],a=i.args.start,o=i.args.end,c=i.args.step;if(!a||!o||!(c instanceof ze))continue;let p=s.args.alias,u=p instanceof ie?p.columns[0]:void 0,E=D(u,G)?u:D(u,h)?u.name:"date_value",g=Le(a,"date"),A=new st({this:"date_add",expressions:[E,w.number(c.name),c.args.unit||""]}),x=Le(A,"date"),m=`_generated_dates${e?`_${e}`:""}`,N=ft(new Se({this:g,alias:E})),R=ft(x).from(m).where(new yt({this:x,expression:Le(o,"date")})),S=N.union(R,{distinct:!1});s.replace(ft(E).from(m).subquery(m)),t.push(oe(new Yt({this:S}),m,{table:[E]})),e++}if(0<t.length){let s=_nullishCoalesce(Pt(n.args.with,ve), () => (new ve({expressions:[]})));s.setArgKey("recursive",!0),s.setArgKey("expressions",[...t,..._nullishCoalesce(s.args.expressions, () => ([]))]),n.setArgKey("with",s)}}return n}function xM(n){let e=n.args.this;if(n instanceof V&&e instanceof Os){let t=new Pe({expressions:[e]});return n.args.alias?oe(t,"_u",{table:[n.args.alias instanceof ie?D(n.args.alias.args.this,G)||typeof n.args.alias.args.this=="string"?n.args.alias.args.this:"":typeof n.args.alias=="string"?n.args.alias:""]}):t}return n}function zh(n){if(n instanceof $&&n.args.distinct&&n.args.distinct.getArgKey("on")instanceof Mt){let e=pn(n.namedSelects,"_row_number"),t=n.args.distinct.pop().getArgKey("on").args.expressions,s=new Fe({this:new aT({}),partitionBy:t}),r=n.args.order;r?s.setArgKey("order",r.pop()):s.setArgKey("order",new ke({expressions:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _918 => _918.map, 'call', _919 => _919(o=>o instanceof h?o.copy():o)]), () => ([]))})),n.select(oe(s,e),{copy:!1});let i=[],a=[e];for(let o of n.selects.slice(0,-1)){if(o.isStar){i=[new ye];break}let c=o;if(!(c instanceof Se)){let p=pn(a,c.outputName||"_col"),u=c instanceof k&&c.args.this instanceof h?!!_optionalChain([c, 'access', _920 => _920.args, 'access', _921 => _921.this, 'optionalAccess', _922 => _922.getArgKey, 'call', _923 => _923("quoted")]):void 0;c=c.replace(oe(c,p,{quoted:u}))}a.push(c.outputName),i.push(c.getArgKey("alias"))}return ft(i).from(n.subquery("_t",{copy:!1})).where(new k({this:e}).eq(1))}return n}function Kh(n){if(n instanceof $&&n.args.qualify){let e=new Set(n.namedSelects);for(let o of n.selects)if(!o.aliasOrName){let c=pn(e,"_c");o.replace(oe(o,c)),e.add(c)}let t=o=>{let c=o.aliasOrName,p=o.getArgKey("alias")||o.args.this;return p instanceof G?Ie({col:c},{quoted:p.args.quoted}):c},s=ft(n.selects.map(t)),r=Pt(n.args.qualify.pop().args.this,h),i={};for(let o of n.selects)o instanceof Se&&(i[o.alias]=o.args.this);let a=n.isStar?[Fe]:[Fe,k];for(let o of[..._nullishCoalesce(_optionalChain([r, 'optionalAccess', _924 => _924.findAll, 'call', _925 => _925(a)]), () => ([]))])if(o instanceof Fe){if(i)for(let u of o.findAll(k)){let E=i[u.name];E&&u.replace(E)}let c=pn(n.namedSelects,"_w");n.select(oe(o,c),{copy:!1});let p=Ie({col:c});o.parent instanceof un?r=p:o.replace(p)}else n.namedSelects.includes(o.name)||n.select(o.copy(),{copy:!1});return s.from(n.subquery("_t",{copy:!1}),{copy:!1}).where(r,{copy:!1})}return n}function Jv(n,e={}){let{unnestUsingArraysZip:t=!0}=e;function s(i,a,o){let{hasMultiExpr:c}=o;if(c){if(!t)throw new uo("Cannot transpile UNNEST with multiple input arrays");let p=[new st({this:"ARRAYS_ZIP",expressions:a})];return i.setArgKey("expressions",p),p}return a}function r(i,a={}){let{hasMultiExpr:o}=a;return i.args.offset?gl:o?Vx:qt}if(n instanceof $){let i=n.args.from;if(i&&i.args.this instanceof Pe){let o=i.args.this,c=o.args.alias,p=o.args.expressions,u=1<(_nullishCoalesce(_optionalChain([p, 'optionalAccess', _926 => _926.length]), () => (0))),[E]=s(o,_nullishCoalesce(p, () => ([])),{hasMultiExpr:u}),g=D(c,ie)?Xe(c.columns,G):[],A=o.args.offset;A&&g.unshift(A instanceof G?A:new G({this:"pos",quoted:!1}));let x=r(o,{hasMultiExpr:u});o.replace(new V({this:new x({this:E}),alias:D(c,ie)?new ie({this:D(c.args.this,h)||typeof c.args.this=="string"?c.args.this:void 0,columns:g}):void 0}))}let a=n.args.joins||[];for(let o of[...a]){let c=o.args.this,p=c instanceof kt,u=p?c.args.this:c;if(u instanceof Pe){let E=p?c.args.alias:u.args.alias,g=u.args.expressions,A=1<(_nullishCoalesce(_optionalChain([g, 'optionalAccess', _927 => _927.length]), () => (0))),x=s(u,_nullishCoalesce(g, () => ([])),{hasMultiExpr:A});a.splice(a.indexOf(o),1);let m=D(E,ie)?E:void 0,N=m?Xe(m.columns,G):[];if(!A&&N.length!==1&&N.length!==2)throw new uo("CROSS JOIN UNNEST to LATERAL VIEW EXPLODE transformation requires explicit column aliases");let R=u.args.offset;R&&N.unshift(R instanceof G?R:new G({this:"pos",quoted:!1}));let S=r(u,{hasMultiExpr:A});for(let I of x)n.append("laterals",new kt({this:new S({this:I}),view:!0,alias:new ie({this:m&&(D(m.args.this,h)||typeof m.args.this=="string")?m.args.this:void 0,columns:N})}))}}}return n}function Xv(n){let e=n.getArgKey("with");for(let t of n.findAll(ve))if(t.parent!==n)if(!e)e=t.pop(),n.setArgKey("with",e);else{t.recursive&&e.setArgKey("recursive",!0);let s=t.findAncestor(Yt);t.pop();let r=t.args.expressions;if(ue(e,ve),s){let i=_nullishCoalesce(_optionalChain([e, 'access', _928 => _928.args, 'access', _929 => _929.expressions, 'optionalAccess', _930 => _930.indexOf, 'call', _931 => _931(s)]), () => (-1));_optionalChain([e, 'access', _932 => _932.args, 'access', _933 => _933.expressions, 'optionalAccess', _934 => _934.splice, 'call', _935 => _935(i,0,...Xe(_nullishCoalesce(r, () => ([])),h))])}else e.setArgKey("expressions",[..._nullishCoalesce(e.args.expressions, () => ([])),...Xe(_nullishCoalesce(r, () => ([])),h)])}return n}function zv(n){if(n instanceof $)for(let e of n.findAll(wt)){let t=e.args.this;if(t instanceof ce||e.parent instanceof Ws||e.parent instanceof ms)continue;let s=e.parent;if(s instanceof Y){let r=new G({this:"x",quoted:!1});e.replace(r);let i=new vs({this:s.copy(),expressions:[r]});s.replace(new js({this:_optionalChain([t, 'optionalAccess', _936 => _936.unnest, 'call', _937 => _937()]),expression:i}))}}return n}function TM(n=0){return e=>{if(e instanceof $){let t=[...e.namedSelects],r=[...new Ce({expression:e}).references].map(([u])=>u),i=(u,E)=>{let g=pn(u,E);return u.push(g),g},a=[],o=i(t,"pos"),c=i(r,"_u"),p=oe(new Pe({expressions:[new Os({start:w.number(n)})]}),c,{table:[o]});for(let u of[...e.selects]){let E=u.find(qt);if(E){let g,A,x;if(u instanceof Se)A=u.alias,x=u;else if(u instanceof Rn)g=u.aliases[0],A=u.aliases[1],x=u.replace(new Se({this:u.args.this,alias:""}));else{let B=new Se({alias:""});u.replace(B),B.setArgKey("this",u),x=B;let fe=x.find(qt);fe&&(E=fe)}let m=E instanceof gl,N=E.args.this;if(E instanceof Cx){let B=N instanceof h?_optionalChain([N, 'access', _938 => _938.args, 'access', _939 => _939.expressions, 'optionalAccess', _940 => _940[0]]):void 0;B instanceof h&&(B.setArgKey("safe",!0),B.setArgKey("offset",!0),N=new st({this:"IF",expressions:[new Ee({this:new st({this:"ARRAY_SIZE",expressions:N!==void 0?[new St({expressions:[N,new Ne({expressions:[]})]})]:void 0}),expression:w.number(0)}),new Ne({expressions:[B.copy()]}),...N!==void 0?[N]:[]]}))}N instanceof k&&t.push(N.outputName);let R=i(r,"_u");A||(A=i(t,"col")),m&&!g&&(g=i(t,"pos")),g||(g=i(t,"pos")),x.setArgKey("alias",new G({this:A,quoted:!1}));let S=_optionalChain([p, 'access', _941 => _941.args, 'access', _942 => _942.alias, 'optionalAccess', _943 => _943.args, 'access', _944 => _944.this]),I=K(R),y=(B,fe)=>new k({this:D(B,G)?B.copy():K(_nullishCoalesce(B, () => (""))),table:typeof fe=="string"?K(fe):_optionalChain([fe, 'optionalAccess', _945 => _945.copy, 'call', _946 => _946()])}),P=new He({this:y(o,S).eq(y(g,I)),true:y(A,I)});if(E.replace(P),m){let B=e.args.expressions,fe=_nullishCoalesce(_optionalChain([B, 'optionalAccess', _947 => _947.indexOf, 'call', _948 => _948(x)]), () => (-1));_optionalChain([B, 'optionalAccess', _949 => _949.splice, 'call', _950 => _950(fe+1,0,oe(new He({this:y(o,S).eq(y(g,I)),true:y(g,I)}),D(g,G)||typeof g=="string"?g:void 0))]),e.setArgKey("expressions",B)}a.length===0&&(e.args.from?e.join(p,{joinType:"cross",copy:!1}):e.from(p,{copy:!1}));let v=new lr({this:N instanceof h?N.copy():N});a.push(v),e.join(oe(new Pe({expressions:N!==void 0?[N instanceof h?N.copy():N]:void 0,offset:new G({this:g,quoted:!1})}),R,{table:[D(A,G)||typeof A=="string"?A:""]}),{joinType:"cross",copy:!1});let H=v;n!==1&&(H=new Ye({this:new dt({this:v,expression:w.number(1)})})),e.where(y(o,S).eq(y(g,I)).or(new Oe({this:new It({this:y(o,S),expression:H}),expression:new Ee({this:y(g,I),expression:H.copy()})})),{copy:!1})}}if(0<a.length){let u=new op({this:a[0],expressions:a.slice(1),ignoreNulls:!1});n!==1&&(u=new dt({this:u,expression:w.number(1-n)})),_optionalChain([Pt, 'call', _951 => _951(_optionalChain([p, 'access', _952 => _952.args, 'access', _953 => _953.expressions, 'optionalAccess', _954 => _954[0]]),h), 'optionalAccess', _955 => _955.setArgKey, 'call', _956 => _956("end",u)])}}return e}}function Kv(n){if(n instanceof Cs&&BD.some(e=>n.args.this instanceof e)&&n.args.expression instanceof ke){let e=_optionalChain([Pt, 'call', _957 => _957(n.args.this,h), 'optionalAccess', _958 => _958.args, 'access', _959 => _959.this]),t=n.find(es),s=t?t.args.this:void 0;return n.replace(new _s({this:s,quantile:e}))}return n}function Qv(n){if(n instanceof ve&&n.recursive){let e=go("_c_");for(let t of _nullishCoalesce(n.args.expressions, () => ([]))){ue(t,Yt);let s=D(t.args.alias,ie)?t.args.alias:void 0;if(!_optionalChain([s, 'optionalAccess', _960 => _960.columns, 'access', _961 => _961.length])){let r=t.args.this;r instanceof be&&(r=r.args.this),ue(r,ce),_optionalChain([s, 'optionalAccess', _962 => _962.setArgKey, 'call', _963 => _963("columns",r.selects.map(i=>K(i.aliasOrName||e())))])}}}return n}function zD(n){return(n instanceof Z||n instanceof Ft)&&n.name.toLowerCase()==="epoch"&&C.TEMPORAL_TYPES.has(_nullishCoalesce(As(Be,_nullishCoalesce((n.args.to instanceof h?_optionalChain([n, 'access', _964 => _964.args, 'access', _965 => _965.to, 'access', _966 => _966.args, 'access', _967 => _967.this, 'optionalAccess', _968 => _968.toString, 'call', _969 => _969()]):_optionalChain([n, 'access', _970 => _970.args, 'access', _971 => _971.to, 'optionalAccess', _972 => _972.toString, 'call', _973 => _973()])), () => (""))), () => ("")))&&_optionalChain([Pt, 'call', _974 => _974(n.args.this,h), 'optionalAccess', _975 => _975.replace, 'call', _976 => _976(w.string("1970-01-01 00:00:00"))]),n}function kR(n){if(n instanceof $){let e=n.args.joins||[];for(let t of[...e]){ue(t,z);let s=t.args.on;if(s&&(t.args.kind==="semi"||t.args.kind==="anti")){let r=ft("1").from(t.args.this).where(s),i=new js({this:r});t.args.kind==="anti"&&(i=i.not()),t.pop(),n.where(i,{copy:!1})}}}return n}function Zv(n){if(n instanceof $){let e=n.args.joins||[],s=Xe(e,z).map((r,i)=>({index:i,join:r})).filter(({join:r})=>r.args.side==="full");if(s.length===1){let r=n.copy();n.setArgKey("limit",void 0);let{index:i,join:a}=s[0],o=_optionalChain([n, 'access', _977 => _977.args, 'access', _978 => _978.from, 'optionalAccess', _979 => _979.aliasOrName]),c=a.aliasOrName,p=a.args.on||new Oe({expressions:(a.args.using||[]).map(A=>new Ee({this:new k({this:A,table:o}),expression:new k({this:A,table:c})}))});a.setArgKey("side","left");let u=ft("1").from(n.args.from).where(p);_optionalChain([r, 'access', _980 => _980.args, 'access', _981 => _981.joins, 'optionalAccess', _982 => _982[i], 'optionalAccess', _983 => _983.setArgKey, 'call', _984 => _984("side","right")]);let g=new js({this:u}).not();return r.where(g),r.setArgKey("with",void 0),n.setArgKey("order",void 0),_nullishCoalesce(NT([n,r],{distinct:!1}), () => (n))}}return n}function eF(n){let e=t=>{(t.isNumber||!(t instanceof Vn)&&t.isType(["unknown",...C.NUMERIC_TYPES])||t instanceof k&&!t.type)&&t.replace(t.neq(0))};for(let t of n.walk())WD(t,e);return n}function tF(n){for(let e of n.findAll(k)){let t=e.parts;for(let s=0;s<t.length-1;s++)t[s].pop()}return n}function sF(n){if(!(n instanceof us))return n;for(let e of n.findAll(Fo))e.parent&&e.parent.pop();return n}function rF(n,e=t=>t){if(!(n instanceof us))return n;let s=_optionalChain([n, 'access', _985 => _985.args, 'access', _986 => _986.properties, 'optionalAccess', _987 => _987.args, 'access', _988 => _988.expressions, 'optionalAccess', _989 => _989.some, 'call', _990 => _990(r=>r instanceof Gr)]);return n.kind==="table"&&s?n.args.expression?new us({kind:"temporary view",this:n.args.this,expression:n.args.expression}):e(n):n}function nF(n){if(!(n instanceof us))return n;let e=n.args.this instanceof Lt,t=n.kind==="table"||n.kind==="view";if(e&&t){let s=n.find(Bt);if(s&&s.args.this&&!(s.args.this instanceof Lt)){let r=n.args.this;ue(r,Lt);let i=new Set(_optionalChain([s, 'access', _991 => _991.args, 'access', _992 => _992.this, 'access', _993 => _993.args, 'access', _994 => _994.expressions, 'optionalAccess', _995 => _995.map, 'call', _996 => _996(o=>o instanceof h?o.name.toUpperCase():o.toString())])),a=_optionalChain([r, 'access', _997 => _997.args, 'access', _998 => _998.expressions, 'optionalAccess', _999 => _999.filter, 'call', _1000 => _1000(o=>i.has(o.name.toUpperCase()))]);r.setArgKey("expressions",_optionalChain([r, 'access', _1001 => _1001.args, 'access', _1002 => _1002.expressions, 'optionalAccess', _1003 => _1003.filter, 'call', _1004 => _1004(o=>!_optionalChain([a, 'optionalAccess', _1005 => _1005.includes, 'call', _1006 => _1006(o)]))])),s.replace(new Bt({this:new Lt({expressions:Xe(_nullishCoalesce(a, () => ([])),h)})})),n.setArgKey("this",r)}}return n}function iF(n){if(n instanceof $&&n.args.windows){let e=n.args.windows;n.setArgKey("windows",void 0);let t={},s=r=>{let i=_optionalChain([r, 'access', _1007 => _1007.alias, 'optionalAccess', _1008 => _1008.toLowerCase, 'call', _1009 => _1009()]);if(i===void 0)return;let a=t[i];if(a){r.setArgKey("alias",void 0);for(let o of["partitionBy","order","spec"]){let c=a.getArgKey(o);c instanceof h&&r.setArgKey(o,c.copy()),Array.isArray(c)&&0<c.length&&r.setArgKey(o,[...c])}}};for(let r of e)s(r),t[r.name.toLowerCase()]=r;for(let r of Mr(n,[Fe]))s(r)}return n}function SM(n){if(n instanceof Ne&&n.args.structNameInheritance&&_optionalChain([n, 'access', _1010 => _1010.args, 'access', _1011 => _1011.expressions, 'optionalAccess', _1012 => _1012[0]])instanceof Hs){let e=n.args.expressions[0];if(!_optionalChain([e, 'access', _1013 => _1013.args, 'access', _1014 => _1014.expressions, 'optionalAccess', _1015 => _1015.every, 'call', _1016 => _1016(s=>s instanceof At)]))return n;let t=e.args.expressions.map(s=>s.args.this);for(let s of n.args.expressions.slice(1)){if(!(s instanceof Hs)||_optionalChain([s, 'access', _1017 => _1017.args, 'access', _1018 => _1018.expressions, 'optionalAccess', _1019 => _1019.length])!==t.length)continue;let r=s.args.expressions.map((i,a)=>{if(!(i instanceof At)){let o=t[a],c=o instanceof h?o.args.this:o,p=new At({this:new G({this:c instanceof h?c.copy():_optionalChain([c, 'optionalAccess', _1020 => _1020.toString, 'call', _1021 => _1021()])||"",quoted:!1}),expression:i});return p.type=i.type,p}return i});s.setArgKey("expressions",r)}}return n}var $V=/\\(\d+)/g;function so(n,...e){let t=n._constructor.name,s=this.dialect._constructor.name;for(let r of e){let[i,a]=typeof r=="string"?[r,void 0]:r;n.getArgKey(i)&&this.unsupported(_nullishCoalesce(a, () => (`Argument '${i}' is not supported for expression '${t}' when targeting ${s}.`)))}}var aF,oF,cF,pF,lF,uF,EF,hF,gF,dF,AF,fF,nn;fF=[O,O],AF=[O],dF=[O],gF=[O],hF=[O],EF=[O],uF=[O],lF=[O],pF=[O],cF=[O],oF=[O],aF=[O];var L=class{constructor(e={}){this.pretty=void 0;this.identify=void 0;this.normalize=void 0;this.pad=void 0;this.indentAmount=void 0;this.normalizeFunctions=void 0;this.unsupportedLevel=void 0;this.maxUnsupported=void 0;this.leadingComma=void 0;this.maxTextWidth=void 0;this.comments=void 0;this.dialect=void 0;this.unsupportedMessages=void 0;this.escapedQuoteEnd=void 0;this.nextName=void 0;this.escapedByteQuoteEnd=void 0;this.escapedIdentifierEnd=void 0;this.identifierStart=void 0;this.identifierEnd=void 0;this.quoteJsonPathKeyUsingBrackets=void 0;this.pretty=_nullishCoalesce(e.pretty, () => (!1)),this.identify=_nullishCoalesce(e.identify, () => (!1)),this.normalize=_nullishCoalesce(e.normalize, () => (!1)),this.pad=_nullishCoalesce(e.pad, () => (2)),this.indentAmount=_nullishCoalesce(e.indent, () => (2)),this.unsupportedLevel=_nullishCoalesce(e.unsupportedLevel, () => (1)),this.maxUnsupported=_nullishCoalesce(e.maxUnsupported, () => (3)),this.leadingComma=_nullishCoalesce(e.leadingComma, () => (!1)),this.maxTextWidth=_nullishCoalesce(e.maxTextWidth, () => (80)),this.comments=_nullishCoalesce(e.comments, () => (!0)),this.dialect=W.getOrRaise(e.dialect);let t=this.dialect._constructor;this.normalizeFunctions=_nullishCoalesce(_nullishCoalesce(e.normalizeFunctions, () => (t.NORMALIZE_FUNCTIONS)), () => ("upper"));let s=t.tokenizerClass.STRING_ESCAPES,r=s&&0<s.length?s[0]:"";this.escapedQuoteEnd=r+this.dialect._constructor.QUOTE_END,this.escapedByteQuoteEnd=this.dialect._constructor.BYTE_END?r+this.dialect._constructor.BYTE_END:"",this.escapedIdentifierEnd=this.dialect._constructor.IDENTIFIER_END+this.dialect._constructor.IDENTIFIER_END,this.identifierStart=this.dialect._constructor.IDENTIFIER_START,this.identifierEnd=this.dialect._constructor.IDENTIFIER_END,this.unsupportedMessages=[],this.nextName=go("_t"),this.quoteJsonPathKeyUsingBrackets=!0}static get NULL_ORDERING_SUPPORTED(){return"supported"}static get SUPPORTED_JSON_PATH_PARTS(){return new Set([...AM])}static get UNWRAPPED_INTERVAL_VALUES(){return new Set([k,w,Ps,Ye])}static get WITH_SEPARATED_COMMENTS(){return new Set([jn,us,ei,Jn,Tn,Ge,Ss,z,Oo,ke,Ys,$t,$,be,sr,at,ve])}static get EXCLUDE_COMMENTS(){return new Set([Y,be])}static get TYPE_MAPPING(){return new Map([["datetime2","TIMESTAMP"],["nchar","CHAR"],["nvarchar","VARCHAR"],["mediumtext","TEXT"],["longtext","TEXT"],["tinytext","TEXT"],["blob","VARBINARY"],["mediumblob","BLOB"],["longblob","BLOB"],["tinyblob","BLOB"],["inet","INET"],["rowversion","VARBINARY"],["smalldatetime","TIMESTAMP"]])}static get UNSUPPORTED_TYPES(){return new Set}static get PARAMETERIZABLE_TEXT_TYPES(){return new Set(["nvarchar","varchar","char","nchar"])}static get TOKEN_MAPPING(){return{}}static get ORIGINAL_TRANSFORMS(){return new Map([[mE,function(e){return this.binary(e,"-|-")}],[ji,function(e){return`ALLOWED_VALUES ${this.expressions(e,{flat:!0})}`}],[Lo,function(e){return this.sql(e,"this")}],[Mo,function(e){return this.expressions(e,{prefix:"WITH ",sep:" "})}],[ql,function(e){return this.binary(e,"@>")}],[Yy,function(e){return this.binary(e,"&&")}],[Qi,function(e){return`AUTO REFRESH ${this.sql(e,"this")}`}],[Zi,function(e){return`BACKUP ${this.sql(e,"this")}`}],[Gi,e=>`${e.getArgKey("not")?"NOT ":""}CASESPECIFIC`],[Ir,function(e){return this.ceilFloor(e)}],[rE,function(e){return`CHARACTER SET ${this.sql(e,"this")}`}],[ri,function(e){return`${e.getArgKey("default")?"DEFAULT ":""}CHARACTER SET=${this.sql(e,"this")}`}],[Uo,function(e){return`CLUSTERED (${this.expressions(e,{key:"this",indent:!1})})`}],[nE,function(e){return`COLLATE ${this.sql(e,"this")}`}],[iE,function(e){return`COMMENT ${this.sql(e,"this")}`}],[yg,function(e){return`CONNECT_BY_ROOT ${this.sql(e,"this")}`}],[Ly,function(e){return this.func("CONVERT",[e.args.this,e.args.dest,e.args.source])}],[ta,()=>"COPY GRANTS"],[Op,function(e){return`CREDENTIALS=(${this.expressions(e,{key:"expressions",sep:" "})})`}],[vp,()=>"CURRENT_CATALOG"],[Fp,()=>"SESSION_USER"],[aE,function(e){return`FORMAT ${this.sql(e,"this")}`}],[oE,function(e){return`DEFAULT ${this.sql(e,"this")}`}],[Aa,()=>"DYNAMIC"],[fa,()=>"EMPTY"],[cE,function(e){return`ENCODE ${this.sql(e,"this")}`}],[ga,function(e){return`ENVIRONMENT (${this.expressions(e,{flat:!0})})`}],[Zc,function(e){return`EPHEMERAL${e.args.this?" "+this.sql(e,"this"):""}`}],[pE,function(e){return`EXCLUDE ${this.sql(e,"this").trimStart()}`}],[fn,function(e){return this.nakedProperty(e)}],[Yr,function(e){return this.setOperations(e)}],[Nn,()=>"EXTERNAL"],[wn,function(e){return this.ceilFloor(e)}],[Ch,function(e){return this.getPutSql(e)}],[pa,()=>"GLOBAL"],[oa,()=>"HEAP"],[la,()=>"ICEBERG"],[ua,function(e){return`INHERITS (${this.expressions(e,{flat:!0})})`}],[uE,function(e){return`INLINE LENGTH ${this.sql(e,"this")}`}],[Ea,function(e){return`INPUT${this.sql(e,"this")}`}],[yn,function(e){return this.setOperations(e)}],[Kn,function(e){return`${this.sql(e,"this")} TO ${this.sql(e,"expression")}`}],[Qx,function(e){return this.sql(Le(e.args.this||"","bigint"))}],[oc,function(e){return this.binary(e,"?|")}],[cc,function(e){return this.binary(e,"?&")}],[pc,function(e){return this.binary(e,"#-")}],[Xr,function(e){return`?${e.args.this}`}],[Ai,function(e){return`..${e.args.this||""}`}],[Ls,()=>"$"],[zr,function(e){return`(${e.args.this}`}],[di,function(e){return`[${this.jsonPathPart(e.args.this)}]`}],[fi,function(e){return[e.args.start,e.args.end,e.args.step].filter(t=>t!==void 0).map(t=>t===!1?"":this.jsonPathPart(t)).join(":")}],[Ln,function(e){return`[${(_nullishCoalesce(e.args.expressions, () => ([]))).map(s=>this.jsonPathPart(s)).join(",")}]`}],[hs,()=>"*"],[ni,function(e){return this.nakedProperty(e)}],[Es,function(e){return this.nakedProperty(e)}],[xa,e=>`${e.getArgKey("no")?"NO ":""}LOG`],[Ta,()=>"MATERIALIZED"],[rT,function(e){return`NET.${this.sql(e,"this")}`}],[qo,function(e){return`NONCLUSTERED (${this.expressions(e,{key:"this",indent:!1})})`}],[Sa,()=>"NO PRIMARY INDEX"],[si,()=>"NOT FOR REPLICATION"],[Xn,e=>`ON COMMIT ${e.getArgKey("delete")?"DELETE":"PRESERVE"} ROWS`],[Br,function(e){return`ON ${this.sql(e,"this")}`}],[EE,function(e){return`ON UPDATE ${this.sql(e,"this")}`}],[ic,function(e){return this.binary(e,"")}],[ha,function(e){return`OUTPUT${this.sql(e,"this")}`}],[fE,function(e){return this.binary(e,"&<")}],[xE,function(e){return this.binary(e,"&>")}],[gE,function(e){return`PATH ${this.sql(e,"this")}`}],[ii,function(e){return this.func("BUCKET",[e.args.this,e.args.expression])}],[ai,function(e){return this.func("TRUNCATE",[e.args.this,e.args.expression])}],[Fi,function(e){return`ANY${this.sql(e,"this")}`}],[Ph,function(e){return`#${this.sql(e,"this")}`}],[CR,function(e){return`PROJECTION POLICY ${this.sql(e,"this")}`}],[dc,()=>"ZEROFILL"],[Rp,function(e){return this.getPutSql(e)}],[Ra,function(e){return`REMOTE WITH CONNECTION ${this.sql(e,"this")}`}],[oi,function(e){return e.getArgKey("null")?"RETURNS NULL ON NULL INPUT":this.nakedProperty(e)}],[bx,function(e){return`SAFE.${this.sql(e,"this")}`}],[Ia,function(e){return`SAMPLE BY ${this.sql(e,"this")}`}],[Ma,()=>"SECURE"],[ya,function(e){return`SECURITY ${this.sql(e,"this")}`}],[Np,function(e){return this.sql(e,"this")}],[zn,e=>`${e.getArgKey("multi")?"MULTI":""}SET`],[ba,function(e){return`SETTINGS${this.seg("")}${this.expressions(e)}`}],[Ca,function(e){return`SHARING=${this.sql(e,"this")}`}],[qr,e=>e.name],[wa,function(e){return`SQL SECURITY ${this.sql(e,"this")}`}],[vr,e=>e.name],[_o,function(e){return`STREAM ${this.sql(e,"this")}`}],[ma,()=>"STREAMING"],[Oa,()=>"STRICT"],[xo,function(e){return`SWAP WITH ${this.sql(e,"this")}`}],[Gn,function(e){return this.sql(e.args.this)}],[Ip,function(e){return`TAG (${this.expressions(e,{flat:!0})})`}],[Gr,()=>"TEMPORARY"],[hE,function(e){return`TITLE ${this.sql(e,"this")}`}],[tT,function(e){return`MAP ${this.sql(e,"this")}`}],[ca,function(e){return`TO ${this.sql(e.args.this)}`}],[La,function(e){return this.func("TRANSFORM",e.args.expressions||[])}],[In,()=>"TRANSIENT"],[$r,function(e){return this.setOperations(e)}],[Da,()=>"UNLOGGED"],[yp,function(e){return`USING TEMPLATE ${this.sql(e,"this")}`}],[Do,function(e){return`USING DATA ${this.sql(e,"this")}`}],[Bo,()=>"UPPERCASE"],[AC,function(e){return this.sql(new xn({this:w.string("UTC")}))}],[Gx,function(e){return this.sql(new Ba({this:w.string("UTC")}))}],[$x,function(e){return this.sql(new ir({this:w.string("UTC")}))}],[Mh,function(e){return`VARIADIC ${this.sql(e,"this")}`}],[gr,function(e){return this.func("MAP",[e.args.keys,e.args.values])}],[_a,function(e){return`WITH ${this.sql(e,"this")}`}],[Vs,()=>"VOLATILE"],[ka,function(e){return`WITH JOURNAL TABLE=${this.sql(e,"this")}`}],[qa,function(e){return`WITH ${this.expressions(e,{flat:!0})}`}],[Ua,function(e){return`WITH SCHEMA ${this.sql(e,"this")}`}],[To,function(e){return`${this.sql(e,"this")} WITH ${this.sql(e,"op")}`}],[Pp,()=>"FORCE"]])}static get TRANSFORMS(){let e=new Map(this.ORIGINAL_TRANSFORMS);for(let t of Array.from(AM).filter(s=>!this.SUPPORTED_JSON_PATH_PARTS.has(s)))e.delete(t);return e}static get PROPERTIES_LOCATION(){return new Map([[ji,"postSchema"],[zi,"postCreate"],[Ki,"postSchema"],[Qi,"postSchema"],[Zi,"postSchema"],[Go,"postName"],[ri,"postSchema"],[$o,"postName"],[ea,"postSchema"],[ta,"postSchema"],[qi,"postSchema"],[da,"postSchema"],[na,"postSchema"],[Vo,"postSchema"],[Yo,"postName"],[Ho,"postSchema"],[sa,"postCreate"],[Ko,"postSchema"],[zo,"postSchema"],[Aa,"postCreate"],[ra,"postSchema"],[ia,"postSchema"],[fa,"postSchema"],[Cp,"postExpression"],[aa,"postSchema"],[ga,"postSchema"],[fn,"postSchema"],[Nn,"postCreate"],[Wo,"postName"],[$s,"postWith"],[jo,"postName"],[pa,"postCreate"],[oa,"postWith"],[ua,"postSchema"],[la,"postCreate"],[bp,"postSchema"],[Ea,"postSchema"],[Jo,"postName"],[Xo,"postName"],[ni,"postSchema"],[Qo,"postSchema"],[Es,"postSchema"],[Ha,"postSchema"],[Zo,"postAlias"],[xa,"postName"],[Ta,"postCreate"],[Yi,"postName"],[Sa,"postExpression"],[Br,"postSchema"],[Xn,"postExpression"],[ke,"postSchema"],[ha,"postSchema"],[Bt,"postWith"],[ec,"postSchema"],[mo,"postSchema"],[U,"postWith"],[_h,"postSchema"],[Ra,"postSchema"],[oi,"postSchema"],[Dh,"unsupported"],[Na,"postSchema"],[tc,"postSchema"],[sc,"postSchema"],[Ia,"postSchema"],[Nr,"postSchema"],[Ma,"postCreate"],[ya,"postSchema"],[ci,"postSchema"],[fo,"postSchema"],[ba,"postSchema"],[zn,"postCreate"],[Np,"postSchema"],[Ca,"postExpression"],[Wn,"postExpression"],[Pa,"postSchema"],[qr,"postSchema"],[wa,"postCreate"],[vr,"postSchema"],[pi,"postSchema"],[ma,"postCreate"],[Oa,"postSchema"],[Ip,"postWith"],[Gr,"postCreate"],[ca,"postSchema"],[In,"postCreate"],[La,"postSchema"],[vi,"postSchema"],[Da,"postCreate"],[yp,"postSchema"],[_a,"postSchema"],[Vs,"postCreate"],[li,"postExpression"],[ka,"postName"],[qa,"postSchema"],[Ua,"postSchema"],[rc,"postSchema"],[Pp,"postCreate"]])}get _constructor(){return this.constructor}generate(e,t={}){let{copy:s=!0}=t,r=s?e.copy():e;r=this.preprocess(r),this.unsupportedMessages=[];let i=this.sql(r).trim();if(this.pretty&&(i=i.replaceAll(this._constructor.SENTINEL_LINE_BREAK,`
|
|
5
|
+
`)),this.unsupportedLevel===0)return i;if(this.unsupportedLevel===1)for(let a of this.unsupportedMessages)console.warn(a);else if(this.unsupportedLevel===2&&0<this.unsupportedMessages.length)throw new uo(mw(this.unsupportedMessages,this.maxUnsupported));return i}preprocess(e){return e=this.moveCtesToTopLevel(e),this._constructor.ENSURE_BOOLS&&(e=eF(e)),e}moveCtesToTopLevel(e){return!e.parent&&this.constructor.EXPRESSIONS_WITHOUT_NESTED_CTES.has(e._constructor)&&[...e.findAll(ve)].some(t=>t.parent!==e)?Xv(e):e}unsupported(e){if(this.unsupportedLevel===3)throw new uo(e);this.unsupportedMessages.push(e)}sep(e=" "){return this.pretty?`${e.trim()}
|
|
6
|
+
`:e}seg(e,t=" "){return`${this.sep(t)}${e}`}sanitizeComment(e){let t=e;return t[0]&&t[0].trim()!==""&&(t=" "+t),t[t.length-1]&&t[t.length-1].trim()!==""&&(t=t+" "),this.dialect._constructor.tokenizerClass.NESTED_COMMENTS||(t=t.replace(/\*\//g,"* /")),t}wrap(e){let t;return typeof e!="string"&&En.some(s=>e instanceof s)?t=this.sql(e):t=this.sql(e,"this"),t?(t=this.indent(t,{level:1,pad:0}),`(${this.sep("")}${t}${this.seg(")","")}`):"()"}noIdentify(e,...t){let s=this.identify;this.identify=!1;let r=e(...t);return this.identify=s,r}normalizeFunc(e){return this.normalizeFunctions==="upper"?e.toUpperCase():this.normalizeFunctions==="lower"?e.toLowerCase():e}indent(e,t={}){let{skipFirst:s=!1,skipLast:r=!1,pad:i=this.pad,level:a=0}=t;if(!this.pretty||!e)return e;let o=e.split(`
|
|
7
|
+
`);return o.map((c,p)=>s&&p===0||r&&p===o.length-1?c:`${" ".repeat(a*this.indentAmount+i)}${c}`).join(`
|
|
8
|
+
`)}sql(e,t,s={}){let{comment:r=!0}=s;if(e===void 0)return"";if(typeof e=="number"||typeof e=="string"||typeof e=="boolean")return e.toString();if(Array.isArray(e))return e.map(o=>this.sql(o)).join(", ");if(t){let o=e.getArgKey(t);return o&&(typeof o=="string"||o instanceof h)?this.sql(o):""}let i=this._constructor.TRANSFORMS.get(e._constructor),a="";if(i instanceof Function)a=i.call(this,e);else if(e instanceof h){let o=`${e._constructor.key}Sql`,c=this[o];if(c instanceof Function)a=c.call(this,e);else if(e instanceof d||fg.has(e._constructor))a=this.functionFallbackSql(e);else if(e instanceof U)a=this.propertySql(e);else throw new Error(`Unsupported expression type ${e._constructor.name}`)}else throw new Error(`Expected an Expression. Received ${typeof e}: ${e}`);return this.comments&&r?this.maybeComment(a,e):a}maybeComment(e,t,s,r=!1){let i=this.comments?s!==void 0?s:_optionalChain([t, 'optionalAccess', _1022 => _1022.comments]):void 0;if(!i||i.length===0||t&&[...this._constructor.EXCLUDE_COMMENTS].some(c=>t instanceof c))return e;let a=i.filter(c=>c).map(c=>`/*${this.sanitizeComment(c)}*/`).join(" ");if(!a)return e;let o=this.replaceLineBreaks(a);return r||t&&[...this._constructor.WITH_SEPARATED_COMMENTS].some(c=>t instanceof c)?!e||e[0]===" "||e[0]===`
|
|
9
|
+
`?`${this.sep()}${o}${e}`:`${o}${this.sep()}${e}`:`${e} ${o}`}uncacheSql(e){let t=this.sql(e,"this");return`UNCACHE TABLE${e.args.exists?" IF EXISTS":""} ${t}`}cacheSql(e){let t=e.args.lazy?" LAZY":"",s=this.sql(e,"this"),r=e.args.options,i=_optionalChain([r, 'optionalAccess', _1023 => _1023.length])?` OPTIONS(${this.sql(r[0])} = ${this.sql(r[1])})`:"",a=this.sql(e,"expression");return a=a?` AS${this.sep()}${a}`:"",a=`CACHE${t} TABLE ${s}${i}${a}`,this.prependCtes(e,a)}characterSetSql(e){return e.parent instanceof Z?`CHAR CHARACTER SET ${this.sql(e,"this")}`:`${e.args.default?"DEFAULT ":""}CHARACTER SET=${this.sql(e,"this")}`}columnParts(e){return[e.args.catalog,e.args.db,e.args.table,e.args.this].filter(Boolean).map(s=>this.sql(s)).join(".")}columnSql(e){let t=e.args.joinMark?" (+)":"";return t&&!this.dialect._constructor.SUPPORTS_COLUMN_JOIN_MARKS?(this.unsupported("Outer join syntax using the (+) operator is not supported."),this.columnParts(e)):`${this.columnParts(e)}${t}`}pseudocolumnSql(e){return this.columnSql(e)}columnPositionSql(e){let t=this.sql(e,"this"),s=t?` ${t}`:"";return`${this.sql(e,"position")}${s}`}columnDefSql(e,t={}){let{sep:s=" "}=t,r=this.sql(e,"this"),i=this.sql(e,"kind"),a=this.expressions(e,{key:"constraints",sep:" ",flat:!0}),o=e.args.exists?"IF NOT EXISTS ":"";i=i?`${s}${i}`:"";let c=a?` ${a}`:"",p=this.sql(e,"position");return p=p?` ${p}`:"",0<Array.from(e.findAll(An)).length&&!this._constructor.COMPUTED_COLUMN_WITH_TYPE&&(i=""),`${o}${r}${i}${c}${p}`}columnConstraintSql(e){let t=this.sql(e,"this"),s=this.sql(e,"kind").trim();return t?`CONSTRAINT ${t} ${s}`:s}computedColumnConstraintSql(e){let t=this.sql(e,"this"),s;return e.args.notNull?s=" PERSISTED NOT NULL":e.args.persisted?s=" PERSISTED":s="",`AS ${t}${s}`}autoIncrementColumnConstraintSql(e){return this.tokenSql("autoIncrement")}compressColumnConstraintSql(e){let t;return Array.isArray(e.args.this)?t=this.wrap(this.expressions(e,{key:"this",flat:!0})):t=this.sql(e,"this"),`COMPRESS ${t}`}generatedAsIdentityColumnConstraintSql(e){let t="";if(e.args.this!==void 0){let m=e.args.onNull?" ON NULL":"";t=e.args.this?" ALWAYS":` BY DEFAULT${m}`}let s=e.args.start,r=s?`START WITH ${s}`:"",i=e.args.increment,a=i?` INCREMENT BY ${i}`:"",o=e.args.minvalue,c=o?` MINVALUE ${o}`:"",p=e.args.maxvalue,u=p?` MAXVALUE ${p}`:"",E=e.args.cycle,g="";E!==void 0&&(g=`${E?"":" NO"} CYCLE`,g=!r&&!a?g.trim():g);let A="";(r||a||g)&&(A=`${r}${a}${c}${u}${g}`,A=` (${A.trim()})`);let x=this.sql(e,"expression");return x=x?`(${x})`:"IDENTITY",`GENERATED${t} AS ${x}${A}`}generatedAsRowColumnConstraintSql(e){let t=e.args.start?"START":"END",s=e.args.hidden?" HIDDEN":"";return`GENERATED ALWAYS AS ROW ${t}${s}`}periodForSystemTimeConstraintSql(e){return`PERIOD FOR SYSTEM_TIME (${this.sql(e,"this")}, ${this.sql(e,"expression")})`}notNullColumnConstraintSql(e){return e.args.allowNull?"NULL":"NOT NULL"}primaryKeyColumnConstraintSql(e){let t=e.args.desc;if(t!==void 0)return`PRIMARY KEY${t?" DESC":" ASC"}`;let s=this.expressions(e,{key:"options",flat:!0,sep:" "});return s=s?` ${s}`:"",`PRIMARY KEY${s}`}uniqueColumnConstraintSql(e){let t=this.sql(e,"this");t=t?` ${t}`:"";let s=e.args.indexType,r=s?` USING ${s}`:"",i=this.sql(e,"onConflict");i=i?` ${i}`:"";let a=e.args.nulls?" NULLS NOT DISTINCT":"",o=this.expressions(e,{key:"options",flat:!0,sep:" "});return o=o?` ${o}`:"",`UNIQUE${a}${t}${r}${i}${o}`}inOutColumnConstraintSql(e){let t=e.args.input,s=e.args.output;return e.args.variadic?"VARIADIC":t&&s?`IN${this._constructor.INOUT_SEPARATOR}OUT`:t?"IN":s?"OUT":""}createableSql(e,t){return this.sql(e,"this")}createSql(e){let t=this.sql(e,"kind").toUpperCase();t=_nullishCoalesce(this.dialect._constructor.INVERSE_CREATABLE_KIND_MAPPING[t], () => (t));let s=e.args.properties;s&&ue(s,mt);let r=s?this.locateProperties(s):new Map,i=this.createableSql(e,r),a="",o=r.get("postSchema"),c=r.get("postWith");if(o||c){let rs=new mt({expressions:[..._nullishCoalesce(o, () => ([])),..._nullishCoalesce(c, () => ([]))]});rs.parent=e,a=this.sql(rs),o?a=this.sep()+a:this.pretty||(a=` ${a}`)}let p=e.args.begin?" BEGIN":"",u=e.args.end?" END":"",E=this.sql(e,"expression");if(E&&(E=`${p}${this.sep()}${E}${u}`,this._constructor.CREATE_FUNCTION_RETURN_AS||!(e.args.expression instanceof bo))){let rs="",wr=r.get("postAlias");wr&&(rs=this.properties(new mt({expressions:wr}),{wrapped:!1})),rs=rs?` ${rs}`:"",E=` AS${rs}${E}`}let g="",A=r.get("postIndex");A&&(g=this.properties(new mt({expressions:A}),{wrapped:!1,prefix:" "}));let x=this.expressions(e,{key:"indexes",indent:!1,sep:" "});x=x?` ${x}`:"";let m=x+g,N=e.args.replace?" OR REPLACE":"",R=e.args.refresh?" OR REFRESH":"",S=e.args.unique?" UNIQUE":"",I=e.args.clustered,y="";I===void 0?y="":I?y=" CLUSTERED COLUMNSTORE":y=" NONCLUSTERED COLUMNSTORE";let P="",v=r.get("postCreate");v&&(P=this.properties(new mt({expressions:v}),{sep:" ",prefix:" ",wrapped:!1}));let H=`${y}${N}${R}${S}${P}`,B="",fe=r.get("postExpression");fe&&(B=this.properties(new mt({expressions:fe}),{sep:" ",prefix:" ",wrapped:!1}));let _e=e.args.concurrently?" CONCURRENTLY":"",Is=e.args.exists?" IF NOT EXISTS":"",zt=e.args.noSchemaBinding?" WITH NO SCHEMA BINDING":"",on=this.sql(e,"clone");on=on?` ${on}`:"";let ys;return this._constructor.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES.has(t)?ys=`${E}${a}`:ys=`${a}${E}`,E=`CREATE${H} ${t}${_e}${Is} ${i}${ys}${B}${m}${zt}${on}`,this.prependCtes(e,E)}sequencePropertiesSql(e){let t=this.sql(e,"start");t=t?`START WITH ${t}`:"";let s=this.sql(e,"increment");s=s?` INCREMENT BY ${s}`:"";let r=this.sql(e,"minvalue");r=r?` MINVALUE ${r}`:"";let i=this.sql(e,"maxvalue");i=i?` MAXVALUE ${i}`:"";let a=this.sql(e,"owned");a=a?` OWNED BY ${a}`:"";let o=e.args.cache,c="";o===void 0?c="":o===!0?c=" CACHE":c=` CACHE ${o}`;let p=this.expressions(e,{key:"options",flat:!0,sep:" "}),u=p?` ${p}`:"";return`${t}${s}${r}${i}${c}${u}${a}`.trimStart()}cloneSql(e){let t=this.sql(e,"this"),s=e.args.shallow?"ShaLLOW ":"",r=e.args.copy&&this._constructor.SUPPORTS_TABLE_COPY?"COPY":"CLONE";return`${s}${r} ${t}`}describeSql(e){let t=e.args.style,s=t?` ${t}`:"",r=this.sql(e,"partition");r=r?` ${r}`:"";let i=this.sql(e,"format");i=i?` ${i}`:"";let a=e.args.asJson?" AS JSON":"";return`DESCRIBE${s}${i} ${this.sql(e,"this")}${r}${a}`}heredocSql(e){let t=this.sql(e,"tag");return`$${t}$${this.sql(e,"this")}$${t}$`}prependCtes(e,t){let s=this.sql(e,"with");return s?`${s}${this.sep()}${t}`:t}withSql(e){let t=this.expressions(e,{flat:!0}),s=this._constructor.CTE_RECURSIVE_KEYWORD_REQUIRED&&e.args.recursive?"RECURSIVE ":"",r=this.sql(e,"search");return r=r?` ${r}`:"",`WITH ${s}${t}${r}`}cteSql(e){let t=e.args.alias;t&&_optionalChain([t, 'access', _1024 => _1024.addComments, 'optionalCall', _1025 => _1025(e.popComments())]);let s=this.sql(e,"alias"),r=e.args.materialized,i="";r===!1?i="NOT MATERIALIZED ":r&&(i="MATERIALIZED ");let a=this.expressions(e,{key:"keyExpressions",flat:!0}),o=a?` USING KEY (${a})`:"";return`${s}${o} AS ${i}${this.wrap(e)}`}tableAliasSql(e){let t=this.sql(e,"this"),s=this.expressions(e,{key:"columns",flat:!0});return s=s?`(${s})`:"",s&&!this._constructor.SUPPORTS_TABLE_ALIAS_COLUMNS&&(s="",this.unsupported("Named columns are not supported in table alias.")),!t&&!this.dialect._constructor.UNNEST_COLUMN_ONLY&&(t=this.nextName()),`${t}${s}`}bitStringSql(e){let t=this.sql(e,"this");return this.dialect._constructor.BIT_START?`${this.dialect._constructor.BIT_START}${t}${this.dialect._constructor.BIT_END}`:`${parseInt(t,2)}`}hexStringSql(e,t={}){let{binaryFunctionRepr:s}=t,r=this.sql(e,"this"),i=e.args.isInteger;if(i&&!this.dialect._constructor.HEX_STRING_IS_INTEGER_TYPE||!this.dialect._constructor.HEX_START&&!s)return`${parseInt(r,16)}`;if(!i){if(s)return this.func(s,[gg(r)]);this.dialect._constructor.HEX_STRING_IS_INTEGER_TYPE&&this.unsupported("Unsupported transpilation from BINARY/BLOB hex string")}return`${this.dialect._constructor.HEX_START}${r}${this.dialect._constructor.HEX_END}`}byteStringSql(e){let t=this.sql(e,"this");if(this.dialect._constructor.BYTE_START){let s=this.escapeStr(t,{escapeBackslash:!1,delimiter:this.dialect._constructor.BYTE_END,escapedDelimiter:this.escapedByteQuoteEnd,isByteString:!0}),r=e.args.isBytes||!1,i=`${this.dialect._constructor.BYTE_START}${s}${this.dialect._constructor.BYTE_END}`;return r&&!this.dialect._constructor.BYTE_STRING_IS_BYTES_TYPE?this.sql(Le(i,"BINARY",{dialect:this.dialect})):!r&&this.dialect._constructor.BYTE_STRING_IS_BYTES_TYPE?this.sql(Le(i,"VARCHAR",{dialect:this.dialect})):i}return t}unicodeStringSql(e){let t=this.sql(e,"this"),s=e.args.escape,r,i,a;this.dialect._constructor.UNICODE_START?(r="\\$1",i=this.dialect._constructor.UNICODE_START,a=this.dialect._constructor.UNICODE_END):(r="\\u$1",i=this.dialect._constructor.QUOTE_START,a=this.dialect._constructor.QUOTE_END);let o,c;s?(o=new RegExp(`${s.name}(\\d+)`,"g"),c=this._constructor.SUPPORTS_UESCAPE?` UESCAPE ${this.sql(s)}`:""):(o=$V,c="");let p=t;if(!this.dialect._constructor.UNICODE_START||s&&!this._constructor.SUPPORTS_UESCAPE){let u=this._constructor.UNICODE_SUBSTITUTE||r;p=p.replace(o,u)}return`${i}${p}${a}${c}`}rawStringSql(e){let t=_optionalChain([e, 'access', _1026 => _1026.args, 'access', _1027 => _1027.this, 'optionalAccess', _1028 => _1028.toString, 'call', _1029 => _1029()])||"";return this.dialect._constructor.tokenizerClass.STRING_ESCAPES.includes("\\")&&(t=_optionalChain([t, 'optionalAccess', _1030 => _1030.replace, 'call', _1031 => _1031(/\\/g,"\\\\")])),t=this.escapeStr(t,{escapeBackslash:!1}),`${this.dialect._constructor.QUOTE_START}${t}${this.dialect._constructor.QUOTE_END}`}dataTypeParamSql(e){let t=this.sql(e,"this"),s=this.sql(e,"expression"),r=s&&this._constructor.DATA_TYPE_SPECIFIERS_ALLOWED?` ${s}`:"";return`${t}${r}`}dataTypeSql(e){let t="",s="",r=e.args.nested,i=r&&this.pretty?this.expressions(e,{dynamic:!0,newLine:!0,skipFirst:!0,skipLast:!0}):this.expressions(e,{flat:!0}),a=e.args.this;typeof a=="string"&&this._constructor.UNSUPPORTED_TYPES.has(a)&&this.unsupported(`Data type ${a} is not supported when targeting ${this.dialect._constructor.name}`);let o;if(a instanceof h)o=this.sql(a);else if(a==="user-defined"&&e.args.kind)o=this.sql(e,"kind");else{let c=a&&this._constructor.TYPE_MAPPING.get(a),p=a!==void 0&&Object.values(Be).includes(a);o=c!==void 0?c:a&&(p?Lw(a):a)}if(i)if(r){let c=this._constructor.STRUCT_DELIMITER;if(t=`${c[0]}${i}${c[1]}`,_optionalChain([e, 'access', _1032 => _1032.args, 'access', _1033 => _1033.values, 'optionalAccess', _1034 => _1034.length])){let p=a==="array"?["[","]"]:["(",")"],u=this.expressions(e,{key:"values",flat:!0});s=`${p[0]}${u}${p[1]}`}}else a==="interval"?t=` ${i}`:t=`(${i})`;return o=`${o}${t}${s}`,this._constructor.TZ_TO_WITH_TIME_ZONE&&(a==="timetz"||a==="timestamptz")&&(o=`${o} WITH TIME ZONE`),o}directorySql(e){let t=e.args.local?"LOCAL ":"",s=this.sql(e,"rowFormat");return s=s?` ${s}`:"",`${t}DIRECTORY ${this.sql(e,"this")}${s}`}deleteSql(e){let t=this.sql(e,"this"),s=t?` FROM ${t}`:"",r=this.expressions(e,{key:"using"});r=r?` USING ${r}`:"";let i=this.sql(e,"cluster");i=i?` ${i}`:"";let a=this.sql(e,"where"),o=this.sql(e,"returning"),c=this.sql(e,"order"),p=this.sql(e,"limit"),u=this.expressions(e,{key:"tables"});u=u?` ${u}`:"";let E;return this._constructor.RETURNING_END?E=`${s}${r}${i}${a}${o}${c}${p}`:E=`${o}${s}${r}${i}${a}${c}${p}`,this.prependCtes(e,`DELETE${u}${E}`)}dropSql(e){let t=this.sql(e,"this"),s=this.expressions(e,{flat:!0});s=s?` (${s})`:"";let r=_optionalChain([e, 'access', _1035 => _1035.args, 'access', _1036 => _1036.kind, 'optionalAccess', _1037 => _1037.toString, 'call', _1038 => _1038()]),i=r&&(_optionalChain([this, 'access', _1039 => _1039.dialect, 'access', _1040 => _1040._constructor, 'access', _1041 => _1041.INVERSE_CREATABLE_KIND_MAPPING, 'optionalAccess', _1042 => _1042[r]])||r).toUpperCase(),a=e.args.exists?" IF EXISTS ":" ",o=e.args.concurrently?" CONCURRENTLY":"",c=this.sql(e,"cluster");c=c?` ${c}`:"";let p=e.args.temporary?" TEMPORARY":"",u=e.args.materialized?" MATERIALIZED":"",E=e.args.cascade?" CASCADE":"",g=e.args.constraints?" CONSTRAINTS":"",A=e.args.purge?" PURGE":"";return`DROP${p}${u} ${i}${o}${a}${t}${c}${s}${E}${g}${A}`}setOperation(e){let t=e._constructor,s=t.key.toUpperCase(),r=e.args.distinct;r===!1&&(e instanceof Yr||e instanceof yn)&&!this._constructor.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE&&this.unsupported(`${s} ALL is not supported`);let i=_optionalChain([this, 'access', _1043 => _1043.dialect, 'access', _1044 => _1044._constructor, 'access', _1045 => _1045.SET_OP_DISTINCT_BY_DEFAULT, 'optionalAccess', _1046 => _1046[t.key]]);r===void 0&&(r=i,r===void 0&&this.unsupported(`${s} requires DISTINCT or ALL to be specified`));let a;r===i?a="":a=r?" DISTINCT":" ALL";let o=[e.args.side,e.args.kind].filter(Boolean).join(" ").toUpperCase(),c=o?`${o} `:"",p=e.args.byName?" BY NAME":"",u=this.expressions(e,{key:"on",flat:!0});return u=u?` ON (${u})`:"",`${c}${s}${a}${p}${u}`}setOperations(e){if(!this._constructor.SET_OP_MODIFIERS){let i=e.args.limit,a=e.args.order;if(i||a){let c=this.moveCtesToTopLevel(gM(e,"_l_0",{copy:!1}).select("*",{copy:!1}));return i&&(c=c.limit(typeof i=="number"?i:i.pop(),{copy:!1})),a&&(c=c.orderBy(a.pop(),{copy:!1})),this.sql(c)}}let t=[],s=[e];for(;0<s.length;){let i=s.pop();if(i instanceof be)i.args.expression&&s.push(i.args.expression),s.push(this.maybeComment(this.setOperation(i),void 0,i.comments,!0)),i.args.this&&s.push(i.args.this);else{let a=typeof i=="string"?i:this.sql(i);t.push(a)}}let r=t.join(this.sep());return r=this.queryModifiers(e,r),this.prependCtes(e,r)}fetchSql(e){let t=e.args.direction,s=t?` ${t}`:"",r=this.sql(e,"count"),i=r?` ${r}`:"",a=this.sql(e,"limitOptions"),o=a?`${a}`:" ROWS ONLY";return`${this.seg("FETCH")}${s}${i}${o}`}limitOptionsSql(e){let t=e.args.percent?" PERCENT":"",s=e.args.rows?" ROWS":"",r=e.args.withTies?" WITH TIES":"";return!r&&s&&(r=" ONLY"),`${t}${s}${r}`}filterSql(e){if(this._constructor.AGGREGATE_FILTER_SUPPORTED){let a=this.sql(e,"this"),o=this.sql(e,"expression").trim();return`${a} FILTER(${o})`}let s=e.args.this,r=s?s.args.this:void 0,i=_optionalChain([e, 'access', _1047 => _1047.args, 'access', _1048 => _1048.expression, 'optionalAccess', _1049 => _1049.args, 'access', _1050 => _1050.this]);return r instanceof h&&i instanceof h&&r.replace(new He({this:i.copy(),true:r.copy()})),this.sql(s)}hintSql(e){return this._constructor.QUERY_HINTS?` /*+ ${this.expressions(e,{sep:this._constructor.QUERY_HINT_SEP}).trim()} */`:(this.unsupported("Hints are not supported"),"")}indexParametersSql(e){let t=this.sql(e,"using");t=t?` USING ${t}`:"";let s=this.expressions(e,{key:"columns",flat:!0}),r=s?`(${s})`:"",i=this.expressions(e,{key:"partitionBy",flat:!0}),a=i?` PARTITION BY ${i}`:"",o=this.sql(e,"where"),c=this.expressions(e,{key:"include",flat:!0});c&&(c=` INCLUDE (${c})`);let p=this.expressions(e,{key:"withStorage",flat:!0}),u=p?` WITH (${p})`:"",E=this.sql(e,"tablespace"),g=E?` USING INDEX TABLESPACE ${E}`:"",A=this.sql(e,"on"),x=A?` ON ${A}`:"";return`${t}${r}${c}${u}${g}${a}${o}${x}`}indexSql(e){let t=e.args.unique?"UNIQUE ":"",s=e.args.primary?"PRIMARY ":"",r=e.args.amp?"AMP ":"",i=this.sql(e,"this");i=i?`${i} `:"";let a=this.sql(e,"table");a=a?`${this._constructor.INDEX_ON} ${a}`:"";let o=a?"":"INDEX ",c=this.sql(e,"params");return`${t}${s}${r}${o}${i}${a}${c}`}identifierSql(e){let t=e.name,s=t.toLowerCase();return t=this.normalize&&!e.args.quoted?s:t,t=t.replaceAll(this.identifierEnd,this.escapedIdentifierEnd),(e.args.quoted||this.dialect.canQuote(e,{identify:this.identify})||this._constructor.RESERVED_KEYWORDS.has(s)||!this.dialect._constructor.IDENTIFIERS_CAN_START_WITH_DIGIT&&/^\d/.test(t))&&(t=`${this.identifierStart}${t}${this.identifierEnd}`),t}hexSql(e){let t=this._constructor.HEX_FUNC,s=this.func(t,[this.sql(e,"this")]);return this.dialect._constructor.HEX_LOWERCASE&&(s=this.func("LOWER",[s])),s}lowerHexSql(e){let t=this._constructor.HEX_FUNC,s=this.func(t,[this.sql(e,"this")]);return this.dialect._constructor.HEX_LOWERCASE||(s=this.func("LOWER",[s])),s}inputOutputFormatSql(e){let t=this.sql(e,"inputFormat"),s=t?`INPUTFORMAT ${t}`:"",r=this.sql(e,"outputFormat"),i=r?`OUTPUTFORMAT ${r}`:"";return[s,i].join(this.sep())}nationalSql(e,t={}){let{prefix:s="N"}=t,r=this.sql(gg(e.name));return`${s}${r}`}partitionSql(e){return`${e.args.subpartition?"SUBPARTITION":"PARTITION"}(${this.expressions(e,{flat:!0})})`}propertiesSql(e){let t=[],s=[];for(let c of e.args.expressions||[]){let p=this._constructor.PROPERTIES_LOCATION.get(c._constructor);p==="postWith"?s.push(c):p==="postSchema"&&t.push(c)}let r=new mt({expressions:t});r.parent=e.parent;let i=new mt({expressions:s});i.parent=e.parent;let a=this.rootProperties(r),o=this.withProperties(i);return a&&o&&!this.pretty&&(o=` ${o}`),a+o}rootProperties(e){return 0<(e.args.expressions||[]).length?this.expressions(e,{indent:!1,sep:" "}):""}properties(e,t={}){let{prefix:s="",sep:r=", ",suffix:i="",wrapped:a=!0}=t;if(0<(e.args.expressions||[]).length){let o=this.expressions(e,{sep:r,indent:!1});if(o){let c=a?this.wrap(o):o;return`${s}${s.trim()?" ":""}${c}${i}`}}return""}withProperties(e){return this.properties(e,{prefix:this.seg(this._constructor.WITH_PROPERTIES_PREFIX,"")})}locateProperties(e){let t=new Map,s=e.args.expressions||[];for(let r of s){let i=this._constructor.PROPERTIES_LOCATION.get(r._constructor)||"unsupported";i!=="unsupported"?(t.has(i)||t.set(i,[]),_optionalChain([t, 'access', _1051 => _1051.get, 'call', _1052 => _1052(i), 'optionalAccess', _1053 => _1053.push, 'call', _1054 => _1054(r)])):this.unsupported(`Unsupported property ${r._constructor.key}`)}return t}propertyName(e,t={}){let{stringKey:s=!1}=t;return e.args.this instanceof me?this.sql(e,"this"):s?`'${e.name}'`:e.name}propertySql(e){let t=e._constructor;if(t===U)return`${this.propertyName(e)}=${this.sql(e,"value")}`;let s=_optionalChain([mt, 'access', _1055 => _1055.PROPERTY_TO_NAME, 'optionalAccess', _1056 => _1056[t.key]]);return s||this.unsupported(`Unsupported property ${e._constructor.key}`),`${s}=${this.sql(e,"this")}`}likePropertySql(e){if(this._constructor.SUPPORTS_CREATE_TABLE_LIKE){let t=(e.args.expressions||[]).map(r=>`${r.name} ${this.sql(r,"value")}`).join(" "),s=t?` ${t}`:"";return`LIKE ${this.sql(e,"this")}${s}`}return this.propertySql(e)}fallbackPropertySql(e){let t=e.args.no?"NO ":"",s=e.args.protection?" PROTECTION":"";return`${t}FALLBACK${s}`}journalPropertySql(e){let t=e.args.no?"NO ":"",s=e.args.local,r=s?`${s} `:"",i=e.args.dual?"DUAL ":"",a=e.args.before?"BEFORE ":"",o=e.args.after?"AFTER ":"";return`${t}${r}${i}${a}${o}JOURNAL`}freespacePropertySql(e){let t=this.sql(e,"this"),s=e.args.percent?" PERCENT":"";return`FREESPACE=${t}${s}`}checksumPropertySql(e){let t;return e.args.default?t="DEFAULT":e.args.on?t="ON":t="OFF",`CHECKSUM=${t}`}mergeBlockRatioPropertySql(e){if(e.args.no)return"NO MERGEBLOCKRATIO";if(e.args.default)return"DEFAULT MERGEBLOCKRATIO";let t=e.args.percent?" PERCENT":"";return`MERGEBLOCKRATIO=${this.sql(e,"this")}${t}`}dataBlocksizePropertySql(e){let t=e.args.default,s=e.args.minimum,r=e.args.maximum;if(t||s||r){let o;return t?o="DEFAULT":s?o="MINIMUM":o="MAXIMUM",`${o} DATABLOCKSIZE`}let i=e.args.units,a=i?` ${i}`:"";return`DATABLOCKSIZE=${this.sql(e,"size")}${a}`}blockCompressionPropertySql(e){let t=e.args.autotemp,s=e.args.always,r=e.args.default,i=e.args.manual,a=e.args.never,o;return t!==void 0?o=`AUTOTEMP${this.sql(t)}`:s?o="ALWAYS":r?o="DEFAULT":i?o="MANUAL":a?o="NEVER":o="",`BLOCKCOMPRESSION=${o}`}isolatedLoadingPropertySql(e){let s=e.args.no?" NO":"",i=e.args.concurrent?" CONCURRENT":"",a=this.sql(e,"target");return a=a?` ${a}`:"",`WITH${s}${i} ISOLATED LOADING${a}`}partitionBoundSpecSql(e){if(Array.isArray(e.args.this))return`IN (${this.expressions(e,{key:"this",flat:!0})})`;if(e.args.this){let r=this.sql(e,"this"),i=this.sql(e,"expression");return`WITH (MODULUS ${r}, REMAINDER ${i})`}let t=this.expressions(e,{key:"fromExpressions",flat:!0}),s=this.expressions(e,{key:"toExpressions",flat:!0});return`FROM (${t}) TO (${s})`}partitionedOfPropertySql(e){let t=this.sql(e,"this"),s=_nullishCoalesce(e.args.expression, () => (""));return s instanceof yo?s=` FOR VALUES ${this.sql(s)}`:s=" DEFAULT",`PARTITION OF ${t}${s}`}lockingPropertySql(e){let t=e.args.kind,s=e.args.this?` ${this.sql(e,"this")}`:"",r=e.args.forOrIn,i=r?` ${r}`:"",a=e.args.lockType,o=e.args.override?" OVERRIDE":"";return`LOCKING ${t}${s}${i} ${a}${o}`}withDataPropertySql(e){let t=`WITH ${e.args.no?"NO ":""}DATA`,s=e.args.statistics,r="";return s!==void 0&&(r=` AND ${s?"":"NO "}STATISTICS`),`${t}${r}`}withSystemVersioningPropertySql(e){let t=this.sql(e,"this");t=t?`HISTORY_TABLE=${t}`:"";let s=this.sql(e,"dataConsistency"),r=s?`DATA_CONSISTENCY_CHECK=${s}`:void 0,i=this.sql(e,"retentionPeriod"),a=i?`HISTORY_RETENTION_PERIOD=${i}`:void 0,o;t?o=this.func("ON",[t,r,a]):o=e.args.on?"ON":"OFF";let c=`SYSTEM_VERSIONING=${o}`;return e.args.with?`WITH(${c})`:c}insertSql(e){let t=this.sql(e,"hint"),s=e.args.overwrite,r=e.args.this instanceof So,i;r?i=s?" OVERWRITE":" INTO":i=s?this._constructor.INSERT_OVERWRITE:" INTO";let a=this.sql(e,"stored"),o=a?` ${a}`:"",c=e.args.alternative,p=c?` OR ${c}`:"",u=e.args.ignore?" IGNORE":"";e.args.isFunction&&(i=`${i} FUNCTION`);let g=`${i} ${this.sql(e,"this")}`,A=e.args.exists?" IF EXISTS":"",x=this.sql(e,"where"),m=x?`${this.sep()}REPLACE WHERE ${x}`:"",N=`${this.sep()}${this.sql(e,"expression")}`,R=this.sql(e,"conflict"),S=R?` ${R}`:"",I=e.args.byName?" BY NAME":"",y=e.args.default?"DEFAULT VALUES":"",P=this.sql(e,"returning");this._constructor.RETURNING_END?N=`${N}${S}${y}${P}`:N=`${P}${N}${S}`;let v=this.sql(e,"partition"),H=v?` ${v}`:"",B=this.sql(e,"settings"),fe=B?` ${B}`:"",_e=this.sql(e,"source"),Is=_e?`TABLE ${_e}`:"",zt=`INSERT${t}${p}${u}${g}${o}${I}${A}${H}${fe}${m}${N}${Is}`;return this.prependCtes(e,zt)}introducerSql(e){return`_${this.sql(e,"this")} ${this.sql(e,"expression")}`}killSql(e){return`KILL ${e.args.kind?`${e.args.kind} `:""}${this.sql(e,"this")}`}pseudoTypeSql(e){return e.name}objectIdentifierSql(e){return e.name}onConflictSql(e){let t=e.args.duplicate?"ON DUPLICATE KEY":"ON CONFLICT",s=this.sql(e,"constraint");s=s?` ON CONSTRAINT ${s}`:"";let r=this.expressions(e,{key:"conflictKeys",flat:!0});r&&(r=`(${r})`);let i=this.sql(e,"indexPredicate");r=`${r}${i} `;let a=this.sql(e,"action"),o=this.expressions(e,{flat:!0});o&&(o=` ${this._constructor.DUPLICATE_KEY_UPDATE_WITH_SET?"SET ":""}${o}`);let c=this.sql(e,"where");return`${t}${s}${r}${a}${o}${c}`}returningSql(e){return this.opExpressions("RETURNING",e)}rowFormatDelimitedPropertySql(e){let t=this.sql(e,"fields"),s=t?` FIELDS TERMINATED BY ${t}`:"",r=this.sql(e,"collectionItems"),i=r?` COLLECTION ITEMS TERMINATED BY ${r}`:"",a=this.sql(e,"mapKeys"),o=a?` MAP KEYS TERMINATED BY ${a}`:"",c=this.sql(e,"lines"),p=c?` LINES TERMINATED BY ${c}`:"",u=this.sql(e,"null"),E=u?` NULL DEFINED AS ${u}`:"";return`ROW FORMAT DELIMITED${s}${i}${o}${p}${E}`}withTableHintSql(e){return`WITH (${this.expressions(e,{flat:!0})})`}indexTableHintSql(e){let t=`${this.sql(e,"this")} INDEX`,s=this.sql(e,"target");return s=s?` FOR ${s}`:"",`${t}${s} (${this.expressions(e,{flat:!0})})`}historicalDataSql(e){let t=this.sql(e,"this"),s=this.sql(e,"kind"),r=this.sql(e,"expression");return`${t} (${s} => ${r})`}tableParts(e){return[e.args.catalog,e.args.db,e.args.this].filter(t=>t!==void 0).map(t=>this.sql(t)).join(".")}tableSql(e,t={}){let{sep:s=" AS "}=t,r=this.tableParts(e),i=e.args.only?"ONLY ":"",a=this.sql(e,"partition");a=a?` ${a}`:"";let o=this.sql(e,"version");o=o?` ${o}`:"";let c=this.sql(e,"alias");c=c?`${s}${c}`:"";let p=this.sql(e,"sample"),u,E;this.dialect._constructor.ALIAS_POST_TABLESAMPLE?(u=p,E=""):(u="",E=p);let g=this.expressions(e,{key:"hints",sep:" "});g=g&&this._constructor.TABLE_HINTS?` ${g}`:"";let A=this.expressions(e,{key:"pivots",sep:"",flat:!0}),x=this.indent(this.expressions(e,{key:"joins",sep:"",flat:!0}),{skipFirst:!0}),m=this.expressions(e,{key:"laterals",sep:""}),N=this.sql(e,"format");if(N){let B=this.sql(e,"pattern"),fe=B?`, PATTERN => ${B}`:"";N=` (FILE_FORMAT => ${N}${fe})`}let R=e.args.ordinality||"";R&&(R=` WITH ORDINALITY${c}`,c="");let S=this.sql(e,"when"),I=r;S&&(I=`${r} ${S}`);let y=this.sql(e,"changes");y=y?` ${y}`:"";let P=this.expressions(e,{key:"rowsFrom"});P&&(I=`ROWS FROM ${this.wrap(P)}`);let v=e.args.indexed,H;return v!==void 0?H=v?` INDEXED BY ${this.sql(v)}`:" NOT INDEXED":H="",`${i}${I}${y}${a}${o}${N}${u}${c}${H}${g}${A}${E}${x}${m}${R}`}tableFromRowsSql(e){let t=this.func("TABLE",[e.args.this]),s=this.sql(e,"alias");s=s?` AS ${s}`:"";let r=this.sql(e,"sample"),i=this.expressions(e,{key:"pivots",sep:"",flat:!0}),a=this.indent(this.expressions(e,{key:"joins",sep:"",flat:!0}),{skipFirst:!0});return`${t}${s}${i}${r}${a}`}pivotSql(e){let t=this.expressions(e,{flat:!0}),s=e.args.unpivot?"UNPIVOT":"PIVOT",r=this.sql(e,"group");if(e.args.this){let E=this.sql(e,"this"),g;if(!t)g=`UNPIVOT ${E}`;else{let A=`${this.seg("ON")} ${t}`,x=this.sql(e,"into");x=x?`${this.seg("INTO")} ${x}`:"";let m=this.expressions(e,{key:"using",flat:!0});m=m?`${this.seg("USING")} ${m}`:"",g=`${s} ${E}${A}${x}${m}${r}`}return this.prependCtes(e,g)}let i=this.sql(e,"alias");i=i?` AS ${i}`:"";let a=this.expressions(e,{key:"fields",sep:" ",dynamic:!0,newLine:!0,skipFirst:!0,skipLast:!0}),o=e.args.includeNulls,c;o!==void 0?c=o?" INCLUDE NULLS ":" EXCLUDE NULLS ":c="";let p=this.sql(e,"defaultOnNull");p=p?` DEFAULT ON NULL (${p})`:"";let u=`${this.seg(s)}${c}(${t} FOR ${a}${p}${r})${i}`;return this.prependCtes(e,u)}versionSql(e){let t=`FOR ${e.name}`,s=_optionalChain([e, 'access', _1057 => _1057.text, 'optionalCall', _1058 => _1058("kind")])||"",r=this.sql(e,"expression");return`${t} ${s} ${r}`}tupleSql(e){return`(${this.expressions(e,{dynamic:!0,newLine:!0,skipFirst:!0,skipLast:!0})})`}updateFromJoinsSql(e){let t=e.args.from;if(this.constructor.UPDATE_STATEMENT_SUPPORTS_FROM||!t)return["",this.sql(e,"from")];let s=e.args.this;if(s instanceof V){let o=K(s.aliasOrName);for(let c of e.args.expressions||[]){let p=c.args.this;p instanceof k&&!p.table&&p.setArgKey("table",o)}}let r=t.args.this,i=(D(r,h)?r.args.joins:void 0)||[];0<i.length&&D(r,h)&&r.setArgKey("joins",void 0);let a=D(r,h)?this.sql(new z({this:r,on:$e()})):"";for(let o of i)!o.getArgKey("on")&&!o.getArgKey("using")&&o.setArgKey("on",$e()),a+=this.sql(o);return[a,""]}updateSql(e){let t=this.sql(e,"this"),[s,r]=this.updateFromJoinsSql(e),i=this.expressions(e,{flat:!0}),a=this.sql(e,"where"),o=this.sql(e,"returning"),c=this.sql(e,"order"),p=this.sql(e,"limit"),u;this._constructor.RETURNING_END?u=`${r}${a}${o}`:u=`${o}${r}${a}`;let E=this.expressions(e,{key:"options"});E=E?` OPTION(${E})`:"";let g=`UPDATE ${t}${s} SET ${i}${u}${c}${p}${E}`;return this.prependCtes(e,g)}valuesSql(e,t={}){let{valuesAsTable:s=!0}=t;if(s&&this._constructor.VALUES_AS_TABLE||!e.findAncestor(Ge,z)){let E=this.expressions(e),g=this.sql(e,"alias"),A=`VALUES${this.seg("")}${E}`;return this._constructor.WRAP_DERIVED_VALUES&&(g||[Ge,V].some(m=>e.parent instanceof m))&&(A=`(${A})`),A=this.queryModifiers(e,A),g?`${A} AS ${g}`:A}let i=D(e.args.alias,ie)?e.args.alias:void 0,a=_optionalChain([i, 'optionalAccess', _1059 => _1059.columns]),o=[],c=e.args.expressions;if(c)for(let E=0;E<c.length;E++){let A=c[E].args.expressions||[];E===0&&a&&0<a.length&&(A=A.map((x,m)=>{let N=a[m];return oe(x,N instanceof G?N:N.name,{copy:!1})})),o.push(new $({expressions:A}))}if(o.length===0)return"";if(this.pretty){let E=o.reduce((x,m)=>_nullishCoalesce(NT([x,m],{distinct:!1,copy:!1}), () => (x))),g=_optionalChain([i, 'optionalAccess', _1060 => _1060.args, 'access', _1061 => _1061.this]),A=g instanceof h?g:void 0;return this.subquerySql(E.subquery(A,{copy:!1}))}let p=i?` AS ${this.sql(i,"this")}`:"";return`(${o.map(E=>this.sql(E)).join(" UNION ALL ")})${p}`}varSql(e){return this.sql(e,"this")}intoSql(e){so.call(this,e,"expressions");let t=e.args.temporary?" TEMPORARY":"",s=e.args.unlogged?" UNLOGGED":"",r=t||s;return`${this.seg("INTO")}${r} ${this.sql(e,"this")}`}fromSql(e){return`${this.seg("FROM")} ${this.sql(e,"this")}`}groupingSetsSql(e){let t=this.expressions(e,{indent:!1});return`GROUPING SETS ${this.wrap(t)}`}rollupSql(e){let t=this.expressions(e,{indent:!1});return t?`ROLLUP ${this.wrap(t)}`:"WITH ROLLUP"}rollupIndexSql(e){let t=this.sql(e,"this"),s=this.expressions(e,{flat:!0}),r=this.sql(e,"fromIndex"),i=r?` FROM ${r}`:"",a=e.args.properties;a&&ue(a,mt);let o=a?` ${this.properties(a,{prefix:"PROPERTIES"})}`:"";return`${t}(${s})${i}${o}`}rollupPropertySql(e){return`ROLLUP (${this.expressions(e,{flat:!0})})`}cubeSql(e){let t=this.expressions(e,{indent:!1});return t?`CUBE ${this.wrap(t)}`:"WITH CUBE"}groupSql(e){let t=e.args.all,s="";t===!0?s=" ALL":t===!1&&(s=" DISTINCT");let r=this.opExpressions(`GROUP BY${s}`,e),i=this.expressions(e,{key:"groupingSets"}),a=this.expressions(e,{key:"cube"}),o=this.expressions(e,{key:"rollup"}),c=SO([i?this.seg(i):"",a?this.seg(a):"",o?this.seg(o):"",e.args.totals?this.seg("WITH TOTALS"):""],{sep:this._constructor.GROUPINGS_SEP}),p=r;return _optionalChain([e, 'access', _1062 => _1062.args, 'access', _1063 => _1063.expressions, 'optionalAccess', _1064 => _1064.length])&&c&&c.trim()!=="WITH CUBE"&&c.trim()!=="WITH ROLLUP"&&(p=`${p}${this._constructor.GROUPINGS_SEP}`),`${p}${c}`}havingSql(e){let t=this.indent(this.sql(e,"this"));return`${this.seg("HAVING")}${this.sep()}${t}`}connectSql(e){let t=this.sql(e,"start");t=t?this.seg(`START WITH ${t}`):"";let s=e.args.nocycle?" NOCYCLE":"",r=this.sql(e,"connect"),i=this.seg(`CONNECT BY${s} ${r}`);return t+i}priorSql(e){return`PRIOR ${this.sql(e,"this")}`}joinSql(e){let t=this._constructor,s;!t.SEMI_ANTI_JOIN_WITH_SIDE&&(e.args.kind==="semi"||e.args.kind==="anti")?s=void 0:s=_optionalChain([e, 'access', _1065 => _1065.args, 'access', _1066 => _1066.side, 'optionalAccess', _1067 => _1067.toUpperCase, 'call', _1068 => _1068()]);let r=[e.args.method,e.args.global?"GLOBAL":void 0,s,e.args.kind==="straightJoin"?"STRAIGHT_JOIN":_optionalChain([e, 'access', _1069 => _1069.args, 'access', _1070 => _1070.kind, 'optionalAccess', _1071 => _1071.toUpperCase, 'call', _1072 => _1072()]),e.args.hint&&t.JOIN_HINTS?e.args.hint:void 0,e.args.directed&&t.DIRECTED_JOINS?"DIRECTED":void 0].filter(A=>A).join(" "),i=this.sql(e,"matchCondition");i=i?` MATCH_CONDITION (${i})`:"";let a=this.sql(e,"on"),o=e.args.using;!a&&o&&(a=o.map(A=>this.sql(A)).join(", "));let c=e.args.this,p=this.sql(c),u=this.expressions(e);if(u&&(p=`${p},${this.seg(u)}`),a){a=this.indent(a,{skipFirst:!0});let A=this.pretty?this.seg(" ".repeat(this.pad)):" ";o?a=`${A}USING (${a})`:a=`${A}ON ${a}`}else if(!r)return c instanceof kt&&c.args.crossApply!==void 0?` ${p}`:`, ${p}`;let E=e.args.kind!=="straightJoin"?r?`${r} JOIN`:"JOIN":r,g=this.expressions(e,{key:"pivots",sep:"",flat:!0});return`${this.seg(E)} ${p}${i}${a}${g}`}lambdaSql(e,t={}){let{arrowSep:s="->",wrap:r=!0}=t,i=this.expressions(e,{flat:!0});return i=r&&1<i.split(",").length?`(${i})`:i,`${i} ${s} ${this.sql(e,"this")}`}lateralOp(e){let t=e.args.crossApply,s="";return t===!0?s="INNER JOIN ":t===!1&&(s="LEFT JOIN "),`${s}LATERAL`}lateralSql(e){let t=this.sql(e,"this");if(e.args.view){let i=e.args.alias,a=this.expressions(i,{key:"columns",flat:!0}),o=_optionalChain([i, 'optionalAccess', _1073 => _1073.name])?` ${i.name}`:"",c=a?` AS ${a}`:"",p=e.args.outer?" OUTER":"";return`${this.seg(`LATERAL VIEW${p}`)}${this.sep()}${t}${o}${c}`}let s=this.sql(e,"alias");s=s?` AS ${s}`:"";let r=e.args.ordinality||"";return r&&(r=` WITH ORDINALITY${s}`,s=""),`${this.lateralOp(e)} ${t}${s}${r}`}limitSql(e,t={}){let{top:s=!1}=t,r=this.sql(e,"this"),i=["offset","expression"].map(u=>e.getArgKey(u)).filter(Boolean).map(u=>this._constructor.LIMIT_ONLY_LITERALS?this.simplifyUnlessLiteral(u):u),a=i.map(u=>this.sql(u)).join(", ");s&&i.some(u=>!u.isNumber)&&(a=`(${a})`);let o=this.expressions(e,{flat:!0}),c=this.sql(e,"limitOptions");o=o?` BY ${o}`:"";let p=s?"TOP":"LIMIT";return`${r}${this.seg(p)} ${a}${c}${o}`}offsetSql(e){let t=this.sql(e,"this"),s=e.args.expression;s=this._constructor.LIMIT_ONLY_LITERALS?this.simplifyUnlessLiteral(s):s;let r=this.expressions(e,{flat:!0}),i=r?` BY ${r}`:"";return`${t}${this.seg("OFFSET")} ${this.sql(s)}${i}`}setItemSql(e){let t=this.sql(e,"kind");!this._constructor.SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD&&t==="VARIABLE"?t="":t=t?`${t} `:"";let s=this.sql(e,"this"),r=this.expressions(e),i=this.sql(e,"collate");return i=i?` COLLATE ${i}`:"",`${e.args.global?"GLOBAL ":""}${t}${s}${r}${i}`}setSql(e){let t=` ${this.expressions(e,{flat:!0})}`,s=e.args.tag?" TAG":"";return`${e.args.unset?"UNSET":"SET"}${s}${t}`}queryBandSql(e){let t=this.sql(e,"this"),s=e.args.update?" UPDATE":"",r=this.sql(e,"scope"),i=r?` FOR ${r}`:"";return`QUERY_BAND = ${t}${s}${i}`}pragmaSql(e){return`PRAGMA ${this.sql(e,"this")}`}lockSql(e){if(!this._constructor.LOCKING_READS_SUPPORTED)return this.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported"),"";let t=e.args.update,s=e.args.key,r;(t instanceof w?t.args.this!=="0":!!t)?r=s?"FOR NO KEY UPDATE":"FOR UPDATE":r=s?"FOR KEY SHARE":"FOR SHARE";let a=this.expressions(e,{flat:!0}),o=a?` OF ${a}`:"",c=e.args.wait,p="";return c!==void 0&&(c instanceof w?p=` WAIT ${this.sql(c)}`:p=c?" NOWAIT":" SKIP LOCKED"),`${r}${o}${p||""}`}literalSql(e){let t=e.args.this||"";return e.isString&&(t=`${this.dialect._constructor.QUOTE_START}${this.escapeStr(t)}${this.dialect._constructor.QUOTE_END}`),t}escapeStr(e,t={}){let{escapeBackslash:s=!0,delimiter:r,escapedDelimiter:i,isByteString:a=!1}=t;(a?this.dialect._constructor.BYTE_STRINGS_SUPPORT_ESCAPED_SEQUENCES:this.dialect._constructor.STRINGS_SUPPORT_ESCAPED_SEQUENCES)&&(e=Array.from(e).map(p=>{let u=this.dialect._constructor.ESCAPED_SEQUENCES[p];return u!==void 0&&(s||p!=="\\")?u:p}).join(""));let c=r||this.dialect._constructor.QUOTE_END;return this.replaceLineBreaks(e).replaceAll(c,i||this.escapedQuoteEnd)}loadDataSql(e){let t=e.args.local?" LOCAL":"",s=` INPATH ${this.sql(e,"inpath")}`,r=e.args.overwrite?" OVERWRITE":"",i=` INTO TABLE ${this.sql(e,"this")}`,a=this.sql(e,"partition"),o=a?` ${a}`:"",c=this.sql(e,"inputFormat"),p=c?` INPUTFORMAT ${c}`:"",u=this.sql(e,"serde"),E=u?` SERDE ${u}`:"";return`LOAD DATA${t}${s}${r}${i}${o}${p}${E}`}nullSql(...e){return"NULL"}booleanSql(e){return e.args.this?"TRUE":"FALSE"}boolandSql(e){return`((${this.sql(e,"this")}) AND (${this.sql(e,"expression")}))`}boolorSql(e){return`((${this.sql(e,"this")}) OR (${this.sql(e,"expression")}))`}orderSql(e,t={}){let{flat:s=!1}=t,r=this.sql(e,"this");r=r&&`${r} `;let i=e.args.siblings?"SIBLINGS ":"";return this.opExpressions(`${r}ORDER ${i}BY`,e,{flat:s||!!r})}withFillSql(e){let t=this.sql(e,"from");t=t?` FROM ${t}`:"";let s=this.sql(e,"to");s=s?` TO ${s}`:"";let r=this.sql(e,"step");r=r?` STEP ${r}`:"";let a=_optionalChain([e, 'access', _1074 => _1074.args, 'access', _1075 => _1075.interpolate, 'optionalAccess', _1076 => _1076.map, 'call', _1077 => _1077(c=>c instanceof Se?`${this.sql(c,"alias")} AS ${this.sql(c,"this")}`:this.sql(c,"this"))])||[],o=a.length?` INTERPOLATE (${a.join(", ")})`:"";return`WITH FILL${t}${s}${r}${o}`}clusterSql(e){return this.opExpressions("CLUSTER BY",e)}distributeSql(e){return this.opExpressions("DISTRIBUTE BY",e)}sortSql(e){return this.opExpressions("SORT BY",e)}orderedSql(e){let t=e.args.desc,s=!t,r=e.args.nullsFirst,i=!r,a=this.dialect._constructor.NULL_ORDERING==="nulls_are_large",o=this.dialect._constructor.NULL_ORDERING==="nulls_are_small",c=this.dialect._constructor.NULL_ORDERING==="nulls_are_last",p=this.sql(e,"this"),u=t?" DESC":t===!1?" ASC":"",E="";if(r&&(s&&a||t&&o||c)?E=" NULLS FIRST":i&&(s&&o||t&&a)&&!c&&(E=" NULLS LAST"),E&&this._constructor.NULL_ORDERING_SUPPORTED!=="supported"){let A=e.findAncestor(Fe,$);if(A instanceof Fe&&A.args.spec)this.unsupported(`'${E.trim()}' translation not supported in window functions`),E="";else if(this._constructor.NULL_ORDERING_SUPPORTED==="partial"&&(s&&E===" NULLS LAST"||t&&E===" NULLS FIRST")){let x=e.findAncestor(q,Fe,$);x instanceof Fe&&(x=x.args.this),x instanceof q&&(this.unsupported(`'${E.trim()}' translation not supported for aggregate functions with ${u} sort order`),E="")}else this._constructor.NULL_ORDERING_SUPPORTED==="unsupported"&&(_optionalChain([e, 'access', _1078 => _1078.args, 'access', _1079 => _1079.this, 'optionalAccess', _1080 => _1080.isInteger])?this.unsupported(`'${E.trim()}' translation not supported with positional ordering`):e.args.this instanceof xr||(p=`CASE WHEN ${p} IS NULL THEN 1 ELSE 0 END${E===" NULLS FIRST"?" DESC":""}, ${p}`),E="")}let g=this.sql(e,"withFill");return g=g?` ${g}`:"",`${p}${u}${E}${g}`}matchRecognizeMeasureSql(e){let t=this.sql(e,"windowFrame"),s=t?`${t} `:"",r=this.sql(e,"this");return`${s}${r}`}matchRecognizeSql(e){let t=this.partitionBySql(e),s=this.sql(e,"order"),r=this.expressions(e,{key:"measures"}),i=r?this.seg(`MEASURES${this.seg(r)}`):"",a=this.sql(e,"rows"),o=a?this.seg(a):"",c=this.sql(e,"after"),p=c?this.seg(c):"",u=this.sql(e,"pattern"),E=u?this.seg(`PATTERN (${u})`):"",g=(e.args.define||[]).map(S=>`${this.sql(S,"alias")} AS ${this.sql(S,"this")}`),A=this.expressions(void 0,{sqls:g}),x=A?this.seg(`DEFINE${this.seg(A)}`):"",m=[t,s,i,o,p,E,x].join(""),N=this.sql(e,"alias"),R=N?` ${N}`:"";return`${this.seg("MATCH_RECOGNIZE")} ${this.wrap(m)}${R}`}queryModifiers(e,...t){let s=e.getArgKey("limit");if(s!==void 0&&!(s instanceof Sn||s instanceof Ct))return"";let r=this._constructor.LIMIT_FETCH;return r==="LIMIT"&&s instanceof Sn?s=new Ct({expression:bt(s.args.count)}):r==="FETCH"&&s instanceof Ct&&(s=new Sn({direction:"FIRST",count:bt(s.args.expression)})),SO([...t,..._nullishCoalesce(_optionalChain([e, 'access', _1081 => _1081.args, 'access', _1082 => _1082.joins, 'optionalAccess', _1083 => _1083.map, 'call', _1084 => _1084(i=>this.sql(i))]), () => ([])),this.sql(e,"match"),..._nullishCoalesce(_optionalChain([e, 'access', _1085 => _1085.args, 'access', _1086 => _1086.laterals, 'optionalAccess', _1087 => _1087.map, 'call', _1088 => _1088(i=>this.sql(i))]), () => ([])),this.sql(e,"prewhere"),this.sql(e,"where"),this.sql(e,"connect"),this.sql(e,"group"),this.sql(e,"having"),...Array.from(this._constructor.AFTER_HAVING_MODIFIER_TRANSFORMS.values()).map(i=>i.call(this,e)),this.sql(e,"order"),...this.offsetLimitModifiers(e,{fetch:s instanceof Sn},s),...this.afterLimitModifiers(e),this.optionsModifier(e),this.forModifiers(e)],{sep:""})}optionsModifier(e){let t=this.expressions(e,{key:"options"});return t?` ${t}`:""}forModifiers(e){let t=this.expressions(e,{key:"for"});return t?`${this.sep()}FOR XML${this.seg(t)}`:""}queryOptionSql(e){return this.unsupported("Unsupported query option."),""}afterLimitModifiers(e){let t=this.expressions(e,{key:"locks",sep:" "});return t=t?` ${t}`:"",[t,this.sql(e,"sample")]}selectSql(e){let t=e.args.into;!this._constructor.SUPPORTS_SELECT_INTO&&t&&t.pop();let s=this.sql(e,"hint"),r=this.sql(e,"distinct");r=r?` ${r}`:"";let i=this.sql(e,"kind"),a=e.args.limit,o="";this._constructor.LIMIT_IS_TOP&&a instanceof Ct&&(o=this.limitSql(a,{top:!0}),a.pop());let c=this.expressions(e),p=this._constructor;if(i)if(p.SELECT_KINDS.includes(i))i=` AS ${i}`;else{if(i==="STRUCT"){let m=(e.args.expressions||[]).map(N=>N instanceof Se?new At({this:N.args.alias instanceof G?N.args.alias:new G({this:_optionalChain([N, 'access', _1089 => _1089.args, 'access', _1090 => _1090.alias, 'optionalAccess', _1091 => _1091.toString, 'call', _1092 => _1092()])||""}),expression:N.args.this}):N);c=this.expressions(void 0,{sqls:[new Hs({expressions:m})]})}i=""}let u=this.expressions(e,{key:"operationModifiers",sep:" "}),E=u?`${this.sep()}${u}`:"",g=p.LIMIT_IS_TOP?`${r}${s}${o}`:`${o}${s}${r}`;c=c&&`${this.sep()}${c}`;let A=this.queryModifiers(e,`SELECT${g}${E}${i}${c}`,this.sql(e,"into",{comment:!1}),this.sql(e,"from",{comment:!1}));if(A=this.prependCtes(e,A),!p.SUPPORTS_SELECT_INTO&&t){ue(t,Ro);let x="";t.args.temporary?x=" TEMPORARY":p.SUPPORTS_UNLOGGED_TABLES&&t.args.unlogged&&(x=" UNLOGGED"),A=`CREATE${x} TABLE ${this.sql(t.args.this)} AS ${A}`}return A}schemaSql(e){let t=this.sql(e,"this"),s=this.schemaColumnsSql(e);return t&&s?`${t} ${s}`:t||s}schemaColumnsSql(e){return _optionalChain([e, 'access', _1093 => _1093.args, 'access', _1094 => _1094.expressions, 'optionalAccess', _1095 => _1095.length])?`(${this.sep("")}${this.expressions(e)}${this.seg(")","")}`:""}starSql(e){let t=this.expressions(e,{key:"except",flat:!0});t=t?`${this.seg(this._constructor.STAR_EXCEPT)} (${t})`:"";let s=this.expressions(e,{key:"replace",flat:!0});s=s?`${this.seg("REPLACE")} (${s})`:"";let r=this.expressions(e,{key:"rename",flat:!0});return r=r?`${this.seg("RENAME")} (${r})`:"",`*${t}${s}${r}`}parameterSql(e){let t=this.sql(e,"this");return`${this._constructor.PARAMETER_TOKEN}${t}`}sessionParameterSql(e){let t=this.sql(e,"this"),s=e.text("kind");return s&&(s=`${s}.`),`@@${s}${t}`}placeholderSql(e){return e.args.this!==void 0?`${this._constructor.NAMED_PLACEHOLDER_TOKEN}${e.name}`:"?"}subquerySql(e,t={}){let{sep:s=" AS "}=t,r=this.sql(e,"alias");r=r?`${s}${r}`:"";let i=this.sql(e,"sample");this.dialect._constructor.ALIAS_POST_TABLESAMPLE&&i&&(r=`${i}${r}`,e.setArgKey("sample",void 0));let a=this.expressions(e,{key:"pivots",sep:"",flat:!0}),o=this.queryModifiers(e,this.wrap(e),r,a);return this.prependCtes(e,o)}qualifySql(e){let t=this.indent(this.sql(e,"this"));return`${this.seg("QUALIFY")}${this.sep()}${t}`}unnestSql(e){let t=this.expressions(e,{flat:!0}),s=e.args.alias,r=e.args.offset;this._constructor.UNNEST_WITH_ORDINALITY&&s&&r instanceof G&&(ue(s,ie),s.args.columns?s.args.columns.push(r):s.setArgKey("columns",[r]));let i="";if(s&&this.dialect._constructor.UNNEST_COLUMN_ONLY){ue(s,ie);let o=s.columns;i=o[0]?this.sql(o[0]):""}else i=this.sql(s);i=i&&` AS ${i}`;let a="";return this._constructor.UNNEST_WITH_ORDINALITY?a=r?` WITH ORDINALITY${i}`:i:r instanceof h?a=`${i} WITH OFFSET AS ${this.sql(r)}`:r?a=`${i} WITH OFFSET`:a=i,`UNNEST(${t})${a}`}preWhereSql(e){return""}whereSql(e){let t=this.indent(this.sql(e,"this"));return`${this.seg("WHERE")}${this.sep()}${t}`}windowSql(e){let t=this.sql(e,"this"),s=this.partitionBySql(e),r=e.args.order;r&&ue(r,ke);let i=r?this.orderSql(r,{flat:!0}):"",a=this.sql(e,"spec"),o=this.sql(e,"alias"),c=this.sql(e,"over")||"OVER";t=`${t} ${e.argKey==="windows"?"AS":c}`;let p=e.args.first,u="";if(p!==void 0&&(u=p?"FIRST":"LAST"),!s&&!i&&!a&&o)return`${t} ${o}`;let E=this.formatArgs([o,u,s,i,a].filter(g=>g),{sep:" "});return`${t} (${E})`}partitionBySql(e){let t=this.expressions(e,{key:"partitionBy",flat:!0});return t?`PARTITION BY ${t}`:""}windowSpecSql(e){let t=this.sql(e,"kind"),s=SO([this.sql(e,"start"),this.sql(e,"startSide")],{sep:" "}),r=SO([this.sql(e,"end"),this.sql(e,"endSide")],{sep:" "})||"CURRENT ROW",i=`${t} BETWEEN ${s} AND ${r}`,a=this.sql(e,"exclude");return a&&(this._constructor.SUPPORTS_WINDOW_EXCLUDE?i+=` EXCLUDE ${a}`:this.unsupported("EXCLUDE clause is not supported in the WINDOW clause")),i}withinGroupSql(e){let t=this.sql(e,"this"),s=this.sql(e,"expression");return s=s.substring(1),`${t} WITHIN GROUP (${s})`}betweenSql(e){let t=this.sql(e,"this"),s=this.sql(e,"low"),r=this.sql(e,"high"),i=e.args.symmetric;if(i&&!this._constructor.SUPPORTS_BETWEEN_FLAGS)return`(${t} BETWEEN ${s} AND ${r} OR ${t} BETWEEN ${r} AND ${s})`;let a=i?" SYMMETRIC":i===!1&&this._constructor.SUPPORTS_BETWEEN_FLAGS?" ASYMMETRIC":"";return`${t} BETWEEN${a} ${s} AND ${r}`}bracketOffsetExpressions(e,t={}){let{indexOffset:s}=t,r=(s!==void 0?s:this.dialect._constructor.INDEX_OFFSET)-(e.args.offset||0),i=e.args.this instanceof h?e.args.this:new h({});return WT(i,e.args.expressions||[],r,{dialect:this.dialect})}bracketSql(e){let s=this.bracketOffsetExpressions(e).map(r=>this.sql(r)).join(", ");return`${this.sql(e,"this")}[${s}]`}allSql(e){let t=this.sql(e,"this"),s=e.args.this;return s&&!(s instanceof Mt||s instanceof Ye)&&(t=this.wrap(t)),`ALL ${t}`}anySql(e){let t=this.sql(e,"this"),s=e.args.this;return En.some(r=>s instanceof r)||s instanceof Ye?(En.some(r=>s instanceof r)&&(t=this.wrap(t)),`ANY${t}`):`ANY ${t}`}existsSql(e){return`EXISTS${this.wrap(e)}`}caseSql(e){let t=this.sql(e,"this"),s=[t?`CASE ${t}`:"CASE"],r=e.args.ifs;if(r)for(let a of r)s.push(`WHEN ${this.sql(a,"this")}`),s.push(`THEN ${this.sql(a,"true")}`);let i=this.sql(e,"default");return i&&s.push(`ELSE ${i}`),s.push("END"),this.pretty&&this.tooWide(s)?this.indent(s.join(`
|
|
10
|
+
`),{skipFirst:!0,skipLast:!0}):s.join(" ")}constraintSql(e){let t=this.sql(e,"this"),s=this.expressions(e,{flat:!0});return`CONSTRAINT ${t} ${s}`}nextValueForSql(e){let t=e.args.order;t&&ue(t,ke);let s=t?` OVER (${this.orderSql(t,{flat:!0})})`:"";return`NEXT VALUE FOR ${this.sql(e,"this")}${s}`}extractSql(e){let t=e.args.this;this._constructor.NORMALIZE_EXTRACT_DATE_PARTS&&(t=TF(t,{dialect:this.dialect})||t);let s=this._constructor.EXTRACT_ALLOWS_QUOTES?this.sql(t):t.name,r=this.sql(e,"expression");return`EXTRACT(${s} FROM ${r})`}trimSql(e){let t=this.sql(e,"position"),s;return t==="LEADING"?s="LtRIM":t==="TRAILING"?s="RTRIM":s="TRIM",this.func(s,[e.args.this,e.args.expression])}convertConcatArgs(e){let t=e.args.expressions||[];if(e instanceof xs&&(t=t.slice(1)),this.dialect._constructor.STRICT_STRING_CONCAT&&e.args.safe&&(t=t.map(s=>Le(s,"text",{dialect:this.dialect}))),!this.dialect._constructor.CONCAT_COALESCE&&e.args.coalesce){let s=r=>(r.type||(r=os(r,{dialect:this.dialect})),r.isString||r.isType("array")?r:new St({this:r,expressions:[new w({this:"",isString:!0})]}));t=t.map(s)}return t}concatSql(e){if(this.dialect._constructor.CONCAT_COALESCE&&!e.args.coalesce)return xF.call(this,e);let t=this.convertConcatArgs(e);return!this._constructor.SUPPORTS_SINGLE_ARG_CONCAT&&t.length===1?this.sql(t[0]):this.func("CONCAT",t)}concatWsSql(e){let s=(e.args.expressions||[])[0],r=this.convertConcatArgs(e);return this.func("CONCAT_WS",[s,...r])}checkSql(e){return`CHECK (${this.sql(e,"this")})`}foreignKeySql(e){let t=this.expressions(e,{flat:!0});t=t?` (${t})`:"";let s=this.sql(e,"reference");s=s?` ${s}`:"";let r=this.sql(e,"delete");r=r?` ON DELETE ${r}`:"";let i=this.sql(e,"update");i=i?` ON UPDATE ${i}`:"";let a=this.expressions(e,{key:"options",flat:!0,sep:" "});return a=a?` ${a}`:"",`FOREIGN KEY${t}${s}${r}${i}${a}`}primaryKeySql(e){let t=this.sql(e,"this");t=t?` ${t}`:"";let s=this.expressions(e,{flat:!0}),r=this.sql(e,"include"),i=this.expressions(e,{key:"options",flat:!0,sep:" "});return i=i?` ${i}`:"",`PRIMARY KEY${t} (${s})${r}${i}`}ifSql(e){return e.parent instanceof Ht?`WHEN ${this.sql(e,"this")} THEN ${this.sql(e,"true")}`:this.caseSql(new Ht({ifs:[e],default:e.args.false}))}matchAgainstSql(e){let t=e.args.expressions||[];this._constructor.MATCH_AGAINST_TABLE_PREFIX?t=t.map(i=>i instanceof V?`TABLE ${this.sql(i)}`:i):t=e.args.expressions||[];let s=e.args.modifier,r=s?` ${s}`:"";return`${this.func("MATCH",t)} AGAINST(${this.sql(e,"this")}${r})`}jsonKeyValueSql(e){return`${this.sql(e,"this")}${this._constructor.JSON_KEY_VALUE_PAIR_SEP} ${this.sql(e,"expression")}`}jsonPathSql(e){let t=this.expressions(e,{sep:"",flat:!0}).replace(/^\.+/,"");return e.args.escape&&(t=this.escapeStr(t)),this._constructor.QUOTE_JSON_PATH&&(t=`${this.dialect._constructor.QUOTE_START}${t}${this.dialect._constructor.QUOTE_END}`),t}jsonPathPart(e){if(e===void 0)return"";if(e instanceof Rs){let s=this._constructor.TRANSFORMS.get(e._constructor);return typeof s!="function"?(this.unsupported(`Unsupported JsonPathPart type ${e._constructor.name}`),""):s.call(this,e)}return typeof e=="number"?String(e):this.quoteJsonPathKeyUsingBrackets&&this._constructor.JSON_PATH_SINGLE_QUOTE_ESCAPE?`\\'${e.toString().replaceAll("'","\\'")}\\'`:`"${e.toString().replace(/"/g,'\\"')}"`}formatJsonSql(e){return`${this.sql(e,"this")} FORMAT JSON`}formatPhraseSql(e){let t=this.sql(e,"this"),s=this.sql(e,"format");return`${t} (FORMAT ${s})`}jsonObjectSql(e){let t=e.args.nullHandling,s=t?` ${t}`:"",r=e.args.uniqueKeys,i="";r!=null&&(i=` ${r?"WITH":"WITHOUT"} UNIQUE KEYS`);let a=this.sql(e,"returnType"),o=a?` RETURNING ${a}`:"",c=this.sql(e,"encoding"),p=c?` ENCODING ${c}`:"",u=e instanceof pp?"JSON_OBJECT":"JSON_OBJECTAGG";return this.func(u,e.args.expressions||[],{suffix:`${s}${i}${o}${p})`})}jsonObjectAggSql(e){return this.jsonObjectSql(e)}jsonArraySql(e){let t=e.args.nullHandling,s=t?` ${t}`:"",r=this.sql(e,"returnType"),i=r?` RETURNING ${r}`:"",a=e.args.strict?" STRICT":"";return this.func("JSON_ARRAY",e.args.expressions||[],{suffix:`${s}${i}${a})`})}jsonArrayAggSql(e){let t=this.sql(e,"this"),s=this.sql(e,"order"),r=e.args.nullHandling,i=r?` ${r}`:"",a=this.sql(e,"returnType"),o=a?` RETURNING ${a}`:"",c=e.args.strict?" STRICT":"";return this.func("JSON_ARRAYAGG",[t],{suffix:`${s}${i}${o}${c})`})}jsonColumnDefSql(e){let t=this.sql(e,"path"),s=t?` PATH ${t}`:"",r=this.sql(e,"nestedSchema");if(r)return`NESTED${s} ${r}`;let i=this.sql(e,"this"),a=this.sql(e,"kind"),o=a?` ${a}`:"",c=e.args.ordinality?" FOR ORDINALITY":"";return`${i}${o}${s}${c}`}jsonSchemaSql(e){return this.func("COLUMNS",e.args.expressions||[])}jsonTableSql(e){let t=this.sql(e,"this"),s=this.sql(e,"path"),r=s?`, ${s}`:"",i=e.args.errorHandling,a=i?` ${i}`:"",o=e.args.emptyHandling,c=o?` ${o}`:"",p=this.sql(e,"schema");return this.func("JSON_TABLE",[t],{suffix:`${r}${a}${c} ${p})`})}openJsonColumnDefSql(e){let t=this.sql(e,"this"),s=this.sql(e,"kind"),r=this.sql(e,"path"),i=r?` ${r}`:"",a=e.args.asJson?" AS JSON":"";return`${t} ${s}${i}${a}`}openJsonSql(e){let t=this.sql(e,"this"),s=this.sql(e,"path"),r=s?`, ${s}`:"",i=this.expressions(e),a=i?` WITH (${this.seg(this.indent(i),"")}${this.seg(")","")}`:"";return`OPENJSON(${t}${r})${a}`}inSql(e){let t=e.args.query,s=e.args.unnest,r=e.args.field,i=e.args.isGlobal?" GLOBAL":"",a;if(t)a=this.sql(t);else if(s)a=this.inUnnestOp(s);else if(r)a=this.sql(r);else{let o={dynamic:!0,newLine:!0,skipFirst:!0,skipLast:!0};a=`(${this.expressions(e,o)})`}return`${this.sql(e,"this")}${i} IN ${a}`}inUnnestOp(e){return`(SELECT ${this.sql(e)})`}intervalSql(e){let t=e.args.unit,s=t?this.sql(t):"";this._constructor.INTERVAL_ALLOWS_PLURAL_FORM||(s=this._constructor.TIME_PART_SINGULARS[s]||s);let r=s?` ${s}`:"";if(this._constructor.SINGLE_STRING_INTERVAL){let a=e.args.this instanceof h?_optionalChain([e, 'access', _1096 => _1096.args, 'access', _1097 => _1097.this, 'optionalAccess', _1098 => _1098.name])||"":e.args.this;return a?t instanceof Kn?`INTERVAL '${a}'${r}`:`INTERVAL '${a}${r}'`:`INTERVAL${r}`}let i=this.sql(e,"this");return i&&(i=e.args.this instanceof h&&this._constructor.UNWRAPPED_INTERVAL_VALUES.has(e.args.this._constructor)?` ${i}`:` (${i})`),`INTERVAL${i}${r}`}returnSql(e){return`RETURN ${this.sql(e,"this")}`}referenceSql(e){let t=this.sql(e,"this"),s=this.expressions(e,{flat:!0});s=s?`(${s})`:"";let r=this.expressions(e,{key:"options",flat:!0,sep:" "});return r=r?` ${r}`:"",`REFERENCES ${t}${s}${r}`}anonymousSql(e){let t=e.parent,s=t instanceof me&&t.args.expression===e;return this.func(this.sql(e,"this"),e.args.expressions||[],{normalize:!s})}parenSql(e){return`(${this.seg(this.indent(this.sql(e,"this")),"")}${this.seg(")","")}`}negSql(e){let t=this.sql(e,"this");return`-${t[0]==="-"?" ":""}${t}`}notSql(e){return`NOT ${this.sql(e,"this")}`}aliasSql(e){let t=this.sql(e,"alias");return t=t?` AS ${t}`:"",`${this.sql(e,"this")}${t}`}pivotAliasSql(e){let t=e.args.alias,s=e.parent,r=s&&s.parent;if(r instanceof ls&&r.unpivot){let i=t instanceof G,a=t instanceof w;i&&!this._constructor.UNPIVOT_ALIASES_ARE_IDENTIFIERS?t.replace(new w({this:t.name,isString:!0})):!i&&a&&this._constructor.UNPIVOT_ALIASES_ARE_IDENTIFIERS&&t.replace(new G({this:t.name}))}return this.aliasSql(e)}aliasesSql(e){return`${this.sql(e,"this")} AS (${this.expressions(e,{flat:!0})})`}atIndexSql(e){let t=this.sql(e,"this"),s=this.sql(e,"expression");return`${t} AT ${s}`}atTimeZoneSql(e){let t=this.sql(e,"this"),s=this.sql(e,"zone");return`${t} AT TIME ZONE ${s}`}fromTimeZoneSql(e){let t=this.sql(e,"this"),s=this.sql(e,"zone");return`${t} AT TIME ZONE ${s} AT TIME ZONE 'UTC'`}addSql(e){return this.binary(e,"+")}andSql(e,t){return this.connectorSql(e,"AND",t)}orSql(e,t){return this.connectorSql(e,"OR",t)}xorSql(e,t){return this.connectorSql(e,"XOR",t)}connectorSql(e,t,s){if(s!==void 0){if(e.args.expressions&&0<e.args.expressions.length)s.push(this.expressions(e,{sep:` ${t} `}));else{if(s.push(e.right||""),e.comments&&this.comments)for(let c of e.comments)c&&(t+=` /*${this.sanitizeComment(c)}*/`);s.push(t,e.left||"")}return t}let r=[e],i=[],a=new Set;for(;0<r.length;){let c=r.pop();if(c instanceof We){let p=`${c._constructor.key}Sql`,u=this[p];typeof u=="function"&&a.add(u.call(this,c,r))}else{let p=this.sql(c),u=i[i.length-1];0<i.length&&a.has(u)?i[i.length-1]+=` ${p}`:i.push(p)}}let o=this.pretty&&this.tooWide(i)?`
|
|
11
|
+
`:" ";return i.join(o)}bitwiseAndSql(e){return this.binary(e,"&")}bitwiseLeftShiftSql(e){return this.binary(e,"<<")}bitwiseNotSql(e){return`~${this.sql(e,"this")}`}bitwiseOrSql(e){return this.binary(e,"|")}bitwiseRightShiftSql(e){return this.binary(e,">>")}bitwiseXorSql(e){return this.binary(e,"^")}castSql(e,t={}){let{safePrefix:s}=t,r=this.sql(e,"format");r=r?` FORMAT ${r}`:"";let i=this.sql(e,"to");i=i?` ${i}`:"";let a=this.sql(e,"action");a=a?` ${a}`:"";let o=this.sql(e,"default");return o=o?` DEFAULT ${o} ON CONVERSION ERROR`:"",`${s||""}CAST(${this.sql(e,"this")} AS${i}${o}${r}${a})`}strToTimeSql(e){return this.func("STR_TO_TIME",[_nullishCoalesce(e.args.this, () => ("")),e.args.format])}currentDateSql(e){let t=this.sql(e,"this");return t?`CURRENT_DATE(${t})`:"CURRENT_DATE"}collateSql(e){return this._constructor.COLLATE_IS_FUNC?this.functionFallbackSql(e):this.binary(e,"COLLATE")}commandSql(e){let t=this.sql(e,"this"),s=e.text("expression").trim();return`${t} ${s}`}commentSql(e){let t=this.sql(e,"this"),s=e.args.kind,r=e.args.materialized?" MATERIALIZED":"",i=e.args.exists?" IF EXISTS ":" ",a=this.sql(e,"expression");return`COMMENT${i}ON${r} ${s} ${t} IS ${a}`}mergeTreeTtlActionSql(e){let t=this.sql(e,"this"),s=e.args.delete?" DELETE":"",r=this.sql(e,"recompress"),i=r?` RECOMPRESS ${r}`:"",a=this.sql(e,"toDisk"),o=a?` TO DISK ${a}`:"",c=this.sql(e,"toVolume"),p=c?` TO VOLUME ${c}`:"";return`${t}${s}${i}${o}${p}`}mergeTreeTtlSql(e){let t=this.sql(e,"where"),s=this.sql(e,"group"),r=this.expressions(e,{key:"aggregates"}),i=r?`${this.seg("SET")}${this.seg(r)}`:"";return!t&&!s&&!i&&_optionalChain([e, 'access', _1099 => _1099.args, 'access', _1100 => _1100.expressions, 'optionalAccess', _1101 => _1101.length])===1?`TTL ${this.expressions(e,{flat:!0})}`:`TTL${this.seg(this.expressions(e))}${t}${s}${i}`}transactionSql(e){let t=this.expressions(e,{key:"modes"});return`BEGIN${t?` ${t}`:""}`}commitSql(e){let t=e.args.chain,s="";return t!==void 0&&(s=t?" AND CHAIN":" AND NO CHAIN"),`COMMIT${s}`}rollbackSql(e){let t=e.args.savepoint;return`ROLLBACK${t?` TO ${t}`:""}`}alterColumnSql(e){let t=this.sql(e,"this"),s=this.sql(e,"dtype");if(s){let p=this.sql(e,"collate");p=p?` COLLATE ${p}`:"";let u=this.sql(e,"using");u=u?` USING ${u}`:"";let E=this._constructor.ALTER_SET_TYPE,g=E?`${E} `:"";return`ALTER COLUMN ${t} ${g}${s}${p}${u}`}let r=this.sql(e,"default");if(r)return`ALTER COLUMN ${t} SET DEFAULT ${r}`;let i=this.sql(e,"comment");if(i)return`ALTER COLUMN ${t} COMMENT ${i}`;let a=e.args.visible;if(a)return`ALTER COLUMN ${t} SET ${a}`;let o=e.args.allowNull,c=e.args.drop;return!c&&!o&&this.unsupported("Unsupported ALTER COLUMN syntax"),o!==void 0?`ALTER COLUMN ${t} ${c?"DROP":"SET"} NOT NULL`:`ALTER COLUMN ${t} DROP DEFAULT`}alterIndexSql(e){let t=this.sql(e,"this"),r=e.args.visible?"VISIBLE":"INVISIBLE";return`ALTER INDEX ${t} ${r}`}alterDistStyleSql(e){let t=this.sql(e,"this");return e.args.this instanceof Ze||(t=`KEY DISTKEY ${t}`),`ALTER DISTSTYLE ${t}`}alterSortKeySql(e){let t=e.args.compound?" COMPOUND":"",s=this.sql(e,"this"),r=this.expressions(e,{flat:!0});return r=r?`(${r})`:"",`ALTER${t} SORTKEY ${s||r}`}alterRenameSql(e,t={}){let{includeTo:s=!0}=t,r=e;this._constructor.RENAME_TABLE_WITH_DB||(r=e.transform(o=>o instanceof V?new V({this:o.args.this}):o).assertIs(Vi));let i=this.sql(r,"this");return`RENAME${s?" TO":""} ${i}`}renameColumnSql(e){let t=e.args.exists?" IF EXISTS":"",s=this.sql(e,"this"),r=this.sql(e,"to");return`RENAME COLUMN${t} ${s} TO ${r}`}alterSetSql(e){let t=this.expressions(e,{flat:!0});return this._constructor.ALTER_SET_WRAPPED&&(t=`(${t})`),`SET ${t}`}alterSql(e){let t=e.args.actions||[],s;if(!this.dialect._constructor.ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN&&t[0]instanceof we)s=this.expressions(e,{key:"actions",flat:!0}),s=`ADD ${s}`;else{let A=[];for(let x of t){let m=x,N;m instanceof we||m instanceof Lt?N=this.addColumnSql(m):(N=this.sql(m),(m instanceof $||m instanceof $r)&&(N=`AS ${N}`)),A.push(N)}s=this.formatArgs(A).replace(/^\n+/,"")}let r=e.args.exists?" IF EXISTS":"",i=this.sql(e,"cluster");i=i?` ${i}`:"";let a=e.args.only?" ONLY":"",o=this.expressions(e,{key:"options"});o=o?`, ${o}`:"";let c=this.sql(e,"kind").toUpperCase(),p=e.args.notValid?" NOT VALID":"",u=e.args.check?" WITH CHECK":"",E=e.args.cascade&&this.dialect._constructor.ALTER_TABLE_SUPPORTS_CASCADE?" CASCADE":"",g=this.sql(e,"this");return g=g?` ${g}`:"",`ALTER ${c}${r}${a}${g}${i}${u}${this.sep()}${s}${p}${o}${E}`}alterSessionSql(e){let t=this.expressions(e,{flat:!0});return`${e.args.unset?"UNSET":"SET"} ${t}`}addColumnSql(e){let t=this.sql(e),s;return e instanceof Lt?s=" COLUMNS":e instanceof we&&this._constructor.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD?s=" COLUMN":s="",`ADD${s} ${t}`}dropPartitionSql(e){let t=this.expressions(e);return`DROP${e.args.exists?" IF EXISTS ":" "}${t}`}addConstraintSql(e){return`ADD ${this.expressions(e,{indent:!1})}`}addPartitionSql(e){let t=e.args.exists?"IF NOT EXISTS ":"",s=this.sql(e,"location");return s=s?` ${s}`:"",`ADD ${t}${this.sql(e,"this")}${s}`}distinctSql(e){let t=this.expressions(e,{flat:!0});if(!this._constructor.MULTI_ARG_DISTINCT&&1<(_nullishCoalesce(_optionalChain([e, 'access', _1102 => _1102.args, 'access', _1103 => _1103.expressions, 'optionalAccess', _1104 => _1104.length]), () => (0)))){let r=dM();for(let i of e.args.expressions||[])r=r.when(i.is(Ke()),Ke());t=this.sql(r.else(`(${t})`))}t=t?` ${t}`:"";let s=this.sql(e,"on");return s=s?` ON ${s}`:"",`DISTINCT${t}${s}`}ignoreNullsSql(e){return this.embedIgnoreNulls(e,"IGNORE NULLS")}respectNullsSql(e){return this.embedIgnoreNulls(e,"RESPECT NULLS")}havingMaxSql(e){let t=this.sql(e,"this"),s=this.sql(e,"expression"),r=e.args.max?"MAX":"MIN";return`${t} HAVING ${r} ${s}`}intDivSql(e){return this.sql(new Z({this:new jt({this:e.args.this,expression:e.args.expression}),to:new C({this:"int"})}))}dPipeSql(e){if(this.dialect._constructor.STRICT_STRING_CONCAT&&e.args.safe){let t=Array.from(e.flatten()).map(s=>Le(s,"text",{copy:!1}));return this.func("CONCAT",t)}return this.binary(e,"||")}divSql(e){let t=e.left,s=e.right;if(!this.dialect._constructor.SAFE_DIVISION&&e.args.safe&&_optionalChain([s, 'optionalAccess', _1105 => _1105.replace, 'call', _1106 => _1106(new zx({this:s.copy(),expression:w.number(0)}))]),this.dialect._constructor.TYPED_DIVISION&&!e.args.typed)!_optionalChain([t, 'optionalAccess', _1107 => _1107.isType, 'call', _1108 => _1108(Array.from(C.REAL_TYPES))])&&!_optionalChain([s, 'optionalAccess', _1109 => _1109.isType, 'call', _1110 => _1110(Array.from(C.REAL_TYPES))])&&_optionalChain([t, 'optionalAccess', _1111 => _1111.replace, 'call', _1112 => _1112(Le(t.copy(),"double"))]);else if(!this.dialect._constructor.TYPED_DIVISION&&e.args.typed&&_optionalChain([t, 'optionalAccess', _1113 => _1113.isType, 'call', _1114 => _1114(Array.from(C.INTEGER_TYPES))])&&_optionalChain([s, 'optionalAccess', _1115 => _1115.isType, 'call', _1116 => _1116(Array.from(C.INTEGER_TYPES))]))return this.sql(Le(t.div(s),"bigint"));return this.binary(e,"/")}safeDivideSql(e){let t=xc(e.args.this,Y),s=xc(e.args.expression,Y);return!t||!s?"":this.sql(new He({this:s.neq(0),true:t.div(s),false:Ke()}))}overlapsSql(e){return this.binary(e,"OVERLAPS")}distanceSql(e){return this.binary(e,"<->")}dotSql(e){return`${this.sql(e,"this")}.${this.sql(e,"expression")}`}eqSql(e){return this.binary(e,"=")}propertyEqSql(e){return this.binary(e,":=")}escapeSql(e){return this.binary(e,"ESCAPE")}globSql(e){return this.binary(e,"GLOB")}gtSql(e){return this.binary(e,">")}gteSql(e){return this.binary(e,">=")}isSql(e){if(!this._constructor.IS_BOOL_ALLOWED&&e.args.expression instanceof Et){let t=e.args.this;return this.sql(e.args.expression.args.this?t:Hn(t instanceof h||typeof t=="string"?t:void 0))}return this.binary(e,"IS")}iLikeSql(e){return this.likeSql(e)}likeSql(e){let t=e.args.this,s=e.args.expression,r,i;if(e instanceof Ws?(r=Ws,i="LIKE"):(r=ms,i="ILIKE"),(s instanceof qs||s instanceof wt)&&!this._constructor.SUPPORTS_LIKE_QUANTIFIERS){let a,o=s.args.this instanceof h?s.args.this.unnest():void 0;o instanceof Mt?a=o.args.expressions:o?a=[o]:a=[];let c=s instanceof wt?bs:nt,p=new r({this:t,expression:_optionalChain([a, 'optionalAccess', _1117 => _1117[0]])});for(let E=1;E<(_optionalChain([a, 'optionalAccess', _1118 => _1118.length])||0);E++)p=c([p,new r({this:t,expression:_optionalChain([a, 'optionalAccess', _1119 => _1119[E]])||0})]);let u=e.parent;return u instanceof Qe&&!(u instanceof p._constructor)&&(p=_r(p,{copy:!1})),this.sql(p)}return this.binary(e,i)}matchSql(e){return this.binary(e,"MATCH")}similarToSql(e){return this.binary(e,"SIMILAR TO")}ltSql(e){return this.binary(e,"<")}lteSql(e){return this.binary(e,"<=")}modSql(e){return this.binary(e,"%")}mulSql(e){return this.binary(e,"*")}neqSql(e){return this.binary(e,"<>")}nullSafeEqSql(e){return this.binary(e,"IS NOT DISTINCT FROM")}nullSafeNeqSql(e){return this.binary(e,"IS DISTINCT FROM")}subSql(e){return this.binary(e,"-")}tryCastSql(e){return this.castSql(e,{safePrefix:"TRY_"})}jsonCastSql(e){return this.castSql(e)}trySql(e){return this._constructor.TRY_SUPPORTED?this.func("TRY",[e.args.this]):(this.unsupported("Unsupported TRY function"),this.sql(e,"this"))}logSql(e){let t=e.args.this,s=e.args.expression;if(this.dialect._constructor.LOG_BASE_FIRST===!1)[t,s]=[s,t];else if(this.dialect._constructor.LOG_BASE_FIRST===void 0&&s){if(!t)return"";let r=t.name;if(r==="2"||r==="10")return this.func(`LOG${r}`,[s]);this.unsupported(`Unsupported logarithm with base ${this.sql(t)}`)}return this.func("LOG",[t,s])}useSql(e){let t=this.sql(e,"kind"),s=t?` ${t}`:"",r=this.sql(e,"this")||this.expressions(e,{flat:!0}),i=r?` ${r}`:"";return`USE${s}${i}`}binary(e,t){let s=[],r=[e],i=e._constructor;for(;0<r.length;){let a=r.pop();if(a instanceof Y&&a._constructor===i){let o=a.args.operator;o&&(t=`OPERATOR(${this.sql(o)})`),r.push(a.right||""),r.push(` ${this.maybeComment(t,void 0,a.comments)} `),r.push(a.left||"")}else s.push(this.sql(a))}return s.join("")}ceilFloor(e){let t=this.sql(e,"to");return t?`${e._constructor.sqlName}(${this.sql(e,"this")} TO ${t})`:this.functionFallbackSql(e)}functionFallbackSql(e){let t=[];for(let r of e._constructor.availableArgs){let i=e.getArgKey(r);Array.isArray(i)?t.push(...i):t.push(i)}let s;return this.dialect._constructor.PRESERVE_ORIGINAL_NAMES?s=_optionalChain([e, 'access', _1120 => _1120.meta, 'optionalAccess', _1121 => _1121.name])||e._constructor.sqlName():s=e._constructor.sqlName(),this.func(s,t)}func(e,t,s={}){let{prefix:r="(",suffix:i=")",normalize:a=!0}=s;return`${a?this.normalizeFunc(e):e}${r}${this.formatArgs(t)}${i}`}formatArgs(e,t={}){let{sep:s=", "}=t,r=e.filter(i=>i!==void 0&&typeof i!="boolean").map(i=>this.sql(i)).filter(i=>i!=="");if(this.pretty&&this.tooWide(r)){let i=r.join(`${s.trim()}
|
|
12
|
+
`);return this.indent(`
|
|
13
|
+
${i}
|
|
14
|
+
`,{skipFirst:!0,skipLast:!0})}return r.join(s)}tooWide(e){let t=e.reduce((s,r)=>s+r.length,0);return this.maxTextWidth<t}expressions(e,t={}){let{flat:s=!1,indent:r=!0,skipFirst:i=!1,skipLast:a=!1,sep:o=", ",prefix:c="",dynamic:p=!1,newLine:u=!1,key:E,sqls:g}=t,A=e?e.getArgKey(E||"expressions"):g;if(!A||Array.isArray(A)&&A.length===0)return"";let x=Array.isArray(A)?A:[A];if(s)return x.map(S=>this.sql(S)).filter(S=>S).join(o);let m=x.length,N=[];for(let S=0;S<m;S++){let I=x[S],y=this.sql(I,void 0,{comment:!1});if(!y)continue;let P=I instanceof h?this.maybeComment("",I):"";if(this.pretty)if(this.leadingComma)N.push(`${0<S?o:""}${c}${y}${P}`);else{let v=S+1<m?P?o.trimEnd():o:"";N.push(`${c}${y}${v}${P}`)}else N.push(`${c}${y}${P}${S+1<m?o:""}`)}let R;return this.pretty&&(!p||this.tooWide(N))?(u&&(N.unshift(""),N.push("")),R=N.map(S=>S.trimEnd()).join(`
|
|
15
|
+
`)):R=N.join(""),r?this.indent(R,{skipFirst:i,skipLast:a}):R}opExpressions(e,t,s={}){let r=(_nullishCoalesce(s.flat, () => (!1)))||t.parent instanceof mt,i=this.expressions(t,{flat:r});return r?`${e} ${i}`:`${this.seg(e)}${i?this.sep():""}${i}`}nakedProperty(e){let t=mt.PROPERTY_TO_NAME[e._constructor.key];return t||this.unsupported(`Unsupported property ${e._constructor.key}`),`${t||""} ${this.sql(e,"this")}`}tagSql(e){let t=e.args.prefix||"",s=e.args.postfix||"";return`${t}${this.sql(e.args.this)}${s}`}tokenSql(e){return _nullishCoalesce(this._constructor.TOKEN_MAPPING[e], () => (e.replace(/([A-Z])/g,"_$1").toUpperCase()))}userDefinedFunctionSql(e){let t=this.sql(e,"this"),s=this.noIdentify(this.expressions.bind(this),e);return e.args.wrapped?s=this.wrap(s):s=s?` ${s}`:"",s.trim()!==""?`${t}${s}`:t}joinHintSql(e){let t=this.sql(e,"this"),s=this.expressions(e,{flat:!0});return`${t}(${s})`}kwargSql(e){return this.binary(e,"=>")}whenSql(e){let t=e.args.matched?"MATCHED":"NOT MATCHED",s=this._constructor.MATCHED_BY_SOURCE&&e.args.source?" BY SOURCE":"",r=this.sql(e,"condition"),i=r?` AND ${r}`:"",a=e.args.then,o="";if(a instanceof Ss){let c=this.sql(a,"this");c=c?`INSERT ${c}`:"INSERT";let p=this.sql(a,"expression");o=p?`${c} VALUES ${p}`:c}else if(a instanceof sr)if(a.getArgKey("expressions")instanceof ye)o=`UPDATE ${this.sql(a,"expressions")}`;else{let c=this.expressions(a);o=c?`UPDATE SET${this.sep()}${c}`:"UPDATE"}else o=this.sql(a);return`WHEN ${t}${s}${i} THEN ${o}`}whensSql(e){return this.expressions(e,{sep:" ",indent:!1})}mergeSql(e){let t=e.args.this,s="";if(D(t,V)){let u=t.args.hints||[];if(0<u.length&&t.alias&&u[0]instanceof Po){let E=t.args.alias,g=D(E,h)?E.pop():void 0;s=g?` AS ${this.sql(g)}`:""}}let r=this.sql(t),i=`USING ${this.sql(e,"using")}`,a=this.sql(e,"whens"),o=this.sql(e,"on");if(o=o?`ON ${o}`:"",!o){let u=this.expressions(e,{key:"usingCond"});o=u?`USING (${u})`:""}let c=this.sql(e,"returning");c&&(a=`${a}${c}`);let p=this.sep();return this.prependCtes(e,`MERGE INTO ${r}${s}${p}${i}${p}${o}${p}${a}`)}toCharSql(e){return so.call(this,e,"format"),this.sql(Le(e.args.this,"text"))}toNumberSql(e){if(!this._constructor.SUPPORTS_TO_NUMBER)return this.unsupported("Unsupported TO_NUMBER function"),this.sql(Le(e.args.this,"double"));let t=e.args.format;return t?this.func("TO_NUMBER",[e.args.this,t]):(this.unsupported("Conversion format is required for TO_NUMBER"),this.sql(Le(e.args.this,"double")))}dictPropertySql(e){let t=this.sql(e,"this"),s=this.sql(e,"kind"),r=this.expressions(e,{key:"settings",sep:" "}),i=r?`(${this.sep("")}${r}${this.seg(")","")}`:"()";return`${t}(${s}${i})`}dictRangeSql(e){let t=this.sql(e,"this"),s=this.sql(e,"max"),r=this.sql(e,"min");return`${t}(MIN ${r} MAX ${s})`}dictSubPropertySql(e){return`${this.sql(e,"this")} ${this.sql(e,"value")}`}duplicateKeyPropertySql(e){return`DUPLICATE KEY (${this.expressions(e,{flat:!0})})`}distributedByPropertySql(e){let t=this.expressions(e,{flat:!0});t=t?` ${this.wrap(t)}`:"";let s=this.sql(e,"buckets"),r=this.sql(e,"kind"),i=s?` BUCKETS ${s}`:"",a=this.sql(e,"order");return`DISTRIBUTED BY ${r}${t}${i}${a}`}onClusterSql(e){return""}clusteredByPropertySql(e){let t=this.expressions(e,{key:"expressions",flat:!0}),s=this.expressions(e,{key:"sortedBy",flat:!0});s=s?` SORTED BY (${s})`:"";let r=this.sql(e,"buckets");return`CLUSTERED BY (${t})${s} INTO ${r} BUCKETS`}anyValueSql(e){let t=this.sql(e,"this"),s=this.sql(e,"having");if(s){let r=e.args.max;return this.func("ANY_VALUE",[`${t} HAVING ${r?"MAX":"MIN"} ${s}`])}return this.func("ANY_VALUE",[e.args.this])}queryTransformSql(e){let t=this.func("TRANSFORM",e.args.expressions||[]),s=this.sql(e,"rowFormatBefore");s=s?` ${s}`:"";let r=this.sql(e,"recordWriter");r=r?` RECORDWRITER ${r}`:"";let i=` USING ${this.sql(e,"commandScript")}`,a=this.sql(e,"schema");a=a?` AS ${a}`:"";let o=this.sql(e,"rowFormatAfter");o=o?` ${o}`:"";let c=this.sql(e,"recordReader");return c=c?` RECORDREADER ${c}`:"",`${t}${s}${r}${i}${a}${o}${c}`}indexConstraintOptionSql(e){let t=this.sql(e,"keyBlockSize");if(t)return`KEY_BLOCK_SIZE = ${t}`;let s=this.sql(e,"using");if(s)return`USING ${s}`;let r=this.sql(e,"parser");if(r)return`WITH PARSER ${r}`;let i=this.sql(e,"comment");if(i)return`COMMENT ${i}`;let a=e.args.visible;if(a!==void 0)return a?"VISIBLE":"INVISIBLE";let o=this.sql(e,"engineAttr");if(o)return`ENGINE_ATTRIBUTE = ${o}`;let c=this.sql(e,"secondaryEngineAttr");return c?`SECONDARY_ENGINE_ATTRIBUTE = ${c}`:(this.unsupported("Unsupported index constraint option."),"")}checkColumnConstraintSql(e){let t=e.args.enforced?" ENFORCED":"";return`CHECK (${this.sql(e,"this")})${t}`}indexColumnConstraintSql(e){let t=this.sql(e,"kind"),s=t?`${t} INDEX`:"INDEX",r=this.sql(e,"this");r=r?` ${r}`:"";let i=this.sql(e,"indexType");i=i?` USING ${i}`:"";let a=this.expressions(e,{flat:!0});a=a?` (${a})`:"";let o=this.expressions(e,{key:"options",flat:!0,sep:" "});return o=o?` ${o}`:"",`${s}${r}${i}${a}${o}`}nvl2Sql(e){if(this._constructor.NVL2_SUPPORTED)return this.functionFallbackSql(e);let t=e.args.this;if(!t)return"";let s=new Ht({}).when(t.is(Ke()).not({copy:!1}),_nullishCoalesce(e.args.true, () => ("")),{copy:!1}),r=e.args.false;return r&&s.else(r,{copy:!1}),this.sql(s)}comprehensionSql(e){let t=this.sql(e,"this"),s=this.sql(e,"expression"),r=this.sql(e,"position"),i=r?`, ${r}`:"",a=this.sql(e,"iterator"),o=this.sql(e,"condition"),c=o?` IF ${o}`:"";return`${t} FOR ${s}${i} IN ${a}${c}`}columnPrefixSql(e){return`${this.sql(e,"this")}(${this.sql(e,"expression")})`}opclassSql(e){return`${this.sql(e,"this")} ${this.sql(e,"expression")}`}mlSql(e,t){let s=`MODEL ${this.sql(e,"this")}`,r=e.args.expression,i;if(r){let o=this.sql(e,"expression");i=r instanceof ae?o:`TABLE ${o}`}let a=this.sql(e,"paramsStruct")||void 0;return this.func(t,[s,i,a])}predictSql(e){return this.mlSql(e,"PREDICT")}generateEmbeddingSql(e){let t=e.args.isText?"GENERATE_TEXT_EMBEDDING":"GENERATE_EMBEDDING";return this.mlSql(e,t)}mlTranslateSql(e){return this.mlSql(e,"TRANSLATE")}mlForecastSql(e){return this.mlSql(e,"FORECAST")}featuresAtTimeSql(e){let t=e.args.this,s=this.sql(e,"this");return t instanceof V&&(s=`TABLE ${s}`),this.func("FEATURES_AT_TIME",[s,e.args.time,...e.args.numRows||[void 0],...e.args.ignoreFeatureNulls||[void 0]])}vectorSearchSql(e){let t=this.sql(e,"this");e.args.this instanceof V&&(t=`TABLE ${t}`);let s=e.args.queryTable,r=s?this.sql(s):void 0;return s instanceof V&&(r=`TABLE ${r}`),this.func("VECTOR_SEARCH",[t,e.args.columnToSearch,r,e.args.queryColumnToSearch,e.args.topK,e.args.distanceType,...e.args.options||[void 0]])}forInSql(e){let t=this.sql(e,"this"),s=this.sql(e,"expression");return`FOR ${t} DO ${s}`}refreshSql(e){let t=this.sql(e,"this");return`REFRESH ${e.args.this instanceof w?"":`${e.args.kind||""} `}${t}`}toArraySql(e){let t=e.args.this;if(!t)return"";if(t.type||(t=os(t,{dialect:this.dialect})),t.isType("array"))return this.sql(t);let s=t.is(Ke());return this.sql(DR("IF",s,Ke(),jT(t,{copy:!1})))}tsOrDsToTimeSql(e){let t=e.args.this;if(!t)return"";let s=this.formatTime(e);return s?this.sql(Le(new Jt({this:t,format:e.args.format||s}),"time")):e.args.this instanceof pl||t.isType("time")?this.sql(t):this.sql(Le(t,"time"))}tsOrDsToTimestampSql(e){let t=e.args.this;return t?t instanceof iP||t.isType("timestamp")?this.sql(t):this.sql(Le(t,"timestamp")):""}tsOrDsToDatetimeSql(e){let t=e.args.this;return t?e.args.this instanceof nP||t.isType("datetime")?this.sql(t):this.sql(Le(t,"datetime")):""}tsOrDsToDateSql(e){let t=e.args.this;if(!t)return"";let s=this.formatTime(e),r=e.args.safe;return s&&![this.dialect._constructor.TIME_FORMAT,this.dialect._constructor.DATE_FORMAT].includes(s)?this.sql(Le(new Jt({this:t,format:s,safe:r}),"date")):e.args.this instanceof Ue||t.isType("date")?this.sql(t):r?this.sql(new Ft({this:t,to:new C({this:"date"})})):this.sql(Le(t,"date"))}unixDateSql(e){let t=Le(w.string("1970-01-01"),"date");return this.func("DATEDIFF",[e.args.this,t,"day"])}lastDaySql(e){if(this._constructor.LAST_DAY_SUPPORTS_DATE_PART)return this.functionFallbackSql(e);let t=e.text("unit"),s=t?this.sql(t):"";return s&&s!=="MONTH"&&this.unsupported("Date parts are not supported in LAST_DAY."),this.func("LAST_DAY",[e.args.this])}dateAddSql(e){return this.func("DATE_ADD",[e.args.this,e.args.expression,ro(e)])}arrayAnySql(e){if(this._constructor.CAN_IMPLEMENT_ARRAY_ANY){let t=new wR({this:e.args.this,expression:e.args.expression}),s=new lr({this:t}).neq(0),r=new lr({this:e.args.this}).eq(0);return this.sql(_r(r.or(s)))}return this.dialect._constructor===W&&this.unsupported("ARRAY_ANY is unsupported"),this.functionFallbackSql(e)}structSql(e){return e.setArgKey("expressions",(_nullishCoalesce(e.args.expressions, () => ([]))).map(t=>{if(t instanceof At){let s=t.args.this,r=zU(s,a=>a instanceof G?a:a.name),i=t.args.expression;return oe(i instanceof h||typeof i=="string"?i:"",r)}return t})),this.functionFallbackSql(e)}partitionRangeSql(e){let t=this.sql(e,"this"),s=this.sql(e,"expression");return`${t} TO ${s}`}truncateTableSql(e){let t=e.args.isDatabase?"DATABASE":"TABLE",s=` ${this.expressions(e)}`,r=e.args.exists?" IF EXISTS":"",i=this.sql(e,"cluster");i=i?` ${i}`:"";let a=this.sql(e,"identity");a=a?` ${a} IDENTITY`:"";let o=this.sql(e,"option");o=o?` ${o}`:"";let c=this.sql(e,"partition");return c=c?` ${c}`:"",`TRUNCATE ${t}${r}${s}${i}${a}${o}${c}`}convertSql(e){let t=e.args.this,s=e.args.expression,r=e.args.style,i=e.args.safe,a=e.getArgKey("strict");if(!t||!s)return"";ue(t,C);let o=t;!b(_nullishCoalesce(t.args.expressions, () => ([])),0)&&this._constructor.PARAMETERIZABLE_TEXT_TYPES.has(t.args.this)&&(o=_nullishCoalesce(C.build(t.args.this,{expressions:[w.number(30)],nested:!1}), () => (o)));let c,p=a?Z:Ft;if(r instanceof w&&r.isInteger){let u=r.name,g=_nullishCoalesce(_optionalChain([W, 'access', _1122 => _1122.get, 'call', _1123 => _1123("tsql"), 'optionalAccess', _1124 => _1124.CONVERT_FORMAT_MAPPING, 'optionalAccess', _1125 => _1125[u]]), () => (""));g||this.unsupported(`Unsupported T-SQL 'style' value: ${u}`);let A=w.string(g);o.args.this==="date"?c=new ar({this:s,format:A}):o.args.this==="datetime"||o.args.this==="datetime2"?c=new Jt({this:s,format:A}):this._constructor.PARAMETERIZABLE_TEXT_TYPES.has(o.args.this)?c=new p({this:new Ns({this:s,format:A}),to:o,safe:i}):o.args.this==="text"&&(c=new Ns({this:s,format:A}))}return c||(c=new p({this:s,to:o,safe:i})),this.sql(c)}jsonPathKeySql(e){let t=e.args.this;if(t instanceof hs){let r=this.jsonPathPart(t);return r?`.${r}`:""}if(typeof t=="string"&&this._constructor.SAFE_JSON_PATH_KEY_RE.test(t))return`.${t}`;let s=this.jsonPathPart(typeof t=="string"?t:t instanceof h?_nullishCoalesce(t.name, () => ("")):"");return this.quoteJsonPathKeyUsingBrackets&&this._constructor.JSON_PATH_BRACKETED_KEY_SUPPORTED?`[${s}]`:`.${s}`}jsonPathSubscriptSql(e){let t=e.args.this,s=this.jsonPathPart(t);return s?`[${s}]`:""}simplifyUnlessLiteral(e){return e instanceof w||(e=vc(e,{dialect:this.dialect})),e}embedIgnoreNulls(e,t){let s=e.args.this;if(this._constructor.RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS.some(r=>s instanceof r))return this.unsupported(`RESPECT/IGNORE NULLS is not supported for ${_optionalChain([s, 'optionalAccess', _1126 => _1126._constructor, 'access', _1127 => _1127.key])} in ${this.dialect.constructor.name}`),this.sql(s);if(this._constructor.IGNORE_NULLS_IN_FUNC&&!_optionalChain([e, 'access', _1128 => _1128.meta, 'optionalAccess', _1129 => _1129.inline])){let r=[...e.findAll([On,ke,Ct])].sort((a,o)=>{let c=p=>p instanceof On?0:p instanceof ke?1:2;return c(a)-c(o)});if(0<r.length){let a=r[0],o=new e._constructor({this:_optionalChain([a, 'access', _1130 => _1130.args, 'access', _1131 => _1131.this, 'optionalAccess', _1132 => _1132.copy, 'call', _1133 => _1133()])});return o.meta={...o.meta,inline:!0},_optionalChain([a, 'access', _1134 => _1134.args, 'access', _1135 => _1135.this, 'optionalAccess', _1136 => _1136.replace, 'call', _1137 => _1137(o)]),this.sql(e.args.this)}let i=e.find(q);if(i){let a=this.sql(i,void 0,{comment:!1}).slice(0,-1)+` ${t})`;return this.maybeComment(a,void 0,i.comments)}}return`${this.sql(e,"this")} ${t}`}replaceLineBreaks(e){return this.pretty?e.replace(/\n/g,this._constructor.SENTINEL_LINE_BREAK):e}copyParameterSql(e){let t=this.sql(e,"this");if(e.args.expressions&&0<e.args.expressions.length){let i=t.toUpperCase(),a=i==="FILE_FORMAT"?" ":", ",o=i==="COPY_OPTIONS"||i==="FORMAT_OPTIONS"?" ":" = ",c=this.expressions(e,{flat:!0,sep:a});return`${t}${o}(${c})`}let s=this.sql(e,"expression");if(!s)return t;let r=this._constructor.COPY_PARAMS_EQ_REQUIRED?" = ":" ";return`${t}${r}${s}`}credentialsSql(e){let t=e.args.credentials,s="";if(t instanceof w){let g=this.sql(e,"credentials");s=g?`CREDENTIALS ${g}`:""}else{let g=this.expressions(e,{key:"credentials",flat:!0,sep:" "});s=t!=null?`CREDENTIALS = (${g})`:""}let r=this.sql(e,"storage"),i=r?`STORAGE_INTEGRATION = ${r}`:"",a=this.expressions(e,{key:"encryption",flat:!0,sep:" "}),o=a?` ENCRYPTION = (${a})`:"",c=this.sql(e,"iamRole"),p=c?`IAM_ROLE ${c}`:"",u=this.sql(e,"region"),E=u?` REGION ${u}`:"";return`${s}${i}${o}${p}${E}`}copySql(e){let t=this._constructor,s=this.sql(e,"this");s=t.COPY_HAS_INTO_KEYWORD?` INTO ${s}`:` ${s}`;let r=this.sql(e,"credentials");r=r?this.seg(r):"";let i=this.expressions(e,{key:"files",flat:!0}),a=i&&e.args.kind?this.seg("FROM"):i?this.seg("TO"):"",c=this.dialect._constructor.COPY_PARAMS_ARE_CSV||!1?", ":" ",p=this.expressions(e,{key:"params",sep:c,newLine:!0,skipLast:!0,skipFirst:!0,indent:t.COPY_PARAMS_ARE_WRAPPED});return p&&(t.COPY_PARAMS_ARE_WRAPPED?p=` WITH (${p})`:!this.pretty&&(i||r)&&(p=` ${p}`)),`COPY${s}${a} ${i}${r}${p}`}semicolonSql(e){return""}dataDeletionPropertySql(e){let t=e.args.on?"ON":"OFF",s=this.sql(e,"filterColumn"),r=s?`FILTER_COLUMN=${s}`:void 0,i=this.sql(e,"retentionPeriod"),a=i?`RETENTION_PERIOD=${i}`:void 0;return r||a?`DATA_DELETION=${this.func("ON",[r,a])}`:`DATA_DELETION=${t}`}gapFillSql(e){let t=this.sql(e,"this");t=`TABLE ${t}`;let s=Object.entries(e.args).filter(([r])=>r!=="this").map(([r,i])=>i);return this.func("GAP_FILL",[t,...s])}scopeResolution(e,t){return this.func("SCOPE_RESOLUTION",[t||void 0,e])}scopeResolutionSql(e){let t=this.sql(e,"this"),s=e.args.expression,r;if(s instanceof d){let i=this.sql(s,"this"),a=this.formatArgs(s.args.expressions||[]);r=`${i}(${a})`}else r=this.sql(e,"expression");return this.scopeResolution(r,t)}parseJsonSql(e){let t=this._constructor.PARSE_JSON_NAME;return t==null?this.sql(e.args.this):this.func(t,[e.args.this,e.args.expression])}randSql(e){let t=this.sql(e,"lower"),s=this.sql(e,"upper");return t&&s?`(${s} - ${t}) * ${this.func("RAND",[e.args.this])} + ${t}`:this.func("RAND",[e.args.this])}changesSql(e){let s=`INFORMATION => ${this.sql(e,"information")}`,r=this.sql(e,"atBefore"),i=r?`${this.seg("")}${r}`:"",a=this.sql(e,"end"),o=a?`${this.seg("")}${a}`:"";return`CHANGES (${s})${i}${o}`}padSql(e){let t=e.args.isLeft?"L":"R",s=this.sql(e,"fillPattern");return!s&&this._constructor.PAD_FILL_PATTERN_IS_REQUIRED&&(s="' '"),this.func(`${t}PAD`,[e.args.this,e.args.expression,s])}summarizeSql(e){return`SUMMARIZE${e.args.table?" TABLE":""} ${this.sql(e.args.this)}`}explodingGenerateSeriesSql(e){let t=new Os({...e.args}),s=e.parent;return(s instanceof Se||s instanceof ie)&&(s=s.parent),this._constructor.SUPPORTS_EXPLODING_PROJECTIONS&&!(s instanceof V)&&!(s instanceof Pe)?this.sql(new Pe({expressions:[t]})):(s instanceof $&&this.unsupported("GenerateSeries projection unnesting is not supported."),this.sql(t))}convertTimezoneSql(e){if(this._constructor.SUPPORTS_CONVERT_TIMEZONE)return this.functionFallbackSql(e);let t=e.args.sourceTz,s=e.args.targetTz,r=e.args.timestamp;t&&r&&(r=new Or({this:Le(r,"timestampntz"),zone:t}));let i=new Or({this:r,zone:s});return this.sql(i)}jsonSql(e){let t=this.sql(e,"this"),s=t?` ${t}`:"",r=e.args.with,i="";r==null?i="":r?i=" WITH":i=" WITHOUT";let a=e.args.unique?" UNIQUE KEYS":"";return`JSON${s}${i}${a}`}jsonValueSql(e){let t=this.sql(e,"path"),s=this.sql(e,"returning");s=s?` RETURNING ${s}`:"";let r=this.sql(e,"onCondition");return r=r?` ${r}`:"",this.func("JSON_VALUE",[e.args.this,`${t}${s}${r}`])}conditionalInsertSql(e){let t=e.args.else?"ELSE ":"",s=this.sql(e,"expression"),r=s?`WHEN ${s} THEN `:t,i=this.sql(e,"this").substring(6).trim();return`${r}${i}`}multitableInsertsSql(e){let t=this.sql(e,"kind"),s=this.seg(this.expressions(e,{sep:" "}));return`INSERT ${t}${s}${this.seg(this.sql(e,"source"))}`}onConditionSql(e){let t=e.args.empty,s="";t instanceof h?s=`DEFAULT ${this.sql(t)} ON EMPTY`:s=this.sql(e,"empty");let r=e.args.error,i="";r instanceof h?i=`DEFAULT ${this.sql(r)} ON ERROR`:i=this.sql(e,"error"),i&&s&&(this._constructor.ON_CONDITION_EMPTY_BEFORE_ERROR?i=`${s} ${i}`:i=`${i} ${s}`,s="");let a=this.sql(e,"null");return`${s}${i}${a}`}jsonExtractSql(e){return this.functionFallbackSql(e)}jsonExtractScalarSql(e){return this.functionFallbackSql(e)}jsonbExtractSql(e){return this.functionFallbackSql(e)}jsonbExtractScalarSql(e){return this.functionFallbackSql(e)}jsonExtractQuoteSql(e){let t=e.args.scalar?" ON SCALAR STRING":"";return`${this.sql(e,"option")} QUOTES${t}`}jsonExistsSql(e){let t=this.sql(e,"this"),s=this.sql(e,"path"),r=this.expressions(e,{key:"passing"}),i=r?` PASSING ${r}`:"",a=this.sql(e,"onCondition");return a=a?` ${a}`:"",s=`${s}${i}${a}`,this.func("JSON_EXISTS",[t,s])}addArrayAggNullFilter(e,t,s){if(!(this.dialect._constructor.ARRAY_AGG_INCLUDES_NULLS&&t.args.nullsExcluded))return e;let r=t.parent;if(r instanceof ti){let i=_optionalChain([r, 'access', _1138 => _1138.args, 'access', _1139 => _1139.expression, 'optionalAccess', _1140 => _1140.args, 'access', _1141 => _1141.this]);if(!i)return e;i.replace(i.and(s.is(Ke()).not()))}else if(s.find(k)){let i=s instanceof ct?this.expressions(s):this.sql(s);e=`${e} FILTER(WHERE ${i} IS NOT NULL)`}return e}arrayAggSql(e){let t=this.functionFallbackSql(e),s=e.args.this instanceof h?e.args.this:void 0;return s?this.addArrayAggNullFilter(t,e,s):t}sliceSql(e){let t=this.sql(e,"step"),s=this.sql(typeof e.args.expression=="number"?e.args.expression.toString():e.args.expression),r=this.sql(e.args.this),i=t?`${s}:${t}`:s;return i?`${r}:${i}`:`${r}:`}applySql(e){let t=this.sql(e,"this"),s=this.sql(e,"expression");return`${t} APPLY(${s})`}grantOrRevokeSql(e,t={}){let{keyword:s,preposition:r,grantOptionPrefix:i="",grantOptionSuffix:a=""}=t,o=this.expressions(e,{key:"privileges",flat:!0}),c=this.sql(e,"kind"),p=c?` ${c}`:"",u=this.sql(e,"securable");u=u?` ${u}`:"";let E=this.expressions(e,{key:"principals",flat:!0}),g=i,A=a;e.args.grantOption||(g=A="");let x=this.sql(e,"cascade"),m=x?` ${x}`:"";return`${s} ${g}${o} ON${p}${u} ${r} ${E}${A}${m}`}grantSql(e){return this.grantOrRevokeSql(e,{keyword:"GRANT",preposition:"TO",grantOptionSuffix:" WITH GRANT OPTION"})}revokeSql(e){return this.grantOrRevokeSql(e,{keyword:"REVOKE",preposition:"FROM",grantOptionPrefix:"GRANT OPTION FOR "})}grantPrivilegeSql(e){let t=this.sql(e,"this"),s=this.expressions(e,{flat:!0}),r=s?`(${s})`:"";return`${t}${r}`}grantPrincipalSql(e){let t=this.sql(e,"this"),s=this.sql(e,"kind");return`${s?`${s} `:""}${t}`}columnsSql(e){let t=this.functionFallbackSql(e);return e.args.unpack?`*${t}`:t}overlaySql(e){let t=this.sql(e,"this"),s=this.sql(e,"expression"),r=this.sql(e,"from"),i=this.sql(e,"for"),a=i?` FOR ${i}`:"";return`OVERLAY(${t} PLACING ${s} FROM ${r}${a})`}toDoubleSql(e){so.call(this,e,"format");let t=e.args.safe?Ft:Z;return this.sql(new t({this:e.args.this,to:new C({this:"double"})}))}stringSql(e){let t=e.args.this,s=e.args.zone;return s&&(t=new Qn({sourceTz:new w({this:"UTC",isString:!0}),targetTz:s,timestamp:t})),this.sql(Le(t,"VARCHAR",{dialect:this.dialect}))}medianSql(e){return this._constructor.SUPPORTS_MEDIAN?this.functionFallbackSql(e):this.sql(new yc({this:e.args.this,expression:w.number(.5)}))}overflowTruncateBehaviorSql(e){let t=this.sql(e,"this"),s=t?` ${t}`:"",r=e.args.withCount?"WITH COUNT":"WITHOUT COUNT";return`TRUNCATE${s} ${r}`}unixSecondsSql(e){if(this._constructor.SUPPORTS_UNIX_SECONDS)return this.functionFallbackSql(e);let t=Le(w.string("1970-01-01 00:00:00+00"),"timestamptz");return this.sql(new Va({this:e.args.this,expression:t,unit:new Ze({this:"SECONDS"})}))}arraySizeSql(e){let t=e.args.expression;return t&&this._constructor.ARRAY_SIZE_DIM_REQUIRED===void 0&&(t.isInteger&&t.name==="1"||this.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH"),t=void 0),this._constructor.ARRAY_SIZE_DIM_REQUIRED&&!t&&(t=new w({this:"1",isString:!1})),this.func(this._constructor.ARRAY_SIZE_NAME,[e.args.this,t])}attachSql(e){let t=this.sql(e,"this"),s=e.args.exists?" IF NOT EXISTS":"",r=this.expressions(e);return r=r?` (${r})`:"",`ATTACH${s} ${t}${r}`}detachSql(e){let t=this.sql(e,"this");return`DETACH${e.args.exists?" DATABASE IF EXISTS":""} ${t}`}attachOptionSql(e){let t=this.sql(e,"this"),s=this.sql(e,"expression");return s=s?` ${s}`:"",`${t}${s}`}watermarkColumnConstraintSql(e){return`WATERMARK FOR ${this.sql(e,"this")} AS ${this.sql(e,"expression")}`}encodePropertySql(e){let s=`${e.args.key?"KEY ENCODE":"ENCODE"} ${this.sql(e,"this")}`,r=e.args.properties;return r&&(ue(r,mt),s=`${s} ${this.properties(r)}`),s}includePropertySql(e){let s=`INCLUDE ${this.sql(e,"this")}`,r=this.sql(e,"columnDef");r&&(s=`${s} ${r}`);let i=this.sql(e,"alias");return i&&(s=`${s} AS ${i}`),s}xmlElementSql(e){let s=`${e.args.evalname?"EVALNAME":"NAME"} ${this.sql(e,"this")}`;return this.func("XmlELEMENT",[s,...e.args.expressions||[]])}xmlKeyValueOptionSql(e){let t=this.sql(e,"this"),s=this.sql(e,"expression"),r=s?`(${s})`:"";return`${t}${r}`}partitionByRangePropertySql(e){let t=this.expressions(e,{key:"partitionExpressions"}),s=this.expressions(e,{key:"createExpressions"});return`PARTITION BY RANGE ${this.wrap(t)} ${this.wrap(s)}`}partitionByRangePropertyDynamicSql(e){let t=this.sql(e,"start"),s=this.sql(e,"end"),r=e.args.every;r instanceof ze&&_optionalChain([r, 'access', _1142 => _1142.args, 'access', _1143 => _1143.this, 'optionalAccess', _1144 => _1144.isString])&&r.args.this.replace(w.number(r.name));let i=this.sql(r);return`START(${t}) END(${s}) EVERY(${i})`}unpivotColumnsSql(e){let t=this.sql(e,"this"),s=this.expressions(e,{flat:!0});return`NAME ${t} VALUE ${s}`}analyzeSampleSql(e){let t=this.sql(e,"kind");return`SAMPLE ${this.sql(e,"sample")} ${t}`}analyzeStatisticsSql(e){let t=this.sql(e,"kind"),s=this.sql(e,"option");s=s?` ${s}`:"";let r=this.sql(e,"this");r=r?` ${r}`:"";let i=this.expressions(e);return i=i?` ${i}`:"",`${t}${s} STATISTICS${r}${i}`}analyzeHistogramSql(e){let t=this.sql(e,"this"),s=this.expressions(e),r=this.sql(e,"expression");r=r?` ${r}`:"";let i=this.sql(e,"updateOptions");return i=i?` ${i} UPDATE`:"",`${t} HISTOGRAM ON ${s}${r}${i}`}analyzeDeleteSql(e){let t=this.sql(e,"kind");return t=t?` ${t}`:"",`DELETE${t} STATISTICS`}analyzeListChainedRowsSql(e){return`LIST CHAINED ROWS${this.sql(e,"expression")}`}analyzeValidateSql(e){let t=this.sql(e,"kind"),s=this.sql(e,"this");s=s?` ${s}`:"";let r=this.sql(e,"expression");return`VALIDATE ${t}${s}${r}`}analyzeSql(e){let t=this.expressions(e,{key:"options",sep:" "});t=t?` ${t}`:"";let s=this.sql(e,"kind");s=s?` ${s}`:"";let r=this.sql(e,"this");r=r?` ${r}`:"";let i=this.sql(e,"mode");i=i?` ${i}`:"";let a=this.sql(e,"properties");a=a?` ${a}`:"";let o=this.sql(e,"partition");o=o?` ${o}`:"";let c=this.sql(e,"expression");return c=c?` ${c}`:"",`ANALYZE${t}${s}${r}${i}${a}${o}${c}`}xmlTableSql(e){let t=this.sql(e,"this"),s=this.expressions(e,{key:"namespaces"}),r=s?`XMLNAMESPACES(${s}), `:"",i=this.expressions(e,{key:"passing"}),a=i?`${this.sep()}PASSING${this.seg(i)}`:"",o=this.expressions(e,{key:"columns"}),c=o?`${this.sep()}COLUMNS${this.seg(o)}`:"",p=e.args.byRef?`${this.sep()}RETURNING SEQUENCE BY REF`:"";return`XMLTABLE(${this.sep("")}${this.indent(r+t+a+p+c)}${this.seg(")","")}`}xmlNamespaceSql(e){let t=this.sql(e,"this");return e.args.this instanceof Se?t:`DEFAULT ${t}`}exportSql(e){let t=this.sql(e,"this"),s=this.sql(e,"connection"),r=s?`WITH CONNECTION ${s} `:"",i=this.sql(e,"options");return`EXPORT DATA ${r}${i} AS ${t}`}declareSql(e){return`DECLARE ${this.expressions(e,{flat:!0})}`}declareItemSql(e){let t=this.sql(e,"this"),s=this.sql(e,"default"),r=s?` = ${s}`:"",i=this.sql(e,"kind");return e.args.kind instanceof Lt&&(i=`TABLE ${i}`),`${t} AS ${i}${r}`}recursiveWithSearchSql(e){let t=this.sql(e,"kind"),s=this.sql(e,"this"),r=this.sql(e,"expression"),i=this.sql(e,"using"),a=i?` USING ${i}`:"";return`${t==="CYCLE"?t:`SEARCH ${t} FIRST BY`} ${s} SET ${r}${a}`}parameterizedAggSql(e){let t=this.expressions(e,{key:"params",flat:!0}),s=e.name||"";return this.func(s,e.args.expressions||[])+`(${t})`}anonymousAggFuncSql(e){let t=e.name||"";return this.func(t,e.args.expressions||[])}combinedAggFuncSql(e){return this.anonymousAggFuncSql(e)}combinedParameterizedAggSql(e){return this.parameterizedAggSql(e)}showSql(e){return this.unsupported("Unsupported SHOW statement"),""}installSql(e){return this.unsupported("Unsupported INSTALL statement"),""}getPutSql(e){let t=e.args.properties;t&&ue(t,mt);let s=t?this.properties(t,{prefix:" ",sep:" ",wrapped:!1}):"",r=this.sql(e,"this"),i=this.sql(e,"target");return e instanceof Rp?`PUT ${r} ${i}${s}`:`GET ${i} ${r}${s}`}translateCharactersSql(e){let t=this.sql(e,"this"),s=this.sql(e,"expression"),r=e.args.withError?" WITH ERROR":"";return`TRANSLATE(${t} USING ${s}${r})`}decodeCaseSql(e){if(this._constructor.SUPPORTS_DECODE_CASE)return this.func("DECODE",_nullishCoalesce(e.args.expressions, () => ([])));let[t,...s]=_nullishCoalesce(e.args.expressions, () => ([])),r=[];for(let o=0;o<s.length-1;o+=2){let c=s[o],p=s[o+1];if(c instanceof w)r.push(new He({this:t.eq(c),true:p}));else if(c instanceof Qt)r.push(new He({this:t.is(Ke()),true:p}));else{let u=c;u instanceof Y&&(u=_r(u));let E=bs([t.eq(u),nt([t.is(Ke()),u.is(Ke())],{copy:!1})],{copy:!1});r.push(new He({this:E,true:p}))}}let i=s.length%2===1?s[s.length-1]:void 0,a=new Ht({ifs:r,default:i});return this.sql(a)}semanticViewSql(e){let t=this.sql(e,"this"),s=this.seg(t,""),r=this.expressions(e,{key:"dimensions",dynamic:!0,skipFirst:!0,skipLast:!0}),i=r?this.seg(`DIMENSIONS ${r}`):"",a=this.expressions(e,{key:"metrics",dynamic:!0,skipFirst:!0,skipLast:!0}),o=a?this.seg(`METRICS ${a}`):"",c=this.expressions(e,{key:"facts",dynamic:!0,skipFirst:!0,skipLast:!0}),p=c?this.seg(`FACTS ${c}`):"",u=this.sql(e,"where"),E=u?this.seg(`WHERE ${u}`):"";return`SEMANTIC_VIEW(${this.indent(s+o+i+p+E,{skipFirst:!0})}${this.seg(")","")}`}getExtractSql(e){let t=e.args.this,s=e.args.expression;return t?((!t.type||!e.type)&&(t=os(t,{dialect:this.dialect})),t.isType(["array","map"])?this.sql(new fs({this:t,expressions:s?[s]:[]})):this.sql(new Zt({this:t,expression:this.dialect.toJsonPath(s)}))):""}dateFromUnixDateSql(e){return this.sql(new ut({this:Le(w.string("1970-01-01"),"date"),expression:e.args.this,unit:Te("DAY")}))}spaceSql(e){return this.func("REPEAT",[gg(" "),e.args.this])}buildPropertySql(e){return`BUILD ${this.sql(e,"this")}`}refreshTriggerPropertySql(e){let t=this.sql(e,"method"),s=e.args.kind;if(!s)return`REFRESH ${t}`;let r=this.sql(e,"every"),i=this.sql(e,"unit"),a=r?` EVERY ${r} ${i}`:"",o=this.sql(e,"starts");return o=o?` STARTS ${o}`:"",`REFRESH ${t} ON ${s}${a}${o}`}modelAttributeSql(e){return this.unsupported("The model!attribute syntax is not supported"),""}directoryStageSql(e){return this.func("DIRECTORY",[e.args.this])}uuidSql(e){let t=this.func("UUID",[]);return e.args.isString&&!this.dialect._constructor.UUID_IS_STRING_TYPE?this.sql(Le(Te(t),"varchar")):t}initcapSql(e){let t=e.args.expression;return t&&(this.dialect._constructor.INITCAP_SUPPORTS_CUSTOM_DELIMITERS?t.isString&&t.args.this===this.dialect._constructor.INITCAP_DEFAULT_DELIMITER_CHARS&&(t=void 0):t=void 0),this.func("INITCAP",[e.args.this,t])}localtimeSql(e){let t=e.args.this;return t?this.func("LOCALTIME",[t]):"LOCALTIME"}localtimestampSql(e){let t=e.args.this;return t?this.func("LOCALTIMESTAMP",[t]):"LOCALTIMESTAMP"}weekStartSql(e){let t=e.args.this,s=_optionalChain([t, 'optionalAccess', _1145 => _1145.name, 'access', _1146 => _1146.toUpperCase, 'call', _1147 => _1147()]);return this.dialect._constructor.WEEK_OFFSET===-1&&s==="SUNDAY"?"WEEK":this.func("WEEK",[t])}chrSql(e,t={}){let{name:s="CHR"}=t,r=this.expressions(e),i=this.sql(e,"charset"),a=i?` USING ${i}`:"";return this.func(s,[r+a])}blockSql(e){let t=this.expressions(e,{sep:"; ",flat:!0});return t?`${t}`:""}tableSampleSql(e,t={}){let{tablesampleKeyword:s}=t,r=this.sql(e,"method");r=r&&this._constructor.TABLESAMPLE_WITH_METHOD?`${r} `:"";let i=this.sql(e,"bucketNumerator"),a=this.sql(e,"bucketDenominator"),o=this.sql(e,"bucketField");o=o?` ON ${o}`:"";let c=i?`BUCKET ${i} OUT OF ${a}${o}`:"",p=this.sql(e,"seed");p=p?` ${this._constructor.TABLESAMPLE_SEED_KEYWORD} (${p})`:"";let u=this.sql(e,"size");u&&this._constructor.TABLESAMPLE_SIZE_IS_ROWS&&(u=`${u} ROWS`);let E=this.sql(e,"percent");E&&!this.dialect._constructor.TABLESAMPLE_SIZE_IS_PERCENT&&(E=`${E} PERCENT`);let g=`${c}${E}${u}`;return this._constructor.TABLESAMPLE_REQUIRES_PARENS&&(g=`(${g})`),` ${s||this._constructor.TABLESAMPLE_KEYWORDS} ${r}${g}${p}`}maskingPolicyColumnConstraintSql(e){let t=this.sql(e,"this"),s=this.expressions(e,{flat:!0});return s=s?` USING (${s})`:"",`MASKING POLICY ${t}${s}`}uniqueKeyPropertySql(e,t={}){let{prefix:s="UNIQUE KEY"}=t;return`${s} (${this.expressions(e,{flat:!0})})`}formatTime(e,t,s){let r=this.dialect._constructor,i=t||r.INVERSE_TIME_MAPPING,a=s||r.INVERSE_TIME_TRIE;return dg(this.sql(e,"format"),i,a)}ceilSql(e){return this.ceilFloor(e)}floorSql(e){return this.ceilFloor(e)}offsetLimitModifiers(e,t,s){let{fetch:r}=t;return[r?this.sql(e,"offset"):this.sql(s),r?this.sql(s):this.sql(e,"offset")]}};nn=re(null),T(nn,10,"NULL_ORDERING_SUPPORTED",fF,L),T(nn,10,"SUPPORTED_JSON_PATH_PARTS",AF,L),T(nn,10,"UNWRAPPED_INTERVAL_VALUES",dF,L),T(nn,10,"WITH_SEPARATED_COMMENTS",gF,L),T(nn,10,"EXCLUDE_COMMENTS",hF,L),T(nn,10,"TYPE_MAPPING",EF,L),T(nn,10,"UNSUPPORTED_TYPES",uF,L),T(nn,10,"PARAMETERIZABLE_TEXT_TYPES",lF,L),T(nn,10,"TOKEN_MAPPING",pF,L),T(nn,10,"ORIGINAL_TRANSFORMS",cF,L),T(nn,10,"TRANSFORMS",oF,L),T(nn,10,"PROPERTIES_LOCATION",aF,L),te(nn,L),se(nn,3,L),L.IGNORE_NULLS_IN_FUNC=!1,L.RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS=[],L.LOCKING_READS_SUPPORTED=!1,L.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE=!0,L.WRAP_DERIVED_VALUES=!0,L.CREATE_FUNCTION_RETURN_AS=!0,L.MATCHED_BY_SOURCE=!0,L.SINGLE_STRING_INTERVAL=!1,L.INTERVAL_ALLOWS_PLURAL_FORM=!0,L.LIMIT_FETCH="ALL",L.LIMIT_ONLY_LITERALS=!1,L.RENAME_TABLE_WITH_DB=!0,L.GROUPINGS_SEP=",",L.INDEX_ON="ON",L.INOUT_SEPARATOR=" ",L.JOIN_HINTS=!0,L.DIRECTED_JOINS=!1,L.TABLE_HINTS=!0,L.QUERY_HINTS=!0,L.QUERY_HINT_SEP=", ",L.IS_BOOL_ALLOWED=!0,L.DUPLICATE_KEY_UPDATE_WITH_SET=!0,L.LIMIT_IS_TOP=!1,L.RETURNING_END=!0,L.EXTRACT_ALLOWS_QUOTES=!0,L.TZ_TO_WITH_TIME_ZONE=!1,L.NVL2_SUPPORTED=!0,L.SELECT_KINDS=["STRUCT","VALUE"],L.VALUES_AS_TABLE=!0,L.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD=!0,L.UNNEST_WITH_ORDINALITY=!0,L.AGGREGATE_FILTER_SUPPORTED=!0,L.SEMI_ANTI_JOIN_WITH_SIDE=!0,L.COMPUTED_COLUMN_WITH_TYPE=!0,L.SUPPORTS_TABLE_COPY=!0,L.TABLESAMPLE_REQUIRES_PARENS=!0,L.TABLESAMPLE_SIZE_IS_ROWS=!0,L.TABLESAMPLE_SIZE_IS_PERCENT=!1,L.TABLESAMPLE_KEYWORDS="TABLESAMPLE",L.TABLESAMPLE_WITH_METHOD=!0,L.TABLESAMPLE_SEED_KEYWORD="SEED",L.COLLATE_IS_FUNC=!1,L.DATA_TYPE_SPECIFIERS_ALLOWED=!1,L.ENSURE_BOOLS=!1,L.CTE_RECURSIVE_KEYWORD_REQUIRED=!0,L.SUPPORTS_SINGLE_ARG_CONCAT=!0,L.LAST_DAY_SUPPORTS_DATE_PART=!0,L.SUPPORTS_TABLE_ALIAS_COLUMNS=!0,L.UNPIVOT_ALIASES_ARE_IDENTIFIERS=!0,L.JSON_KEY_VALUE_PAIR_SEP=":",L.INSERT_OVERWRITE=" OVERWRITE TABLE",L.SUPPORTS_SELECT_INTO=!1,L.SUPPORTS_UNLOGGED_TABLES=!1,L.SUPPORTS_CREATE_TABLE_LIKE=!0,L.LIKE_PROPERTY_INSIDE_SCHEMA=!1,L.MULTI_ARG_DISTINCT=!0,L.JSON_TYPE_REQUIRED_FOR_EXTRACTION=!1,L.JSON_PATH_BRACKETED_KEY_SUPPORTED=!0,L.JSON_PATH_SINGLE_QUOTE_ESCAPE=!1,L.CAN_IMPLEMENT_ARRAY_ANY=!1,L.SUPPORTS_TO_NUMBER=!0,L.SUPPORTS_WINDOW_EXCLUDE=!1,L.SET_OP_MODIFIERS=!0,L.COPY_PARAMS_ARE_WRAPPED=!0,L.COPY_PARAMS_EQ_REQUIRED=!1,L.COPY_HAS_INTO_KEYWORD=!0,L.TRY_SUPPORTED=!0,L.SUPPORTS_UESCAPE=!0,L.UNICODE_SUBSTITUTE=void 0,L.STAR_EXCEPT="EXCEPT",L.HEX_FUNC="HEX",L.WITH_PROPERTIES_PREFIX="WITH",L.QUOTE_JSON_PATH=!0,L.PAD_FILL_PATTERN_IS_REQUIRED=!1,L.SUPPORTS_EXPLODING_PROJECTIONS=!0,L.ARRAY_CONCAT_IS_VAR_LEN=!0,L.SUPPORTS_CONVERT_TIMEZONE=!1,L.SUPPORTS_MEDIAN=!0,L.SUPPORTS_UNIX_SECONDS=!1,L.ALTER_SET_WRAPPED=!1,L.NORMALIZE_EXTRACT_DATE_PARTS=!1,L.PARSE_JSON_NAME="PARSE_JSON",L.ARRAY_SIZE_NAME="ARRAY_LENGTH",L.ALTER_SET_TYPE="SET DATA TYPE",L.ARRAY_SIZE_DIM_REQUIRED=void 0,L.SUPPORTS_DECODE_CASE=!0,L.ON_CONDITION_EMPTY_BEFORE_ERROR=!1,L.SUPPORTS_BETWEEN_FLAGS=!1,L.SUPPORTS_LIKE_QUANTIFIERS=!0,L.MATCH_AGAINST_TABLE_PREFIX=void 0,L.SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD=!1,L.UPDATE_STATEMENT_SUPPORTS_FROM=!0,L.STAR_EXCLUDE_REQUIRES_DERIVED_TABLE=!0,L.AFTER_HAVING_MODIFIER_TRANSFORMS=new Map([["cluster",function(e){return this.sql(e,"cluster")}],["distribute",function(e){return this.sql(e,"distribute")}],["sort",function(e){return this.sql(e,"sort")}],["windows",function(e){return e.getArgKey("windows")?this.seg("WINDOW ")+this.expressions(e,{key:"windows",flat:!0}):""}],["qualify",function(e){return this.sql(e,"qualify")}]]),L.SAFE_JSON_PATH_KEY_RE=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/,L.SENTINEL_LINE_BREAK="__SQLGLOT__LB__",L.TIME_PART_SINGULARS={MICROSECONDS:"MICROSECOND",SECONDS:"SECOND",MINUTES:"MINUTE",HOURS:"HOUR",DAYS:"DAY",WEEKS:"WEEK",MONTHS:"MONTH",QUARTERS:"QUARTER",YEARS:"YEAR"},L.STRUCT_DELIMITER=["<",">"],L.PARAMETER_TOKEN="@",L.NAMED_PLACEHOLDER_TOKEN=":",L.RESERVED_KEYWORDS=new Set,L.EXPRESSIONS_WITHOUT_NESTED_CTES=new Set,L.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES=new Set;function YV(n,e){return new L(e).generate(n)}var SF,mF,mM;mF=[O],SF=[O];var IT=class IT{static get TIMESTAMP_EXPRESSIONS(){return new Set([ir,Jt,Xs,Tc,Hx,Us])}static get EXPRESSION_METADATA(){let e=new Map,t=(s,r)=>{for(let i of s)e.set(i,r)};return t([hl,lr,UP,Qx,aP,oP,cP,pP],{returns:"BIGINT"}),t([$C,Bh],{returns:"BINARY"}),t([qs,wt,Fs,Et,Qy,Kb,js,it,rb,Kx,Al,dl,lc,hg],{returns:"BOOLEAN"}),t([xn,Hp,kC,Wa,Vp,vh,ar,al,Ue],{returns:"DATE"}),t([lC,fC,Uc,qc],{returns:"DATETIME"}),t([Mp,sy,wp,ty,_s,Lp,ry,hT,rp,_p,py,Dp,jp,TT,Ga,Vr,Ub,zp,eo,Zp,Ka,Hh,kp,cy,$a,sw,rw,nw,Up,wx,Cy,xT,xl,aw],{returns:"DOUBLE"}),t([Oy,eT,Ir,xC,KC,Jx,Va,DC,ul,Yp,Si,Er,rl,ps,ll,Kp],{returns:"INT"}),t([ze,jy,Jy,Xy,NC],{returns:"INTERVAL"}),e.set(up,{returns:"Json"}),t([Ba,np,tP,Fh,LC],{returns:"TIME"}),e.set(lP,{returns:"TIMESTAMPLTZ"}),t([uC,uP],{returns:"TIMESTAMPTZ"}),IT.TIMESTAMP_EXPRESSIONS.forEach(s=>e.set(s,{returns:"TIMESTAMP"})),t([Zr,Kr,ur,Bp,Qr,Js,Un,xi,qn,RC,OC],{returns:"TINYINT"}),t([qp,Vt,xs,sp,vp,SC,UC,Ar,tr,cp,hi,Pb,el,Qa,Ms,Gy,Ns,sP,or,YC,Gh,qx,rP,mc,El,Ep,jc,eP],{returns:"VARCHAR"}),t([xy,Ic,wP,By,Uh,ti,On,fT,Ct,ke,oT,Fe],{annotator:(s,r)=>s.annotateByArgs(r,["this"])}),t([Pn,St,op,Pg,rn,fl],{annotator:(s,r)=>s.annotateByArgs(r,["this","expressions"])}),t([vy,Fy],{annotator:(s,r)=>s.annotateByArrayElement(r)}),t([ut,Wt,Bs],{annotator:(s,r)=>s.annotateTimeunit(r)}),t([Z,Ft],{annotator:(s,r)=>s.setType(r,r.args.to)}),t([Eo,gr],{annotator:(s,r)=>s.annotateMap(r)}),e.set(st,{annotator:(s,r)=>s.setType(r,s.schema.getUdfType(r))}),e.set(Ne,{annotator:(s,r)=>s.annotateByArgs(r,["expressions"],{array:!0})}),e.set(nr,{annotator:(s,r)=>s.annotateByArgs(r,["this"],{array:!0})}),e.set(fs,{annotator:(s,r)=>s.annotateBracket(r)}),e.set(Ht,{annotator:(s,r)=>s.annotateByArgs(r,[...Xe(_nullishCoalesce(r.args.ifs, () => ([])),He).flatMap(i=>_nullishCoalesce(i.args.true, () => ([]))),"default"])}),e.set(uc,{annotator:(s,r)=>s.setType(r,r.args.bigInt?"bigint":"int")}),e.set(ks,{annotator:(s,r)=>s.setType(r,r.args.bigInt?"bigint":"int")}),e.set(C,{annotator:(s,r)=>s.setType(r,r.copy())}),e.set(jt,{annotator:(s,r)=>s.annotateDiv(r)}),e.set(ct,{annotator:(s,r)=>s.annotateByArgs(r,["expressions"])}),e.set(me,{annotator:(s,r)=>s.annotateDot(r)}),e.set(qt,{annotator:(s,r)=>s.annotateExplode(r)}),e.set(Zn,{annotator:(s,r)=>s.annotateExtract(r)}),e.set(Xi,{annotator:(s,r)=>s.setType(r,r.args.isInteger?"bigint":"binary")}),e.set(Os,{annotator:(s,r)=>s.annotateByArgs(r,["start","end","step"],{array:!0})}),e.set(Mn,{annotator:(s,r)=>s.setType(r,C.build("ARRAY<DATE>"))}),e.set(jx,{annotator:(s,r)=>s.setType(r,C.build("ARRAY<TIMESTAMP>"))}),e.set(He,{annotator:(s,r)=>s.annotateByArgs(r,["true","false"])}),e.set(w,{annotator:(s,r)=>s.annotateLiteral(r)}),e.set(Qt,{returns:"NULL"}),e.set(zx,{annotator:(s,r)=>s.annotateByArgs(r,["this","expression"])}),e.set(At,{annotator:(s,r)=>s.annotateByArgs(r,["expression"])}),e.set(Hs,{annotator:(s,r)=>s.annotateStruct(r)}),e.set(tw,{annotator:(s,r)=>s.annotateByArgs(r,["this","expressions"],{promote:!0})}),e.set($p,{annotator:(s,r)=>s.setType(r,r.args.withTz?"timestamptz":"timestamp")}),e.set(tT,{annotator:(s,r)=>s.annotateToMap(r)}),e.set(Pe,{annotator:(s,r)=>s.annotateUnnest(r)}),e.set(ae,{annotator:(s,r)=>s.annotateSubquery(r)}),e.set(rt,{annotator:(s,r)=>s.annotateUnary(r)}),e.set(Ps,{annotator:(s,r)=>s.annotateUnary(r)}),e.set(bn,{annotator:(s,r)=>s.annotateUnary(r)}),e.set(Ye,{annotator:(s,r)=>s.annotateUnary(r)}),e.set(Se,{annotator:(s,r)=>s.annotateUnary(r)}),e}};mM=re(null),T(mM,10,"TIMESTAMP_EXPRESSIONS",mF,IT),T(mM,10,"EXPRESSION_METADATA",SF,IT),te(mM,IT),se(mM,3,IT);var gs=IT;function VV(n){let e=n.args.this;if(!D(e,h))return n;let t=e.type;return this.setType(n,e.isType(C.INTEGER_TYPES)?"double":D(t,C)?t:void 0),n}function WV(n){let e=n.args.this,t=n.args.expression;return D(e,h)&&D(t,h)&&e.isType(C.INTEGER_TYPES)&&t.isType(C.INTEGER_TYPES)?this.setType(n,"double"):NF.call(this,n)}function NF(n){let e=n.args.this,t=n.args.expression,s=D(e,h)?e.type:void 0,r=D(t,h)?t.type:void 0;return this.setType(n,this.maybeCoerce(D(s,C)?s:void 0,D(r,C)?r:void 0)),n}function RF(n){let e=n.args.this,t=D(e,h)?e.type:void 0,s=D(t,C)?t:new C({this:"unknown"}),r=new C({this:"struct",expressions:[s,new C({this:"bigint"})],nested:!0});return this.setType(n,new C({this:"array",expressions:[r],nested:!0})),n}function jV(n,e){return n.annotateByArgs(e,["expressions"]),e.isType(["binary","unknown"])||n.setType(e,"varchar"),e}function JV(n,e){let t=e.args.expressions;if(t&&t.length===1){let s=t[0];if(!D(s,h))return e;let r=s.unnest(),i;if(r instanceof $){let a=_optionalChain([r, 'access', _1148 => _1148.meta, 'optionalAccess', _1149 => _1149.queryType]),o=D(a,C)?a:void 0;if(o&&o.isType("struct")&&_optionalChain([o, 'access', _1150 => _1150.args, 'access', _1151 => _1151.expressions, 'optionalAccess', _1152 => _1152.length])===1){let c=o.args.expressions[0];if(D(c,we)){let p=c.args.kind;D(p,C)&&!p.isType("unknown")&&(i=p)}}}else if(r instanceof be){let a=n.getSetopColumnTypes(r),o=r.left;if(a&&D(o,ce)&&0<o.selects.length){let c=o.selects[0].aliasOrName;i=a[c]}}if(i&&!(i instanceof C&&i.isType("unknown")||i==="unknown")){let a=i instanceof C?i.copy():new C({this:i}),o=new C({this:"array",expressions:[a],nested:!0});return n.setType(e,o),e}}return n.annotateByArgs(e,["expressions"],{array:!0}),e}var OF,KD;OF=[O];var UR=class{static get EXPRESSION_METADATA(){let e=new Map(gs.EXPRESSION_METADATA),t=(s,r)=>{for(let i of s)e.set(i,r)};return t([hT,Ir,jp,wn,Ga,Vr,Ka,$a],{annotator:(s,r)=>VV.call(s,r)}),t([Wr,jr,ut,Bs,TC,AT,tr,dn,Zt,DP,Ja,hi,rT,_P,Fa,Xh,br,Xa,Qp,za,Bi,Xp,_n,bx,Wb,rl,Ms,er,qx,or,Ep],{annotator:(s,r)=>s.annotateByArgs(r,["this"])}),t([Rc,kh,Oc,Nc,Ux,qP,Sy,ET,bC,Er,BP,YP,vb,iT,aT],{returns:"bigint"}),t([Qc,My,en,el,Qa,tl,sl,mi],{returns:"binary"}),t([fy,yC],{returns:"boolean"}),t([Sb,Jh],{returns:"datetime"}),t([Cr,pT,Lx,ny,mT,ST,iy,ay,iw,Dx,my,CC,GP,xr,Px,oy],{returns:"double"}),t([ab,hb,gb,pp,lb,ob,cb],{returns:"json"}),t([Tb,Ti,_C,pl],{returns:"time"}),t([Dy,Zx,_b,Rr,ub,PC,Ec,wg,kb,Jb,tn,Ao],{returns:"varchar"}),t([yc,Hb,Hh,Vb,jb],{annotator:(s,r)=>NF.call(s,r)}),t([mP,Eb,kn,nl],{annotator:(s,r)=>s.annotateByArgs(r,["this"],{array:!0})}),gs.TIMESTAMP_EXPRESSIONS.forEach(s=>e.set(s,{returns:"timestamptz"})),e.set(uT,{annotator:(s,r)=>RF.call(s,r)}),e.set(SP,{annotator:(s,r)=>RF.call(s,r)}),e.set(Ne,{annotator:JV}),e.set(Vt,{annotator:jV}),e.set(Yx,{returns:"date"}),e.set(jx,{annotator:(s,r)=>s.setType(r,C.build("ARRAY<TIMESTAMP>",{dialect:"bigquery"}))}),e.set(Sc,{annotator:(s,r)=>s.setType(r,r.args.toJson?"json":"varchar")}),e.set(ib,{annotator:(s,r)=>s.setType(r,C.build("ARRAY<VARCHAR>",{dialect:"bigquery"}))}),e.set(pb,{annotator:(s,r)=>s.setType(r,C.build("ARRAY<VARCHAR>",{dialect:"bigquery"}))}),e.set(LP,{annotator:(s,r)=>s.annotateByArgs(r,["this","default"])}),e.set(db,{returns:"bigdecimal"}),e.set(Ab,{returns:"decimal"}),e.set(Hh,{annotator:(s,r)=>WV.call(s,r)}),e.set(Iy,{annotator:(s,r)=>s.setType(r,C.build("ARRAY<BIGINT>",{dialect:"bigquery"}))}),e}};KD=re(null),T(KD,10,"EXPRESSION_METADATA",OF,UR),te(KD,UR),se(KD,3,UR);var IF,QD;IF=[O];var qR=class{static get EXPRESSION_METADATA(){let e=new Map(gs.EXPRESSION_METADATA),t=(s,r)=>{for(let i of s)e.set(i,r)};return t([eT,Zr,Kr,ur,Qr,Jx,Er,Xx,Js,Kp,ja,Un,qn],{returns:"bigint"}),t([Jp],{returns:"int128"}),t([Cr,_x,xr,Za],{returns:"double"}),e.set(mC,{returns:"interval"}),e.set(Ti,{returns:"time"}),e}};QD=re(null),T(QD,10,"EXPRESSION_METADATA",IF,qR),te(QD,qR),se(QD,3,qR);var yF,ZD;yF=[O];var Cc=class{static get EXPRESSION_METADATA(){let e=new Map(gs.EXPRESSION_METADATA),t=(s,r)=>{for(let i of s)e.set(i,r)};return t([Wp,mi],{returns:"binary"}),t([pT,Gp],{returns:"double"}),t([Fx,qh,ap,ac,Qp,za,tn],{returns:"varchar"}),t([Vh,Jp],{returns:"bigint"}),t([Js,ja],{returns:"int"}),e.set(St,{annotator:(s,r)=>s.annotateByArgs(r,["this","expressions"],{promote:!0})}),e.set(He,{annotator:(s,r)=>s.annotateByArgs(r,["true","false"],{promote:!0})}),e.set($h,{returns:"ARRAY<STRING>"}),e.set(Xp,{annotator:(s,r)=>s.annotateByArgs(r,["this"])}),e}};ZD=re(null),T(ZD,10,"EXPRESSION_METADATA",yF,Cc),te(ZD,Cc),se(ZD,3,Cc);var CF,e_;CF=[O];var Zh=class{static get EXPRESSION_METADATA(){let e=new Map(gs.EXPRESSION_METADATA),t=(s,r)=>{for(let i of s)e.set(i,r)};return t([Cr,Mx],{returns:"double"}),t([Dn,wC],{returns:"varchar"}),t([Kr,ur,Qr,Js,ja,Un],{returns:"int"}),e.set(np,{returns:"datetime"}),e}};e_=re(null),T(e_,10,"EXPRESSION_METADATA",CF,Zh),te(e_,Zh),se(e_,3,Zh);var bF,t_;bF=[O];var eg=class{static get EXPRESSION_METADATA(){let e=new Map(gs.EXPRESSION_METADATA),t=(s,r)=>{for(let i of s)e.set(i,r)};return t([Cn,bn,ui,Ei,Er,Si,ps,lT],{returns:"bigint"}),t([Ir,wn,Ka,rl],{annotator:(s,r)=>s.annotateByArgs(r,["this"])}),e.set(Hr,{annotator:(s,r)=>s.annotateByArgs(r,["this","expression"])}),e.set(xr,{annotator:(s,r)=>r.args.this?s.annotateByArgs(r,["this"]):s.setType(r,"double")}),e.set(en,{returns:"varbinary"}),e}};t_=re(null),T(t_,10,"EXPRESSION_METADATA",bF,eg),te(t_,eg),se(t_,3,eg);var XV=new Set(["DAY","WEEK","MONTH","QUARTER","YEAR"]),lw=38,zV=37;function KV(n){return this.annotateByArgs(n,["this"]),n.isType("null")&&this.setType(n,"varchar"),n}function QV(n){return n.args.zone?this.setType(n,"timestamptz"):this.setType(n,"timestamp"),n}function PF(n){let e=n.args.this;return D(e,h)&&e.isType("date")&&!XV.has(n.text("unit").toUpperCase())?this.setType(n,"timestampntz"):this.annotateByArgs(n,["this"]),n}function ZV(n){let e=_nullishCoalesce(n.args.expressions, () => ([])),t=[];for(let r=2;r<e.length;r+=2)t.push(e[r].type);e.length%2===0&&t.push(e[e.length-1].type);let s;for(let r of t){let i=D(r,C)?r:void 0;s=this.maybeCoerce(s||i,i)}return this.setType(n,s),n}function wF(n){let e=n.args.this,t=D(e,h)?e.type:void 0;return this.setType(n,n.args.count?"array":D(t,C)?t:void 0),n}function eW(n){let e=n.args.this,t=n.args.expression,s=D(t,ke)?_nullishCoalesce(t.args.expressions, () => ([])):[];if((D(e,Xh)||D(e,yc))&&D(t,ke)&&s.length===1&&D(s[0],es)){let r=s[0].args.this,i=D(r,h)?r.type:void 0;this.setType(n,D(i,C)?i:void 0)}return n}function tW(n){this.annotateByArgs(n,["this"]);let e=n.args.this,t=D(e,h)?e.type:void 0;if(!D(t,C))return n;if(t.isType("double"))this.setType(n,"double");else{let s=Xe(_nullishCoalesce(t.args.expressions, () => ([])),h),r=s[0]?Number(s[0].text("this")):lw,i=s[1]?Number(s[1].text("this")):0,a=Math.min(r+3,lw),o=Math.min(i+3,zV),c=C.build(`NUMBER(${a}, ${o})`,{dialect:"snowflake"});this.setType(n,c)}return n}function sW(n){this.annotateByArgs(n,["this"]);let e=n.args.this,t=D(e,h)?e.type:void 0;if(!D(t,C))return n;if(t.isType("decfloat"))this.setType(n,C.build("DECFLOAT",{dialect:"snowflake"}));else if(t.isType(["float","double"]))this.setType(n,"double");else{let s=Xe(_nullishCoalesce(t.args.expressions, () => ([])),h),r=s[1]?Number(s[1].text("this")):0,i=r===0?6:Math.max(12,r),a=C.build(`NUMBER(${lw}, ${i})`,{dialect:"snowflake"});this.setType(n,a)}return n}function rW(n){this.annotateByArgs(n,["this"]);let e=n.args.this,t=D(e,h)?e.type:void 0;return D(t,C)?(t.isType("decfloat")?this.setType(n,C.build("DECFLOAT",{dialect:"snowflake"})):t.isType(["float","double"])?this.setType(n,"double"):this.setType(n,C.build(`NUMBER(${lw}, 12)`,{dialect:"snowflake"})),n):(this.setType(n,C.build(`NUMBER(${lw}, 12)`,{dialect:"snowflake"})),n)}function nW(n){this.annotateByArgs(n,["this"]);let e=n.args.this;if(D(e,h)&&e.isType("decfloat")){let t=e.type;this.setType(n,D(t,C)?t:void 0)}else this.setType(n,"double");return n}function iW(n){let e=n.args.targetType,t=D(e,C)?e:"timestamp";return this.setType(n,t),n}var MF,s_;MF=[O];var vR=class{static get EXPRESSION_METADATA(){let e=new Map(gs.EXPRESSION_METADATA),t=(s,r)=>{for(let i of s)e.set(i,r)};return t([Lb,Ir,Bs,wn,Ja,FP,Fa,_n,Ka,il,Ms,MC,er],{annotator:(s,r)=>s.annotateByArgs(r,["this"])}),t([uT,Ty,Ne,nr,Ng,Uy,Pn,qy,Ig,RE,Wy,vn,MP,yb,kn,nl,$y],{returns:"array"}),t([hy,Ey,kx,Jp,yP,wb,Mb,xr,Yb,gP],{returns:"bigint"}),t([HC,AP,fP,eb,tb,qC,vC,FC,BC,Xi,en,tl,sl,Wx,jC,XC,mi],{returns:"binary"}),t([dy,gy,Ay,dP,GC,nb,Ob,Qb,Zb,Ny],{returns:"boolean"}),t([EP,IC],{returns:"date"}),t([Rc,Oc,Nc,Fb,iT,yy],{annotator:(s,r)=>s.setType(r,C.build("NUMBER",{dialect:"snowflake"}))}),t([qb,IP,Lx,mT,ST,ly,Dx,uy,Gp,Db],{returns:"double"}),t([by,Py],{returns:"decfloat"}),t([wp,Mp,Lp,Cr,rp,_p,Dp,Mx,jp,Ga,Vr,zp,Zp,jP,WP,JP,XP,zP,ew,KP,QP,ZP,HP,VP,kp,$a,Up,wx],{annotator:(s,r)=>nW.call(s,r)}),t([Ux,ET,_x,bb,Xx,mb,ja,Bb,Gb,$b,lT],{returns:"int"}),t([$P,RP,xP,TP,kP,xb,fb,hP],{returns:"object"}),t([Rb,Nb,Ib,Cb],{returns:"map"}),e.set(wy,{returns:"file"}),t([Ti,pl],{returns:"time"}),t([ir,ip],{returns:"timestampltz"}),e.set(Kp,{returns:"tinyint"}),t([bP,_y,PP,VC,WC,zy,Ky,vl,vx,Zy,eC,tC,sC,Fx,rC,nC,iC,aC,oC,Dn,cC,pC,dC,hC,Cg,gC,EC,sb,QC,ZC,sT,nT,br,Xa,Qp,za,tn,Xb,zb,JC,zC,Ao],{returns:"varchar"}),t([OP,NP],{returns:"variant"}),t([xT,xl],{annotator:(s,r)=>sW.call(s,r)}),e.set(Wr,{annotator:(s,r)=>wF.call(s,r)}),e.set(jr,{annotator:(s,r)=>wF.call(s,r)}),e.set(xs,{annotator:(s,r)=>s.annotateByArgs(r,["expressions"])}),e.set(Qn,{annotator:(s,r)=>s.setType(r,r.args.sourceTz?"timestampntz":"timestamptz")}),e.set(ut,{annotator:(s,r)=>PF.call(s,r)}),e.set(bg,{annotator:(s,r)=>ZV.call(s,r)}),e.set(CP,{annotator:(s,r)=>s.setType(r,C.build("NUMBER(19, 0)",{dialect:"snowflake"}))}),e.set(TT,{annotator:(s,r)=>rW.call(s,r)}),e.set(vP,{annotator:(s,r)=>tW.call(s,r)}),e.set(Xp,{annotator:(s,r)=>KV.call(s,r)}),e.set(Jt,{annotator:(s,r)=>iW.call(s,r)}),e.set(Fh,{annotator:(s,r)=>PF.call(s,r)}),e.set(Jh,{annotator:(s,r)=>QV.call(s,r)}),e.set(Cs,{annotator:(s,r)=>eW.call(s,r)}),e}};s_=re(null),T(s_,10,"EXPRESSION_METADATA",MF,vR),te(s_,vR),se(s_,3,vR);function LF(n,e,t){let s=[];for(let a of e){let o=n.args[a];if(o){let c=Array.isArray(o)?o:[o];s.push(...Xe(c,h))}}let r,i=!1;for(let a of s)if(a.isType("unknown"))i=!0;else if(a.isType(t)){i=!1,r=t;break}else{let o=a.type;r=D(o,C)?o:void 0}return this.setType(n,i?"unknown":r),n}var DF,r_;DF=[O];var tg=class{static get EXPRESSION_METADATA(){let e=new Map(Cc.EXPRESSION_METADATA),t=(s,r)=>{for(let i of s)e.set(i,r)};return t([Cr,Eg],{returns:"double"}),t([Zx,_n],{returns:"varchar"}),e.set(Vt,{annotator:(s,r)=>LF.call(s,r,["expressions"],"text")}),e.set(Fa,{annotator:(s,r)=>LF.call(s,r,["this","fillPattern"],"text")}),e.set(Ms,{annotator:(s,r)=>s.annotateByArgs(r,["this"])}),e}};r_=re(null),T(r_,10,"EXPRESSION_METADATA",DF,tg),te(r_,tg),se(r_,3,tg);var _F,n_;_F=[O];var FR=class{static get EXPRESSION_METADATA(){let e=new Map(tg.EXPRESSION_METADATA),t=(s,r)=>{for(let i of s)e.set(i,r)};return t([Px],{returns:"double"}),t([vx,Bx,sT,nT,Fp],{returns:"varchar"}),e.set(kx,{returns:"bigint"}),e.set(ip,{returns:"timestampntz"}),e.set(Wx,{returns:"binary"}),e.set(Yx,{returns:"date"}),e.set(lr,{returns:"int"}),e.set(Mg,{annotator:(s,r)=>s.annotateByArgs(r,["this"])}),e}};n_=re(null),T(n_,10,"EXPRESSION_METADATA",_F,FR),te(n_,FR),se(n_,3,FR);var kF,i_;kF=[O];var BR=class{static get EXPRESSION_METADATA(){let e=new Map(gs.EXPRESSION_METADATA),t=(s,r)=>{for(let i of s)e.set(i,r)};return t([wp,Mp,Lp,Cr,_p,Dp,kp,Up],{returns:"float"}),t([tn,il],{returns:"varchar"}),e.set(Bx,{returns:"nvarchar"}),e.set(Zp,{annotator:(s,r)=>s.annotateByArgs(r,["this"])}),e}};i_=re(null),T(i_,10,"EXPRESSION_METADATA",kF,BR),te(i_,BR),se(i_,3,BR);var aW={"\\a":"\x07","\\b":"\b","\\f":"\f","\\n":`
|
|
16
|
+
`,"\\r":"\r","\\t":" ","\\v":"\v","\\\\":"\\"};var Qh=(Je=>(Je.DIALECT="",Je.ATHENA="athena",Je.BIGQUERY="bigquery",Je.CLICKHOUSE="clickhouse",Je.DATABRICKS="databricks",Je.DORIS="doris",Je.DREMIO="dremio",Je.DRILL="drill",Je.DRUID="druid",Je.DUCKDB="duckdb",Je.DUNE="dune",Je.FABRIC="fabric",Je.HIVE="hive",Je.MATERIALIZE="materialize",Je.MYSQL="mysql",Je.ORACLE="oracle",Je.POSTGRES="postgres",Je.PRESTO="presto",Je.PRQL="prql",Je.REDSHIFT="redshift",Je.RISINGWAVE="risingwave",Je.SINGLESTORE="singlestore",Je.SNOWFLAKE="snowflake",Je.SOLR="solr",Je.SPARK="spark",Je.SPARK2="spark2",Je.SQLITE="sqlite",Je.STARROCKS="starrocks",Je.TABLEAU="tableau",Je.TERADATA="teradata",Je.TRINO="trino",Je.TSQL="tsql",Je.EXASOL="exasol",Je))(Qh||{}),uw=(i=>(i.LOWERCASE="lowercase",i.UPPERCASE="uppercase",i.CASE_SENSITIVE="caseSensitive",i.CASE_INSENSITIVE="caseInsensitive",i.CASE_INSENSITIVE_UPPERCASE="caseInsensitiveUppercase",i))(uw||{}),UF,qF,vF,FF,BF,GF,$F,YF,HF,VF,WF,jF,JF,XF,zF,KF,QF,ZF,eB,tB,sB,rB,nB,iB,aB,Rt;aB=[O],iB=[O],nB=[O],rB=[O],sB=[O],tB=[O],eB=[O],ZF=[O],QF=[O],KF=[O],zF=[O],XF=[O],JF=[O],jF=[O],WF=[O],VF=[O],HF=[O],YF=[O],$F=[O],GF=[O],BF=[O],FF=[O],vF=[O],qF=[O],UF=[O];var F=class F{constructor(e={}){this.version=void 0;this.normalizationStrategy=void 0;this.settings=void 0;let{version:t=Number.MAX_SAFE_INTEGER,normalizationStrategy:s}=e,r=t.toString().split(".");for(;r.length<3;)r.push("0");this.version={major:parseInt(r[0]),minor:parseInt(r[1]),patch:parseInt(r[2])},this.normalizationStrategy=_nullishCoalesce(As(uw,s), () => (this._constructor.NORMALIZATION_STRATEGY)),this.settings=e;for(let i of Object.keys(e))this._constructor.SUPPORTED_SETTINGS.has(i)||_L("setting",i,[...this._constructor.SUPPORTED_SETTINGS])}static get SUPPORTS_COLUMN_JOIN_MARKS(){return!!this.tokenizerClass.KEYWORDS["(+)"]}static get NULL_ORDERING(){return"nulls_are_small"}static get TIME_MAPPING(){return{}}static get FORMAT_MAPPING(){return{}}static get UNESCAPED_SEQUENCES(){let e={};return this.STRINGS_SUPPORT_ESCAPED_SEQUENCES||this.BYTE_STRINGS_SUPPORT_ESCAPED_SEQUENCES?e={...aW,...this.ORIGINAL_UNESCAPED_SEQUENCES}:e=this.ORIGINAL_UNESCAPED_SEQUENCES,e}static get PSEUDOCOLUMNS(){return new Set}static get SET_OP_DISTINCT_BY_DEFAULT(){return{except:!0,intersect:!0,union:!0}}static get CREATABLE_KIND_MAPPING(){return{}}static get INITCAP_SUPPORTS_CUSTOM_DELIMITERS(){return["","bigquery","snowflake"].includes(this.DIALECT_NAME)}static get DEFAULT_FUNCTIONS_COLUMN_NAMES(){return new Map}static get DEFAULT_NULL_TYPE(){return"unknown"}static get UNMERGABLE_ARGS(){return new Set(Array.from($.availableArgs).filter(e=>!["expressions","from","joins","where","order","hint"].includes(e)))}static get TRY_SUPPORTED(){return["","athena","presto","trino","duckdb"].includes(this.DIALECT_NAME)}static get SUPPORTS_UESCAPE(){return["","athena","presto","trino","duckdb"].includes(this.DIALECT_NAME)}static get tokenizerClass(){let e=this._tokenizerClassCache.get(this);if(e)return e;if(Object.prototype.hasOwnProperty.call(this,"Tokenizer"))return this.Tokenizer;let s=_optionalChain([Object, 'access', _1153 => _1153.getPrototypeOf, 'call', _1154 => _1154(this), 'optionalAccess', _1155 => _1155.tokenizerClass]);if(!s)return this._tokenizerClassCache.set(this,Dt),Dt;class r extends s{}return this._tokenizerClassCache.set(this,r),r}static get jsonpathTokenizerClass(){let e=this._jsonpathTokenizerClassCache.get(this);if(e)return e;if(Object.prototype.hasOwnProperty.call(this,"JsonPathTokenizer"))return this.JsonPathTokenizer;let s=_optionalChain([Object, 'access', _1156 => _1156.getPrototypeOf, 'call', _1157 => _1157(this), 'optionalAccess', _1158 => _1158.JsonPathTokenizer]);if(!s)return this._jsonpathTokenizerClassCache.set(this,zs),zs;class r extends s{}return this._jsonpathTokenizerClassCache.set(this,r),r}static get parserClass(){let e=this._parserClassCache.get(this);if(e)return e;if(Object.prototype.hasOwnProperty.call(this,"Parser"))return this.Parser;let s=_optionalChain([Object, 'access', _1159 => _1159.getPrototypeOf, 'call', _1160 => _1160(this), 'optionalAccess', _1161 => _1161.parserClass]);if(!s)return this._parserClassCache.set(this,he),he;class r extends s{}return this._parserClassCache.set(this,r),r}static get generatorClass(){let e=this._generatorClassCache.get(this);if(e)return e;if(Object.prototype.hasOwnProperty.call(this,"Generator"))return this.Generator;let s=_optionalChain([Object, 'access', _1162 => _1162.getPrototypeOf, 'call', _1163 => _1163(this), 'optionalAccess', _1164 => _1164.generatorClass]);if(!s)return this._generatorClassCache.set(this,L),L;class r extends s{}return this._generatorClassCache.set(this,r),r}static get TIME_TRIE(){return hr(Object.keys(this.TIME_MAPPING).map(e=>Array.from(e)))}static get FORMAT_TRIE(){let e=0<Object.keys(this.FORMAT_MAPPING).length?this.FORMAT_MAPPING:this.TIME_MAPPING;return hr(Object.keys(e).map(t=>Array.from(t)))}static get INVERSE_TIME_MAPPING(){return Object.fromEntries(Object.entries(this.TIME_MAPPING).map(([e,t])=>[t,e]))}static get INVERSE_TIME_TRIE(){return hr(Object.keys(this.INVERSE_TIME_MAPPING).map(e=>Array.from(e)))}static get INVERSE_FORMAT_MAPPING(){return Object.fromEntries(Object.entries(this.FORMAT_MAPPING).map(([e,t])=>[t,e]))}static get INVERSE_CREATABLE_KIND_MAPPING(){return Object.fromEntries(Object.entries(this.CREATABLE_KIND_MAPPING).map(([e,t])=>[t,e]))}static get ESCAPED_SEQUENCES(){return Object.fromEntries(Object.entries(this.UNESCAPED_SEQUENCES).map(([e,t])=>[t,e]))}static get QUOTE_START(){return _optionalChain([Object, 'access', _1165 => _1165.entries, 'call', _1166 => _1166(this.tokenizerClass._QUOTES), 'access', _1167 => _1167[0], 'optionalAccess', _1168 => _1168[0]])}static get QUOTE_END(){return _optionalChain([Object, 'access', _1169 => _1169.entries, 'call', _1170 => _1170(this.tokenizerClass._QUOTES), 'access', _1171 => _1171[0], 'optionalAccess', _1172 => _1172[1]])}static get IDENTIFIER_START(){return _optionalChain([Object, 'access', _1173 => _1173.entries, 'call', _1174 => _1174(this.tokenizerClass._IDENTIFIERS), 'access', _1175 => _1175[0], 'optionalAccess', _1176 => _1176[0]])}static get IDENTIFIER_END(){return _optionalChain([Object, 'access', _1177 => _1177.entries, 'call', _1178 => _1178(this.tokenizerClass._IDENTIFIERS), 'access', _1179 => _1179[0], 'optionalAccess', _1180 => _1180[1]])}static getStartEnd(e){let t=Object.entries(this.tokenizerClass._FORMAT_STRINGS).find(([s,[r,i]])=>i===e);if(t){let[s,[r]]=t;return[s,r]}return[void 0,void 0]}static get BIT_START(){return this.getStartEnd("bitString")[0]}static get BIT_END(){return this.getStartEnd("bitString")[1]}static get HEX_START(){return this.getStartEnd("hexString")[0]}static get HEX_END(){return this.getStartEnd("hexString")[1]}static get BYTE_START(){return this.getStartEnd("byteString")[0]}static get BYTE_END(){return this.getStartEnd("byteString")[1]}static get UNICODE_START(){return this.getStartEnd("unicodeString")[0]}static get UNICODE_END(){return this.getStartEnd("unicodeString")[1]}static get DATE_PART_MAPPING(){return{Y:"YEAR",YY:"YEAR",YYY:"YEAR",YYYY:"YEAR",YR:"YEAR",YEARS:"YEAR",YRS:"YEAR",MM:"MONTH",MON:"MONTH",MONS:"MONTH",MONTHS:"MONTH",D:"DAY",DD:"DAY",DAYS:"DAY",DAYOFMONTH:"DAY","DAY OF WEEK":"DAYOFWEEK",WEEKDAY:"DAYOFWEEK",DOW:"DAYOFWEEK",DW:"DAYOFWEEK",WEEKDAY_ISO:"DAYOFWEEKISO",DOW_ISO:"DAYOFWEEKISO",DW_ISO:"DAYOFWEEKISO",DAYOFWEEK_ISO:"DAYOFWEEKISO","DAY OF YEAR":"DAYOFYEAR",DOY:"DAYOFYEAR",DY:"DAYOFYEAR",W:"WEEK",WK:"WEEK",WEEKOFYEAR:"WEEK",WOY:"WEEK",WY:"WEEK",WEEK_ISO:"WEEKISO",WEEKOFYEARISO:"WEEKISO",WEEKOFYEAR_ISO:"WEEKISO",Q:"QUARTER",QTR:"QUARTER",QTRS:"QUARTER",QUARTERS:"QUARTER",H:"HOUR",HH:"HOUR",HR:"HOUR",HOURS:"HOUR",HRS:"HOUR",M:"MINUTE",MI:"MINUTE",MIN:"MINUTE",MINUTES:"MINUTE",MINS:"MINUTE",S:"SECOND",SEC:"SECOND",SECONDS:"SECOND",SECS:"SECOND",MS:"MILLISECOND",MSEC:"MILLISECOND",MSECS:"MILLISECOND",MSECOND:"MILLISECOND",MSECONDS:"MILLISECOND",MILLISEC:"MILLISECOND",MILLISECS:"MILLISECOND",MILLISECON:"MILLISECOND",MILLISECONDS:"MILLISECOND",US:"MICROSECOND",USEC:"MICROSECOND",USECS:"MICROSECOND",MICROSEC:"MICROSECOND",MICROSECS:"MICROSECOND",USECOND:"MICROSECOND",USECONDS:"MICROSECOND",MICROSECONDS:"MICROSECOND",NS:"NANOSECOND",NSEC:"NANOSECOND",NANOSEC:"NANOSECOND",NSECOND:"NANOSECOND",NSECONDS:"NANOSECOND",NANOSECS:"NANOSECOND",EPOCH_SECOND:"EPOCH",EPOCH_SECONDS:"EPOCH",EPOCH_MILLISECONDS:"EPOCH_MILLISECOND",EPOCH_MICROSECONDS:"EPOCH_MICROSECOND",EPOCH_NANOSECONDS:"EPOCH_NANOSECOND",TZH:"TIMEZONE_HOUR",TZM:"TIMEZONE_MINUTE",DEC:"DECADE",DECS:"DECADE",DECADES:"DECADE",MIL:"MILLENNIUM",MILS:"MILLENNIUM",MILLENIA:"MILLENNIUM",C:"CENTURY",CENT:"CENTURY",CENTS:"CENTURY",CENTURIES:"CENTURY"}}static get COERCES_TO(){return new Map}static get EXPRESSION_METADATA(){return gs.EXPRESSION_METADATA}static get SUPPORTED_SETTINGS(){return new Set(["normalizationStrategy","version"])}static get QUOTE_DELIMITERS(){return Object.entries(this.tokenizerClass.QUOTES)[0]}static get IDENTIFIER_DELIMITERS(){return Object.entries(this.tokenizerClass.IDENTIFIERS)[0]}static get BASE_VALID_INTERVAL_UNITS(){return new Set}static get VALID_INTERVAL_UNITS(){let e=this.DATE_PART_MAPPING;return new Set([...this.BASE_VALID_INTERVAL_UNITS,...Object.keys(e),...Object.values(e)])}static get STRINGS_SUPPORT_ESCAPED_SEQUENCES(){return this.tokenizerClass.STRING_ESCAPES.includes("\\")}static get BYTE_STRINGS_SUPPORT_ESCAPED_SEQUENCES(){return this.tokenizerClass.BYTE_STRING_ESCAPES.includes("\\")}static equals(e){return this===e?!0:typeof e=="string"?this===this.get(e):e instanceof F?this===e.constructor:!1}static register(e,t){this.registry.set(e,t)}static get(e,t){return this.registry.get(e)||t}static getOrRaise(e){if(!e)return new this;if(typeof e=="function"&&(e===F||e.prototype instanceof F))return new e;if(e instanceof F)return e;if(typeof e=="string"){let t,s={};try{let[i,...a]=e.split(",");t=i.trim();for(let o of a){let c=o.split("="),p=c[0].trim(),u=!0;c.length===2&&(u=c[1].trim()),s[p]=_nullishCoalesce(XU(u), () => (u))}}catch (e14){throw new Error(`Invalid dialect format: '${e}'. Please use the correct format: 'dialect [, k1 = v2 [, ...]]'.`)}let r=this.get(t);if(!r){let i=new Set(Object.keys(Qh));_L("dialect",t,Array.from(i))}return new r(s)}throw new Error(`Invalid dialect type for '${e}': '${typeof e}'.`)}static formatTime(e){return typeof e=="string"?w.string(_nullishCoalesce(dg(e.slice(1,-1),this.TIME_MAPPING,this.TIME_TRIE), () => (""))):e instanceof h&&e.isString?w.string(_nullishCoalesce(dg(e.args.this,this.TIME_MAPPING,this.TIME_TRIE), () => (""))):e}equals(e){return this===e?!0:e instanceof F?this.constructor===e.constructor:!1}hash(){return this.constructor.name.toLowerCase()}normalizeIdentifier(e){if(e instanceof G&&this.normalizationStrategy!=="caseSensitive"&&(!e.args.quoted||this.normalizationStrategy==="caseInsensitive"||this.normalizationStrategy==="caseInsensitiveUppercase")){let t=this.normalizationStrategy==="uppercase"||this.normalizationStrategy==="caseInsensitiveUppercase",s=e.args.this;if(typeof s=="string"){let r=t?s.toUpperCase():s.toLowerCase();e.setArgKey("this",r)}}return e}caseSensitive(e){if(this.normalizationStrategy==="caseInsensitive")return!1;let t=this.normalizationStrategy==="uppercase"?s=>s===s.toLowerCase()&&s!==s.toUpperCase():s=>s===s.toUpperCase()&&s!==s.toLowerCase();return Array.from(e).some(t)}canQuote(e,t={}){let{identify:s="safe"}=t;if(e.args.quoted)return!0;if(!s)return!1;if(s===!0)return!0;let r=_nullishCoalesce(e.name, () => ("")),i=!this.caseSensitive(r)&&cw.test(r);if(s==="safe")return i;if(s==="unsafe")return!i;throw new Error(`Unexpected argument for identify: '${s}'`)}quoteIdentifier(e,t={}){let{identify:s=!0}=t;return e instanceof G&&e.setArgKey("quoted",this.canQuote(e,{identify:s||"unsafe"})),e}toJsonPath(e){if(e instanceof w){let t=e.name;e.isNumber&&(t=`[${t}]`);try{return $D(t,{dialect:this})}catch(s){let r=this._constructor.STRICT_JSON_PATH_SYNTAX,i=t.trimStart(),a=i.startsWith("lax")||i.startsWith("strict");r&&!a&&console.warn(`Invalid JSON path syntax. ${s instanceof Error?s.message:String(s)}`)}}return e}parse(e,t){return this.parser(t).parse(this.tokenize(e),e)}parser(e){return new this._constructor.parserClass({dialect:this,...e})}parseIntoTypes(e,t,s){return this.parser(s).parseIntoTypes(e,this.tokenize(t),t)}generate(e,t={}){let{copy:s=!0,...r}=t;return this.generator(r).generate(e,{copy:s})}generator(e={}){return new this._constructor.generatorClass({dialect:this,...e})}tokenize(e,t={}){return this.tokenizer(t).tokenize(e)}tokenizer(e={}){return new this._constructor.tokenizerClass({dialect:this,...e})}jsonpathTokenizer(e={}){return new this._constructor.jsonpathTokenizerClass({dialect:this,...e})}transpile(e,t={}){return this.parse(e,t).map(s=>s?this.generate(s,{copy:!1,...t}):"")}generateValuesAliases(e){let t=_optionalChain([e, 'access', _1181 => _1181.args, 'access', _1182 => _1182.expressions, 'optionalAccess', _1183 => _1183[0]]);return t instanceof h?(_nullishCoalesce(t.args.expressions, () => ([]))).map((r,i)=>K(`_col_${i}`)):[]}get _constructor(){return this.constructor}};Rt=re(null),T(Rt,10,"NULL_ORDERING",aB,F),T(Rt,10,"TIME_MAPPING",iB,F),T(Rt,10,"FORMAT_MAPPING",nB,F),T(Rt,10,"UNESCAPED_SEQUENCES",rB,F),T(Rt,10,"PSEUDOCOLUMNS",sB,F),T(Rt,10,"SET_OP_DISTINCT_BY_DEFAULT",tB,F),T(Rt,10,"CREATABLE_KIND_MAPPING",eB,F),T(Rt,10,"DEFAULT_FUNCTIONS_COLUMN_NAMES",ZF,F),T(Rt,10,"DEFAULT_NULL_TYPE",QF,F),T(Rt,10,"UNMERGABLE_ARGS",KF,F),T(Rt,10,"TIME_TRIE",zF,F),T(Rt,10,"FORMAT_TRIE",XF,F),T(Rt,10,"INVERSE_TIME_MAPPING",JF,F),T(Rt,10,"INVERSE_TIME_TRIE",jF,F),T(Rt,10,"INVERSE_FORMAT_MAPPING",WF,F),T(Rt,10,"INVERSE_CREATABLE_KIND_MAPPING",VF,F),T(Rt,10,"ESCAPED_SEQUENCES",HF,F),T(Rt,10,"DATE_PART_MAPPING",YF,F),T(Rt,10,"COERCES_TO",$F,F),T(Rt,10,"EXPRESSION_METADATA",GF,F),T(Rt,10,"SUPPORTED_SETTINGS",BF,F),T(Rt,10,"QUOTE_DELIMITERS",FF,F),T(Rt,10,"IDENTIFIER_DELIMITERS",vF,F),T(Rt,10,"BASE_VALID_INTERVAL_UNITS",qF,F),T(Rt,10,"VALID_INTERVAL_UNITS",UF,F),te(Rt,F),se(Rt,3,F),F.DIALECT_NAME="",F.INDEX_OFFSET=0,F.WEEK_OFFSET=0,F.UNNEST_COLUMN_ONLY=!1,F.ALIAS_POST_TABLESAMPLE=!1,F.TABLESAMPLE_SIZE_IS_PERCENT=!1,F.NORMALIZATION_STRATEGY="lowercase",F.IDENTIFIERS_CAN_START_WITH_DIGIT=!1,F.DPIPE_IS_STRING_CONCAT=!0,F.STRICT_STRING_CONCAT=!1,F.SUPPORTS_USER_DEFINED_TYPES=!0,F.SUPPORTS_SEMI_ANTI_JOIN=!0,F.COPY_PARAMS_ARE_CSV=!0,F.NORMALIZE_FUNCTIONS="upper",F.PRESERVE_ORIGINAL_NAMES=!1,F.LOG_BASE_FIRST=!0,F.TYPED_DIVISION=!1,F.SAFE_DIVISION=!1,F.CONCAT_COALESCE=!1,F.HEX_LOWERCASE=!1,F.DATE_FORMAT="'%Y-%m-%d'",F.DATEINT_FORMAT="'%Y%m%d'",F.TIME_FORMAT="'%Y-%m-%d %H:%M:%S'",F.ORIGINAL_UNESCAPED_SEQUENCES={},F.PREFER_CTE_ALIAS_COLUMN=!1,F.FORCE_EARLY_ALIAS_REF_EXPANSION=!1,F.EXPAND_ONLY_GROUP_ALIAS_REF=!1,F.ANNOTATE_ALL_SCOPES=!1,F.DISABLES_ALIAS_REF_EXPANSION=!1,F.SUPPORTS_ALIAS_REFS_IN_JOIN_CONDITIONS=!1,F.SUPPORTS_ORDER_BY_ALL=!1,F.PROJECTION_ALIASES_SHADOW_SOURCE_NAMES=!1,F.TABLES_REFERENCEABLE_AS_COLUMNS=!1,F.SUPPORTS_STRUCT_STAR_EXPANSION=!1,F.EXCLUDES_PSEUDOCOLUMNS_FROM_STAR=!1,F.QUERY_RESULTS_ARE_STRUCTS=!1,F.REQUIRES_PARENTHESIZED_STRUCT_ACCESS=!1,F.SUPPORTS_NULL_TYPE=!1,F.COALESCE_COMPARISON_NON_STANDARD=!1,F.HAS_DISTINCT_ARRAY_CONSTRUCTORS=!1,F.SUPPORTS_FIXED_SIZE_ARRAYS=!1,F.STRICT_JSON_PATH_SYNTAX=!0,F.ON_CONDITION_EMPTY_BEFORE_ERROR=!0,F.ARRAY_AGG_INCLUDES_NULLS=!0,F.ARRAY_FUNCS_PROPAGATES_NULLS=!1,F.PROMOTE_TO_INFERRED_DATETIME_TYPE=!1,F.SUPPORTS_VALUES_DEFAULT=!0,F.NUMBERS_CAN_BE_UNDERSCORE_SEPARATED=!1,F.HEX_STRING_IS_INTEGER_TYPE=!1,F.REGEXP_EXTRACT_DEFAULT_GROUP=0,F.REGEXP_EXTRACT_POSITION_OVERFLOW_RETURNS_NULL=!0,F.ALTER_TABLE_SUPPORTS_CASCADE=!1,F.ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN=!0,F.TRY_CAST_REQUIRES_STRING=void 0,F.SAFE_TO_ELIMINATE_DOUBLE_NEGATION=!0,F.INITCAP_DEFAULT_DELIMITER_CHARS=`
|
|
17
|
+
\r\f\v!"#$%&'()*+,\\-./:;<=>?@\\[\\]^_\`{|}~`,F.BYTE_STRING_IS_BYTES_TYPE=!1,F.UUID_IS_STRING_TYPE=!1,F.JSON_EXTRACT_SCALAR_SCALAR_ONLY=!1,F.LEAST_GREATEST_IGNORES_NULLS=!0,F.PRIORITIZE_NON_LITERAL_TYPES=!1,F._tokenizerClassCache=new WeakMap,F._jsonpathTokenizerClassCache=new WeakMap,F._parserClassCache=new WeakMap,F._generatorClassCache=new WeakMap,F.registry=new Map;var W=F;W.register("",W);function X(n){return function(e){let s=e._constructor.argOrder;if(s&&0<s.length){let a=s.map(o=>e.getArgKey(o)).filter(o=>o!==void 0).reduce((o,c)=>Array.isArray(c)?o.concat(c):o.concat([c]),[]);return this.func(n,a)}let r=Object.values(e.args).filter(i=>i!==void 0);return this.func(n,r)}}function oB(n){return so.call(this,n,"accuracy"),this.func("APPROX_COUNT_DISTINCT",[n.args.this])}function RM(n="IF",e){return function(t){return t.parent instanceof Ht?`WHEN ${this.sql(t,"this")} THEN ${this.sql(t,"true")}`:this.func(n,[t.args.this,t.args.true,t.args.false||e])}}function cB(n){let e=n.args.this;if(this._constructor.JSON_TYPE_REQUIRED_FOR_EXTRACTION&&e instanceof w&&e.isString){let s=new C({this:"json"});e.replace(Le(e.copy(),s))}let t=n instanceof Zt?"->":"->>";return this.binary(n,t)}function GR(n){let e=new Ws({this:new hi({this:n.args.this}),expression:new hi({this:n.args.expression})});return this.likeSql(e)}function pB(n){let e=this.sql(n,"this");return e?`CURRENT_DATE AT TIME ZONE ${e}`:"CURRENT_DATE"}function lB(n){return n.args.recursive&&(this.unsupported("Recursive CTEs are unsupported"),n.setArgKey("recursive",!1)),this.withSql(n)}function uB(n){return this.unsupported("TABLESAMPLE unsupported"),this.sql(n.args.this)}function OM(n){return this.unsupported("PIVOT unsupported"),""}function NM(n){return this.castSql(n)}function EB(n){return`${this.propertyName(n,{stringKey:!0})}=${this.sql(n,"value")}`}function $R(n,e={}){let{funcName:t="STRPOS",supportsPosition:s=!1,supportsOccurrence:r=!1,useAnsiPosition:i=!0}=e,a=n.args.this,o=n.args.substr,c=n.args.position,p=n.args.occurrence,u=w.number(0),E=w.number(1);r&&p&&s&&!c&&(c=E);let g=c&&!s;g&&(a=new Ms({this:a,start:c}));let A;if(t==="POSITION"&&i)A=new st({this:t,expressions:[new it({this:o,field:a})]});else{let x=t==="LOCATE"||t==="CHARINDEX"?[o,a]:[a,o];s&&c!==void 0&&x.push(c),p&&(r?x.push(p):this.unsupported(`${t} does not support the occurrence parameter.`)),A=new st({this:t,expressions:x.filter(m=>m!==void 0)})}if(g){let x=new dt({this:new lt({this:A,expression:c}),expression:E}),m=new He({this:A.eq(u),true:u,false:x});return this.sql(m)}return this.sql(A)}function IM(n){return`${this.sql(n,"this")}.${this.sql(K(_nullishCoalesce(_optionalChain([n, 'access', _1184 => _1184.args, 'access', _1185 => _1185.expression, 'optionalAccess', _1186 => _1186.name]), () => (""))))}`}function a_(n,e="MAP"){let t=n.args.keys,s=n.args.values;if(!(t instanceof Ne)||!(s instanceof Ne))return this.unsupported("Cannot convert array columns into map."),this.func(e,[...pe(t),...pe(s)]);let r=[],i=t.args.expressions,a=s.args.expressions;for(let o=0;o<Math.min(_optionalChain([i, 'optionalAccess', _1187 => _1187.length])||0,_optionalChain([a, 'optionalAccess', _1188 => _1188.length])||0);o++)r.push(this.sql(_optionalChain([i, 'optionalAccess', _1189 => _1189[o]]))),r.push(this.sql(_optionalChain([a, 'optionalAccess', _1190 => _1190[o]])));return this.func(e,r)}function Ri(n,e){let{dialect:t,defaultValue:s}=e;return r=>new n({this:b(r,0),format:_optionalChain([W, 'access', _1191 => _1191.get, 'call', _1192 => _1192(t), 'optionalAccess', _1193 => _1193.formatTime, 'call', _1194 => _1194(b(r,1)||(s===!0?_optionalChain([W, 'access', _1195 => _1195.get, 'call', _1196 => _1196(t), 'optionalAccess', _1197 => _1197.TIME_FORMAT]):void 0))])})}function o_(n){return function(e){let t=this.formatTime(e);return t!==_optionalChain([W, 'access', _1198 => _1198.getOrRaise, 'call', _1199 => _1199(n), 'optionalAccess', _1200 => _1200._constructor, 'access', _1201 => _1201.TIME_FORMAT])?t:void 0}}function JT(n,e,t={}){let{defaultUnit:s="DAY",supportsTimezone:r=!1}=t;return i=>{let a=3<=i.length,o=i.length===4,c=a?i[2]:b(i,0),p;if(a||s){p=a?i[0]:w.string(s);let E=_optionalChain([p, 'access', _1202 => _1202.name, 'optionalAccess', _1203 => _1203.toLowerCase, 'call', _1204 => _1204()]);if(e&&E&&e[E]&&(p=Te(e[E])),(p instanceof Ze||p instanceof k||p instanceof w)&&!(p instanceof k&&p.parts.length!==1)){let g={D:"DAY",H:"HOUR",M:"MINUTE",MS:"MILLISECOND",NS:"NANOSECOND",Q:"QUARTER",S:"SECOND",US:"MICROSECOND",W:"WEEK",Y:"YEAR"};p=new Ze({this:(g[p.name]||p.name).toUpperCase()})}}let u=new n({this:c,expression:b(i,1),unit:p});return r&&o&&u.setArgKey("zone",i[i.length-1]),u}}function yM(n){return e=>{if(e.length<2)throw new Error(`Expected at least 2 arguments but got ${e.length}`);let t=e[1];if(!(t instanceof ze))throw new Error(`INTERVAL expression expected but got '${t}'`);return new n({this:e[0],expression:t.args.this,unit:ro(t)})}}function hB(n){let e=b(n,0),t=b(n,1);return t instanceof Z&&t.isType("date")?new Bs({unit:e,this:t}):new er({this:t,unit:e})}function c_(n,e){return function(t){let s=this.sql(t,"this"),r=new ze({this:t.args.expression,unit:LM(t)});return`${n}_${e}(${s}, ${this.sql(r)})`}}function gB(n={}){let{func:e="DATE_TRUNC",zone:t=!1}=n;return function(s){let r=[ro(s),s.args.this];return t&&r.push(s.args.zone),this.func(e,r)}}function CM(n){return this.sql(new Ms({this:n.args.this,start:w.number(1),length:n.args.expression}))}function bM(n){return this.sql(new Ms({this:n.args.this,start:new dt({this:new Er({this:n.args.this}),expression:new Ye({this:new dt({this:n.args.expression,expression:w.number(1)})})})}))}function Tl(n,e={}){let{includePrecision:t=!1}=e,s=C.build(n.args.zone?"timestamptz":"timestamp");if(n.args.this instanceof w&&t){let r=KU(n.args.this.name);0<r&&s&&(s=C.build(s.args.this,{expressions:new Jr({this:w.number(r)})}))}return this.sql(Le(n.args.this,s,{dialect:this.dialect}))}function YR(n){let e=n.args.this,t=e instanceof h||typeof e=="string"?e:"";return this.sql(Le(t,"date"))}function p_(n,e,t={}){let{replace:s=!0}=t,r=n.args.charset;return r&&!["utf-8","utf8"].includes(_optionalChain([r, 'access', _1205 => _1205.name, 'optionalAccess', _1206 => _1206.toLowerCase, 'call', _1207 => _1207()]))&&this.unsupported(`Expected utf-8 character set, got ${r}.`),this.func(e,[n.args.this,s?n.getArgKey("replace"):void 0])}function PM(n){let e=0<(_nullishCoalesce(_optionalChain([n, 'access', _1208 => _1208.args, 'access', _1209 => _1209.expressions, 'optionalAccess', _1210 => _1210.length]), () => (0)))?"LEAST":"MIN";return X(e).call(this,n)}function wM(n){let e=0<(_nullishCoalesce(_optionalChain([n, 'access', _1211 => _1211.args, 'access', _1212 => _1212.expressions, 'optionalAccess', _1213 => _1213.length]), () => (0)))?"GREATEST":"MAX";return X(e).call(this,n)}function HR(n,e={}){let{defaultTrimType:t=""}=e,s=this.sql(n,"this"),r=this.sql(n,"position")||t,i=this.sql(n,"expression"),a=this.sql(n,"collation");if(!i)return this.trimSql(n);let o=r?`${r} `:"",c=i?`${i} `:"",p=o||c?"FROM ":"",u=a?` COLLATE ${a}`:"";return`TRIM(${o}${c}${p}${s}${u})`}function xF(n){return this.sql((_nullishCoalesce(n.args.expressions, () => ([]))).reduce((e,t)=>new Ar({this:e,expression:t})))}function VR(n){let e=n.args.group;return e&&e.name===String(this.dialect._constructor.REGEXP_EXTRACT_DEFAULT_GROUP)&&(e=void 0),this.func(n._constructor.sqlName(),[n.args.this,n.args.expression,e])}function dB(n){return this.func("REGEXP_REPLACE",[n.args.this,n.args.expression,n.args.replacement])}function MM(n){return e=>new n({this:b(e,0),expression:b(e,1)})}function AB(n){let e=this.sql(n.left),t=this.sql(n.right);return`(${e} AND (NOT ${t})) OR ((NOT ${e}) AND {b})`}function fB(n){return n instanceof up||n instanceof Z&&n.isType("json")}function xB(n){return new Ye({this:new Ut({this:b(n,0),expression:Ke()})})}function l_(n){return function(e){return this.func(n,[e.args.this,e.args.expression])}}function TB(n){if(!n.args.this)return n;let e=n.args.this.copy(),t=n.returnType;return ue(t,C),t.isType("date")&&(e=Le(e,"timestamp")),_optionalChain([n, 'access', _1214 => _1214.args, 'access', _1215 => _1215.this, 'optionalAccess', _1216 => _1216.replace, 'call', _1217 => _1217(Le(e,t))]),n}function ro(n,e={}){let{defaultValue:t="DAY"}=e,s=n.args.unit;return s instanceof w,s?s instanceof rr||!(s instanceof Ze||s instanceof w||s instanceof G||s instanceof k)?s:w.string(s.name.toUpperCase()):t?w.string(t):void 0}function LM(n,e={}){let{defaultValue:t="DAY"}=e,s=n.args.unit;if(s instanceof Ze||s instanceof rr||s instanceof k)return s;let r=_optionalChain([s, 'optionalAccess', _1218 => _1218.name, 'access', _1219 => _1219.toUpperCase, 'call', _1220 => _1220()])||t;return r?Te(r):void 0}function TF(n,e={}){let{dialect:t=W}=e;if(n===void 0)return n;let s=n instanceof h?n.name:n,r=n instanceof h&&!(n instanceof k)&&_optionalChain([n, 'access', _1221 => _1221.parts, 'optionalAccess', _1222 => _1222.length])!==1?W.getOrRaise(t)._constructor.DATE_PART_MAPPING[s.toUpperCase()]:void 0;return r?n instanceof h&&n.isString?w.string(r):typeof n=="string"?w.string(n):Te(r):n instanceof h?n:w.string(n)}function SB(n){let e=_optionalChain([n, 'access', _1223 => _1223.args, 'access', _1224 => _1224.this, 'optionalAccess', _1225 => _1225.args, 'access', _1226 => _1226.alias]),t=i=>i?this.dialect.normalizeIdentifier(i).name:void 0,s=_optionalChain([n, 'access', _1227 => _1227.args, 'access', _1228 => _1228.this, 'optionalAccess', _1229 => _1229.args, 'access', _1230 => _1230.this]),r=new Set([t(D(s,h)?s:void 0)]);D(e,h)&&r.add(typeof e.args.this=="string"?e.args.this:t(D(e.args.this,h)?e.args.this:void 0));for(let i of _optionalChain([n, 'access', _1231 => _1231.args, 'access', _1232 => _1232.whens, 'optionalAccess', _1233 => _1233.args, 'access', _1234 => _1234.expressions])||[]){if(!D(i,Ji))continue;let a=i.args.then;if(a instanceof sr)for(let o of a.findAll(Ee)){let c=o.args.this;c instanceof k&&r.has(t(typeof c.args.table=="string"?K(c.args.table):c.args.table))&&c.replace(new k({this:c.args.this}))}else if(a instanceof Ss){let o=a.args.this;if(o instanceof Mt)for(let c of o.args.expressions||[]){if(!(c instanceof h))continue;let p=c,u=p.getArgKey("table");(p.args.this instanceof G||p.args.this instanceof ye)&&u&&r.has(u instanceof h?t(u):u.toString())&&p.replace(new k({this:p.args.this}))}}}return this.mergeSql(n)}function mB(n){return this.func(`SHA${n.text("length")||"256"}`,[n.args.this])}function RB(n){return this.func(`SHA${n.text("length")||"256"}`,[n.args.this])}function WR(n){let e=n,t=e.args.start,s=e.args.end,r=e.args.step,i=t instanceof Z?t.args.to:s instanceof Z?s.args.to:void 0;if(t!==void 0&&s!==void 0&&(wi(i,["date","timestamp"])&&(ue(i,C),t instanceof Z&&i===t.to?s=Le(s,i):t=Le(t,i)),D(e,Os)&&e.args.isEndExclusive)){let a=r||w.number(1),o=new dt({this:s,expression:a});s=new Ye({this:o});let c=new st({this:"SEQUENCE",expressions:[t,s,...r?[r]:[]]}),p=w.number(0),u=bs([new Ee({this:a.copy(),expression:p.copy()}),nt([new It({this:a.copy(),expression:p.copy()}),new xt({this:t.copy(),expression:s.copy()})]),nt([new Tt({this:a.copy(),expression:p.copy()}),new yt({this:t.copy(),expression:s.copy()})])]),E=new He({this:u,true:new Ne({expressions:[]}),false:c});return this.sql(this.simplifyUnlessLiteral(E))}return this.func("SEQUENCE",[t,s,r])}function jR(n){return(e,{dialect:t})=>{let s={this:b(e,0),expression:b(e,1),group:b(e,2)||w.number(t._constructor.REGEXP_EXTRACT_DEFAULT_GROUP),parameters:b(e,3)};return n===br&&(s.nullIfPosOverflow=t._constructor.REGEXP_EXTRACT_POSITION_OVERFLOW_RETURNS_NULL),new n(s)}}function OB(n){let e=n.args.this,t=n.args.alias,s;if(e instanceof gl&&t){ue(t,ie);let[r,...i]=t.args.columns||[];ue(r,G);let a=i.filter(c=>c instanceof h),o=ft([oe(r.sub(1),r),...a]).from(new Pe({expressions:[...e.args.this?[e.args.this]:[]],offset:!0,alias:new ie({this:t.args.this,columns:[...a,r]})}));s=new kt({this:o.subquery()})}else e instanceof qt&&(s=new Pe({expressions:[...e.args.this?[e.args.this]:[]],alias:t}));return s?this.sql(new z({this:s,kind:"cross"})):this.lateralSql(n)}function NB(n){return this.func(n.args.binary?"LENGTH":"CHAR_LENGTH",[n.args.this])}function IB(n,e={}){let{funcName:t="LISTAGG",sep:s=",",withinGroup:r=!0,onOverflow:i=!1}=e,a=n.args.this,o=this.sql(n.args.separator||(s?w.string(s):void 0)),c=i&&this.sql(n,"on_overflow")?` ON OVERFLOW ${this.sql(n,"on_overflow")}`:"",p;a instanceof Ct&&(p=a,a=_optionalChain([p, 'access', _1235 => _1235.args, 'access', _1236 => _1236.this, 'optionalAccess', _1237 => _1237.pop, 'call', _1238 => _1238()]));let u=_optionalChain([a, 'optionalAccess', _1239 => _1239.find, 'call', _1240 => _1240(ke)]);_optionalChain([u, 'optionalAccess', _1241 => _1241.args, 'access', _1242 => _1242.this])&&(a=u.args.this.pop());let E=[a,o?`${o}${c}`:c||void 0].filter(Boolean).join(", "),g=new st({this:t,expressions:[E]}),A=this.sql(p);return u&&(r?g=new Cs({this:g,expression:u}):A=`${this.sql(u)}${A}`),A&&g.setArgKey("expressions",[`${E}${A}`]),this.sql(g)}function yB(n){return new za({this:b(n,0),expression:b(n,1),replacement:b(n,2)||w.string("")})}var gi=(f=>(f.L_PAREN="lParen",f.R_PAREN="rParen",f.L_BRACKET="lBracket",f.R_BRACKET="rBracket",f.L_BRACE="lBrace",f.R_BRACE="rBrace",f.COMMA="comma",f.DOT="dot",f.DASH="dash",f.PLUS="plus",f.COLON="colon",f.DOTCOLON="dotcolon",f.DCOLON="dcolon",f.DCOLONDOLLAR="dcolondollar",f.DCOLONPERCENT="dcolonpercent",f.DCOLONQMARK="dcolonqmark",f.DQMARK="dqmark",f.SEMICOLON="semicolon",f.STAR="star",f.BACKSLASH="backslash",f.SLASH="slash",f.LT="lt",f.LTE="lte",f.GT="gt",f.GTE="gte",f.NOT="not",f.EQ="eq",f.NEQ="neq",f.NULLSAFE_EQ="nullsafeEq",f.COLON_EQ="colonEq",f.COLON_GT="colonGt",f.NCOLON_GT="ncolonGt",f.AND="and",f.OR="or",f.AMP="amp",f.DPIPE="dpipe",f.PIPE_GT="pipeGt",f.PIPE="pipe",f.PIPE_SLASH="pipeSlash",f.DPIPE_SLASH="dpipeSlash",f.CARET="caret",f.CARET_AT="caretAt",f.TILDE="tilde",f.ARROW="arrow",f.DARROW="darrow",f.FARROW="farrow",f.HASH="hash",f.HASH_ARROW="hashArrow",f.DHASH_ARROW="dhashArrow",f.LR_ARROW="lrArrow",f.DAT="dat",f.LT_AT="ltAt",f.AT_GT="atGt",f.DOLLAR="dollar",f.PARAMETER="parameter",f.SESSION="session",f.SESSION_PARAMETER="sessionParameter",f.SESSION_USER="sessionUser",f.DAMP="damp",f.AMP_LT="ampLt",f.AMP_GT="ampGt",f.ADJACENT="adjacent",f.XOR="xor",f.DSTAR="dstar",f.QMARK_AMP="qmarkAmp",f.QMARK_PIPE="qmarkPipe",f.HASH_DASH="hashDash",f.EXCLAMATION="exclamation",f.URI_START="uriStart",f.BLOCK_START="blockStart",f.BLOCK_END="blockEnd",f.SPACE="space",f.BREAK="break",f.STRING="string",f.NUMBER="number",f.IDENTIFIER="identifier",f.DATABASE="database",f.COLUMN="column",f.COLUMN_DEF="columnDef",f.SCHEMA="schema",f.TABLE="table",f.WAREHOUSE="warehouse",f.STAGE="stage",f.STREAMLIT="streamlit",f.VAR="var",f.BIT_STRING="bitString",f.HEX_STRING="hexString",f.BYTE_STRING="byteString",f.NATIONAL_STRING="nationalString",f.RAW_STRING="rawString",f.HEREDOC_STRING="heredocString",f.UNICODE_STRING="unicodeString",f.BIT="bit",f.BOOLEAN="boolean",f.TINYINT="tinyint",f.UTINYINT="utinyint",f.SMALLINT="smallint",f.USMALLINT="usmallint",f.MEDIUMINT="mediumint",f.UMEDIUMINT="umediumint",f.INT="int",f.UINT="uint",f.BIGINT="bigint",f.UBIGINT="ubigint",f.BIGNUM="bignum",f.INT128="int128",f.UINT128="uint128",f.INT256="int256",f.UINT256="uint256",f.FLOAT="float",f.DOUBLE="double",f.UDOUBLE="udouble",f.DECIMAL="decimal",f.DECIMAL32="decimal32",f.DECIMAL64="decimal64",f.DECIMAL128="decimal128",f.DECIMAL256="decimal256",f.DECFLOAT="decfloat",f.UDECIMAL="udecimal",f.BIGDECIMAL="bigdecimal",f.CHAR="char",f.NCHAR="nchar",f.VARCHAR="varchar",f.NVARCHAR="nvarchar",f.BPCHAR="bpchar",f.TEXT="text",f.MEDIUMTEXT="mediumtext",f.LONGTEXT="longtext",f.BLOB="blob",f.MEDIUMBLOB="mediumblob",f.LONGBLOB="longblob",f.TINYBLOB="tinyblob",f.TINYTEXT="tinytext",f.NAME="name",f.BINARY="binary",f.VARBINARY="varbinary",f.JSON="json",f.JSONB="jsonb",f.TIME="time",f.TIMETZ="timetz",f.TIME_NS="timeNs",f.TIMESTAMP="timestamp",f.TIMESTAMPTZ="timestamptz",f.TIMESTAMPLTZ="timestampltz",f.TIMESTAMPNTZ="timestampntz",f.TIMESTAMP_S="timestampS",f.TIMESTAMP_MS="timestampMs",f.TIMESTAMP_NS="timestampNs",f.DATETIME="datetime",f.DATETIME2="datetime2",f.DATETIME64="datetime64",f.SMALLDATETIME="smalldatetime",f.DATE="date",f.DATE32="date32",f.INT4RANGE="int4range",f.INT4MULTIRANGE="int4multirange",f.INT8RANGE="int8range",f.INT8MULTIRANGE="int8multirange",f.NUMRANGE="numrange",f.NUMMULTIRANGE="nummultirange",f.TSRANGE="tsrange",f.TSMULTIRANGE="tsmultirange",f.TSTZRANGE="tstzrange",f.TSTZMULTIRANGE="tstzmultirange",f.DATERANGE="daterange",f.DATEMULTIRANGE="datemultirange",f.UUID="uuid",f.GEOGRAPHY="geography",f.GEOGRAPHYPOINT="geographypoint",f.NULLABLE="nullable",f.GEOMETRY="geometry",f.POINT="point",f.RING="ring",f.LINESTRING="linestring",f.LOCALTIME="localtime",f.LOCALTIMESTAMP="localtimestamp",f.SYSTIMESTAMP="systimestamp",f.MULTILINESTRING="multilinestring",f.POLYGON="polygon",f.MULTIPOLYGON="multipolygon",f.HLLSKETCH="hllsketch",f.HSTORE="hstore",f.SUPER="super",f.SERIAL="serial",f.SMALLSERIAL="smallserial",f.BIGSERIAL="bigserial",f.XML="xml",f.YEAR="year",f.USERDEFINED="userdefined",f.MONEY="money",f.SMALLMONEY="smallmoney",f.ROWVERSION="rowversion",f.IMAGE="image",f.VARIANT="variant",f.OBJECT="object",f.INET="inet",f.IPADDRESS="ipaddress",f.IPPREFIX="ipprefix",f.IPV4="ipv4",f.IPV6="ipv6",f.ENUM="enum",f.ENUM8="enum8",f.ENUM16="enum16",f.FIXEDSTRING="fixedstring",f.LOWCARDINALITY="lowcardinality",f.NESTED="nested",f.AGGREGATEFUNCTION="aggregatefunction",f.SIMPLEAGGREGATEFUNCTION="simpleaggregatefunction",f.TDIGEST="tdigest",f.UNKNOWN="unknown",f.VECTOR="vector",f.DYNAMIC="dynamic",f.VOID="void",f.ALIAS="alias",f.ALTER="alter",f.ALL="all",f.ANTI="anti",f.ANY="any",f.APPLY="apply",f.ARRAY="array",f.ASC="asc",f.ASOF="asof",f.ATTACH="attach",f.AUTO_INCREMENT="autoIncrement",f.BEGIN="begin",f.BETWEEN="between",f.BULK_COLLECT_INTO="bulkCollectInto",f.CACHE="cache",f.CASE="case",f.CHARACTER_SET="characterSet",f.CLUSTER_BY="clusterBy",f.COLLATE="collate",f.COMMAND="command",f.COMMENT="comment",f.COMMIT="commit",f.CONNECT_BY="connectBy",f.CONSTRAINT="constraint",f.COPY="copy",f.CREATE="create",f.CROSS="cross",f.CUBE="cube",f.CURRENT_DATE="currentDate",f.CURRENT_DATETIME="currentDatetime",f.CURRENT_SCHEMA="currentSchema",f.CURRENT_TIME="currentTime",f.CURRENT_TIMESTAMP="currentTimestamp",f.CURRENT_USER="currentUser",f.CURRENT_ROLE="currentRole",f.CURRENT_CATALOG="currentCatalog",f.DECLARE="declare",f.DEFAULT="default",f.DELETE="delete",f.DESC="desc",f.DESCRIBE="describe",f.DETACH="detach",f.DICTIONARY="dictionary",f.DISTINCT="distinct",f.DISTRIBUTE_BY="distributeBy",f.DIV="div",f.DROP="drop",f.ELSE="else",f.END="end",f.ESCAPE="escape",f.EXCEPT="except",f.EXECUTE="execute",f.EXISTS="exists",f.FALSE="false",f.FETCH="fetch",f.FILE="file",f.FILE_FORMAT="fileFormat",f.FILTER="filter",f.FINAL="final",f.FIRST="first",f.FOR="for",f.FORCE="force",f.FOREIGN_KEY="foreignKey",f.FORMAT="format",f.FROM="from",f.FULL="full",f.FUNCTION="function",f.GET="get",f.GLOB="glob",f.GLOBAL="global",f.GRANT="grant",f.GROUP_BY="groupBy",f.GROUPING_SETS="groupingSets",f.HAVING="having",f.HINT="hint",f.IGNORE="ignore",f.ILIKE="ilike",f.IN="in",f.INDEX="index",f.INDEXED_BY="indexedBy",f.INNER="inner",f.INSERT="insert",f.INSTALL="install",f.INTERSECT="intersect",f.INTERVAL="interval",f.INTO="into",f.INTRODUCER="introducer",f.IRLIKE="irlike",f.IS="is",f.ISNULL="isnull",f.JOIN="join",f.JOIN_MARKER="joinMarker",f.KEEP="keep",f.KEY="key",f.KILL="kill",f.LANGUAGE="language",f.LATERAL="lateral",f.LEFT="left",f.LIKE="like",f.LIMIT="limit",f.LIST="list",f.LOAD="load",f.LOCK="lock",f.MAP="map",f.MATCH="match",f.MATCH_CONDITION="matchCondition",f.MATCH_RECOGNIZE="matchRecognize",f.MEMBER_OF="memberOf",f.MERGE="merge",f.MOD="mod",f.MODEL="model",f.NATURAL="natural",f.NEXT="next",f.NOTHING="nothing",f.NOTNULL="notnull",f.NULL="null",f.OBJECT_IDENTIFIER="objectIdentifier",f.OFFSET="offset",f.ON="on",f.ONLY="only",f.OPERATOR="operator",f.ORDER_BY="orderBy",f.ORDER_SIBLINGS_BY="orderSiblingsBy",f.ORDERED="ordered",f.ORDINALITY="ordinality",f.OUT="out",f.INOUT="inout",f.OUTER="outer",f.OVER="over",f.OVERLAPS="overlaps",f.OVERWRITE="overwrite",f.PARTITION="partition",f.PARTITION_BY="partitionBy",f.PERCENT="percent",f.PIVOT="pivot",f.PLACEHOLDER="placeholder",f.POSITIONAL="positional",f.PRAGMA="pragma",f.PREWHERE="prewhere",f.PRIMARY_KEY="primaryKey",f.PROCEDURE="procedure",f.PROPERTIES="properties",f.PSEUDO_TYPE="pseudoType",f.PUT="put",f.QUALIFY="qualify",f.QUOTE="quote",f.QDCOLON="qdcolon",f.RANGE="range",f.RECURSIVE="recursive",f.REFRESH="refresh",f.RENAME="rename",f.REPLACE="replace",f.RETURNING="returning",f.REVOKE="revoke",f.REFERENCES="references",f.RIGHT="right",f.RLIKE="rlike",f.ROLLBACK="rollback",f.ROLLUP="rollup",f.ROW="row",f.ROWS="rows",f.SELECT="select",f.SEMI="semi",f.SEPARATOR="separator",f.SEQUENCE="sequence",f.SERDE_PROPERTIES="serdeProperties",f.SET="set",f.SETTINGS="settings",f.SHOW="show",f.SIMILAR_TO="similarTo",f.SOME="some",f.SORT_BY="sortBy",f.SOUNDS_LIKE="soundsLike",f.START_WITH="startWith",f.STORAGE_INTEGRATION="storageIntegration",f.STRAIGHT_JOIN="straightJoin",f.STRUCT="struct",f.SUMMARIZE="summarize",f.TABLE_SAMPLE="tableSample",f.TAG="tag",f.TEMPORARY="temporary",f.TOP="top",f.THEN="then",f.TRUE="true",f.TRUNCATE="truncate",f.UNCACHE="uncache",f.UNION="union",f.UNNEST="unnest",f.UNPIVOT="unpivot",f.UPDATE="update",f.USE="use",f.USING="using",f.VALUES="values",f.VARIADIC="variadic",f.VIEW="view",f.SEMANTIC_VIEW="semanticView",f.VOLATILE="volatile",f.WHEN="when",f.WHERE="where",f.WINDOW="window",f.WITH="with",f.UNIQUE="unique",f.UTC_DATE="utcDate",f.UTC_TIME="utcTime",f.UTC_TIMESTAMP="utcTimestamp",f.VERSION_SNAPSHOT="versionSnapshot",f.TIMESTAMP_SNAPSHOT="timestampSnapshot",f.OPTION="option",f.SINK="sink",f.SOURCE="source",f.ANALYZE="analyze",f.NAMESPACE="namespace",f.EXPORT="export",f.HIVE_TOKEN_STREAM="hiveTokenStream",f))(gi||{}),Lg=class n{static number(e){return new n("number",String(e))}static string(e){return new n("string",e)}static identifier(e){return new n("identifier",e)}constructor(e,t,s=1,r=1,i=0,a=0,o=[]){this.tokenType=e,this.text=t,this.line=s,this.col=r,this.start=i,this.end=a,this.comments=o}},CB,bB,PB,wB,MB,LB,DB,_B,kB,UB,Oi;UB=[O],kB=[O],_B=[O],DB=[O],LB=[O],MB=[O],wB=[O],PB=[O],bB=[O],CB=[O];var Me=class Me{constructor(e={}){this.sql="";this.size=0;this.tokens=[];this.dialect=void 0;this._start=0;this._current=0;this.line=1;this._col=0;this.comments=[];this.char="";this._end=!1;this.peek="";this.prevTokenLine=-1;let{dialect:t}=e;this.dialect=W.getOrRaise(t),this.reset()}static get BYTE_STRING_ESCAPES(){return this.STRING_ESCAPES}static get _COMMENTS(){let e={};for(let t of this.COMMENTS)typeof t=="string"?e[t]=void 0:e[t[0]]=t[1];return e["{#"]="#}",this.HINT_START in this.KEYWORDS&&(e[this.HINT_START]="*/"),e}static get _FORMAT_STRINGS(){let e={};for(let[t,s]of Object.entries(this._QUOTES))for(let r of["n","N"])e[r+t]=[s,"nationalString"];return{...e,...this.quotesToFormat("bitString",this.BIT_STRINGS),...this.quotesToFormat("byteString",this.BYTE_STRINGS),...this.quotesToFormat("hexString",this.HEX_STRINGS),...this.quotesToFormat("string",this.RAW_STRINGS),...this.quotesToFormat("heredocString",this.HEREDOC_STRINGS),...this.quotesToFormat("unicodeString",this.UNICODE_STRINGS)}}static get _IDENTIFIERS(){return this.convertQuotes(this.IDENTIFIERS)}static get _IDENTIFIER_ESCAPES(){return new Set(this.IDENTIFIER_ESCAPES)}static get _QUOTES(){return this.convertQuotes(this.QUOTES)}static get _STRING_ESCAPES(){return new Set(this.STRING_ESCAPES)}static get _BYTE_STRING_ESCAPES(){return new Set(this.BYTE_STRING_ESCAPES)}static get _ESCAPE_FOLLOW_CHARS(){return new Set(this.ESCAPE_FOLLOW_CHARS)}static get _KEYWORD_TRIE(){let e=Object.keys(this.SINGLE_TOKENS),t=[...Object.keys(this.KEYWORDS),...Object.keys(this._COMMENTS),...Object.keys(this._QUOTES),...Object.keys(this._FORMAT_STRINGS)];return hr(t.filter(s=>s.includes(" ")||e.some(r=>s.includes(r))).map(s=>Array.from(s.toUpperCase())))}static get KEYWORDS(){return this.ORIGINAL_KEYWORDS}reset(){this.sql="",this.size=0,this.tokens=[],this._start=0,this._current=0,this.line=1,this._col=0,this.comments=[],this.char="",this._end=!1,this.peek="",this.prevTokenLine=-1}tokenize(e){this.reset(),this.sql=e,this.size=e.length;try{this.scan()}catch (e15){let t=Math.max(this._current-50,0),s=Math.min(this._current+50,this.size-1),r=this.sql.slice(t,s);throw new cg(`Error tokenizing '${r}'`)}return this.tokens}scan(e){for(;this.size&&!this._end;){let t=this._current;for(;t<this.size;){let r=this.sql[t];if(this.isWhitespace(r)&&(r===" "||r===" "))t++;else break}let s=this._current<t?t-this._current:1;if(this._start=t,this.advance({i:s}),this.isWhitespace(this.char)||(this.isDigit(this.char)?this.scanNumber():this.char in this._constructor._IDENTIFIERS?this.scanIdentifier(this._constructor._IDENTIFIERS[this.char]):this.scanKeywords()),_optionalChain([e, 'optionalCall', _1243 => _1243()]))break}this.tokens.length&&this.comments.length&&this.tokens[this.tokens.length-1].comments.push(...this.comments)}chars(e){if(e===1)return this.char;let t=this._current-1,s=t+e;return s<=this.size?this.sql.slice(t,s):""}advance(e={}){let{i:t=1,alnum:s=!1}=e;if(this._constructor.WHITE_SPACE[this.char]==="break"?this.char==="\r"&&this.peek===`
|
|
18
|
+
`||(this._col=t,this.line+=1):this._col+=t,this._current+=t,this._end=this.size<=this._current,this.char=this.sql[this._current-1],this.char===void 0)throw new Error("Index out of bound");if(this.peek=this._end?"":this.sql[this._current],s&&this.isAlnum(this.char)){let{_col:i,_current:a,_end:o,peek:c}=this;for(;this.isAlnum(c);)i+=1,a+=1,o=this.size<=a,c=o?"":this.sql[a];this._col=i,this._current=a,this._end=o,this.peek=c,this.char=this.sql[a-1]}}get text(){return this.sql.slice(this._start,this._current)}add(e,t){this.prevTokenLine=this.line,this.comments.length&&e==="semicolon"&&this.tokens.length&&(this.tokens[this.tokens.length-1].comments.push(...this.comments),this.comments=[]),this.tokens.push(new Lg(e,_nullishCoalesce(t, () => (this.text)),this.line,this._col,this._start,this._current-1,this.comments)),this.comments=[];let s=this._constructor;if(s.COMMANDS.has(e)&&this.peek!==";"&&(this.tokens.length===1||s.COMMAND_PREFIX_TOKENS.has(this.tokens[this.tokens.length-2].tokenType))){let r=this._current,i=this.tokens.length;this.scan(()=>this.peek===";"),this.tokens=this.tokens.slice(0,i);let a=this.sql.slice(r,this._current).trim();a&&this.add("string",a)}}scanKeywords(){let e=0,t,s=this.text,r=s,i=!1,a=!1,o=this._constructor,c=o._KEYWORD_TRIE,p=r in this._constructor.SINGLE_TOKENS;for(;s;){let E;if(a?E=1:[E,c]=Il(c,Array.from(r.toUpperCase())),E===0)break;E===2&&(t=s);let g=this._current+e;if(e+=1,g<this.size){r=this.sql[g],p=p||r in this._constructor.SINGLE_TOKENS;let A=this.isWhitespace(r);!A||!i?(A&&(r=" "),s+=r,i=A,a=!1):a=!0}else{r="";break}}if(t){if(this.scanString(t)||this.scanComment(t))return;if(i||p||!r){this.advance({i:e-1});let E=t.toUpperCase();this.add(o.KEYWORDS[E],E);return}}let u=this._constructor.SINGLE_TOKENS[this.char];if(u!==void 0){this.add(u,this.char);return}this.scanVar()}scanComment(e){let t=this._constructor;if(!(e in t._COMMENTS))return!1;let s=this.line,r=e.length,i=t._COMMENTS[e];if(i){this.advance({i:r});let a=1,o=i.length;for(;!this._end&&!(this.chars(o)===i&&(a-=1,!a));)this.advance({alnum:!0}),t.NESTED_COMMENTS&&!this._end&&this.chars(r)===e&&(this.advance({i:r}),a+=1);this.comments.push(this.text.slice(r,-o+1)),this.advance({i:o-1})}else{for(;!this._end&&t.WHITE_SPACE[this.peek]!=="break";)this.advance({i:1,alnum:!0});this.comments.push(this.text.slice(r))}return e===t.HINT_START&&this.tokens.length&&t.TOKENS_PRECEDING_HINT.has(this.tokens[this.tokens.length-1].tokenType)&&this.add("hint"),s===this.prevTokenLine&&(this.tokens[this.tokens.length-1].comments.push(...this.comments),this.comments=[],this.prevTokenLine=this.line),!0}scanNumber(){let e=this._constructor;if(this.char==="0"){let r=this.peek.toUpperCase();if(r==="B")return e.BIT_STRINGS.length?this.scanBits():this.add("number");if(r==="X")return e.HEX_STRINGS.length?this.scanHex():this.add("number")}let t=!1,s=0;for(;;)if(this.isDigit(this.peek))this.advance();else if(this.peek==="."&&!t){if(this.tokens.length&&this.tokens[this.tokens.length-1].tokenType==="parameter")return this.add("number");t=!0,this.advance()}else if(["-","+"].includes(this.peek)&&s===1)if(this._current+1<this.size&&this.isDigit(this.sql[this._current+1]))s+=1,this.advance();else return this.add("number");else if(this.peek.toUpperCase()==="E"&&!s)s+=1,this.advance();else if(this.peek==="_"&&this.dialect._constructor.NUMBERS_CAN_BE_UNDERSCORE_SEPARATED)this.advance();else if(this.isIdentifierChar(this.peek)){let r=this.text,i="";for(;this.peek.trim()&&!this._constructor.SINGLE_TOKENS[this.peek];)i+=this.peek,this.advance();let a=e.KEYWORDS[e.NUMERIC_LITERALS[i.toUpperCase()]||""];return a?(this.add("number",r),this.add("dcolon","::"),this.add(a,i)):this.dialect._constructor.IDENTIFIERS_CAN_START_WITH_DIGIT?this.add("var"):(this.advance({i:-i.length}),this.add("number",r))}else return this.add("number")}scanBits(){this.advance();let e=this.extractValue();Number.isNaN(parseInt(e,2))?this.add("identifier"):this.add("bitString",e.slice(2))}scanHex(){this.advance();let e=this.extractValue();Number.isNaN(parseInt(e,16))?this.add("identifier"):this.add("hexString",e.slice(2))}extractValue(){for(;;){let e=this.peek.trim();if(e&&!this._constructor.SINGLE_TOKENS[e])this.advance({i:1,alnum:!0});else break}return this.text}scanString(e){let t=this._constructor,s,r="string",i;if(e in t._QUOTES)i=t._QUOTES[e];else if(e in t._FORMAT_STRINGS){if([i,r]=t._FORMAT_STRINGS[e],r==="hexString")s=16;else if(r==="bitString")s=2;else if(r==="heredocString"){this.advance();let o;if(this.char===i?o="":o=this.extractString(i,void 0,{rawString:!0,raiseUnmatched:!t.HEREDOC_TAG_IS_IDENTIFIER}),o&&t.HEREDOC_TAG_IS_IDENTIFIER&&(this._end||this.isDigit(o)||this.isWhitespace(o)))return this._end||this.advance({i:-1}),this.advance({i:-o.length}),this.add(t.HEREDOC_STRING_ALTERNATIVE),!0;i=`${e}${o}${i}`}}else return!1;this.advance({i:e.length});let a=this.extractString(i,r==="byteString"?t._BYTE_STRING_ESCAPES:t._STRING_ESCAPES,{rawString:r==="rawString"});if(s&&a&&Number.isNaN(parseInt(a,s)))throw new Error(`Numeric string contains invalid characters from ${this.line}:${this._start}`);return this.add(r,a),!0}scanIdentifier(e){this.advance();let t=this._constructor,s=new Set([...Array.from(t._IDENTIFIER_ESCAPES),e]),r=this.extractString(e,s);this.add("identifier",r)}scanVar(){let e=this._constructor;for(;;){let t=this.peek.trim();if(t&&(e.VAR_SINGLE_TOKENS.has(t)||!this._constructor.SINGLE_TOKENS[t]))this.advance({i:1,alnum:!0});else break}this.add(this.tokens.length&&this.tokens[this.tokens.length-1].tokenType==="parameter"?"var":e.KEYWORDS[this.text.toUpperCase()]||"var")}extractString(e,t=void 0,s={}){let{rawString:r=!1,raiseUnmatched:i=!0}=s,a=this._constructor,o="",c=e.length;for(t=t===void 0?a._STRING_ESCAPES:t;;){if(!r&&this.dialect._constructor.UNESCAPED_SEQUENCES&&this.peek&&t.has(this.char)){let u=this.dialect._constructor.UNESCAPED_SEQUENCES[this.char+this.peek];if(u){this.advance({i:2}),o+=u;continue}}let p=a.ESCAPE_FOLLOW_CHARS.length&&this.char==="\\"&&!a.ESCAPE_FOLLOW_CHARS.includes(this.peek);if((a.STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS||!r)&&t.has(this.char)&&(this.peek===e||t.has(this.peek)||p)&&(!(this.char in a._QUOTES)||this.char===this.peek))if(this.peek===e?o+=this.peek:p&&this.char!==this.peek?o+=this.peek:o+=this.char+this.peek,this._current+1<this.size)this.advance({i:2});else throw new cg(`Missing ${e} from ${this.line}:${this._current}`);else{if(this.chars(c)===e){1<c&&this.advance({i:c-1});break}if(this._end){if(!i)return o+this.char;throw new cg(`Missing ${e} from ${this.line}:${this._start}`)}let u=this._current-1;this.advance({i:1,alnum:!0}),o+=this.sql.slice(u,this._current-1)}}return o}static convertQuotes(e){let t={};for(let s of e){let r=typeof s=="string"?s:s[0],i=typeof s=="string"?s:s[1];t[r]=i}return t}static quotesToFormat(e,t){let s=this.convertQuotes(t),r={};for(let[i,a]of Object.entries(s))r[i]=[a,e];return r}isWhitespace(e){return/\s/.test(e)}isDigit(e){return/\d/.test(e)}isAlnum(e){return/[a-zA-Z0-9]/.test(e)}isIdentifierChar(e){return/[a-zA-Z_]/.test(e)}get _constructor(){return this.constructor}};Oi=re(null),T(Oi,10,"_COMMENTS",UB,Me),T(Oi,10,"_FORMAT_STRINGS",kB,Me),T(Oi,10,"_IDENTIFIERS",_B,Me),T(Oi,10,"_IDENTIFIER_ESCAPES",DB,Me),T(Oi,10,"_QUOTES",LB,Me),T(Oi,10,"_STRING_ESCAPES",MB,Me),T(Oi,10,"_BYTE_STRING_ESCAPES",wB,Me),T(Oi,10,"_ESCAPE_FOLLOW_CHARS",PB,Me),T(Oi,10,"_KEYWORD_TRIE",bB,Me),T(Oi,10,"KEYWORDS",CB,Me),te(Oi,Me),se(Oi,3,Me),Me.SINGLE_TOKENS={"(":"lParen",")":"rParen","[":"lBracket","]":"rBracket","{":"lBrace","}":"rBrace","&":"amp","^":"caret",":":"colon",",":"comma",".":"dot","-":"dash","=":"eq",">":"gt","<":"lt","%":"mod","!":"not","|":"pipe","+":"plus",";":"semicolon","/":"slash","\\":"backslash","*":"star","~":"tilde","?":"placeholder","@":"parameter","#":"hash","'":"unknown","`":"unknown",'"':"unknown"},Me.BIT_STRINGS=[],Me.BYTE_STRINGS=[],Me.HEX_STRINGS=[],Me.RAW_STRINGS=[],Me.HEREDOC_STRINGS=[],Me.IDENTIFIERS=['"'],Me.QUOTES=["'"],Me.UNICODE_STRINGS=[],Me.STRING_ESCAPES=["'"],Me.VAR_SINGLE_TOKENS=new Set,Me.ESCAPE_FOLLOW_CHARS=[],Me.IDENTIFIER_ESCAPES=[],Me.HEREDOC_TAG_IS_IDENTIFIER=!1,Me.HEREDOC_STRING_ALTERNATIVE="var",Me.STRING_ESCAPES_ALLOWED_IN_RAW_STRINGS=!0,Me.NESTED_COMMENTS=!0,Me.HINT_START="/*+",Me.TOKENS_PRECEDING_HINT=new Set(["select","insert","update","delete"]),Me.ORIGINAL_KEYWORDS={"{%":"blockStart","{%+":"blockStart","{%-":"blockStart","%}":"blockEnd","+%}":"blockEnd","-%}":"blockEnd","{{+":"blockStart","{{-":"blockStart","+}}":"blockEnd","-}}":"blockEnd",[Me.HINT_START]:"hint","&<":"ampLt","&>":"ampGt","==":"eq","::":"dcolon","?::":"qdcolon","||":"dpipe","|>":"pipeGt",">=":"gte","<=":"lte","<>":"neq","!=":"neq",":=":"colonEq","<=>":"nullsafeEq","->":"arrow","->>":"darrow","=>":"farrow","#>":"hashArrow","#>>":"dhashArrow","<->":"lrArrow","&&":"damp","??":"dqmark","~~~":"glob","~~":"like","~~*":"ilike","~*":"irlike","-|-":"adjacent",ALL:"all",AND:"and",ANTI:"anti",ANY:"any",ASC:"asc",AS:"alias",ASOF:"asof",AUTOINCREMENT:"autoIncrement",AUTO_INCREMENT:"autoIncrement",BEGIN:"begin",BETWEEN:"between",CACHE:"cache",UNCACHE:"uncache",CASE:"case","CHARACTER SET":"characterSet","CLUSTER BY":"clusterBy",COLLATE:"collate",COLUMN:"column",COMMIT:"commit","CONNECT BY":"connectBy",CONSTRAINT:"constraint",COPY:"copy",CREATE:"create",CROSS:"cross",CUBE:"cube",CURRENT_DATE:"currentDate",CURRENT_SCHEMA:"currentSchema",CURRENT_TIME:"currentTime",CURRENT_TIMESTAMP:"currentTimestamp",CURRENT_USER:"currentUser",CURRENT_CATALOG:"currentCatalog",DATABASE:"database",DEFAULT:"default",DELETE:"delete",DESC:"desc",DESCRIBE:"describe",DISTINCT:"distinct","DISTRIBUTE BY":"distributeBy",DIV:"div",DROP:"drop",ELSE:"else",END:"end",ENUM:"enum",ESCAPE:"escape",EXCEPT:"except",EXECUTE:"execute",EXISTS:"exists",FALSE:"false",FETCH:"fetch",FILTER:"filter",FILE:"file",FIRST:"first",FULL:"full",FUNCTION:"function",FOR:"for","FOREIGN KEY":"foreignKey",FORMAT:"format",FROM:"from",GEOGRAPHY:"geography",GEOMETRY:"geometry",GLOB:"glob","GROUP BY":"groupBy","GROUPING SETS":"groupingSets",HAVING:"having",ILIKE:"ilike",IN:"in",INDEX:"index",INET:"inet",INNER:"inner",INSERT:"insert",INTERVAL:"interval",INTERSECT:"intersect",INTO:"into",IS:"is",ISNULL:"isnull",JOIN:"join",KEEP:"keep",KILL:"kill",LATERAL:"lateral",LEFT:"left",LIKE:"like",LIMIT:"limit",LOAD:"load",LOCALTIME:"localtime",LOCALTIMESTAMP:"localtimestamp",LOCK:"lock",MERGE:"merge",NAMESPACE:"namespace",NATURAL:"natural",NEXT:"next",NOT:"not",NOTNULL:"notnull",NULL:"null",OBJECT:"object",OFFSET:"offset",ON:"on",OR:"or",XOR:"xor","ORDER BY":"orderBy",ORDINALITY:"ordinality",OUT:"out",OUTER:"outer",OVER:"over",OVERLAPS:"overlaps",OVERWRITE:"overwrite",PARTITION:"partition","PARTITION BY":"partitionBy","PARTITIONED BY":"partitionBy",PARTITIONED_BY:"partitionBy",PERCENT:"percent",PIVOT:"pivot",PRAGMA:"pragma","PRIMARY KEY":"primaryKey",PROCEDURE:"procedure",OPERATOR:"operator",QUALIFY:"qualify",RANGE:"range",RECURSIVE:"recursive",REGEXP:"rlike",RENAME:"rename",REPLACE:"replace",RETURNING:"returning",REFERENCES:"references",RIGHT:"right",RLIKE:"rlike",ROLLBACK:"rollback",ROLLUP:"rollup",ROW:"row",ROWS:"rows",SCHEMA:"schema",SELECT:"select",SEMI:"semi",SESSION:"session",SESSION_USER:"sessionUser",SET:"set",SETTINGS:"settings",SHOW:"show","SIMILAR TO":"similarTo",SOME:"some","SORT BY":"sortBy","START WITH":"startWith",STRAIGHT_JOIN:"straightJoin",TABLE:"table",TABLESAMPLE:"tableSample",TEMP:"temporary",TEMPORARY:"temporary",THEN:"then",TRUE:"true",TRUNCATE:"truncate",UNION:"union",UNKNOWN:"unknown",UNNEST:"unnest",UNPIVOT:"unpivot",UPDATE:"update",USE:"use",USING:"using",UUID:"uuid",VALUES:"values",VIEW:"view",VOLATILE:"volatile",WHEN:"when",WHERE:"where",WINDOW:"window",WITH:"with",APPLY:"apply",ARRAY:"array",BIT:"bit",BOOL:"boolean",BOOLEAN:"boolean",BYTE:"tinyint",MEDIUMINT:"mediumint",INT1:"tinyint",TINYINT:"tinyint",INT16:"smallint",SHORT:"smallint",SMALLINT:"smallint",HUGEINT:"int128",UHUGEINT:"uint128",INT2:"smallint",INTEGER:"int",INT:"int",INT4:"int",INT32:"int",INT64:"bigint",INT128:"int128",INT256:"int256",LONG:"bigint",BIGINT:"bigint",INT8:"tinyint",UINT:"uint",UINT128:"uint128",UINT256:"uint256",DEC:"decimal",DECIMAL:"decimal",DECIMAL32:"decimal32",DECIMAL64:"decimal64",DECIMAL128:"decimal128",DECIMAL256:"decimal256",DECFLOAT:"decfloat",BIGDECIMAL:"bigdecimal",BIGNUMERIC:"bigdecimal",BIGNUM:"bignum",LIST:"list",MAP:"map",NULLABLE:"nullable",NUMBER:"decimal",NUMERIC:"decimal",FIXED:"decimal",REAL:"float",FLOAT:"float",FLOAT4:"float",FLOAT8:"double",DOUBLE:"double","DOUBLE PRECISION":"double",JSON:"json",JSONB:"jsonb",CHAR:"char",CHARACTER:"char","CHAR VARYING":"varchar","CHARACTER VARYING":"varchar",NCHAR:"nchar",VARCHAR:"varchar",VARCHAR2:"varchar",NVARCHAR:"nvarchar",NVARCHAR2:"nvarchar",BPCHAR:"bpchar",STR:"text",STRING:"text",TEXT:"text",LONGTEXT:"longtext",MEDIUMTEXT:"mediumtext",TINYTEXT:"tinytext",CLOB:"text",LONGVARCHAR:"text",BINARY:"binary",BLOB:"varbinary",LONGBLOB:"longblob",MEDIUMBLOB:"mediumblob",TINYBLOB:"tinyblob",BYTEA:"varbinary",VARBINARY:"varbinary",TIME:"time",TIMETZ:"timetz",TIME_NS:"timeNs",TIMESTAMP:"timestamp",TIMESTAMPTZ:"timestamptz",TIMESTAMPLTZ:"timestampltz",TIMESTAMP_LTZ:"timestampltz",TIMESTAMPNTZ:"timestampntz",TIMESTAMP_NTZ:"timestampntz",DATE:"date",DATETIME:"datetime",INT4RANGE:"int4range",INT4MULTIRANGE:"int4multirange",INT8RANGE:"int8range",INT8MULTIRANGE:"int8multirange",NUMRANGE:"numrange",NUMMULTIRANGE:"nummultirange",TSRANGE:"tsrange",TSMULTIRANGE:"tsmultirange",TSTZRANGE:"tstzrange",TSTZMULTIRANGE:"tstzmultirange",DATERANGE:"daterange",DATEMULTIRANGE:"datemultirange",UNIQUE:"unique",VECTOR:"vector",STRUCT:"struct",SEQUENCE:"sequence",VARIANT:"variant",ALTER:"alter",ANALYZE:"analyze",CALL:"command",COMMENT:"comment",EXPLAIN:"command",GRANT:"grant",REVOKE:"revoke",OPTIMIZE:"command",PREPARE:"command",VACUUM:"command","USER-DEFINED":"userdefined","FOR VERSION":"versionSnapshot","FOR TIMESTAMP":"timestampSnapshot"},Me.WHITE_SPACE={" ":"space"," ":"space","\n":"break","\r":"break"},Me.COMMANDS=new Set(["command","execute","fetch","show","rename"]),Me.COMMAND_PREFIX_TOKENS=new Set(["semicolon","begin"]),Me.NUMERIC_LITERALS={},Me.COMMENTS=["--",["/*","*/"]];var Dt=Me;var u_=class{constructor(e){this.expression=e}toJSON(){return{type:"Insert",expression:this.expression.sql()}}},E_=class{constructor(e){this.expression=e}toJSON(){return{type:"Remove",expression:this.expression.sql()}}},DM=class{constructor(e,t){this.source=e;this.target=t}toJSON(){return{type:"Move",source:this.source.sql(),target:this.target.sql()}}},_M=class{constructor(e,t){this.source=e;this.target=t}toJSON(){return{type:"Update",source:this.source.sql(),target:this.target.sql()}}},h_=class{constructor(e,t){this.source=e;this.target=t}toJSON(){return{type:"Keep",source:this.source.sql(),target:this.target.sql()}}};function oW(n,e,t={}){let{matchings:s=[],deltaOnly:r=!1,...i}=t;function a(x,m){let N=new Map;for(let R=0;R<x.length;R++){let S=x[x.length-1-R],I=m[m.length-1-R];I.computeHash(),N.set(S,I)}return N}let o=Array.from(n.walk()),c=Array.from(e.walk()),p=new Set(o),u=new Set(c),E=o.length!==p.size||c.length!==u.size||o.some(x=>u.has(x)),g=E?n.copy():n,A=E?e.copy():e;try{if(E&&0<s.length){let x=a(o,Array.from(g.walk())),m=a(c,Array.from(A.walk()));s=s.map(([N,R])=>[x.get(N),m.get(R)])}else[...o,...c].reverse().forEach(x=>{x.computeHash()});return new g_(i).diff(g,A,{deltaOnly:r,matchings:s})}finally{E||[...o,...c].forEach(x=>{x.resetHash()})}}var cW=[Se,Et,k,C,vs,w,V,Fe],kM=[G],g_=class{constructor(e={}){this.bigramHistoCache=new Map;this.unmatchedSourceNodes=new Set;this.unmatchedTargetNodes=new Set;this.sourceIndex=new Map;this.targetIndex=new Map;let{f:t=.6,t:s=.6,dialect:r}=e;this.f=t,this.t=s,this.sqlGenerator=W.getOrRaise(r).generator({comments:!1})}diff(e,t,s={}){let{deltaOnly:r=!1,matchings:i=[]}=s,a=new Map(i);this.source=e,this.target=t;for(let c of e.bfs())kM.some(p=>c instanceof p)||(this.sourceIndex.set(c,c),a.has(c)||this.unmatchedSourceNodes.add(c));for(let c of t.bfs())if(!kM.some(p=>c instanceof p)){this.targetIndex.set(c,c);let p=!1;for(let u of a.values())if(u===c){p=!0;break}p||this.unmatchedTargetNodes.add(c)}this.bigramHistoCache.clear();let o=this.computeMatchingSet();return a.forEach((c,p)=>o.set(p,c)),this.generateEditScript(o,{deltaOnly:r})}generateEditScript(e,t){let{deltaOnly:s}=t,r=[];return this.unmatchedSourceNodes.forEach(i=>r.push(new E_(i))),this.unmatchedTargetNodes.forEach(i=>r.push(new u_(i))),e.forEach((i,a)=>{let o=a.equals(i);if(!cW.some(c=>a instanceof c)||o){if(o){let u=a.parent,E=i.parent;(!u&&E||u&&!E||u&&E&&e.get(u)!==E)&&r.push(new DM(a,i))}else r.push(...this.generateMoveEdits(a,i,e));let c=Object.fromEntries(qB(a)),p=Object.fromEntries(qB(i));JSON.stringify(c)!==JSON.stringify(p)?r.push(new _M(a,i)):s||r.push(new h_(a,i))}else r.push(new _M(a,i))}),r}generateMoveEdits(e,t,s){let r=[...FB(e)],i=[...FB(t)],a=pW(r,i,(p,u)=>s.get(p)===u),o=new Set(a),c=[];for(let p of r)if(!o.has(p)&&!this.unmatchedSourceNodes.has(p)){let u=s.get(p);c.push(new DM(this.sourceIndex.get(p),this.targetIndex.get(u)))}return c}computeMatchingSet(){let e=this.computeLeafMatchingSet(),t=new Map(e),s=[];for(let i of _nullishCoalesce(_optionalChain([this, 'access', _1244 => _1244.source, 'optionalAccess', _1245 => _1245.bfs, 'call', _1246 => _1246()]), () => ([])))this.unmatchedSourceNodes.has(i)&&s.push(i);let r=[];for(let i of _nullishCoalesce(_optionalChain([this, 'access', _1247 => _1247.target, 'optionalAccess', _1248 => _1248.bfs, 'call', _1249 => _1249()]), () => ([])))this.unmatchedTargetNodes.has(i)&&r.push(i);for(let i of s)for(let a of r)if(vB(i,a)){let o=new Set(Ew(i)),c=new Set(Ew(a)),p=Math.max(o.size,c.size),u=0;if(0<p){let g=0;for(let[A,x]of e)o.has(A)&&c.has(x)&&g++;u=g/p}let E=4<Math.min(o.size,c.size)?this.t:.4;if(.8<=u||E<=u&&this.f<=this.diceCoefficient(i,a)){t.set(i,a),this.unmatchedSourceNodes.delete(i),this.unmatchedTargetNodes.delete(a),r.splice(r.indexOf(a),1);break}}return t}diceCoefficient(e,t){let s=this.getBigramHisto(e),r=this.getBigramHisto(t),i=0;s.forEach(p=>i+=p);let a=0;r.forEach(p=>a+=p);let o=i+a;if(o===0)return e.equals(t)?1:0;let c=0;return s.forEach((p,u)=>{let E=r.get(u);E!==void 0&&(c+=Math.min(p,E))}),2*c/o}computeLeafMatchingSet(){let e=[],t=this.source?[...Ew(this.source)]:[],s=this.target?[...Ew(this.target)]:[];for(let i of t)for(let a of s)if(vB(i,a)){let o=this.diceCoefficient(i,a);this.f<=o&&e.push({similarity:-o,parentSimilarity:-BB(i,a),index:e.length,sourceLeaf:i,targetLeaf:a})}e.sort((i,a)=>i.similarity!==a.similarity?i.similarity-a.similarity:i.parentSimilarity!==a.parentSimilarity?i.parentSimilarity-a.parentSimilarity:i.index-a.index);let r=new Map;for(let i of e){let{sourceLeaf:a,targetLeaf:o}=i;this.unmatchedSourceNodes.has(a)&&this.unmatchedTargetNodes.has(o)&&(r.set(a,o),this.unmatchedSourceNodes.delete(a),this.unmatchedTargetNodes.delete(o))}return r}getBigramHisto(e){let t=this.bigramHistoCache.get(e);if(t!==void 0)return t;let s=this.sqlGenerator.generate(e),r=new Map;for(let i=0;i<s.length-1;i++){let a=s.substring(i,i+2);r.set(a,(r.get(a)||0)+1)}return this.bigramHistoCache.set(e,r),r}};function*Ew(n){let e=!1;for(let t of n.iterExpressions())kM.some(s=>t instanceof s)||(e=!0,yield*Ew(t));e||(yield n)}function*qB(n){for(let[e,t]of Object.entries(n.args))t==null||t instanceof h||Array.isArray(t)&&t[0]instanceof h||(yield[e,t])}function vB(n,e){if(n.constructor===e.constructor){if(n instanceof z&&e instanceof z)return n.args.side===e.args.side;if(n instanceof st&&e instanceof st){let t=n.args.this,s=e.args.this;return t instanceof h&&s instanceof h?t.equals(s):t===s}return!0}return!1}function BB(n,e){return!n||!e||n.constructor!==e.constructor?0:1+BB(n.parent,e.parent)}function*FB(n){for(let e of n.iterExpressions())kM.some(t=>e instanceof t)||(yield e)}function pW(n,e,t){let s=[...n],r=[...e],i=s.length,a=r.length,o=Array.from({length:i+1},()=>Array.from({length:a+1},()=>[]));for(let c=1;c<=i;c++)for(let p=1;p<=a;p++)if(t(s[c-1],r[p-1]))o[c][p]=[...o[c-1][p-1],s[c-1]];else{let u=o[c-1][p],E=o[c][p-1];o[c][p]=E.length<u.length?u:E}return o[i][a]}function d_(n,e={}){let{schema:t,dialect:s}=e,r=Qs(t,{dialect:s});for(let i of _t(n))if(Object.keys(i.selectedSources).length!==1)for(let[,a]of Object.entries(i.selectedSources)){let[o,c]=a;if(!(c instanceof V))continue;let p=o;if(!p.parent)continue;let u=_optionalChain([r, 'access', _1250 => _1250.columnNames, 'optionalCall', _1251 => _1251(c)]);if(!u||u.length===0||p.parent instanceof ae||_optionalChain([p, 'access', _1252 => _1252.parent, 'optionalAccess', _1253 => _1253.parent]) instanceof V)continue;if(!p.alias)throw new is("Tables require an alias. Run qualify_tables optimization.");let g=p.aliasOrName,A=ft("*").from(oe(p,g,{table:!0}),{copy:!1}).subquery(g,{copy:!1});p.replace(A)}return n}var yT=class n{constructor(e,t,s={}){let{inferSchema:r=!0}=s;this.scope=e,this.schema=t,this.dialect=t.dialect||new W,this.inferSchema=r,this.getSourceColumnsCache=new Rl}getTable(e){let t=typeof e=="string"?e:e.name,s=this.getTableNameFromSources(t);if(!s&&typeof e!="string"){let o=this.getColumnJoinContext(e);if(o)try{let c=this.getAvailableSourceColumns(o);s=this.getTableNameFromSources(t,c)}catch(c){if(!(c instanceof is))throw c}}if(!s&&this.inferSchema){let o=this.getAllSourceColumns(),c=[];for(let[p,u]of o)(!u||u.length===0||u.includes("*"))&&c.push(p);c.length===1&&(s=c[0])}if(!s)return;let r=this.scope.selectedSources[s];if(!r)return K(s);let[i]=r,a=i;if(a instanceof ce)for(;a&&a.alias!==s;)a=a.parent;if(a){let o=a.getArgKey("alias");if(o instanceof h&&(o.args.this instanceof G||typeof o.args.this=="string"))return K(o.args.this)}return K(s)}get allColumns(){if(!this.allColumnsCache){this.allColumnsCache=new Set;for(let e of this.getAllSourceColumns().values())for(let t of e)this.allColumnsCache.add(t)}return this.allColumnsCache}getSourceColumnsFromSetOp(e){if(e instanceof $)return e.namedSelects;if(e instanceof ae){let a=e.args.this;if(a instanceof be)return this.getSourceColumnsFromSetOp(a)}if(!(e instanceof be))throw new Error(`Unknown set operation: ${e}`);let t=e,s=t.args.on;if(s)return s.map(a=>a.name);let r=t.args.side,i=t.args.kind;if(r||i){let a=t.args.this,o=t.args.expression;if(!a||!o)return[];let c=this.getSourceColumnsFromSetOp(a),p=this.getSourceColumnsFromSetOp(o);if(r==="left")return c;if(r==="full"){let u=[...c,...p];return Array.from(new Set(u))}else if(i==="inner"){let u=new Set(c),E=new Set(p);return Array.from(u).filter(g=>E.has(g))}}return e.namedSelects}getSourceColumns(e,t={}){let{onlyVisible:s=!1}=t;if(this.getSourceColumnsCache.has(e,s))return _nullishCoalesce(this.getSourceColumnsCache.get(e,s), () => ([]));let r=this.scope.sources.get(e);if(!r)throw new is(`Unknown table: ${e}`);let i=[];if(r instanceof V)i=_optionalChain([this, 'access', _1254 => _1254.schema, 'access', _1255 => _1255.columnNames, 'optionalCall', _1256 => _1256(r,{onlyVisible:s})])||[];else if(r instanceof Ce){let c=r.expression;if(c instanceof Gs||c instanceof Pe){if(i=c.namedSelects,this.dialect._constructor.UNNEST_COLUMN_ONLY&&c instanceof Pe){let p=c;if(!p.type||wi(p.type,"unknown")){let u=p.args.expressions,E=b(_nullishCoalesce(u, () => ([])),0);if(E instanceof k&&this.scope.parent){let g=this.getUnnestColumnType(E);if(_optionalChain([g, 'optionalAccess', _1257 => _1257.isType, 'call', _1258 => _1258("array")])){let A=g.args.expressions;A&&0<A.length?p.type=A[0].copy():p.type=g.copy()}}}if(p.isType("struct"))for(let u of(p.type instanceof h?p.type.args.expressions:void 0)||[])D(u,h)&&i.push(u.name)}}else if(c instanceof be)i=this.getSourceColumnsFromSetOp(c);else{let p=b(_nullishCoalesce(c.args.expressions, () => ([])),0);if(p instanceof pr){let u=p.args.schema;i=u?_nullishCoalesce(_optionalChain([u, 'access', _1259 => _1259.args, 'access', _1260 => _1260.expressions, 'optionalAccess', _1261 => _1261.map, 'call', _1262 => _1262(E=>E instanceof h?E.name:String(E))]), () => ([])):["key","value"]}else i=c.namedSelects}}let[a]=this.scope.selectedSources[e]||[void 0,void 0],o;if(a instanceof Ce?o=a.expression.aliasColumnNames:a instanceof h?o=a.aliasColumnNames:o=[],o.length){let c=[];for(let p=0;p<Math.max(i.length,o.length);p++){let u=b(o,p),E=b(i,p);c.push(u||E||"")}i=c}return this.getSourceColumnsCache.set(e,s,i),i}getAllSourceColumns(){if(!this.sourceColumns){this.sourceColumns=new Map;let e={...this.scope.selectedSources,...Object.fromEntries(this.scope.lateralSources.entries())};for(let t of Object.keys(e))this.sourceColumns.set(t,this.getSourceColumns(t))}return this.sourceColumns}getTableNameFromSources(e,t){let s;return t?s=this.getUnambiguousColumns(t):(this.unambiguousColumns||(this.unambiguousColumns=this.getUnambiguousColumns(this.getAllSourceColumns())),s=this.unambiguousColumns),s.get(e)}getColumnJoinContext(e){if(!this.scope.expression.args.joins||this.scope.expression.getArgKey("laterals")||this.scope.expression.getArgKey("pivots"))return;let s=e.findAncestor(z,$);if(s instanceof z&&Object.keys(this.scope.selectedSources).includes(s.aliasOrName))return s}getAvailableSourceColumns(e){let{from:t,joins:s}=this.scope.expression.args;if(!t||!s)return new Map;let r=new Map,i=t instanceof h?t.aliasOrName:t;i&&r.set(i,this.getSourceColumns(i));for(let a of s.slice(0,s.indexOf(e)+1)){let o=a.aliasOrName;o&&r.set(o,this.getSourceColumns(o))}return r}getUnambiguousColumns(e){if(e.size===0)return new Map;let t=Array.from(e.entries()),[s,r]=t[0];if(t.length===1)return new Mw(r,s);let i=new Map;if(this.dialect._constructor.UNNEST_COLUMN_ONLY){for(let[c,p]of this.scope.sources)if(p instanceof Ce&&p.expression instanceof Pe){let u=p.expression.args.alias;D(u,ie)&&u.columns.length&&i.set(u.columns[0].name,c)}}let a=new Map;for(let c of r)a.set(c,s);let o=new Set(r);for(let[c,p]of t.slice(1)){let u=new Set(p),E=new Set([...o].filter(g=>u.has(g)));for(let g of p)o.add(g);for(let g of E){let A=i.get(g);if(A!==void 0){a.set(g,A);continue}a.delete(g)}for(let g of u)E.has(g)||a.set(g,c)}return a}getUnnestColumnType(e){let t=this.scope.parent;if(!t)return;let s;if(e.table)s=e.table;else{let a=new n(t,this.schema,{inferSchema:this.inferSchema}).getTable(e);if(!a)return;s=a.name}let r=t.sources.get(s);return r?this.getColumnTypeFromScope(r,e):void 0}getColumnTypeFromScope(e,t){if(e instanceof V){let s=_optionalChain([this, 'access', _1263 => _1263.schema, 'access', _1264 => _1264.getColumnType, 'optionalCall', _1265 => _1265(e,t)]);if(s&&(typeof s.args.this=="string"?s.args.this:"unknown")!=="unknown")return s}else if(e instanceof Ce)for(let[,s]of e.sources){let r=this.getColumnTypeFromScope(s,t);if(r&&(typeof r.args.this=="string"?r.args.this:"unknown")!=="unknown")return r}}};function A_(n,e={}){let{schema:t,expandAliasRefs:s=!0,expandStars:r=!0,inferSchema:i,allowPartialQualification:a=!1,dialect:o}=e,c=Qs(t,{dialect:o}),p=new $n({schema:c}),u=_nullishCoalesce(i, () => (!!c.empty)),E=c.dialect||new W,g=E._constructor,A=g.PSEUDOCOLUMNS;for(let x of _t(n)){g.PREFER_CTE_ALIAS_COLUMN&&zB(x);let N=x.expression instanceof $;lW(x,A);let R=new yT(x,c,{inferSchema:u});GB(x.ctes),GB(x.derivedTables);let S=uW(x,R);(c.empty||g.FORCE_EARLY_ALIAS_REF_EXPANSION)&&s&&$B(x,R,E,{expandOnlyGroupby:g.EXPAND_ONLY_GROUP_ALIAS_REF}),EW(x,R),hW(x,R,{allowPartialQualification:a}),!c.empty&&s&&$B(x,R,E,{expandOnlyGroupby:!1}),N&&(r&&AW(x,R,S,A,p),jB(x)),fW(x,E),xW(x,R),g.ANNOTATE_ALL_SCOPES&&p.annotateScope(x)}return n}function f_(n,e){let t=[];for(let s of _t(n)){if(!(s.expression instanceof $))continue;let r=s.unqualifiedColumns;if(0<s.externalColumns.length&&!s.isCorrelatedSubquery&&s.pivots.length===0){let i=s.externalColumns[0],a=i.table?` for table: '${i.table}'`:"",o=_optionalChain([i, 'access', _1266 => _1266.args, 'access', _1267 => _1267.this, 'optionalAccess', _1268 => _1268.meta, 'optionalAccess', _1269 => _1269.line]),c=_optionalChain([i, 'access', _1270 => _1270.args, 'access', _1271 => _1271.this, 'optionalAccess', _1272 => _1272.meta, 'optionalAccess', _1273 => _1273.col]),p=_optionalChain([i, 'access', _1274 => _1274.args, 'access', _1275 => _1275.this, 'optionalAccess', _1276 => _1276.meta, 'optionalAccess', _1277 => _1277.start]),u=_optionalChain([i, 'access', _1278 => _1278.args, 'access', _1279 => _1279.this, 'optionalAccess', _1280 => _1280.meta, 'optionalAccess', _1281 => _1281.end]),E=`Column '${i.name}' could not be resolved${a}.`;if(o&&c&&(E+=` Line: ${o}, Col: ${c}`),e&&p!==void 0&&u!==void 0){let{formattedSql:g}=oO({sql:e,positions:[[p,u]]});E+=`
|
|
19
|
+
${g}`}throw new is(E)}if(0<r.length&&0<s.pivots.length&&s.pivots[0].unpivot){let i=new Set(WB(s.pivots[0]));r=r.filter(a=>!i.has(a))}t.push(...r)}if(0<t.length){let s=t[0],r=s.args.this,i=D(r,h)?r.meta.line:void 0,a=D(r,h)?r.meta.col:void 0,o=D(r,h)?r.meta.start:void 0,c=D(r,h)?r.meta.end:void 0,p=`Ambiguous column '${s.name}'`;if(i&&a&&(p+=` (Line: ${i}, Col: ${a})`),e&&o!==void 0&&c!==void 0){let{formattedSql:u}=oO({sql:e,positions:[[o,c]]});p+=`
|
|
20
|
+
${u}`}throw new is(p)}return n}function lW(n,e){if(e.size===0)return;let t=!1,s=n.expression;for(let r of n.columns){let i=r.name.toUpperCase();e.has(i)&&(i!=="LEVEL"||s instanceof $&&s.args.connect)&&(r.replace(new Ml({...r.args})),t=!0)}t&&n.clearCache()}function WB(n){let t=(n.args.fields||[]).filter(r=>r instanceof it&&r.args.this instanceof k).map(r=>r.args.this),s=[];for(let r of n.args.expressions)for(let i of r.findAll(k))s.push(i);return[...t,...s]}function GB(n){for(let e of n){if(e.parent instanceof ve&&e.parent.args.recursive)continue;let t=e.getArgKey("alias");t instanceof ie&&t.setArgKey("columns",void 0)}}function uW(n,e){let t=n.expression.args.joins||[];if(t.length===0)return new Map;let s=new Set(t.map(c=>c.aliasOrName)),r=Object.keys(n.selectedSources).filter(c=>!s.has(c));if(0<s.size&&r.length===0)throw new is(`Joins ${[...s].join(",")} missing source table ${n.expression}`);let i={},a=c=>{for(let p of e.getSourceColumns(c))p in i||(i[p]=c)};for(let c of r)a(c);let o=new Map;for(let c=0;c<t.length;c++){let p=t[c];ue(p,z);let u=r[r.length-1];u&&a(u);let E=p.aliasOrName;r.push(E);let g=p.args.using;if(!g)continue;let A=e.getSourceColumns(E),x=[],m=g.length,N=p.isSemiOrAntiJoin;for(let R of g){let S=R.name,I=i[S];if((!I||!A.includes(S))&&0<Object.keys(i).length&&!("*"in i)&&0<A.length)throw new is(`Cannot automatically join: ${S}`);I=I||u;let y;if(c===0||m===1)y=Ie({col:S,table:I});else{let P=r.slice(0,-1).filter(v=>e.getSourceColumns(v).includes(S)).map(v=>Ie({col:S,table:v}));1<P.length?y=new St({this:P[0],expressions:P.slice(1)}):y=Ie({col:S,table:I})}if(x.push(y.eq(Ie({col:S,table:E}))),!N){let P=o.get(S);P||(P=[],o.set(S,P)),P.includes(I)||P.push(I),P.includes(E)||P.push(E)}}p.setArgKey("using",void 0),p.setArgKey("on",nt(x,{copy:!1}))}if(0<o.size)for(let c of n.columns){let p=c.table?void 0:o.get(c.name);if(p!==void 0){let u=p.map(g=>Ie({col:c.name,table:g})),E=new St({this:u[0],expressions:u.slice(1)});c.parent instanceof $?E=oe(E,c.name,{copy:!1}):c.parent instanceof Hs&&(E=new At({this:K(c.name),expression:E})),n.replace(c,E)}}return o}function $B(n,e,t,s){let{expandOnlyGroupby:r}=s,i=n.expression,a=t._constructor;if(!(i instanceof $)||a.DISABLES_ALIAS_REF_EXPANSION)return;let o=new Map,c=new Set(i.selects.map(A=>A.aliasOrName)),p=!1,u=(A,x={})=>{let{resolveTable:m=!1,literalIndex:N=!1}=x,R=A instanceof Ys,S=A instanceof $t;if(!(!A||r&&!R))for(let I of Lc(A,{prune:y=>y.isStar})){if(!(I instanceof k)||r&&R&&I.parent!==A)continue;let y=!1,P=m&&!I.table?e.getTable(I.name):void 0,v=o.get(I.name),H=v?v[0]:void 0,B=v?v[1]:1;if(H)y=!!(H.find(q)&&I.findAncestor(q)&&!(I.findAncestor(Fe,$)instanceof Fe)),S&&a.PROJECTION_ALIASES_SHADOW_SOURCE_NAMES&&(y=y||Array.from(H.findAll(k)).some(fe=>c.has(_optionalChain([fe, 'access', _1282 => _1282.parts, 'access', _1283 => _1283[0], 'optionalAccess', _1284 => _1284.name])||"")));else if(a.PROJECTION_ALIASES_SHADOW_SOURCE_NAMES&&(R||S)){let fe=P?P.name:I.table;if(fe&&c.has(fe)){I.replace(K(I.name)),p=!0;continue}}if(P&&(!H||y))I.setArgKey("table",P);else if(!I.table&&H&&!y)if((H instanceof w||H.isNumber)&&(N||m))N&&(I.replace(w.number(B)),p=!0);else{p=!0;let fe=I.replace(_r(H)),_e=wL(fe,t);_e!==fe&&fe.replace(_e)}}};for(let A=0;A<i.selects.length;A++){let x=i.selects[A];u(x),x instanceof Se&&o.set(x.alias,[x.args.this,A+1])}let E=n,g=!1;for(;E&&!E.isCte;)E.isUnion&&E.parent&&(g=E.parent.expression.args.expression===E.expression),E=E.parent;if(E&&g){let A=E.expression.parent;if(A&&_optionalChain([A, 'access', _1285 => _1285.findAncestor, 'call', _1286 => _1286(ve), 'optionalAccess', _1287 => _1287.args, 'access', _1288 => _1288.recursive])){let m=A.args.alias,N=m instanceof ie?m.columns:[],R=0<N.length?N:_optionalChain([A, 'access', _1289 => _1289.args, 'access', _1290 => _1290.this, 'optionalAccess', _1291 => _1291.selects])||[];for(let S of R)S instanceof h&&o.delete(S.outputName)}}if(u(i.args.where),u(i.args.group,{literalIndex:!0}),u(i.args.having,{resolveTable:!0}),u(i.args.qualify,{resolveTable:!0}),a.SUPPORTS_ALIAS_REFS_IN_JOIN_CONDITIONS)for(let A of i.args.joins||[])u(A);p&&n.clearCache()}function EW(n,e){let t=!1,s=[...n.columns,...n.stars];for(let r of s){if(r instanceof me)continue;let i=r.table,a=r.meta.dotParts||[];if(delete r.meta.dotParts,i&&!n.sources.has(i)&&(!n.parent||!n.parent.sources.has(i)||!n.isCorrelatedSubquery)){let o=r.parts;if(o.length<2)continue;let c=o[0],p=o.slice(1);if(!c)continue;let u,E,g,A;if(n.sources.has(c.name)){if(p.length===0)continue;g=c,u=p[0],E=p.slice(1),A=!0}else g=e.getTable(c.name),u=c,E=p,A=!1;if(g){t=!0;let x=Ie({col:u,table:g});0<a.length&&(x.meta.dotParts=a.slice(A?2:1)),0<E.length?r.replace(me.build([x,...E])):r.replace(x)}}}t&&n.clearCache()}function hW(n,e,t){let{allowPartialQualification:s}=t,r=e.dialect._constructor;for(let i of n.columns){let a=i.table,o=i.name;if(a&&n.sources.has(a)){let c=e.getSourceColumns(a);if(!s&&0<c.length&&!c.includes(o)&&!c.includes("*"))throw new is(`Unknown column: ${o}`)}if(!a){if(0<n.pivots.length&&!i.findAncestor(ls)){i.setArgKey("table",K(n.pivots[0].alias));continue}let c=e.getTable(i);if(c){let p=n.sources.get(c.name);if(p instanceof Ce&&p.columnIndex.has(i))continue}if(c)i.setArgKey("table",c);else if(r.TABLES_REFERENCEABLE_AS_COLUMNS&&i.parts.length===1&&o in n.selectedSources){let p=i.args.this;n.replace(i,new Gn({this:D(p,h)?p:void 0}))}}}for(let i of n.pivots)if(i instanceof ls){for(let a of i.findAll(k))if(!a.table&&e.allColumns.has(a.name)){let o=e.getTable(a.name);o&&a.setArgKey("table",o)}}}function YB(n,e,t){let s=_nullishCoalesce(n.getArgKey("except"), () => (n.getArgKey("except")));if(!s)return;let r=Array.isArray(s)?s:[s],i=new Set(r.filter(a=>a instanceof h).map(a=>a.name));for(let a of e)t.set(a,i)}function HB(n,e,t){let s=n.getArgKey("rename");if(!s||s.length===0)return;let r={};for(let i of s)if(i instanceof h){let a=i.args.this;a instanceof h&&(r[a.name]=i.alias)}for(let i of e)t.set(i,r)}function VB(n,e,t){let s=n.getArgKey("replace");if(!s||s.length===0)return;let r={};for(let i of s)i instanceof Se&&(r[i.alias]=i);for(let i of e)t.set(i,r)}function gW(n){let e=n.find(k);if(!(e instanceof k)||!e.isType("struct"))return[];let t=e.copy(),s=t.type,r=D(s,C)?s:void 0,i=n.parts.slice(1,-1);e:for(let c of i.slice(1)){let p=_optionalChain([r, 'optionalAccess', _1292 => _1292.args, 'access', _1293 => _1293.expressions])||[];for(let u of p){if(!(u.args.this instanceof G))return[];if(!D(u,we))return[];let E=u.args.kind,g=D(E,C)?E:void 0;if(u.name===c.name&&_optionalChain([g, 'optionalAccess', _1294 => _1294.isType, 'call', _1295 => _1295("struct")])){r=g;break e}}return[]}let a=new Set,o=[];for(let c of _optionalChain([r, 'optionalAccess', _1296 => _1296.args, 'access', _1297 => _1297.expressions])||[]){let p=c.name,u=c.args.this;if(a.has(p)||!(u instanceof G))return[];a.add(p);let E=u.copy(),g=[...i.map(N=>N.copy()),E],[A,...x]=g,m=Ie({col:A,table:t.args.table},{fields:x});o.push(oe(m,E,{copy:!1}))}return o}function dW(n){if(!(n.args.this instanceof Ye))return[];let e=n.find(k);if(!(e instanceof k)||!e.isType("struct"))return[];let t=e.parent,s=e.type,r=D(s,C)?s:void 0;for(;t!==void 0;){if(t instanceof Ye){t=t.parent;continue}if(!(t instanceof me))return[];let c=t.right;if(c instanceof ye)break;if(!(c instanceof G))return[];let p=!1,u=Xe(r.args.expressions||[],we);for(let E of u)if(E.name===c.name){p=!0,r=E.args.kind;break}if(!p)return[];t=t.parent}let i=[],a=n.args.this,o=Xe(r.args.expressions||[],we);for(let c of o){let p=c.args.this instanceof G?c.args.this.copy():new G({this:_optionalChain([c, 'access', _1298 => _1298.args, 'access', _1299 => _1299.this, 'optionalAccess', _1300 => _1300.toString, 'call', _1301 => _1301()])}),u=me.build([a.copy(),p]),E=oe(u,p,{copy:!1});i.push(E)}return i}function AW(n,e,t,s,r){let i=[],a=new Map,o=new Map,c=new Map,p=new Set,u=e.dialect._constructor,E,g=new Set,A=b(n.pivots,0);if(A instanceof ls&&!A.aliasColumnNames.length)if(A.unpivot){E=WB(A).map(x=>x.outputName);for(let x of A.args.fields||[])if(x instanceof it)for(let m of x.args.expressions)for(let N of m.findAll(k))g.add(N.outputName)}else{for(let m of A.findAll(k))g.add(m.outputName);E=(A.getArgKey("columns")||[]).map(m=>m.outputName),E.length||(E=A.args.expressions.map(m=>m.aliasOrName))}u.SUPPORTS_STRUCT_STAR_EXPANSION&&n.stars.some(x=>x instanceof me)&&r.annotateScope(n);for(let x of n.expression.selects){let m=[];if(x instanceof ye)m.push(...Object.keys(n.selectedSources)),YB(x,m,a),VB(x,m,o),HB(x,m,c);else if(x.isStar)if(x instanceof me){if(u.SUPPORTS_STRUCT_STAR_EXPANSION&&!u.REQUIRES_PARENTHESIZED_STRUCT_ACCESS){let N=gW(x);if(0<N.length){i.push(...N);continue}}else if(u.REQUIRES_PARENTHESIZED_STRUCT_ACCESS){let N=dW(x);if(0<N.length){i.push(...N);continue}}}else{let N=x instanceof k?x.table:"";N&&m.push(N);let R=x.args.this;R instanceof h&&(YB(R,m,a),VB(R,m,o),HB(R,m,c))}if(m.length===0){i.push(x);continue}for(let N of m){if(!n.sources.has(N))throw new is(`Unknown table: ${N}`);let R=e.getSourceColumns(N,{onlyVisible:!0});if(R.length||(R=n.outerColumns),0<s.size&&u.EXCLUDES_PSEUDOCOLUMNS_FROM_STAR&&(R=R.filter(P=>!s.has(P.toUpperCase()))),!R.length||R.includes("*"))return;let S=a.get(N)||new Set,I=c.get(N)||{},y=o.get(N)||{};if(A instanceof ls){let P;if(E&&0<g.size?(P=R.filter(v=>!g.has(v)),P.push(...E)):P=A.aliasColumnNames,0<P.length){for(let v of P)S.has(v)||i.push(oe(Ie({col:v,table:A.alias}),v,{copy:!1}));continue}}for(let P of R){if(S.has(P)||p.has(P))continue;let v=t.get(P);if(_optionalChain([v, 'optionalAccess', _1302 => _1302.includes, 'call', _1303 => _1303(N)])){p.add(P);let H=v.map(B=>Ie({col:P,table:B}));i.push(oe(new St({this:H[0],expressions:H.slice(1)}),P,{copy:!1}))}else{let H=_nullishCoalesce(I[P], () => (P)),B=y[P]||Ie({col:P,table:N});i.push(H!==P?oe(B,H,{copy:!1}):B)}}}}0<i.length&&n.expression instanceof $&&n.expression.setArgKey("expressions",i)}function jB(n){let e;if(n instanceof Ce)e=n;else{let a=Ci(n);if(!(a instanceof Ce))return;e=a}if(!(e.expression instanceof $))return;let t=e.expression.selects,s=e.outerColumns,r=[],i=Math.max(t.length,s.length);for(let a=0;a<i;a++){let o=t[a],c=s[a];if(!o||o instanceof pr)break;o instanceof ae?o.outputName||o.setArgKey("alias",new ie({this:K(`_col_${a}`)})):!(o instanceof Se)&&!(o instanceof Rn)&&!o.isStar&&(o=oe(o,o.outputName||`_col_${a}`,{copy:!1})),c&&o.setArgKey("alias",K(c)),r.push(o)}0<r.length&&e.expression instanceof $&&e.expression.setArgKey("expressions",r)}function JB(n,e){let t=Number(e.args.this)-1,s=n.expression.selects[t];if(!(s instanceof Se))throw new is(`Unknown output column: ${e.name}`);return s}function XB(n,e,t,s={}){let{alias:r=!1}=s,i=t._constructor,a=[],o;for(let c of e)if(c.isInteger){let p=JB(n,c);if(r){let u=p.alias;a.push(u?Ie({col:u}):c)}else{let u=p.args.this,E=!1;i.PROJECTION_ALIASES_SHADOW_SOURCE_NAMES&&(o===void 0&&(o=new Set(n.expression.selects.map(g=>g.aliasOrName).filter(g=>g in n.selectedSources))),E=Array.from(u.findAll(k)).some(g=>_optionalChain([o, 'optionalAccess', _1304 => _1304.has, 'call', _1305 => _1305(_optionalChain([g, 'access', _1306 => _1306.parts, 'access', _1307 => _1307[0], 'optionalAccess', _1308 => _1308.name])||"")]))),TO.some(g=>u instanceof g)||u.isNumber||u.find(qt)||u.find(Pe)||E?a.push(c):a.push(u.copy())}}else a.push(c);return a}function fW(n,e){let t=n.expression.args.group;if(!t)return;let s=Xe(t.args.expressions||[],h);t.setArgKey("expressions",XB(n,s,e)),n.expression.setArgKey("group",t)}function xW(n,e){for(let t of["order","distinct"]){let s=n.expression.getArgKey(t);if(s instanceof ct&&(s=s.args.on),!(s instanceof h))continue;let r=s.args.expressions;t==="order"&&(r=r.map(a=>a.args.this));let i=XB(n,r,e.dialect,{alias:!0});for(let a=0;a<r.length;a++){let o=r[a],c=i[a];for(let p of o.findAll(q))for(let u of p.findAll(k))if(!u.table){let E=e.getTable(u.name);E&&u.setArgKey("table",E)}o.replace(c)}if(n.expression.getArgKey("group")){let a=new Map(n.expression.selects.filter(o=>o instanceof Se).map(o=>[o.args.this.sql(),Ie({col:o.aliasOrName})]));for(let o of r)if(o.isInteger)o.replace(K(JB(n,o).alias));else{let c=a.get(o.sql());c&&o.replace(c)}}}}function hw(n,e={}){let{dialect:t,identify:s=!0}=e,r=W.getOrRaise(t);return n.transform(r.quoteIdentifier.bind(r),{identify:s,copy:!1})}function zB(n){for(let e of n.ctes){let t=e.aliasColumnNames;if(0<t.length&&e.args.this instanceof $){let s=e.args.this,r=s.args.expressions||[],i=[];for(let a=0;a<t.length;a++){let o=t[a],c=r[a];if(!c)break;let p;c instanceof Se?(c.setArgKey("alias",K(o)),p=c):p=oe(c,o),i.push(p)}s.setArgKey("expressions",i)}}}function x_(n,e={}){let{db:t,catalog:s,onQualify:r,dialect:i,canonicalizeTableAliases:a=!1}=e,o=W.getOrRaise(i),c=go("_"),p;t&&(p=Cl(t,{dialect:o}),p.meta.isTable=!0,p=Tr(p,{dialect:o}));let u;s&&(u=Cl(s,{dialect:o}),u.meta.isTable=!0,u=Tr(u,{dialect:o}));let E=A=>{A.args.this instanceof G&&(p&&!A.args.db&&A.setArgKey("db",p.copy()),u&&!A.args.catalog&&A.args.db&&A.setArgKey("catalog",u.copy()))};if((p||u)&&!(n instanceof ce)){let x=n.getArgKey("with")||new ve({expressions:[]}),m=new Set((x.args.expressions||[]).map(N=>N.aliasOrName));for(let N of n.walk({prune:R=>R instanceof ce}))N instanceof V&&(m.has(N.name)||E(N))}let g=(A,x,m={})=>{let{targetAlias:N,scope:R,normalize:S=!1,columns:I}=m,y=A.getArgKey("alias");y||(y=new ie({}));let P;if(a)P=c(),x.set(y.name||N||"",P);else if(!y.name)P=N||c(),S&&N&&(P=Tr(P,{dialect:o}).name);else return;y.setArgKey("this",K(P)),I&&y.setArgKey("columns",I.map(v=>K(v))),A.setArgKey("alias",y),R&&R.renameSource("",P)};for(let A of _t(n)){let x=A.localColumns,m=new Map;for(let R of A.subqueries){let S=R.parent;S&&S instanceof ae&&S.unwrap().replace(S)}for(let R of A.derivedTables){let S=R.unnest();if(S instanceof V){let y=S.args.joins;S.setArgKey("joins",void 0);let P=R.args.this;if(P instanceof h){let v=ft("*").from(S.copy(),{copy:!1});P.replace(v),v.setArgKey("joins",y)}}g(R,m,{scope:A});let I=b(R.getArgKey("pivots")||[],0);I&&g(I,m)}let N=new Map;for(let[R,S]of A.sources)if(S instanceof V){let I=!!R,y=S.args.pivots,P=y?b(y,0):void 0,v=R;P&&(v=S.name);let H=S.args.this,B=S.args.alias,fe=[];if(H&&H instanceof d){let on=H.constructor.name;if(B)B instanceof ie&&_optionalChain([B, 'access', _1309 => _1309.args, 'access', _1310 => _1310.columns, 'optionalAccess', _1311 => _1311.length])?fe=B.columns:o._constructor.DEFAULT_FUNCTIONS_COLUMN_NAMES.has(on)&&(fe=Array.from(pe(S.aliasOrName)),S.setArgKey("alias",void 0),v="");else{let ys=o._constructor.DEFAULT_FUNCTIONS_COLUMN_NAMES.get(on);fe=ys?Array.from(pe(ys)):[]}}g(S,m,{targetAlias:v||S.name||void 0,normalize:!0,columns:fe});let _e=_optionalChain([S, 'access', _1312 => _1312.parts, 'optionalAccess', _1313 => _1313.map, 'call', _1314 => _1314(zt=>zt.name), 'access', _1315 => _1315.join, 'call', _1316 => _1316(".")]),Is=_optionalChain([S, 'access', _1317 => _1317.args, 'access', _1318 => _1318.alias, 'optionalAccess', _1319 => _1319.args, 'access', _1320 => _1320.this]);if(Is instanceof G&&N.set(_e,Is.copy()),P){let zt=P.getArgKey("unpivot")?S.alias:void 0;if(g(P,m,{targetAlias:zt,normalize:!0}),A.sources.get(S.aliasOrName)instanceof Ce)continue}I&&(E(S),r&&r(S))}else if(S instanceof Ce&&S.isUdtf){let I=S.expression;if(g(I,m),I instanceof Gs){let y=I.getArgKey("alias");y instanceof ie&&!_optionalChain([y, 'access', _1321 => _1321.args, 'access', _1322 => _1322.columns, 'optionalAccess', _1323 => _1323.length])&&y.setArgKey("columns",o.generateValuesAliases(I).map(P=>Tr(P,{dialect:o})))}}for(let R of A.tables)if(!R.alias&&R.parent){let S=R.parent;(S instanceof Ge||S instanceof z)&&g(R,m,{targetAlias:R.name})}for(let R of x){let S=R.table;if(R.args.db){let I=R.parts.slice(0,-1).map(P=>P.name).join("."),y=N.get(I);y&&(R.setArgKey("table",void 0),R.setArgKey("db",void 0),R.setArgKey("catalog",void 0),R.setArgKey("table",y.copy()))}else if(0<m.size&&S){let I=m.get(S);I&&I!==R.table&&R.setArgKey("table",K(I))}}}return n}function gw(n,e={}){let{dialect:t,db:s,catalog:r,schema:i,expandAliasRefs:a=!0,expandStars:o=!0,inferSchema:c,isolateTables:p=!1,qualifyColumns:u=!0,allowPartialQualification:E=!1,validateQualifyColumns:g=!0,quoteIdentifiers:A=!0,identify:x=!0,canonicalizeTableAliases:m=!1,onQualify:N,sql:R}=e,S=Qs(i,{dialect:t}),I=W.getOrRaise(t);return n=Tr(n,{dialect:I,storeOriginalColumnIdentifiers:!0}),n=x_(n,{db:s,catalog:r,dialect:I,onQualify:N,canonicalizeTableAliases:m}),p&&(n=d_(n,{schema:S,dialect:I})),u&&(n=A_(n,{schema:S,expandAliasRefs:a,expandStars:o,inferSchema:c,allowPartialQualification:E})),A&&(n=hw(n,{dialect:I,identify:x})),g&&f_(n,R),n}var CT=class{constructor(e){this.name=e.name,this.expression=e.expression,this.source=e.source,this.downstream=e.downstream||[],this.sourceName=e.sourceName||"",this.referenceNodeName=e.referenceNodeName||""}*walk(){yield this;for(let e of this.downstream)yield*e.walk()}toHtml(e,t={}){let s={},r=[];for(let i of this.walk()){let a,o,c;i.expression instanceof V?(a=`FROM ${i.expression.args.this}`,o=`<pre>SELECT ${i.name} FROM ${i.expression.args.this}</pre>`,c=1):(a=i.expression.sql({pretty:!0,dialect:e}),o=`<pre>${i.source.transform(E=>E===i.expression?new yx({this:E,prefix:"<b>",postfix:"</b>"}):E,{copy:!1}).sql({pretty:!0,dialect:e})}</pre>`,c=0);let p=_T(i);s[p]={id:p,label:a,title:o,group:c};for(let u of i.downstream)r.push({from:p,to:_T(u)})}return new T_(s,r,t)}};function TW(n,e,t={}){let{schema:s,sources:r,dialect:i,scope:a,trimSelects:o=!0,copy:c=!0,...p}=t,u=ne(e,{copy:c,dialect:i}),E=Tr(n,{dialect:i}).name;if(r){let x={};for(let[m,N]of Object.entries(r))x[m]=ne(N,{copy:c,dialect:i});u=FD(u,x,{dialect:i,copy:c})}let g=a;if(g||(u=gw(u,{dialect:i,schema:s,validateQualifyColumns:!1,identify:!1,...p}),g=Ci(u)),!g)throw new Bn("Cannot build lineage, sql must be SELECT");if(!g.expression.selects.some(x=>x.aliasOrName===E))throw new Bn(`Cannot find column '${E}' in query.`);return JR(E,g,i,{trimSelects:o})}function JR(n,e,t,s={}){let{scopeName:r=void 0,upstream:i=void 0,sourceName:a=void 0,referenceNodeName:o=void 0,trimSelects:c=!0}=s,p;if(typeof n=="number"?p=e.expression.selects[n]:p=e.expression.selects.find(y=>y.aliasOrName===n)||(e.expression.isStar?new ye({}):e.expression),e.expression instanceof ae)for(let I of e.subqueryScopes)return JR(n,I,t,{upstream:i,sourceName:a,referenceNodeName:o,trimSelects:c});if(e.expression instanceof be){let I=e.expression.constructor.name.toUpperCase().replace("EXPR","");i=i||new CT({name:I,source:e.expression,expression:p});let y;if(typeof n=="number"?y=n:y=e.expression.selects.findIndex(P=>P.aliasOrName===n||P.isStar),y===-1)throw new Error(`Could not find ${n} in ${e.expression}`);for(let P of e.unionScopes)JR(y,P,t,{upstream:i,sourceName:a,referenceNodeName:o,trimSelects:c});return i}let u;c&&e.expression instanceof $?u=e.expression.select(p,{append:!1}):u=e.expression;let E=new CT({name:r?`${r}.${n}`:String(n),source:u,expression:p,sourceName:a||"",referenceNodeName:o||""});i&&i.downstream.push(E);let g=new WeakMap;for(let I of e.subqueryScopes)g.set(I.expression,I);for(let I of Mr(p,En)){let y=g.get(I);if(!y){console.warn(`Unknown subquery scope: ${I.sql({dialect:t})}`);continue}for(let P of I.namedSelects||[])JR(P,y,t,{upstream:E,trimSelects:c})}if(p instanceof ye)for(let I of Array.from(e.sources.values())){let y;I instanceof Ce?y=I.expression:y=I,E.downstream.push(new CT({name:p.sql({comments:!1}),source:y,expression:y}))}let A=new Set(Mr(p,[k])),x;if(u instanceof as){let I=u.findAll(k);for(let y of I)A.add(y);x=Array.from(e.sources.values()).filter(y=>y instanceof Ce&&y.isDerivedTable).map(y=>y.expression.parent).filter(y=>y!==void 0)}else x=e.derivedTables;let m=new Map;for(let I of x)I.comments&&_optionalChain([I, 'access', _1324 => _1324.comments, 'access', _1325 => _1325[0], 'optionalAccess', _1326 => _1326.startsWith, 'call', _1327 => _1327("source: ")])&&m.set(I.alias,I.comments[0].split(" ")[1]);let N=e.pivots,R=N.length===1&&!N[0].unpivot?N[0]:void 0,S=new Map;if(R){let I=_nullishCoalesce(R.args.columns, () => ([])),y=_nullishCoalesce(_optionalChain([R, 'access', _1328 => _1328.args, 'access', _1329 => _1329.expressions, 'optionalAccess', _1330 => _1330.length]), () => (0));_optionalChain([R, 'access', _1331 => _1331.args, 'access', _1332 => _1332.expressions, 'optionalAccess', _1333 => _1333.forEach, 'call', _1334 => _1334((P,v)=>{let H=Array.from(P.findAll(k));for(let B=v;B<(_optionalChain([I, 'optionalAccess', _1335 => _1335.length])||0);B+=y)S.set(I[B].name,H)})])}for(let I of Array.from(A)){let y=I.table,P=e.sources.get(y);if(P instanceof Ce){let v;if(P.scopeType==="derivedTable"&&!m.has(y))v=y;else if(P.scopeType==="cte"){let H=_optionalChain([e, 'access', _1336 => _1336.selectedSources, 'access', _1337 => _1337[y], 'optionalAccess', _1338 => _1338[0]]);v=H?H.name:void 0}JR(I.name,P,t,{scopeName:y,upstream:E,sourceName:m.get(y)||a,referenceNodeName:v,trimSelects:c})}else if(R&&R.aliasOrName===I.table){let v=[],H=I.name;_optionalChain([R, 'access', _1339 => _1339.args, 'access', _1340 => _1340.columns, 'optionalAccess', _1341 => _1341.some, 'call', _1342 => _1342(B=>B.name===H)])?v.push(...S.get(H)||[]):v.push(new k({this:I.args.this,table:_optionalChain([R, 'access', _1343 => _1343.parent, 'optionalAccess', _1344 => _1344.aliasOrName])}));for(let B of v){let fe=B.table,_e=e.sources.get(fe);_e instanceof Ce?JR(B.name,_e,t,{scopeName:fe,upstream:E,sourceName:m.get(fe)||a,referenceNodeName:o,trimSelects:c}):(_e=_e||new rr({}),E.downstream.push(new CT({name:B.sql({comments:!1}),source:_e,expression:_e})))}}else P=P||new rr({}),E.downstream.push(new CT({name:I.sql({comments:!1}),source:P,expression:P}))}return E}var T_=class{constructor(e,t,s={}){let{imports:r=!0}=s;this.imports=r,this.nodes=e,this.edges=t,this.options={height:"500px",width:"100%",layout:{hierarchical:{enabled:!0,nodeSpacing:200,sortMethod:"directed"}},interaction:{dragNodes:!1,selectable:!1},physics:{enabled:!1},edges:{arrows:"to"},nodes:{font:"20px monaco",shape:"box",widthConstraint:{maximum:300}},...s||{}}}toString(){let e=JSON.stringify(Object.values(this.nodes)),t=JSON.stringify(this.edges),s=JSON.stringify(this.options);return`<div>
|
|
21
|
+
<div id="sqlglot-lineage"></div>
|
|
22
|
+
${this.imports?`<script type="text/javascript" src="https://unpkg.com/vis-data@latest/peer/umd/vis-data.min.js"></script>
|
|
23
|
+
<script type="text/javascript" src="https://unpkg.com/vis-network@latest/peer/umd/vis-network.min.js"></script>
|
|
24
|
+
<link rel="stylesheet" type="text/css" href="https://unpkg.com/vis-network/styles/vis-network.min.css" />`:""}
|
|
25
|
+
<script type="text/javascript">
|
|
26
|
+
var nodes = new vis.DataSet(${e});
|
|
27
|
+
nodes.forEach(row => {
|
|
28
|
+
row["title"] = new DOMParser().parseFromString(row["title"], "text/html").body.childNodes[0];
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
new vis.Network(
|
|
32
|
+
document.getElementById("sqlglot-lineage"),
|
|
33
|
+
{
|
|
34
|
+
nodes: nodes,
|
|
35
|
+
edges: new vis.DataSet(${t})
|
|
36
|
+
},
|
|
37
|
+
${s}
|
|
38
|
+
);
|
|
39
|
+
</script>
|
|
40
|
+
</div>`}toHtml(){return this.toString()}};function S_(n){let e=Ci(n);if(e){let t=e.refCount(),s=[];for(let r of e.traverse())s.push(r);for(let r=s.length-1;0<=r;r--){let i=s[r];if(i.isCte){let a=i;if((t.get(a)||0)<=0){let c=i.expression.parent;if(!c)continue;let p=c.parent;if(c.pop(),p){let u=p.args.expressions;(!u||u.length===0)&&p.pop()}for(let[,u]of Object.entries(i.selectedSources)){let[,E]=u;if(E instanceof Ce){let g=t.get(E)||0;t.set(E,g-1)}}}}}}return n}function m_(n){for(let e of _t(n)){if(0<e.unqualifiedColumns.length)continue;let t=e.expression.args.joins;if(t)for(let s=t.length-1;0<=s;s--){let r=t[s];if(ue(r,z),r.isSemiOrAntiJoin)continue;let i=r.aliasOrName;i&&SW(e,r,i)&&(r.pop(),e.removeSource(i))}}return n}function SW(n,e,t){let s=n.sources.get(t);if(!(s instanceof Ce)||mW(n,e,t))return!1;let r=e.args.side,i=e.args.on;return r==="left"&&RW(s,e)||!i&&ZB(s)}function mW(n,e,t){let s=e.args.on,r=new Set;if(s)for(let a of s.findAll(k))r.add(a);return n.sourceColumns(t).some(a=>!r.has(a))}function RW(n,e){let t=OW(n);if(!t||t.size===0)return!1;let{joinKeys:s}=UM(e),r=new Set(s.map(i=>i.name));for(let i of t)if(!r.has(i))return!1;return!0}function OW(n){let e=n.expression;if(!(e instanceof $))return;let t=e;if(t.args.distinct)return new Set(t.namedSelects);let s=t.args.group;if(s){let r=new Set((_nullishCoalesce(s.args.expressions, () => ([]))).filter(c=>c instanceof h).map(c=>c.sql())),i=new Set,a=new Set;for(let c of t.selects){if(!(c instanceof h))continue;let p=c.unalias().sql();r.has(p)&&(i.add(p),a.add(c.aliasOrName))}return[...r].every(c=>i.has(c))?a:new Set}return ZB(n)?new Set(t.namedSelects):new Set}function ZB(n){let e=n.expression;if(!(e instanceof $))return!1;let t=e;return!!(!t.args.from||t.selects.every(r=>r instanceof h?r.unalias()instanceof q:!1)||NW(n))}function NW(n){let e=n.expression.getArgKey("limit");return e instanceof Ct?_optionalChain([e, 'access', _1345 => _1345.args, 'access', _1346 => _1346.expression, 'optionalAccess', _1347 => _1347.args, 'access', _1348 => _1348.this])==="1":!1}function UM(n){let e=n.aliasOrName,s=(n.args.on||$e()).copy(),r=[],i=[];function a(o){let[c,p]=o.unnestOperands();if(!c||!p)return;let u=QB(c),E=QB(p);e&&u.has(e)&&!E.has(e)?(i.push(c),r.push(p),o.replace($e())):e&&E.has(e)&&!u.has(e)&&(i.push(p),r.push(c),o.replace($e()))}if(Mi(s)){let o=s instanceof Oe?s:nt([s,$e()],{copy:!1});for(let c of o.flatten())c instanceof Ee&&a(c)}else if(Mi(s,{dnf:!0})){let o;for(let c of s.flatten()){let p=Array.from(c.flatten()).filter(u=>u instanceof Ee);if(o===void 0)o=p;else{let u=[];for(let E of p){let g=o.filter(A=>E.sql()===A.sql());0<g.length&&(u.push(E),u.push(...g))}o=u}}if(o)for(let c of o)a(c)}return{sourceKeys:r,joinKeys:i,on:s}}function QB(n){let e=new Set;for(let t of n.findAll(k))t.table&&e.add(t.table);return e}function qM(n){if(n instanceof ae&&n.args.this)return qM(n.args.this),n;let e=Ci(n);if(!e)return n;let t=new Map;for(let c of e.cteScopes){let p=c.expression.parent;p&&t.set(p.alias,c)}for(let c of e.traverse())for(let[,p]of c.sources)p instanceof V&&t.set(p.name,p);let s=new Map,r=e.expression.args.with,i=!1;if(r){ue(r,ve),i=!!r.args.recursive;for(let c of _nullishCoalesce(r.args.expressions, () => ([])))D(c,Yt)&&c.args.this&&c.args.this&&s.set(c.args.this.sqlKey,c.alias)}let a=[];for(let c of e.cteScopes){for(let u of c.traverse()){if(u===c)continue;let E=eG(u,s,t);E&&a.push(E)}let p=c.expression.parent;p&&a.push(p)}let o=[...e.unionScopes,...e.subqueryScopes,...e.tableScopes];for(let c of o)for(let p of c.traverse()){let u=eG(p,s,t);u&&a.push(u)}return 0<a.length&&_optionalChain([(n instanceof ln?n.args.expression:n), 'optionalAccess', _1349 => _1349.setArgKey, 'call', _1350 => _1350("with",new ve({expressions:a,recursive:i}))]),n}function eG(n,e,t){if(n.isDerivedTable)return IW(n,e,t);if(n.isCte)return yW(n,e,t)}function IW(n,e,t){if(n.parent&&(0<n.parent.pivots.length||n.parent.expression instanceof kt))return;let s=n.expression.parent;if(!s)return;s instanceof ae&&(s=s.unwrap());let[r,i]=tG(n,e,t),a=oe(LR(r),s.alias||r,{copy:!1}),c=s.args.joins;return c&&Array.isArray(c)&&a.setArgKey("joins",c),s.replace(a),i}function yW(n,e,t){let s=n.expression.parent;if(!s)return;let[r,i]=tG(n,e,t),a=s.parent;if(s.pop(),a){let o=a.args.expressions;(!o||o.length===0)&&a.pop()}if(n.parent)for(let o of n.parent.traverse())for(let[,c]of Object.entries(o.selectedSources)){let[p,u]=c;if(u===n){let E=oe(LR(r),p.aliasOrName,{copy:!1});p.replace(E)}}return i}function tG(n,e,t){let s=e.get(n.expression.sqlKey),i=_optionalChain([n, 'access', _1351 => _1351.expression, 'access', _1352 => _1352.parent, 'optionalAccess', _1353 => _1353.alias])||"";i||(i=pn(Array.from(t.keys()),"cte")),s?i=s:t.has(i)&&(i=pn(Array.from(t.keys()),i)),t.set(i,n);let a;return s||(e.set(n.expression.sqlKey,i),a=new Yt({this:n.expression,alias:new ie({this:K(i)})})),[i,a]}function R_(n,e={}){let{leaveTablesIsolated:t=!1}=e;return n=bW(n,{leaveTablesIsolated:t}),n=PW(n,{leaveTablesIsolated:t}),n}var CW=[k,Ee,d,vt,Ye];function bW(n,e){let{leaveTablesIsolated:t}=e,s=Array.from(_t(n)),r=new Map;for(let a of s)for(let[,o]of Object.entries(a.selectedSources)){let[c,p]=o;if(p instanceof Ce&&p.isCte){let u=r.get(p);u||(u=[],r.set(p,u)),u.push([a,p,c])}}let i=[];for(let[,a]of r)a.length===1&&i.push(a[0]);for(let[a,o,c]of i){let p=c.findAncestor(Ge,z);if(p&&sG(a,o,{leaveTablesIsolated:t},p)){let u=c.aliasOrName;rG(a,o,u),nG(a,o,c,u),aG(a,o,u),cG(a,o),iG(a,o,p),oG(a,o,p),pG(a,o),wW(o),a.clearCache()}}return n}function PW(n,e){let{leaveTablesIsolated:t}=e;for(let s of _t(n))for(let r of s.derivedTables){let i=r.findAncestor(Ge,z),a=r.aliasOrName,o=s.sources.get(a);o instanceof Ce&&i&&sG(s,o,{leaveTablesIsolated:t},i)&&(rG(s,o,a),nG(s,o,r,a),aG(s,o,a),cG(s,o),iG(s,o,i),oG(s,o,i),pG(s,o),s.clearCache())}return n}function sG(n,e,t,s){let{leaveTablesIsolated:r}=t,i=e.expression.unnest();function a(){let x=new Set;if(!(i instanceof $))return!1;let m=i;for(let I of m.selects)I instanceof h&&I.find(Fe)&&x.add(I.aliasOrName);let N=s.aliasOrName,R=[];for(let I of n.columns)I.findAncestor(at,Ys,ke,z,$t,q)!==void 0&&R.push(I);return 0<R.filter(I=>I.table===N&&x.has(I.name)).length}function o(){if(!(s instanceof z))return!1;let x=s.aliasOrName,m=s.args.on;if(!m)return!1;let N=Array.from(m.findAll(k)).filter(P=>P.table===x).map(P=>P.name),R=e.expression.getArgKey("from");if(!R)return!1;let S=R.aliasOrName;if(!(e.expression instanceof $))return!1;let I=e.expression,y=new Map;for(let P of I.selects)P instanceof h&&y.set(P.aliasOrName,P);return N.some(P=>{let v=y.get(P);return v?Array.from(v.findAll(k)).some(B=>B.table!==S):!1})}function c(){let x=e.expression.parent,m=n.expression.parent;for(;m;){if(m===x)return!0;m=m.parent}return!1}if(!(n.expression instanceof $))return!1;let p=n.expression;if(p.isStar||!(i instanceof $))return!1;let u=i;for(let x of W.UNMERGABLE_ARGS)if(u.getArgKey(x))return!1;if(!u.args.from||0<n.pivots.length)return!1;for(let x of _nullishCoalesce(u.args.expressions, () => ([])))if(x instanceof h&&(x.find(q)||x.find($)||x.find(qt)))return!1;if(r&&1<Object.keys(n.selectedSources).length||s instanceof z&&u.args.joins&&0<u.args.joins.length)return!1;let E=s instanceof z?s.args.side:void 0;if(s instanceof z&&u.args.where&&(E==="full"||E==="left"||E==="right"))return!1;let g=p.args.joins;return!(s instanceof Ge&&u.args.where&&g&&g.some(x=>D(x,z)&&(x.args.side==="full"||x.args.side==="right"))||o()||a()||c()||u.args.order&&n.isUnion||b(_nullishCoalesce(u.args.expressions, () => ([])),0)instanceof pr)}function rG(n,e,t){let s=new Set(Object.keys(e.selectedSources)),r=new Set(Object.keys(n.selectedSources)),i=new Set(Array.from(s).filter(o=>r.has(o)));i.delete(t);let a=new Set([...r,...s]);for(let o of i){let c=pn(Array.from(a),o),p=e.selectedSources[o];if(!p)continue;let[u]=p,E=K(c);u instanceof V?u.alias?u.setArgKey("alias",E):u.replace(oe(u,E,{copy:!1})):_optionalChain([u, 'optionalAccess', _1354 => _1354.parent]) instanceof ae&&u.parent.setArgKey("alias",new ie({this:E}));for(let g of e.sourceColumns(o))g.setArgKey("table",K(c));e.renameSource(o,c),a.add(c)}}function nG(n,e,t,s){let i=e.expression.getArgKey("from").args.this;i.setArgKey("joins",t.args.joins),t.replace(i);for(let o of n.joinHints){let c=Array.from(o.findAll(V));for(let p of c)p.aliasOrName===t.aliasOrName&&p.setArgKey("this",K(i.aliasOrName))}n.removeSource(s);let a=e.sources.get(i.aliasOrName);a!==void 0&&n.addSource(i.aliasOrName,a)}function iG(n,e,t){let s=[],r=e.expression.getArgKey("joins");if(r)for(let i of r){s.push(i);let a=e.sources.get(i.aliasOrName);a&&n.addSource(i.aliasOrName,a)}if(0<s.length){let i=n.expression.getArgKey("joins")||[],a;t instanceof Ge?a=0:a=i.indexOf(t)+1,i.splice(a,0,...s),n.expression.setArgKey("joins",i)}}function aG(n,e,t){let s=new Map;for(let i of n.columns)if(i.table===t){let a=i.name,o=s.get(a);o||(o=[],s.set(a,o)),o.push(i)}if(!(e.expression instanceof $))return;let r=e.expression;for(let i of _nullishCoalesce(r.args.expressions, () => ([]))){if(!(i instanceof h))continue;let a=i.aliasOrName;if(!a)continue;let o=s.get(a)||[],c=i.unalias(),p=!CW.some(E=>c instanceof E),u=c.isNumber;for(let E of o){let g=E.parent;if(u&&g instanceof Ys){E.replace(K(E.name));continue}let A=c;g&&(g instanceof Zs||g instanceof Y)&&p&&(A=_r(A,{copy:!1})),g instanceof $&&E.name!==A.name&&(A=oe(A,E.name,{copy:!1})),E.replace(A.copy())}}}function oG(n,e,t){let s=e.expression.getArgKey("where");if(!s)return;let r=s.args.this;if(!(r instanceof h))return;let i=n.expression;if(t instanceof z){let a=i.args.from,o=new Set;a&&o.add(a.aliasOrName);let c=i.args.joins;if(c)for(let E of c){let g=E.aliasOrName;if(o.add(g),g===t.aliasOrName)break}let p=to(r);if(Array.from(p).every(E=>o.has(E))){t.on(r,{copy:!1});return}}i.where(r,{copy:!1})}function cG(n,e){let t=n.expression;t.args.group||t.args.distinct||t.args.having||t.args.order||Object.keys(n.selectedSources).length!==1||_optionalChain([t, 'access', _1355 => _1355.args, 'access', _1356 => _1356.expressions, 'optionalAccess', _1357 => _1357.some, 'call', _1358 => _1358(r=>r instanceof h?r.find(q)!==void 0:!1)])||t.setArgKey("order",e.expression.getArgKey("order"))}function pG(n,e){let t=e.expression.getArgKey("hint");if(!t)return;let s=n.expression,r=s.args.hint;if(r){let i=t.args.expressions;for(let a of _nullishCoalesce(i, () => ([])))a instanceof h&&r.append("expressions",a)}else s.setArgKey("hint",t)}function wW(n){let e=n.expression.parent;if(!e)return;let t=e.parent;if(!t)return;_optionalChain([t, 'access', _1359 => _1359.args, 'access', _1360 => _1360.expressions, 'optionalAccess', _1361 => _1361.length])===1?t.pop():e.pop()}var dw=Symbol("SELECT_ALL");function MW(n){let{isAgg:e}=n;return oe(e?new rn({this:w.number(1)}):"1","_")}function O_(n,e={}){let{schema:t,removeUnusedSelections:s=!0,dialect:r}=e,i=Qs(t,{dialect:r}),a=new Map,o=new Map,c=Array.from(_t(n));for(let p=c.length-1;0<=p;p--){let u=c[p],E=o.get(u)||new Set([dw]),g=a.get(u)||0,A=u.expression;if(A.getArgKey("distinct")&&(E=new Set([dw])),A instanceof be){let x=A.args.kind,m=A.args.side;if(!x&&!m){let[N,R]=u.unionScopes;if(N.expression.selects.length!==R.expression.selects.length)throw new Error(`Invalid set operation due to column mismatch: ${u.expression.sql({dialect:r})}.`);if(o.set(N,E),R.expression.selects.some(S=>S instanceof h&&S.isStar))o.set(R,E);else if(!N.expression.selects.some(S=>S instanceof h&&S.isStar))if(A.args.byName)o.set(R,o.get(N)||new Set);else{let S=new Set;o.set(R,S);for(let I=0;I<N.expression.selects.length;I++){let y=N.expression.selects[I];if(y instanceof h&&(E.has(dw)||E.has(y.aliasOrName))){let P=R.expression.selects[I];P instanceof h&&S.add(P.aliasOrName)}}}}}if(A instanceof $){if(s&&LW(u,E,i,g),A.isStar)continue;let x=new Map;for(let m of u.columns){let N=m.table||"",R=m.name,S=x.get(N);S||(S=new Set,x.set(N,S)),S.add(R)}for(let[m,N]of Object.entries(u.selectedSources)){let[R,S]=N;if(S instanceof Ce){let y=b(S.expression.selects,0),P;0<u.pivots.length||y instanceof pr?P=new Set([dw]):P=x.get(m)||new Set;let v=o.get(S);v||(v=new Set,o.set(S,v));for(let H of P)v.add(H)}let I=R.aliasColumnNames;I&&0<I.length&&a.set(S,I.length)}}}return n}function LW(n,e,t,s){let i=n.expression.args.order,a=new Set;if(i)for(let x of i.findAll(k))x.table||a.add(x.name);let o=[],c=!1,p=!1,u=!1,E=s,g=e.has(dw),A=n.expression;for(let x of A.selects){if(typeof x=="string"||typeof x=="number"||typeof x=="boolean")continue;let m=x,N=m.aliasOrName;g||e.has(N)||a.has(N)||0<E?(o.push(m),E-=1):(m.isStar&&(p=!0),c=!0),!u&&m.find(q)&&(u=!0)}if(p){let x=new yT(n,t,{}),m=new Set(o.map(R=>R.aliasOrName)),N=Array.from(e).filter(R=>typeof R=="string").sort();for(let R of N)if(!m.has(R)){let S=x.getTable(R);o.push(oe(Ie({col:R,table:_optionalChain([S, 'optionalAccess', _1362 => _1362.aliasOrName])}),R,{copy:!1}))}}o.length===0&&o.push(MW({isAgg:u})),A.select(o,{append:!1,copy:!1}),c&&n.clearCache()}function N_(n){let e=go("_u_");for(let t of _t(n)){let s=t.expression,r=s.parentSelect;if(!r||!D(r,$)||!D(s,$))continue;let i=s;0<t.externalColumns.length?_W(i,r,t.externalColumns,e):t.scopeType==="subquery"&&DW(i,r,e)}return n}function DW(n,e,t){if(1<n.selects.length)return;let s=n.findAncestor(Qe);if(!s||s instanceof d&&(s.parent instanceof V||s.parent instanceof Ge||s.parent instanceof z)||e!==s.parentSelect||!e.args.from)return;let r=n;n instanceof be&&(r=ft(n.selects).from(n.subquery(t()),{copy:!1}));let i=t(),a=s.findAncestor($t,at,z);if(!(s instanceof it||s instanceof wt)){let x=Ie({col:r.selects[0].aliasOrName,table:i}),m=_optionalChain([a, 'optionalAccess', _1363 => _1363.parentSelect]);if(a instanceof $t&&m===e||(!a||m!==e)&&(e.args.group||e.selects.some(S=>Pl(S,q))))x=new rn({this:x});else if(!(n.parent instanceof ae))return;let N="cross",R;s instanceof js&&(x=x.is(Ke()).not(),N="left",R=$e()),no(n.parent,x),e.join(r,{on:R,joinType:N,joinAlias:i,copy:!1});return}if(r.find([Ct,Fr]))return;let o=s;if(s instanceof wt){let x=s.findAncestor(Ee);if(!x||e!==x.parentSelect)return;o=x}let c=I_(o),p=r.selects[0],u=p.args.this;if(!(u instanceof h))return;let E=Ie({col:p.alias,table:i}),g=E.is(Ke()).not();a instanceof z?(no(o,$e()),e.where(g,{copy:!1})):no(o,g);let A=r.args.group;if(A){let x=new Set((_nullishCoalesce(A.args.expressions, () => ([]))).map(m=>m instanceof h?m.sql():String(m)));(x.size!==1||!x.has(p.args.this.sql()))&&(r=ft(oe(Ie({col:p.alias,table:"_q"}),p.alias,{copy:!1})).from(r.subquery("_q",{copy:!1}),{copy:!1}).groupBy(Ie({col:p.alias,table:"_q"}),{copy:!1}))}else Pl(u,q)||(r=r.groupBy(u,{copy:!1}));c&&e.join(r,{on:c.eq(E),joinType:"left",joinAlias:i,copy:!1})}function _W(n,e,t,s){let r=n.args.where;if(!r||r.find(pt)||n.find([Ct,Fr]))return;let i=s(),a=[];for(let y of t){if(y.findAncestor(at)!==r)return;let P=y.findAncestor(Ve);if(!P||P.findAncestor(at)!==r)return;let v;if(P instanceof Y)v=Array.from(_optionalChain([P, 'access', _1364 => _1364.left, 'optionalAccess', _1365 => _1365.walk, 'call', _1366 => _1366()])||[]).some(H=>H===y)?P.right:P.left;else return;if(!v)return;a.push([v,y,P])}if(!a.some(([,,y])=>y instanceof Ee))return;let o=e.selects.map(y=>y.unalias()).some(y=>y instanceof ae&&y===n.parent),c=n.selects[0],p=c.args.this;if(!(p instanceof h))return;let u=new Map,E=new Map,g=new Set,A=[],x=y=>g.has(y.sql());for(let[y,,P]of a){let v=y.sql();v===p.sql()?(u.set(v,c.alias),E.set(v,y),g.has(v)||(g.add(v),A.push(y))):(u.has(v)||(u.set(v,s()),E.set(v,y)),P instanceof Ee&&!g.has(v)&&(g.add(v),A.push(y)))}let m=n.findAncestor(Ve),N=o?rn:nr;!c.find(q)&&!x(p)&&n.select(oe(new N({this:p}),c.alias,{quoted:!1}),{append:!1,copy:!1}),m instanceof js&&n.setArgKey("expressions",[]);for(let[y,P]of u){let v=E.get(y);g.has(y)?(m instanceof js||y!==c.args.this.sql())&&n.select(`${v} AS ${P}`,{copy:!1}):n.select(oe(new N({this:v.copy()}),P,{quoted:!1}),{copy:!1})}let R=Ie({col:c.alias,table:i}),S=I_(m),I=_optionalChain([m, 'optionalAccess', _1367 => _1367.parent, 'optionalAccess', _1368 => _1368._constructor]);if(m instanceof js)R=Ie({col:Array.from(u.values())[0],table:i}),m=no(m,`NOT ${R} IS NULL`);else if(m instanceof qs){if(!I||!(I.prototype instanceof Y||I===Y))return;let y=new I({this:S,expression:Ie({col:"_x"})});m.parent&&(m=no(m.parent,`ARRAY_ALL(${R}, _x -> ${y})`))}else if(m instanceof wt){if(!I||!(I.prototype instanceof Y||I===Y))return;if(x(c.args.this)){let y=new I({this:S,expression:R});m.parent&&(m=no(m.parent,y))}else{let y=new I({this:S,expression:Ie({col:"_x"})});m=no(m,`ARRAY_ANY(${R}, _x -> ${y})`)}}else if(m instanceof it)x(c.args.this)?m=no(m,`${S} = ${R}`):m=no(m,`ARRAY_ANY(${R}, _x -> _x = ${m.args.this})`);else{if(o&&_optionalChain([n, 'access', _1369 => _1369.parent, 'optionalAccess', _1370 => _1370.alias])&&(R=oe(R,n.parent.alias,{copy:!1})),c.find(uc)){let y=P=>P instanceof uc?w.number(0):P instanceof q?Ke():P;R=new St({this:R,expressions:[c.args.this.transform(y)]})}_optionalChain([n, 'access', _1371 => _1371.parent, 'optionalAccess', _1372 => _1372.replace, 'call', _1373 => _1373(R)])}for(let[y,P,v]of a){v.replace($e());let H=u.get(y.sql());if(!H)continue;let B=Ie({col:H,table:i});if(o){y.replace(B),v instanceof Ee||e.where(v,{copy:!1});continue}x(y)?y.replace(B):v instanceof Ee?m&&(m=no(m,`(${m} AND ARRAY_CONTAINS(${B}, ${P}))`)):(y.replace(K("_x")),m&&(m=no(m,`(${m} AND ARRAY_ANY(${B}, _x -> ${v}))`)))}e.join(n.groupBy(A,{copy:!1}),{on:a.filter(([,,y])=>y instanceof Ee).map(([,,y])=>y),joinType:"left",joinAlias:i,copy:!1})}function no(n,e){return n.replace(pw(e))}function I_(n){if(n instanceof it)return n.args.this;if(n instanceof wt||n instanceof qs)return I_(n.parent);if(n instanceof Y)return n.left instanceof ae||n.left instanceof wt||n.left instanceof js||n.left instanceof qs?n.right:n.left}var FG={YEAR:["ADD_MONTHS",12],MONTH:["ADD_MONTHS",1],QUARTER:["ADD_MONTHS",3],WEEK:["DATE_ADD",7],DAY:["DATE_ADD",1]},kW={MILLISECOND:" * 1000",SECOND:"",MINUTE:" / 60",HOUR:" / 3600"},UW=new Set(["YEAR","QUARTER","MONTH"]);function C_(n){if(n instanceof sn&&!n.args.unit)return this.func("DATE_ADD",[n.args.this,n.args.expression]);let e=n.text("unit").toUpperCase(),[t,s]=FG[e]||["DATE_ADD",1];n instanceof Wt&&(s*=-1);let r=n.args.expression;if(r instanceof w){let i=r.isNumber?parseFloat(_nullishCoalesce(r.args.this, () => ("0"))):parseInt(_nullishCoalesce(r.args.this, () => ("0")));r=w.number(i*s)}else s!==1&&(r=new Ts({this:r,expression:w.number(s)}));return this.func(t,[n.args.this,r])}function uG(n){let e=n.text("unit").toUpperCase(),t=kW[e];if(t!==void 0){let c=this.sql(n,"this"),p=this.sql(n,"expression"),u=`UNIX_TIMESTAMP(${c}) - UNIX_TIMESTAMP(${p})`;return t?`(${u})${t}`:u}let s=UW.has(e),r=s?"MONTHS_BETWEEN":"DATEDIFF",i=_optionalChain([FG, 'access', _1374 => _1374[e], 'optionalAccess', _1375 => _1375[1]])||1,a=1<i?` / ${i}`:"",o=`${r}(${this.formatArgs([n.args.this,n.args.expression])})`;return(s||a)&&(o=`CAST(${o}${a} AS INT)`),o}function qW(n){let e=n.args.this;if(e&&fB(e)){if(e.args.this instanceof w&&e.args.this.isString){let t=w.string(`[${e.args.this.args.this}]`),s=this.func("FROM_JSON",[t,this.func("SCHEMA_OF_JSON",[t])]),r=this.func("TO_JSON",[s]);return this.func("REGEXP_EXTRACT",[r,w.string("'^.(.*).$'"),w.number(1)])}return this.sql(e)}return this.func("TO_JSON",[e,n.args.options])}function vW(n){return n.args.expression&&this.unsupported("Unsupported arg 'expression' for ArraySort"),this.func("SORT_ARRAY",[n.args.this])}function FW(n){return this.func("UNIX_TIMESTAMP",[n.args.this,o_("hive").call(this,n)])}function BW(n){let e=this.sql(n,"this"),t=n.args.scale;return t===void 0||t.toValue()===Us.SECONDS.toValue()?X("FROM_UNIXTIME").call(this,n):`FROM_UNIXTIME(${e} / POW(10, ${t}))`}function GW(n){let e=this.sql(n,"this"),t=this.formatTime(n);return t!=null&&![de.TIME_FORMAT,de.DATE_FORMAT].includes(t)&&(e=`FROM_UNIXTIME(UNIX_TIMESTAMP(${e}, ${t}))`),`CAST(${e} AS DATE)`}function $W(n){let e=this.sql(n,"this"),t=this.formatTime(n);return t!=null&&![de.TIME_FORMAT,de.DATE_FORMAT].includes(t)&&(e=`FROM_UNIXTIME(UNIX_TIMESTAMP(${e}, ${t}))`),`CAST(${e} AS TIMESTAMP)`}function YW(n){let e=this.formatTime(n);return e&&![de.TIME_FORMAT,de.DATE_FORMAT].includes(e)?this.func("TO_DATE",[n.args.this,e]):n.parent instanceof h&&this._constructor.TS_OR_DS_EXPRESSIONS.has(n.parent._constructor)?this.sql(n,"this"):this.func("TO_DATE",[n.args.this])}function vM(n){return e=>{let t=new n({this:b(e,0)});return b(e,1)instanceof Et&&_optionalChain([b, 'call', _1376 => _1376(e,1), 'optionalAccess', _1377 => _1377.args, 'access', _1378 => _1378.this])===!0?new dn({this:t}):t}}function HW(n){let e=Ri(Ue,{dialect:"hive"})(n);return e.setArgKey("safe",!0),e}function VW(n){let e=b(n,1);return e&&(e=e.mul(-1)),new sn({this:b(n,0),expression:e,unit:Te("DAY")})}var EG,hG,gG,dG,AG,fG,xG,sg,io=class extends(xG=Dt,fG=[O],AG=[O],dG=[O],gG=[O],hG=[O],EG=[O],xG){static get QUOTES(){return["'",'"']}static get IDENTIFIERS(){return["`"]}static get STRING_ESCAPES(){return["\\"]}static get SINGLE_TOKENS(){return{...Dt.SINGLE_TOKENS,$:"parameter"}}static get ORIGINAL_KEYWORDS(){return{...Dt.KEYWORDS,"ADD ARCHIVE":"command","ADD ARCHIVES":"command","ADD FILE":"command","ADD FILES":"command","ADD JAR":"command","ADD JARS":"command",MINUS:"except","MSCK REPAIR":"command",REFRESH:"refresh","TIMESTAMP AS OF":"timestampSnapshot","VERSION AS OF":"versionSnapshot",SERDEPROPERTIES:"serdeProperties"}}static get NUMERIC_LITERALS(){return{L:"BIGINT",S:"SMALLINT",Y:"TINYINT",D:"DOUBLE",F:"FLOAT",BD:"DECIMAL"}}};sg=re(xG),T(sg,10,"QUOTES",fG,io),T(sg,10,"IDENTIFIERS",AG,io),T(sg,10,"STRING_ESCAPES",dG,io),T(sg,10,"SINGLE_TOKENS",gG,io),T(sg,10,"ORIGINAL_KEYWORDS",hG,io),T(sg,10,"NUMERIC_LITERALS",EG,io),te(sg,io),se(sg,3,io);var TG,SG,mG,RG,OG,NG,IG,yG,CG,bc,ds=class extends(CG=he,yG=[O],IG=[O],NG=[O],OG=[O],RG=[O],mG=[O],SG=[O],TG=[O],CG){static get ID_VAR_TOKENS(){return new Set([...he.ID_VAR_TOKENS,"sessionUser","currentCatalog","straightJoin"])}static get NO_PAREN_FUNCTIONS(){let t={...he.NO_PAREN_FUNCTIONS};return delete t.currentTime,delete t.localtime,delete t.localtimestamp,t}static get FUNCTION_PARSERS(){return{...he.FUNCTION_PARSERS,PERCENTILE:function(){return this.parseQuantileFunction(eo)},PERCENTILE_APPROX:function(){return this.parseQuantileFunction(_s)}}}static get FUNCTIONS(){return{...he.FUNCTIONS,ADD_MONTHS:t=>new sn({this:b(t,0),expression:b(t,1),unit:Te("MONTH")}),BASE64:t=>Gh.fromArgList(t),COLLECT_LIST:t=>new nr({this:b(t,0),nullsExcluded:!0}),COLLECT_SET:t=>vn.fromArgList(t),DATE_ADD:t=>new sn({this:b(t,0),expression:b(t,1),unit:new Ze({this:"DAY"})}),DATE_FORMAT:t=>Ri(Ns,{dialect:"hive"})([new Xs({this:b(t,0)}),b(t,1)]),DATE_SUB:VW,DATEDIFF:t=>new ks({this:new Ue({this:b(t,0)}),expression:new Ue({this:b(t,1)})}),DAY:t=>new Zr({this:new Ue({this:b(t,0)})}),FIRST:vM(gT),FIRST_VALUE:vM(AT),FROM_UNIXTIME:Ri(mc,{dialect:"hive",defaultValue:!0}),GET_JSON_OBJECT:(t,{dialect:s})=>new Rr({this:b(t,0),expression:s.toJsonPath(b(t,1))}),LAST:vM(dT),LAST_VALUE:vM(fT),MAP:t=>{if(t.length===1&&t[0].isStar)return new NE({this:t[0]});let s=[],r=[];for(let i=0;i<t.length;i+=2)s.push(t[i]),t[i+1]&&r.push(t[i+1]);return new gr({keys:new Ne({expressions:s}),values:new Ne({expressions:r})})},MONTH:t=>new Js({this:new Ue({this:b(t,0)})}),REGEXP_EXTRACT:jR(br),REGEXP_EXTRACT_ALL:jR(kn),SEQUENCE:t=>Os.fromArgList(t),SIZE:t=>lr.fromArgList(t),SPLIT:t=>$h.fromArgList(t),STR_TO_MAP:t=>new Wh({this:b(t,0),pairDelim:b(t,1)||w.string(","),keyValueDelim:b(t,2)||w.string(":")}),TO_DATE:HW,TO_JSON:t=>Sc.fromArgList(t),TRUNC:t=>er.fromArgList(t),UNBASE64:t=>Bh.fromArgList(t),UNIX_TIMESTAMP:t=>Ri(Vh,{dialect:"hive",defaultValue:!0})(0<t.length?t:[new ir({})]),YEAR:t=>new qn({this:new Ue({this:b(t,0)})})}}static get NO_PAREN_FUNCTION_PARSERS(){return{...he.NO_PAREN_FUNCTION_PARSERS,TRANSFORM:function(){return this.parseTransform()}}}static get PROPERTY_PARSERS(){return{...he.PROPERTY_PARSERS,SERDEPROPERTIES:function(){return new ci({expressions:this.parseWrappedCsv(()=>this.parseProperty())})}}}static get ALTER_PARSERS(){return{...he.ALTER_PARSERS,CHANGE:function(){return this.parseAlterTableChange()}}}parseTransform(){if(!this.match("lParen",{advance:!1})){this.retreat(this.index-1);return}let t=this.parseWrappedCsv(()=>this.parseLambda()),s=this.parseRowFormat({matchRow:!0}),r;if(this.matchTextSeq("RECORDWRITER")&&(r=this.parseString()),!this.match("using"))return Ry.fromArgList(t);let i=this.parseString();this.match("alias");let a=this.parseSchema(),o=this.parseRowFormat({matchRow:!0}),c;return this.matchTextSeq("RECORDREADER")&&(c=this.parseString()),this.expression(pr,{expressions:t,commandScript:i,schema:a,rowFormatBefore:s,recordWriter:r,rowFormatAfter:o,recordReader:c})}parseQuantileFunction(t){let s;this.match("distinct")?s=this.expression(ct,{expressions:[this.parseLambda()]}):(this.match("all"),s=this.parseLambda());let r=[s];return this.match("comma")&&r.push(...this.parseFunctionArgs()),t.fromArgList(r)}parseTypes(t={}){let{checkFunc:s=!1,schema:r=!1,allowIdentifiers:i=!0}=t,a=super.parseTypes({checkFunc:s,schema:r,allowIdentifiers:i});return a&&!r?a.transform((o,c)=>o instanceof C&&o.isType(["char","varchar"])?o.replace(C.build("text")):o,{copy:!1}):a}parseAlterTableChange(){this.match("column");let t=this.parseField({anyToken:!0});if(this.constructor.CHANGE_COLUMN_ALTER_SYNTAX&&this.matchTextSeq("TYPE"))return this.expression(ws,{this:t,dtype:this.parseTypes({schema:!0})});let s=this.parseField({anyToken:!0}),r=this.parseTypes({schema:!0}),i=this.match("comment")&&this.parseString();return(!t||!s||!r)&&this.raiseError("Expected 'CHANGE COLUMN' to be followed by 'column_name' 'column_name' 'data_type'"),this.expression(ws,{this:t,renameTo:s,dtype:r,comment:i})}parsePartitionAndOrder(){return[this.matchSet(["partitionBy","distributeBy"])?this.parseCsv(()=>this.parseAssignment()):[],_nullishCoalesce(super.parseOrder({skipOrderToken:this.match("sortBy")}), () => (void 0))]}parseParameter(){this.match("lBrace");let t=this.parseIdentifier()||this.parsePrimaryOrVar(),s=this.match("colon")&&(this.parseIdentifier()||this.parsePrimaryOrVar());return this.match("rBrace"),this.expression(ep,{this:t,expression:s})}toPropEq(t,s){if(t.isStar)return t;let r;return t instanceof k?r=_nullishCoalesce(t.args.this, () => (K(`col${s+1}`))):r=K(`col${s+1}`),this.expression(At,{this:r,expression:t})}static get TABLE_ALIAS_TOKENS(){return new Set([...he.TABLE_ALIAS_TOKENS,"straightJoin"])}};bc=re(CG),T(bc,10,"ID_VAR_TOKENS",yG,ds),T(bc,10,"NO_PAREN_FUNCTIONS",IG,ds),T(bc,10,"FUNCTION_PARSERS",NG,ds),T(bc,10,"FUNCTIONS",OG,ds),T(bc,10,"NO_PAREN_FUNCTION_PARSERS",RG,ds),T(bc,10,"PROPERTY_PARSERS",mG,ds),T(bc,10,"ALTER_PARSERS",SG,ds),T(bc,10,"TABLE_ALIAS_TOKENS",TG,ds),te(bc,ds),se(bc,3,ds),ds.LOG_DEFAULTS_TO_LN=!0,ds.STRICT_CAST=!1,ds.VALUES_FOLLOWED_BY_PAREN=!1,ds.JOINS_HAVE_EQUAL_PRECEDENCE=!0,ds.ADD_JOIN_ON_TRUE=!0,ds.ALTER_TABLE_PARTITIONS=!0,ds.CHANGE_COLUMN_ALTER_SYNTAX=!1;var bG,PG,wG,MG,LG,DG,_G,rg,et=class extends(_G=L,DG=[O],LG=[O],MG=[O],wG=[O],PG=[O],bG=[O],_G){static get EXPRESSIONS_WITHOUT_NESTED_CTES(){return new Set([Ss,$,ae,be])}static get SUPPORTED_JSON_PATH_PARTS(){return new Set([Gt,Ls,Ds,hs])}static get TYPE_MAPPING(){return new Map([...L.TYPE_MAPPING,["bit","BOOLEAN"],["blob","BINARY"],["datetime","TIMESTAMP"],["rowversion","BINARY"],["text","STRING"],["time","TIMESTAMP"],["timestampntz","TIMESTAMP"],["timestamptz","TIMESTAMP"],["utinyint","SMALLINT"],["varbinary","BINARY"]])}static get ORIGINAL_TRANSFORMS(){return new Map([...L.TRANSFORMS,[U,EB],[Ic,X("FIRST")],[hl,oB],[Wr,l_("MAX_BY")],[jr,l_("MIN_BY")],[Ne,Ks([SM])],[Pn,X("CONCAT")],[qp,function(s){return this.func("CONCAT_WS",[s.args.expression,s.args.this])}],[Hy,function(s){return vW.call(this,s)}],[ve,lB],[ut,function(s){return C_.call(this,s)}],[ks,function(s){return uG.call(this,s)}],[Wa,YR],[Wt,function(s){return C_.call(this,s)}],[Yp,function(s){return`CAST(DATE_FORMAT(${this.sql(s,"this")}, ${de.DATEINT_FORMAT}) AS INT)`}],[Vp,function(s){return`TO_DATE(CAST(${this.sql(s,"this")} AS STRING), ${de.DATEINT_FORMAT})`}],[pi,function(s){return`STORED BY ${this.sql(s,"this")}`}],[Bh,X("UNBASE64")],[Os,WR],[Mn,WR],[He,RM()],[ms,GR],[Hi,function(s){return this.binary(s,"DIV")}],[Kx,X("ISNAN")],[Zt,function(s){return this.func("GET_JSON_OBJECT",[s.args.this,s.args.expression])}],[Rr,function(s){return this.func("GET_JSON_OBJECT",[s.args.this,s.args.expression])}],[Sc,function(s){return qW.call(this,s)}],[Ja,CM],[Eo,a_],[rn,wM],[en,function(s){return this.func("UNHEX",[this.func("MD5",[s.args.this])])}],[fl,PM],[Gp,function(s){return this.func("MONTHS_BETWEEN",[s.args.this,s.args.expression])}],[$i,function(s){return s.args.allowNull?"":"NOT NULL"}],[gr,a_],[us,Ks([sF,rF,nF])],[eo,X("PERCENTILE")],[_s,X("PERCENTILE_APPROX")],[br,VR],[kn,VR],[Xa,dB],[lc,function(s){return this.binary(s,"RLIKE")}],[$h,X("SPLIT")],[_n,bM],[Nr,function(s){return this.nakedProperty(s)}],[vn,X("COLLECT_SET")],[nl,function(s){return this.func("SPLIT",[s.args.this,this.func("CONCAT",[w.string("\\Q"),s.args.expression,w.string("\\E")])])}],[$,Ks([Kh,zh,s=>Jv(s,{unnestUsingArraysZip:!1}),zv])],[ps,function(s){return $R.call(this,s,{funcName:"LOCATE",supportsPosition:!0})}],[ar,function(s){return GW.call(this,s)}],[Jt,function(s){return $W.call(this,s)}],[Vh,function(s){return FW.call(this,s)}],[cT,IM],[NE,X("MAP")],[V,Ks([xM])],[al,X("TO_DATE")],[Xs,Tl],[ol,X("UNIX_TIMESTAMP")],[er,function(s){return this.func("TRUNC",[s.args.this,ro(s)])}],[Za,X("UNIX_TIMESTAMP")],[Gh,X("BASE64")],[ll,function(s){return`CAST(SUBSTR(REPLACE(CAST(${this.sql(s,"this")} AS STRING), '-', ''), 1, 8) AS INT)`}],[sn,function(s){return C_.call(this,s)}],[cl,function(s){return uG.call(this,s)}],[Ue,function(s){return YW.call(this,s)}],[Ft,NM],[or,HR],[ul,X("ASCII")],[mc,function(s){return this.func("FROM_UNIXTIME",[s.args.this,o_("hive").call(this,s)])}],[Us,function(s){return BW.call(this,s)}],[El,X("FROM_UNIXTIME")],[Bt,function(s){return`PARTITIONED BY ${this.sql(s,"this")}`}],[jh,X("FORMAT_NUMBER")],[No,function(s){return this.nationalSql(s,{prefix:""})}],[Uo,function(s){return`(${this.expressions(s,{key:"this",indent:!1})})`}],[qo,function(s){return`(${this.expressions(s,{key:"this",indent:!1})})`}],[si,()=>""],[Br,()=>""],[ii,function(s){return this.func("BUCKET",[s.args.expression,s.args.this])}],[ai,function(s){return this.func("TRUNCATE",[s.args.expression,s.args.this])}],[vo,()=>"PRIMARY KEY"],[xi,X("WEEKOFYEAR")],[Kr,X("DAYOFMONTH")],[ur,X("DAYOFWEEK")],[Si,function(s){return so.call(this,s,"insCost","delCost","subCost","maxDist"),X("LEVENSHTEIN").call(this,s)}]])}static get PROPERTIES_LOCATION(){return new Map([...L.PROPERTIES_LOCATION,[$s,"postSchema"],[Bt,"postSchema"],[Vs,"unsupported"],[li,"unsupported"]])}static get TS_OR_DS_EXPRESSIONS(){return new Set([ks,Zr,Js,qn])}unnestSql(t){return X("EXPLODE").call(this,t)}jsonPathKeySql(t){return t.args.this instanceof hs?(this.unsupported("Unsupported wildcard in JSONPathKey expression"),""):super.jsonPathKeySql(t)}parameterSql(t){let s=this.sql(t,"this"),r=this.sql(t,"expression"),i=t.parent;return s=r?`${s}:${r}`:s,i instanceof Ee&&i.parent instanceof mr?s:`\${${s}}`}schemaSql(t){for(let s of t.findAll(es))s.args.desc===!1&&s.setArgKey("desc",void 0);return super.schemaSql(t)}constraintSql(t){for(let i of Array.from(t.findAll(mt)))i.pop();let s=this.sql(t,"this"),r=this.expressions(t,{sep:" ",flat:!0});return`CONSTRAINT ${s} ${r}`}rowFormatSerdePropertySql(t){let s=this.sql(t,"serdeProperties");return s=s?` ${s}`:"",`ROW FORMAT SERDE ${this.sql(t,"this")}${s}`}arrayAggSql(t){return this.func("COLLECT_LIST",[t.args.this instanceof ke?t.args.this.args.this:t.args.this])}truncSql(t){return t.args.decimals&&this.unsupported("Unsupported arg 'decimals' for TRUNC"),this.sql(new Z({this:t.args.this,to:C.build("bigint")}))}dataTypeSql(t){if(t.isType(L.PARAMETERIZABLE_TEXT_TYPES)&&(!t.args.expressions||t.args.expressions[0].name==="MAX"))t=_nullishCoalesce(C.build("text"), () => (t));else if(t.isType("text")&&t.args.expressions)t.setArgKey("this","varchar");else if(t.isType(C.TEMPORAL_TYPES))t=_nullishCoalesce(C.build(t.args.this), () => (t));else if(t.isType("float")){let s=t.find(Jr);s instanceof Jr&&(t=_nullishCoalesce((parseInt(_nullishCoalesce(_optionalChain([s, 'access', _1379 => _1379.args, 'access', _1380 => _1380.this, 'optionalAccess', _1381 => _1381.args, 'access', _1382 => _1382.this, 'optionalAccess', _1383 => _1383.toString, 'call', _1384 => _1384()]), () => ("0")))<=32?C.build("float"):C.build("double")), () => (t)))}return super.dataTypeSql(t)}versionSql(t){return super.versionSql(t).replace("FOR ","")}structSql(t){let s=[];return _optionalChain([t, 'access', _1385 => _1385.args, 'access', _1386 => _1386.expressions, 'optionalAccess', _1387 => _1387.forEach, 'call', _1388 => _1388(r=>{if(r instanceof At){this.unsupported("Hive does not support named structs.");let i=r.args.expression;s.push(i instanceof h||typeof i=="string"?i:"")}else s.push(r)})]),this.func("STRUCT",s)}columnDefSql(t,s={}){let{sep:r=" "}=s;return super.columnDefSql(t,{sep:t.parent instanceof C&&t.parent.isType("struct")?": ":r})}alterColumnSql(t){let s=this.sql(t,"this"),r=this.sql(t,"renameTo")||s,i=this.sql(t,"dtype"),a=this.sql(t,"comment"),o=a?` COMMENT ${a}`:"",c=this.sql(t,"default"),p=t.args.visible,u=t.args.allowNull,E=t.args.drop;return(c||E||p||u)&&this.unsupported("Unsupported CHANGE COLUMN syntax"),i||this.unsupported("CHANGE COLUMN without a type is not supported"),`CHANGE COLUMN ${s} ${r} ${i}${o}`}renameColumnSql(t){return this.unsupported("Cannot rename columns without data type defined in Hive"),""}alterSetSql(t){let s=this.expressions(t,{flat:!0});s=s?` ${s}`:"";let r=this.sql(t,"location");r=r?` LOCATION ${r}`:"";let i=this.expressions(t,{key:"fileFormat",flat:!0,sep:" "});i=i?` FILEFORMAT ${i}`:"";let a=this.sql(t,"serde");a=a?` SERDE ${a}`:"";let o=this.expressions(t,{key:"tag",flat:!0,sep:""});return o=o?` TAGS ${o}`:"",`SET${a}${s}${r}${i}${o}`}serdePropertiesSql(t){let s=t.args.with?"WITH ":"",r=this.expressions(t,{flat:!0});return`${s}SERDEPROPERTIES (${r})`}existsSql(t){return t.args.expression?this.functionFallbackSql(t):super.existsSql(t)}timeToStrSql(t){let s=t.args.this;return s instanceof Xs&&(s=s.args.this),this.func("DATE_FORMAT",[s,this.formatTime(t)])}fileFormatPropertySql(t){let s;return t.args.this instanceof Co?s=this.sql(t,"this"):s=t.name.toUpperCase(),`STORED AS ${s}`}};rg=re(_G),T(rg,10,"EXPRESSIONS_WITHOUT_NESTED_CTES",DG,et),T(rg,10,"SUPPORTED_JSON_PATH_PARTS",LG,et),T(rg,10,"TYPE_MAPPING",MG,et),T(rg,10,"ORIGINAL_TRANSFORMS",wG,et),T(rg,10,"PROPERTIES_LOCATION",PG,et),T(rg,10,"TS_OR_DS_EXPRESSIONS",bG,et),te(rg,et),se(rg,3,et),et.SUPPORTS_DECODE_CASE=!1,et.SELECT_KINDS=[],et.TRY_SUPPORTED=!1,et.SUPPORTS_UESCAPE=!1,et.LIMIT_FETCH="LIMIT",et.TABLESAMPLE_WITH_METHOD=!1,et.JOIN_HINTS=!1,et.TABLE_HINTS=!1,et.QUERY_HINTS=!1,et.INDEX_ON="ON TABLE",et.EXTRACT_ALLOWS_QUOTES=!1,et.NVL2_SUPPORTED=!1,et.LAST_DAY_SUPPORTS_DATE_PART=!1,et.JSON_PATH_SINGLE_QUOTE_ESCAPE=!0,et.SUPPORTS_TO_NUMBER=!1,et.WITH_PROPERTIES_PREFIX="TBLPROPERTIES",et.PARSE_JSON_NAME=void 0,et.PAD_FILL_PATTERN_IS_REQUIRED=!0,et.SUPPORTS_MEDIAN=!1,et.ARRAY_SIZE_NAME="SIZE",et.ALTER_SET_TYPE="";var kG,UG,qG,vG,Aw,de=class extends(vG=W,qG=[O],UG=[O],kG=[O],vG){static get EXPRESSION_METADATA(){return new Map(Cc.EXPRESSION_METADATA)}static get COERCES_TO(){let t=new Map($n.COERCES_TO);for(let s of[...C.NUMERIC_TYPES,...C.TEMPORAL_TYPES,"interval"]){let r=_nullishCoalesce(t.get(s), () => (new Set));t.set(s,new Set([...r,...C.TEXT_TYPES]))}return t}static get NORMALIZATION_STRATEGY(){return"caseInsensitive"}static get TIME_MAPPING(){return{y:"%Y",Y:"%Y",YYYY:"%Y",yyyy:"%Y",YY:"%y",yy:"%y",MMMM:"%B",MMM:"%b",MM:"%m",M:"%-m",dd:"%d",d:"%-d",HH:"%H",H:"%-H",hh:"%I",h:"%-I",mm:"%M",m:"%-M",ss:"%S",s:"%-S",SSSSSS:"%f",a:"%p",DD:"%j",D:"%-j",E:"%a",EE:"%a",EEE:"%a",EEEE:"%A",z:"%Z",Z:"%z"}}};Aw=re(vG),T(Aw,10,"COERCES_TO",qG,de),T(Aw,10,"NORMALIZATION_STRATEGY",UG,de),T(Aw,10,"TIME_MAPPING",kG,de),te(Aw,de),se(Aw,3,de),de.DIALECT_NAME="hive",de.ALIAS_POST_TABLESAMPLE=!0,de.IDENTIFIERS_CAN_START_WITH_DIGIT=!0,de.SUPPORTS_USER_DEFINED_TYPES=!1,de.SAFE_DIVISION=!0,de.ARRAY_AGG_INCLUDES_NULLS=void 0,de.REGEXP_EXTRACT_DEFAULT_GROUP=1,de.ALTER_TABLE_SUPPORTS_CASCADE=!0,de.INITCAP_DEFAULT_DELIMITER_CHARS=`
|
|
41
|
+
\r\f\v`,de.DATE_FORMAT="'yyyy-MM-dd'",de.DATEINT_FORMAT="'yyyyMMdd'",de.TIME_FORMAT="'yyyy-MM-dd HH:mm:ss'",de.Tokenizer=io,de.Parser=ds,de.Generator=et;W.register("hive",de);function le(n,e={}){return function(){return this.parseShowMysql(n,e)}}function WW(n){let e=this.sql(n,"this"),t=n.text("unit").toUpperCase(),s,r;if(t==="WEEK")s=`CONCAT(YEAR(${e}), ' ', WEEK(${e}, 1), ' 1')`,r="%Y %u %w";else if(t==="MONTH")s=`CONCAT(YEAR(${e}), ' ', MONTH(${e}), ' 1')`,r="%Y %c %e";else if(t==="QUARTER")s=`CONCAT(YEAR(${e}), ' ', QUARTER(${e}) * 3 - 2, ' 1')`,r="%Y %c %e";else if(t==="YEAR")s=`CONCAT(YEAR(${e}), ' 1 1')`,r="%Y %c %e";else return t!=="DAY"&&this.unsupported(`Unexpected interval unit: ${t}`),this.func("DATE",[e]);return this.func("STR_TO_DATE",[s,`'${r}'`])}var jW=new Set(["f","H","h","I","i","k","l","p","r","S","s","T"]);function JW(n){let e=0,t=n.length;for(;e<t;){if(n[e]==="%"&&(e+=1,e<t&&jW.has(n[e])))return!0;e+=1}return!1}function XW(n){let e=b(n,1),t=Nt.formatTime(e),s=b(n,0);return e&&JW(e instanceof h?e.name:e)?new Jt({this:s,format:t||""}):new ar({this:s,format:t})}function P_(n){return this.func("STR_TO_DATE",[n.args.this,this.formatTime(n)])}function zW(n){let e=n.args.scale,t=n.args.this;return e===void 0||e.toValue()===Us.SECONDS.toValue()?this.func("FROM_UNIXTIME",[t,this.formatTime(n)]):this.func("FROM_UNIXTIME",[new jt({this:t,expression:DR("POW","10",e.toString())}),this.formatTime(n)])}function b_(n){return function(e){return this.func(`DATE_${n}`,[e.args.this,new ze({this:e.args.expression,unit:LM(e)})])}}function KW(n){return n.args.format?P_.call(this,n):this.func("DATE",[n.args.this])}function Ni(n,e=["this"]){return function(t){for(let s of e){let r=t.getArgKey(s);r instanceof Ue&&!r.args.format&&t.setArgKey(s,r.args.this)}return n?n.call(this,t):this.functionFallbackSql(t)}}var BG,GG,$G,FM,Fn=class extends($G=Dt,GG=[O],BG=[O],$G){constructor(){super(...arguments);this.ESCAPE_FOLLOW_CHARS=["0","b","n","r","t","Z","%","_"];this.NESTED_COMMENTS=!1}static get ORIGINAL_KEYWORDS(){return{...Dt.KEYWORDS,BLOB:"blob",CHARSET:"characterSet",DISTINCTROW:"distinct",EXPLAIN:"describe",FORCE:"force",IGNORE:"ignore",KEY:"key","LOCK TABLES":"command",LONGBLOB:"longblob",LONGTEXT:"longtext",MEDIUMBLOB:"mediumblob",MEDIUMINT:"mediumint",MEDIUMTEXT:"mediumtext","MEMBER OF":"memberOf",MOD:"mod",SEPARATOR:"separator",SERIAL:"serial",SIGNED:"bigint","SIGNED INTEGER":"bigint","SOUNDS LIKE":"soundsLike",START:"begin",TIMESTAMP:"timestamptz",TINYBLOB:"tinyblob",TINYTEXT:"tinytext","UNLOCK TABLES":"command",UNSIGNED:"ubigint","UNSIGNED INTEGER":"ubigint",YEAR:"year",_ARMSCII8:"introducer",_ASCII:"introducer",_BIG5:"introducer",_BINARY:"introducer",_CP1250:"introducer",_CP1251:"introducer",_CP1256:"introducer",_CP1257:"introducer",_CP850:"introducer",_CP852:"introducer",_CP866:"introducer",_CP932:"introducer",_DEC8:"introducer",_EUCJPMS:"introducer",_EUCKR:"introducer",_GB18030:"introducer",_GB2312:"introducer",_GBK:"introducer",_GEOSTD8:"introducer",_GREEK:"introducer",_HEBREW:"introducer",_HP8:"introducer",_KEYBCS2:"introducer",_KOI8R:"introducer",_KOI8U:"introducer",_LATIN1:"introducer",_LATIN2:"introducer",_LATIN5:"introducer",_LATIN7:"introducer",_MACCE:"introducer",_MACROMAN:"introducer",_SJIS:"introducer",_SWE7:"introducer",_TIS620:"introducer",_UCS2:"introducer",_UJIS:"introducer",_UTF8:"introducer",_UTF16:"introducer",_UTF16LE:"introducer",_UTF32:"introducer",_UTF8MB3:"introducer",_UTF8MB4:"introducer","@@":"sessionParameter"}}static get COMMANDS(){let t=new Set([...Dt.COMMANDS,"replace"]);return t.delete("show"),t}};FM=re($G),T(FM,10,"ORIGINAL_KEYWORDS",GG,Fn),T(FM,10,"COMMANDS",BG,Fn),te(FM,Fn),se(FM,3,Fn),Fn.QUOTES=["'",'"'],Fn.COMMENTS=["--","#",["/*","*/"]],Fn.IDENTIFIERS=["`"],Fn.STRING_ESCAPES=["'",'"',"\\"],Fn.BIT_STRINGS=[["b'","'"],["B'","'"],["0b",""]],Fn.HEX_STRINGS=[["x'","'"],["X'","'"],["0x",""]];var YG,HG,VG,WG,jG,JG,XG,zG,KG,QG,ZG,e$,t$,s$,r$,n$,i$,a$,o$,c$,ss,ht=class ht extends(c$=he,o$=[O],a$=[O],i$=[O],n$=[O],r$=[O],s$=[O],t$=[O],e$=[O],ZG=[O],QG=[O],KG=[O],zG=[O],XG=[O],JG=[O],jG=[O],WG=[O],VG=[O],HG=[O],YG=[O],c$){static get ID_VAR_TOKENS(){return new Set([...he.ID_VAR_TOKENS,"currentCatalog"])}static get FUNC_TOKENS(){return new Set([...he.FUNC_TOKENS,"database","mod","schema","values","characterSet"])}static get CONJUNCTION(){return{...he.CONJUNCTION,damp:Oe,xor:Ur}}static get DISJUNCTION(){return{...he.DISJUNCTION,dpipe:pt}}static get TABLE_ALIAS_TOKENS(){return(()=>{let t=new Set(he.TABLE_ALIAS_TOKENS);for(let s of he.TABLE_INDEX_HINT_TOKENS)t.delete(s);return t})()}static get RANGE_PARSERS(){return{...he.RANGE_PARSERS,soundsLike:function(t){return this.expression(Ee,{this:this.expression(tn,{this:t}),expression:this.expression(tn,{this:this.parseTerm()})})},memberOf:function(t){return this.expression(mp,{this:t,expression:this.parseWrapped(this.parseExpression.bind(this))})}}}static get FUNCTIONS(){return{...he.FUNCTIONS,BIT_AND:t=>Rc.fromArgList(t),BIT_OR:t=>Oc.fromArgList(t),BIT_XOR:t=>Nc.fromArgList(t),BIT_COUNT:t=>kh.fromArgList(t),CONVERT_TZ:t=>new Qn({sourceTz:b(t,1),targetTz:b(t,2),timestamp:b(t,0)}),CURDATE:t=>xn.fromArgList(t),DATE:t=>new Ue({this:b(t,0)}),DATE_ADD:t=>yM(ut)(t),DATE_FORMAT:Ri(Ns,{dialect:"mysql"}),DATE_SUB:t=>yM(Wt)(t),DAY:t=>new Zr({this:new Ue({this:b(t,0)})}),DAYOFMONTH:t=>new Kr({this:new Ue({this:b(t,0)})}),DAYOFWEEK:t=>new ur({this:new Ue({this:b(t,0)})}),DAYOFYEAR:t=>new Qr({this:new Ue({this:b(t,0)})}),FORMAT:t=>jh.fromArgList(t),FROM_UNIXTIME:Ri(Us,{dialect:"mysql"}),ISNULL:xB,LENGTH:t=>new Er({this:b(t,0),binary:!0}),MAKETIME:t=>Ti.fromArgList(t),MONTH:t=>new Js({this:new Ue({this:b(t,0)})}),MONTHNAME:t=>new Ns({this:new Ue({this:b(t,0)}),format:new w({this:"%B",isString:!0})}),SCHEMA:t=>qh.fromArgList(t),DATABASE:t=>qh.fromArgList(t),STR_TO_DATE:XW,TIMESTAMPDIFF:JT(Va),TO_DAYS:t=>new ks({this:new Ue({this:b(t,0)}),expression:new Ue({this:new w({this:"0000-01-01",isString:!0})}),unit:new Ze({this:"DAY"})}).add(1),VERSION:t=>Dn.fromArgList(t),WEEK:t=>new Un({this:new Ue({this:b(t,0)}),mode:b(t,1)}),WEEKOFYEAR:t=>new xi({this:new Ue({this:b(t,0)})}),YEAR:t=>new qn({this:new Ue({this:b(t,0)})})}}static get FUNCTION_PARSERS(){return{...he.FUNCTION_PARSERS,GROUP_CONCAT:function(){return this.parseGroupConcat()},VALUES:function(){return this.expression(st,{this:"VALUES",expressions:[this.parseIdVar()]})},JSON_VALUE:function(){return this.parseJsonValue()},SUBSTR:function(){return this.parseSubstring()}}}static get STATEMENT_PARSERS(){return{...he.STATEMENT_PARSERS,show:function(){return this.parseShow()}}}static get PROPERTY_PARSERS(){return{...he.PROPERTY_PARSERS,LOCK:function(){return this.parsePropertyAssignment(Ha)},"PARTITION BY":function(){return this.parsePartitionProperty()}}}static get SET_PARSERS(){return{...he.SET_PARSERS,PERSIST:function(){return this.parseSetItemAssignment({kind:"persist"})},PERSIST_ONLY:function(){return this.parseSetItemAssignment({kind:"PERSIST_ONLY"})},"CHARACTER SET":function(){return this.parseSetItemCharset("CHARACTER SET")},CHARSET:function(){return this.parseSetItemCharset("CHARACTER SET")},NAMES:function(){return this.parseSetItemNames()}}}static get CONSTRAINT_PARSERS(){return{...he.CONSTRAINT_PARSERS,FULLTEXT:function(){return this.parseIndexConstraint("FULLTEXT")},INDEX:function(){return this.parseIndexConstraint()},KEY:function(){return this.parseIndexConstraint()},SPATIAL:function(){return this.parseIndexConstraint("SPATIAL")},ZEROFILL:function(){return this.expression(dc)}}}static get ALTER_PARSERS(){return{...he.ALTER_PARSERS,MODIFY:function(){return this.parseAlterTableAlter()}}}static get ALTER_ALTER_PARSERS(){return{...he.ALTER_ALTER_PARSERS,INDEX:function(){return this.parseAlterTableAlterIndex()}}}static get SCHEMA_UNNAMED_CONSTRAINTS(){return new Set([...he.SCHEMA_UNNAMED_CONSTRAINTS,"FULLTEXT","INDEX","KEY","SPATIAL"])}static get PROFILE_TYPES(){return{ALL:[],CPU:[],IPC:[],MEMORY:[],SOURCE:[],SWAPS:[],BLOCK:["IO"],CONTEXT:["SWITCHES"],PAGE:["FAULTS"]}}static get TYPE_TOKENS(){return new Set([...he.TYPE_TOKENS,"set"])}static get ENUM_TYPE_TOKENS(){return new Set([...he.ENUM_TYPE_TOKENS,"set"])}static get OPERATION_MODIFIERS(){return new Set(["HIGH_PRIORITY","STRAIGHT_JOIN","SQL_SMALL_RESULT","SQL_BIG_RESULT","SQL_BUFFER_RESULT","SQL_NO_CACHE","SQL_CALC_FOUND_ROWS"])}parseGeneratedAsIdentity(){let t=super.parseGeneratedAsIdentity();if(this.matchTexts(["STORED","VIRTUAL"])){let s=_optionalChain([this, 'access', _1389 => _1389.prev, 'optionalAccess', _1390 => _1390.text, 'access', _1391 => _1391.toUpperCase, 'call', _1392 => _1392()])==="STORED";t instanceof An?t.setArgKey("persisted",s):t instanceof Ui&&(t=this.expression(An,{this:t.args.expression,persisted:s}))}return t}parsePrimaryKeyPart(){let t=this.parseIdVar();if(!this.match("lParen"))return t;let s=this.parseNumber();return this.matchRParen(),this.expression(Nh,{this:t,expression:s})}parseIndexConstraint(t){t&&this.matchTexts(["INDEX","KEY"]);let s=this.parseIdVar({anyToken:!1}),r=this.match("using")&&this.advanceAny()&&_optionalChain([this, 'access', _1393 => _1393.prev, 'optionalAccess', _1394 => _1394.text]),i=this.parseWrappedCsv(this.parseOrdered.bind(this)),a=[];for(;;){let o;if(this.matchTextSeq(["KEY_BLOCK_SIZE"])?(this.match("eq"),o=new yr({keyBlockSize:this.parseNumber()})):this.match("using")?o=new yr({using:this.advanceAny()&&_optionalChain([this, 'access', _1395 => _1395.prev, 'optionalAccess', _1396 => _1396.text])}):this.matchTextSeq(["WITH","PARSER"])?o=new yr({parser:this.parseVar({anyToken:!0})}):this.match("comment")?o=new yr({comment:this.parseString()}):this.matchTextSeq(["VISIBLE"])?o=new yr({visible:!0}):this.matchTextSeq(["INVISIBLE"])?o=new yr({visible:!1}):this.matchTextSeq(["ENGINE_ATTRIBUTE"])?(this.match("eq"),o=new yr({engineAttr:this.parseString()})):this.matchTextSeq(["SECONDARY_ENGINE_ATTRIBUTE"])&&(this.match("eq"),o=new yr({secondaryEngineAttr:this.parseString()})),!o)break;a.push(o)}return this.expression(Lh,{this:s,expressions:i,kind:t,indexType:r,options:a})}parseShowMysql(t,s={}){let{target:r=!1,full:i,global:a}=s,o=this.matchTextSeq(["JSON"]),c;r&&(typeof r=="string"&&this.matchTextSeq(r.split(" ")),c=this.parseIdVar());let p=this.matchTextSeq(["IN"])?this.parseString():void 0,u,E;t==="BINLOG EVENTS"||t==="RELAYLOG EVENTS"?u=this.matchTextSeq(["FROM"])?this.parseNumber():void 0:this.match("from")?E=this.parseIdVar():this.match("dot")&&(E=c,c=this.parseIdVar());let g=this.matchTextSeq(["FOR","CHANNEL"])?this.parseIdVar():void 0,A=this.matchTextSeq(["LIKE"])?this.parseString():void 0,x=this.parseWhere(),m,N,R,S;t==="PROFILE"?(m=this.parseCsv(()=>this.parseVarFromOptions(ht.PROFILE_TYPES)),N=this.matchTextSeq(["FOR","QUERY"])?this.parseNumber():void 0,R=this.matchTextSeq(["OFFSET"])?this.parseNumber():void 0,S=this.matchTextSeq(["LIMIT"])?this.parseNumber():void 0):[R,S]=this.parseOldstyleLimit();let I;this.matchTextSeq(["MUTEX"])&&(I=!0),this.matchTextSeq(["STATUS"])&&(I=!1);let y=this.matchTextSeq(["FOR","TABLE"])?this.parseIdVar():void 0,P=this.matchTextSeq(["FOR","GROUP"])?this.parseString():void 0,v=this.matchTextSeq(["FOR","USER"])?this.parseString():void 0,H=this.matchTextSeq(["FOR","ROLE"])?this.parseString():void 0,B=this.matchTextSeq(["INTO","OUTFILE"])?this.parseString():void 0;return this.expression(gc,{this:t,target:c,full:i,log:p,position:u,db:E,channel:g,like:A,where:x,types:m,query:N,offset:R,limit:S,mutex:I,forTable:y,forGroup:P,forUser:v,forRole:H,intoOutfile:B,json:o,global:a})}parseOldstyleLimit(){let t,s;if(this.matchTextSeq(["LIMIT"])){let r=this.parseCsv(this.parseNumber.bind(this));r.length===1?t=r[0]:r.length===2&&(t=r[1],s=r[0])}return[s,t]}parseSetItemCharset(t){let s=this.parseString()||this.parseUnquotedField();return this.expression(mr,{this:s,kind:t})}parseSetItemNames(){let t=this.parseString()||this.parseUnquotedField(),s;return this.matchTextSeq(["COLLATE"])&&(s=this.parseString()||this.parseUnquotedField()),this.expression(mr,{this:t,collate:s,kind:"NAMES"})}parseType(t={}){let{parseInterval:s=!0,fallbackToIdentifier:r=!1}=t;if(this.match("binary",{advance:!1})){let i=this.parseTypes({checkFunc:!0,allowIdentifiers:!1});if(i instanceof C)return this.expression(Z,{this:this.parseColumn(),to:i})}return super.parseType({parseInterval:s,fallbackToIdentifier:r})}parseAlterTableAlterIndex(){let t=this.parseField({anyToken:!0}),s;return this.matchTextSeq(["VISIBLE"])?s=!0:this.matchTextSeq(["INVISIBLE"])&&(s=!1),this.expression(Oh,{this:t,visible:s})}parsePartitionProperty(){let t,s;if(this.matchTextSeq(["RANGE"])?(t=Ac,s=this.parsePartitionRangeValue.bind(this)):this.matchTextSeq(["LIST"])&&(t=fc,s=this.parsePartitionListValue.bind(this)),!t||!s)return;let r=this.parseWrappedCsv(this.parseAssignment.bind(this));if(!this.matchTextSeq(["(","PARTITION"],{advance:!1}))return r;let i=this.parseWrappedCsv(s);return this.expression(t,{partitionExpressions:r,createExpressions:i})}parsePartitionRangeValue(){this.matchTextSeq(["PARTITION"]);let t=this.parseIdVar();if(!this.matchTextSeq(["VALUES","LESS","THAN"]))return t;let s=this.parseWrappedCsv(this.parseExpression.bind(this));s.length===1&&s[0]instanceof k&&s[0].name.toUpperCase()==="MAXVALUE"&&(s=[new Ze({this:"MAXVALUE"})]);let r=this.expression(Ih,{this:t,expressions:s});return this.expression(Wi,{expressions:[r]})}parsePartitionListValue(){this.matchTextSeq(["PARTITION"]);let t=this.parseIdVar();this.matchTextSeq(["VALUES","IN"]);let s=this.parseWrappedCsv(this.parseExpression.bind(this)),r=this.expression(yh,{this:t,expressions:s});return this.expression(Wi,{expressions:[r]})}parsePrimaryKey(t={}){let{wrappedOptional:s=!1,inProps:r=!1,namedPrimaryKey:i=!1}=t;return super.parsePrimaryKey({wrappedOptional:s,inProps:r,namedPrimaryKey:!0})}};ss=re(c$),T(ss,10,"ID_VAR_TOKENS",o$,ht),T(ss,10,"FUNC_TOKENS",a$,ht),T(ss,10,"CONJUNCTION",i$,ht),T(ss,10,"DISJUNCTION",n$,ht),T(ss,10,"TABLE_ALIAS_TOKENS",r$,ht),T(ss,10,"RANGE_PARSERS",s$,ht),T(ss,10,"FUNCTIONS",t$,ht),T(ss,10,"FUNCTION_PARSERS",e$,ht),T(ss,10,"STATEMENT_PARSERS",ZG,ht),T(ss,10,"PROPERTY_PARSERS",QG,ht),T(ss,10,"SET_PARSERS",KG,ht),T(ss,10,"CONSTRAINT_PARSERS",zG,ht),T(ss,10,"ALTER_PARSERS",XG,ht),T(ss,10,"ALTER_ALTER_PARSERS",JG,ht),T(ss,10,"SCHEMA_UNNAMED_CONSTRAINTS",jG,ht),T(ss,10,"PROFILE_TYPES",WG,ht),T(ss,10,"TYPE_TOKENS",VG,ht),T(ss,10,"ENUM_TYPE_TOKENS",HG,ht),T(ss,10,"OPERATION_MODIFIERS",YG,ht),te(ss,ht),se(ss,3,ht),ht.SHOW_PARSERS={"BINARY LOGS":le("BINARY LOGS"),"MASTER LOGS":le("BINARY LOGS"),"BINLOG EVENTS":le("BINLOG EVENTS"),"CHARACTER SET":le("CHARACTER SET"),CHARSET:le("CHARACTER SET"),COLLATION:le("COLLATION"),"FULL COLUMNS":le("COLUMNS",{target:"FROM",full:!0}),COLUMNS:le("COLUMNS",{target:"FROM"}),"CREATE DATABASE":le("CREATE DATABASE",{target:!0}),"CREATE EVENT":le("CREATE EVENT",{target:!0}),"CREATE FUNCTION":le("CREATE FUNCTION",{target:!0}),"CREATE PROCEDURE":le("CREATE PROCEDURE",{target:!0}),"CREATE TABLE":le("CREATE TABLE",{target:!0}),"CREATE TRIGGER":le("CREATE TRIGGER",{target:!0}),"CREATE VIEW":le("CREATE VIEW",{target:!0}),DATABASES:le("DATABASES"),SCHEMAS:le("DATABASES"),ENGINE:le("ENGINE",{target:!0}),"STORAGE ENGINES":le("ENGINES"),ENGINES:le("ENGINES"),ERRORS:le("ERRORS"),EVENTS:le("EVENTS"),"FUNCTION CODE":le("FUNCTION CODE",{target:!0}),"FUNCTION STATUS":le("FUNCTION STATUS"),GRANTS:le("GRANTS",{target:"FOR"}),INDEX:le("INDEX",{target:"FROM"}),"MASTER STATUS":le("MASTER STATUS"),"OPEN TABLES":le("OPEN TABLES"),PLUGINS:le("PLUGINS"),"PROCEDURE CODE":le("PROCEDURE CODE",{target:!0}),"PROCEDURE STATUS":le("PROCEDURE STATUS"),PRIVILEGES:le("PRIVILEGES"),"FULL PROCESSLIST":le("PROCESSLIST",{full:!0}),PROCESSLIST:le("PROCESSLIST"),PROFILE:le("PROFILE"),PROFILES:le("PROFILES"),"RELAYLOG EVENTS":le("RELAYLOG EVENTS"),REPLICAS:le("REPLICAS"),"SLAVE HOSTS":le("REPLICAS"),"REPLICA STATUS":le("REPLICA STATUS"),"SLAVE STATUS":le("REPLICA STATUS"),"GLOBAL STATUS":le("STATUS",{global:!0}),"SESSION STATUS":le("STATUS"),STATUS:le("STATUS"),"TABLE STATUS":le("TABLE STATUS"),"FULL TABLES":le("TABLES",{full:!0}),TABLES:le("TABLES"),TRIGGERS:le("TRIGGERS"),"GLOBAL VARIABLES":le("VARIABLES",{global:!0}),"SESSION VARIABLES":le("VARIABLES"),VARIABLES:le("VARIABLES"),WARNINGS:le("WARNINGS")},ht.LOG_DEFAULTS_TO_LN=!0,ht.STRING_ALIASES=!0,ht.VALUES_FOLLOWED_BY_PAREN=!1,ht.SUPPORTS_PARTITION_SELECTION=!0;var w_=ht,p$,l$,u$,E$,h$,g$,d$,A$,f$,x$,T$,S$,m$,an,ge=class ge extends(m$=L,S$=[O],T$=[O],x$=[O],f$=[O],A$=[O],d$=[O],g$=[O],h$=[O],E$=[O],u$=[O],l$=[O],p$=[O],m$){static get AFTER_HAVING_MODIFIER_TRANSFORMS(){let t=new Map(super.AFTER_HAVING_MODIFIER_TRANSFORMS);return["cluster","distribute","sort"].forEach(s=>t.delete(s)),t}static get NULL_ORDERING_SUPPORTED(){return"unsupported"}static get ORIGINAL_TRANSFORMS(){return new Map([...L.TRANSFORMS,[nr,X("GROUP_CONCAT")],[Rc,X("BIT_AND")],[Oc,X("BIT_OR")],[Nc,X("BIT_XOR")],[kh,X("BIT_COUNT")],[sp,function(t){return this.chrSql(t,{name:"CHAR"})}],[xn,pB],[Dn,X("VERSION")],[ks,Ni(function(t){return this.func("DATEDIFF",[t.args.this,t.args.expression])},["this","expression"])],[ut,Ni(b_("ADD"))],[Wa,YR],[Wt,Ni(b_("SUB"))],[Bs,WW],[Zr,Ni()],[Kr,Ni(X("DAYOFMONTH"))],[ur,Ni(X("DAYOFWEEK"))],[Qr,Ni(X("DAYOFYEAR"))],[tr,function(t){return`GROUP_CONCAT(${this.sql(t,"this")} SEPARATOR ${this.sql(t,"separator")||"','"})`}],[ms,GR],[Rr,cB],[Er,NB],[dl,X("MAX")],[Al,X("MIN")],[rn,wM],[fl,PM],[Js,Ni()],[fr,function(t){return this.binary(t,"<=>")}],[kr,function(t){return`NOT ${this.binary(t,"<=>")}`}],[jh,X("FORMAT")],[ls,OM],[$,Ks([zh,kR,Kh,Zv,jv])],[ps,function(t){return $R.call(this,t,{funcName:"LOCATE",supportsPosition:!0})}],[ar,P_],[Jt,P_],[il,X("INSERT")],[Fp,()=>"SESSION_USER()"],[wo,uB],[Ti,X("MAKETIME")],[Tc,c_("DATE","ADD")],[Va,function(t){return this.func("TIMESTAMPDIFF",[LM(t),t.args.expression,t.args.this])}],[Hx,c_("DATE","SUB")],[ol,X("UNIX_TIMESTAMP")],[Xs,function(t){return Tl.call(this,t,{includePrecision:!t.args.zone})}],[Ns,Ni(function(t){return this.func("DATE_FORMAT",[t.args.this,this.formatTime(t)])})],[or,HR],[Yh,X("TRUNCATE")],[Ft,NM],[sn,b_("ADD")],[cl,function(t){return this.func("DATEDIFF",[t.args.this,t.args.expression])}],[Ue,KW],[ul,function(t){return`ORD(CONVERT(${this.sql(t.args.this)} USING utf32))`}],[Us,zW],[Un,Ni()],[xi,Ni(X("WEEKOFYEAR"))],[qn,Ni()],[$x,X("UTC_TIMESTAMP")],[Gx,X("UTC_TIME")]])}static get UNSIGNED_TYPE_MAPPING(){return new Map([["ubigint","BIGINT"],["uint","INT"],["umediumint","MEDIUMINT"],["usmallint","SMALLINT"],["utinyint","TINYINT"],["udecimal","DECIMAL"],["udouble","DOUBLE"]])}static get TIMESTAMP_TYPE_MAPPING(){return new Map([["datetime2","DATETIME"],["smalldatetime","DATETIME"],["timestamp","DATETIME"],["timestampntz","DATETIME"],["timestamptz","TIMESTAMP"],["timestampltz","TIMESTAMP"]])}static get TYPE_MAPPING(){let t=new Map(L.TYPE_MAPPING);for(let[s,r]of ge.UNSIGNED_TYPE_MAPPING)t.set(s,r);for(let[s,r]of ge.TIMESTAMP_TYPE_MAPPING)t.set(s,r);return t.delete("mediumtext"),t.delete("longtext"),t.delete("tinytext"),t.delete("blob"),t.delete("mediumblob"),t.delete("longblob"),t.delete("tinyblob"),t}static get PROPERTIES_LOCATION(){let t=new Map(L.PROPERTIES_LOCATION);return t.set(In,"unsupported"),t.set(Vs,"unsupported"),t.set(Bt,"unsupported"),t.set(Ac,"postSchema"),t.set(fc,"postSchema"),t}static get CHAR_CAST_MAPPING(){return["longtext","longblob","mediumblob","mediumtext","text","tinyblob","tinytext","varchar"].reduce((t,s)=>({...t,[s]:"CHAR"}),{})}static get SIGNED_CAST_MAPPING(){return["bigint","boolean","int","smallint","tinyint","mediumint"].reduce((t,s)=>({...t,[s]:"SIGNED"}),{})}static get CAST_MAPPING(){return{...ge.CHAR_CAST_MAPPING,...ge.SIGNED_CAST_MAPPING,ubigint:"UNSIGNED"}}static get TIMESTAMP_FUNC_TYPES(){return new Set(["timestamptz","timestampltz"])}static get RESERVED_KEYWORDS(){return new Set(["accessible","add","all","alter","analyze","and","as","asc","asensitive","before","between","bigint","binary","blob","both","by","call","cascade","case","change","char","character","check","collate","column","condition","constraint","continue","convert","create","cross","cube","cume_dist","current_date","current_time","current_timestamp","current_user","cursor","database","databases","day_hour","day_microsecond","day_minute","day_second","dec","decimal","declare","default","delayed","delete","dense_rank","desc","describe","deterministic","distinct","distinctrow","div","double","drop","dual","each","else","elseif","empty","enclosed","escaped","except","exists","exit","explain","false","fetch","first_value","float","float4","float8","for","force","foreign","from","fulltext","function","generated","get","grant","group","grouping","groups","having","high_priority","hour_microsecond","hour_minute","hour_second","if","ignore","in","index","infile","inner","inout","insensitive","insert","int","int1","int2","int3","int4","int8","integer","intersect","interval","into","io_after_gtids","io_before_gtids","is","iterate","join","json_table","key","keys","kill","lag","last_value","lateral","lead","leading","leave","left","like","limit","linear","lines","load","localtime","localtimestamp","lock","long","longblob","longtext","loop","low_priority","master_bind","master_ssl_verify_server_cert","match","maxvalue","mediumblob","mediumint","mediumtext","middleint","minute_microsecond","minute_second","mod","modifies","natural","not","no_write_to_binlog","nth_value","ntile","undefined","numeric","of","on","optimize","optimizer_costs","option","optionally","or","order","out","outer","outfile","over","partition","percent_rank","precision","primary","procedure","purge","range","rank","read","reads","read_write","real","recursive","references","regexp","release","rename","repeat","replace","require","resignal","restrict","return","revoke","right","rlike","row","rows","row_number","schema","schemas","second_microsecond","select","sensitive","separator","set","show","signal","smallint","spatial","specific","sql","sqlexception","sqlstate","sqlwarning","sql_big_result","sql_calc_found_rows","sql_small_result","ssl","starting","stored","straight_join","system","table","terminated","then","tinyblob","tinyint","tinytext","to","trailing","trigger","true","undo","union","unique","unlock","unsigned","update","usage","use","using","utc_date","utc_time","utc_timestamp","values","varbinary","varchar","varcharacter","varying","virtual","when","where","while","window","with","write","xor","year_month","zerofill"])}computedColumnConstraintSql(t){let s=t.args.persisted?"STORED":"VIRTUAL";return`GENERATED ALWAYS AS (${this.sql(_optionalChain([t, 'access', _1397 => _1397.args, 'access', _1398 => _1398.this, 'optionalAccess', _1399 => _1399.unnest, 'call', _1400 => _1400()]))}) ${s}`}arraySql(t){return this.unsupported("Arrays are not supported by MySQL"),this.functionFallbackSql(t)}arrayContainsAllSql(t){return this.unsupported("Array operations are not supported by MySQL"),this.functionFallbackSql(t)}dpipeSql(t){return this.func("CONCAT",[...t.flatten()])}extractSql(t){let s=t.name;return s&&s.toLowerCase()==="epoch"?this.func("UNIX_TIMESTAMP",[t.args.expression]):super.extractSql(t)}dataTypeSql(t){if(this.constructor.VARCHAR_REQUIRES_SIZE&&t.isType("varchar")&&!_optionalChain([t, 'access', _1401 => _1401.args, 'access', _1402 => _1402.expressions, 'optionalAccess', _1403 => _1403.length]))return"TEXT";let s=super.dataTypeSql(t);return ge.UNSIGNED_TYPE_MAPPING.has(t.args.this)&&(s=`${s} UNSIGNED`),s}jsonArrayContainsSql(t){return`${this.sql(t,"this")} MEMBER OF(${this.sql(t,"expression")})`}castSql(t,s={}){let r=t.args.to;if(r instanceof C){let i=r.args.this;if(this._constructor.TIMESTAMP_FUNC_TYPES.has(i))return this.func("TIMESTAMP",[t.args.this]);let a=this._constructor.CAST_MAPPING[i];a&&r.setArgKey("this",a)}return super.castSql(t)}showSql(t){let s=` ${t.name}`,r=t.args.full?" FULL":"",i=t.args.global?" GLOBAL":"",a=this.sql(t,"target");a=a?` ${a}`:"",["COLUMNS","INDEX"].includes(t.name)?a=` FROM${a}`:t.name==="GRANTS"?a=` FOR${a}`:["LINKS","PARTITIONS"].includes(t.name)?a=a?` ON${a}`:"":t.name==="PROJECTIONS"&&(a=a?` ON TABLE${a}`:"");let o=this.prefixedSql("FROM",t,"db"),c=this.prefixedSql("LIKE",t,"like"),p=this.sql(t,"where"),u=this.expressions(t,{key:"types"});u=u&&` ${u}`;let E=this.prefixedSql("FOR QUERY",t,"query"),g="",A="";t.name==="PROFILE"?(g=this.prefixedSql("OFFSET",t,"offset"),A=this.prefixedSql("LIMIT",t,"limit")):A=this.oldStyleLimitSql(t);let x=this.prefixedSql("IN",t,"log"),m=this.prefixedSql("FROM",t,"position"),N=this.prefixedSql("FOR CHANNEL",t,"channel"),R="";t.name==="ENGINE"&&(R=t.args.mutex?" MUTEX":" STATUS");let S=this.prefixedSql("FOR TABLE",t,"forTable"),I=this.prefixedSql("FOR GROUP",t,"forGroup"),y=this.prefixedSql("FOR USER",t,"forUser"),P=this.prefixedSql("FOR ROLE",t,"forRole"),v=this.prefixedSql("INTO OUTFILE",t,"intoOutfile"),H=t.args.json?" JSON":"";return`SHOW${r}${i}${s}${H}${a}${S}${u}${o}${E}${x}${m}${N}${R}${c}${p}${g}${A}${I}${y}${P}${v}`}alterRenameSql(t,s={}){return super.alterRenameSql(t,{includeTo:!1})}alterColumnSql(t){let s=this.sql(t,"dtype");return s?`MODIFY COLUMN ${this.sql(t,"this")} ${s}`:super.alterColumnSql(t)}prefixedSql(t,s,r){let i=this.sql(s,r);return i?` ${t} ${i}`:""}oldStyleLimitSql(t){let s=this.sql(t,"limit"),r=this.sql(t,"offset");return s?` LIMIT ${r?`${r}, ${s}`:s}`:""}timestampTruncSql(t){let s=t.args.unit,r="'0000-01-01 00:00:00'",i=JT(Va)([s,new w({this:r,isString:!0}),t.args.this]),a=new ze({this:i,unit:s}),o=yM(ut)([new w({this:r,isString:!0}),a]);return this.sql(o)}convertTimezoneSql(t){let s=t.args.sourceTz,r=t.args.targetTz,i=t.args.timestamp;return this.func("CONVERT_TZ",[i,s,r])}attimezoneSql(t){return this.unsupported("AT TIME ZONE is not supported by MySQL"),this.sql(t.args.this)}isasciiSql(t){return`REGEXP_LIKE(${this.sql(t.args.this)}, '^[[:ascii:]]*$')`}ignoreNullsSql(t){return this.unsupported("MySQL does not support IGNORE NULLS."),this.sql(t.args.this)}currentSchemaSql(t){return so.call(this,t,"this"),this.func("SCHEMA",[])}partitionSql(t){let s=t.parent;return s instanceof Ac||s instanceof fc?this.expressions(t,{flat:!0}):super.partitionSql(t)}partitionByRangeOrListSql(t,s){let r=this.expressions(t,{key:"partitionExpressions",flat:!0}),i=this.expressions(t,{key:"createExpressions",flat:!0});return`PARTITION BY ${s} (${r}) (${i})`}partitionByRangePropertySql(t){return this.partitionByRangeOrListSql(t,"RANGE")}partitionByListPropertySql(t){return this.partitionByRangeOrListSql(t,"LIST")}partitionListSql(t){let s=this.sql(t,"this"),r=this.expressions(t,{flat:!0});return`PARTITION ${s} VALUES IN (${r})`}partitionRangeSql(t){let s=this.sql(t,"this"),r=this.expressions(t,{flat:!0});return`PARTITION ${s} VALUES LESS THAN (${r})`}};an=re(m$),T(an,10,"AFTER_HAVING_MODIFIER_TRANSFORMS",S$,ge),T(an,10,"NULL_ORDERING_SUPPORTED",T$,ge),T(an,10,"ORIGINAL_TRANSFORMS",x$,ge),T(an,10,"UNSIGNED_TYPE_MAPPING",f$,ge),T(an,10,"TIMESTAMP_TYPE_MAPPING",A$,ge),T(an,10,"TYPE_MAPPING",d$,ge),T(an,10,"PROPERTIES_LOCATION",g$,ge),T(an,10,"CHAR_CAST_MAPPING",h$,ge),T(an,10,"SIGNED_CAST_MAPPING",E$,ge),T(an,10,"CAST_MAPPING",u$,ge),T(an,10,"TIMESTAMP_FUNC_TYPES",l$,ge),T(an,10,"RESERVED_KEYWORDS",p$,ge),te(an,ge),se(an,3,ge),ge.SUPPORTS_DECODE_CASE=!1,ge.SELECT_KINDS=[],ge.TRY_SUPPORTED=!1,ge.SUPPORTS_UESCAPE=!1,ge.INTERVAL_ALLOWS_PLURAL_FORM=!1,ge.LOCKING_READS_SUPPORTED=!0,ge.JOIN_HINTS=!1,ge.TABLE_HINTS=!0,ge.DUPLICATE_KEY_UPDATE_WITH_SET=!1,ge.QUERY_HINT_SEP=" ",ge.VALUES_AS_TABLE=!1,ge.NVL2_SUPPORTED=!1,ge.LAST_DAY_SUPPORTS_DATE_PART=!1,ge.JSON_TYPE_REQUIRED_FOR_EXTRACTION=!0,ge.JSON_PATH_BRACKETED_KEY_SUPPORTED=!1,ge.JSON_KEY_VALUE_PAIR_SEP=",",ge.SUPPORTS_TO_NUMBER=!1,ge.PARSE_JSON_NAME=void 0,ge.PAD_FILL_PATTERN_IS_REQUIRED=!0,ge.WRAP_DERIVED_VALUES=!1,ge.VARCHAR_REQUIRES_SIZE=!0,ge.SUPPORTS_MEDIAN=!1,ge.UPDATE_STATEMENT_SUPPORTS_FROM=!1,ge.SUPPORTS_CONVERT_TIMEZONE=!0,ge.LIMIT_FETCH="LIMIT",ge.LIMIT_ONLY_LITERALS=!0;var M_=ge,R$,O$,N$,I$,y$,XR,Nt=class extends(y$=W,I$=[O],N$=[O],O$=[O],R$=[O],y$){static get NORMALIZATION_STRATEGY(){return"caseSensitive"}static get EXPRESSION_METADATA(){return new Map(Zh.EXPRESSION_METADATA)}static get TIME_MAPPING(){return{"%M":"%B","%c":"%-m","%e":"%-d","%h":"%I","%i":"%M","%s":"%S","%u":"%W","%k":"%-H","%l":"%-I","%T":"%H:%M:%S","%W":"%A"}}static get VALID_INTERVAL_UNITS(){return new Set([...W.VALID_INTERVAL_UNITS,"SECOND_MICROSECOND","MINUTE_MICROSECOND","MINUTE_SECOND","HOUR_MICROSECOND","HOUR_SECOND","HOUR_MINUTE","DAY_MICROSECOND","DAY_SECOND","DAY_MINUTE","DAY_HOUR","YEAR_MONTH"])}};XR=re(y$),T(XR,10,"NORMALIZATION_STRATEGY",I$,Nt),T(XR,10,"EXPRESSION_METADATA",N$,Nt),T(XR,10,"TIME_MAPPING",O$,Nt),T(XR,10,"VALID_INTERVAL_UNITS",R$,Nt),te(XR,Nt),se(XR,3,Nt),Nt.DIALECT_NAME="mysql",Nt.PROMOTE_TO_INFERRED_DATETIME_TYPE=!0,Nt.IDENTIFIERS_CAN_START_WITH_DIGIT=!0,Nt.TIME_FORMAT="'%Y-%m-%d %T'",Nt.DPIPE_IS_STRING_CONCAT=!1,Nt.SUPPORTS_USER_DEFINED_TYPES=!1,Nt.SUPPORTS_SEMI_ANTI_JOIN=!1,Nt.SAFE_DIVISION=!0,Nt.SAFE_TO_ELIMINATE_DOUBLE_NEGATION=!1,Nt.LEAST_GREATEST_IGNORES_NULLS=!1,Nt.Tokenizer=Fn,Nt.Parser=w_,Nt.Generator=M_;W.register("mysql",Nt);function QW(n){let e=n.args.expression;return e&&!(e.isString&&e.args.this===this.dialect._constructor.INITCAP_DEFAULT_DELIMITER_CHARS)&&this.unsupported("INITCAP does not support custom delimiters in Presto."),`REGEXP_REPLACE(${this.sql(n,"this")}, '(\\w)(\\w*)', x -> UPPER(x[1]) || LOWER(x[2]))`}function ZW(n){let e;return n.args.asc instanceof Et&&!n.args.asc.args.this&&(e="(a, b) -> CASE WHEN a < b THEN 1 WHEN a > b THEN -1 ELSE 0 END"),this.func("ARRAY_SORT",[n.args.this,e])}function ej(n){if(n.parent instanceof Bt){n.transform(t=>t instanceof G?t.name:t,{copy:!1});let e=_optionalChain([n, 'access', _1404 => _1404.args, 'access', _1405 => _1405.expressions, 'optionalAccess', _1406 => _1406.map, 'call', _1407 => _1407(t=>t instanceof d||t instanceof U?this.sql(t):this.sql(t,"this"))])||[];return this.sql(new Ne({expressions:e.map(t=>new w({this:t,isString:!0}))}))}if(n.parent){let e=n.parent.findAll(Lt);for(let t of e){if(t===n)continue;let s=[...t.findAll(we)];0<s.length&&t.parent instanceof U&&_optionalChain([n, 'access', _1408 => _1408.args, 'access', _1409 => _1409.expressions, 'optionalAccess', _1410 => _1410.push, 'call', _1411 => _1411(...s)])}}return this.schemaSql(n)}function tj(n){return this.unsupported("Presto does not support exact quantiles; using APPROX_PERCENTILE."),this.func("APPROX_PERCENTILE",[n.args.this,n.args.quantile])}function D_(n){return this.func("DATE_PARSE",[n.args.this,this.formatTime(n)])}function sj(n){let e=this.formatTime(n);if(e&&e!==De.TIME_FORMAT&&e!==De.DATE_FORMAT){let t=D_.call(this,n);return this.sql(new Z({this:t,to:"date".toUpperCase()}))}return this.sql(new Z({this:new Z({this:n.args.this,to:"timestamp".toUpperCase()}),to:"date".toUpperCase()}))}function rj(n){let e=TB(n),t=ro(e);return this.func("DATE_ADD",[t,e.args.expression,e.args.this])}function nj(n){let e=new Z({this:n.args.this,to:"timestamp".toUpperCase()}),t=new Z({this:n.args.expression,to:"timestamp".toUpperCase()}),s=ro(n);return this.func("DATE_DIFF",[s,t,e])}function ij(n){return n.length===4?new _s({this:b(n,0),weight:b(n,1),quantile:b(n,2),accuracy:b(n,3)}):n.length===3?new _s({this:b(n,0),quantile:b(n,1),accuracy:b(n,2)}):_s.fromArgList(n)}function aj(n){return n.length===3?new Us({this:b(n,0),hours:b(n,1),minutes:b(n,2)}):n.length===2?new Us({this:b(n,0),zone:b(n,1)}):Us.fromArgList(n)}function C$(n){return n.findAncestor(Io,$)?this.functionFallbackSql(n):X("ARBITRARY").call(this,n)}function oj(n){let e=n.args.scale,t=this.sql(n,"this");return!e||e.toValue()===Us.SECONDS.toValue()?X("FROM_UNIXTIME").call(this,n):`FROM_UNIXTIME(CAST(${t} AS DOUBLE) / POW(10, ${this.sql(e)}))`}function cj(n){return n.type||os(n,{dialect:this.dialect}),n.type instanceof h&&!C.INTEGER_TYPES.has(n.type.args.this)?new Z({this:n,to:"bigint".toUpperCase()}):n}function pj(n){let e=b(n,1);return e instanceof w&&e.setArgKey("this",(_nullishCoalesce(e.args.this, () => (""))).toUpperCase()),Ri(Ns,{dialect:"teradata"})(n)}function L_(n,e={}){let{negateInterval:t=!1}=e;return function(s){let r=s.args.expression?cj.call(this,s.args.expression):new w({this:"0",isString:!1}),i=t?r.mul(-1):r;return this.func(n,[ro(s),this.sql(i),this.sql(s,"this")])}}function lj(n){let e=n.args.this;if(e instanceof qt){let t=e.args.this instanceof h?e.args.this.type:e.args.this,s=n.args.alias;if(s instanceof ie&&t instanceof C&&t.isType("array")&&0<(_optionalChain([t, 'access', _1412 => _1412.args, 'access', _1413 => _1413.expressions, 'optionalAccess', _1414 => _1414.length])||0)&&_optionalChain([t, 'access', _1415 => _1415.args, 'access', _1416 => _1416.expressions, 'optionalAccess', _1417 => _1417[0], 'access', _1418 => _1418.isType, 'call', _1419 => _1419("struct")])){let r=t.args.expressions[0].args.expressions;s.setArgKey("columns",_optionalChain([r, 'optionalAccess', _1420 => _1420.flatMap, 'call', _1421 => _1421(i=>i instanceof h&&i.args.this instanceof h?i.args.this.copy():[])]))}}else e instanceof Vx&&e.replace(new qt({this:e.args.this instanceof h?e.args.this.copy():_nullishCoalesce(_optionalChain([e, 'access', _1422 => _1422.args, 'access', _1423 => _1423.this, 'optionalAccess', _1424 => _1424.toString, 'call', _1425 => _1425()]), () => (""))}));return OB.call(this,n)}function __(n){if(n instanceof $&&n.type){let e=n.args.laterals||[];for(let t of e){let s=t.args.alias;if(!(t.args.this instanceof qt)||!(s instanceof ie)||_optionalChain([s, 'access', _1426 => _1426.args, 'access', _1427 => _1427.columns, 'optionalAccess', _1428 => _1428.length])!==1)continue;let r=s.args.this,i=s.args.columns[0]instanceof h?s.args.columns[0].name.toLowerCase():s.args.columns[0];for(let a of Mr(n,[k])){let o=_optionalChain([a, 'access', _1429 => _1429.args, 'access', _1430 => _1430.db, 'optionalAccess', _1431 => _1431.toString, 'call', _1432 => _1432(), 'access', _1433 => _1433.toLowerCase, 'call', _1434 => _1434()]),c=_optionalChain([a, 'access', _1435 => _1435.args, 'access', _1436 => _1436.table, 'optionalAccess', _1437 => _1437.toString, 'call', _1438 => _1438(), 'access', _1439 => _1439.toLowerCase, 'call', _1440 => _1440()]),p=a.name.toLowerCase();o===i?a.setArgKey("table",a.args.db instanceof h?a.args.db.pop():a.args.db):c===i?a.setArgKey("table",r instanceof h?r.copy():r):p===i&&a.parent instanceof me&&a.parent.replace(new k({this:a.parent.args.expression,table:Pt(r,"string",h)}))}}}return n}var b$,P$,w$,BM,ig=class extends(w$=Dt,P$=[O],b$=[O],w$){static get HEX_STRINGS(){return[["x'","'"],["X'","'"]]}static get UNICODE_STRINGS(){let t=["U&","u&"],s=Dt.QUOTES,r=[];for(let i of s)for(let a of t)r.push([a+i,i]);return r}static get ORIGINAL_KEYWORDS(){let t={...Dt.KEYWORDS,"DEALLOCATE PREPARE":"command","DESCRIBE INPUT":"command","DESCRIBE OUTPUT":"command","RESET SESSION":"command",START:"begin",MATCH_RECOGNIZE:"matchRecognize",ROW:"struct",IPADDRESS:"ipaddress",IPPREFIX:"ipprefix",TDIGEST:"tdigest",HYPERLOGLOG:"hllsketch"};return delete t["/*+"],delete t.QUALIFY,t}};BM=re(w$),T(BM,10,"UNICODE_STRINGS",P$,ig),T(BM,10,"ORIGINAL_KEYWORDS",b$,ig),te(BM,ig),se(BM,3,ig),ig.NESTED_COMMENTS=!1;var M$,L$,D$,_$,k$,zR,ao=class extends(k$=he,_$=[O],D$=[O],L$=[O],M$=[O],k$){static get ID_VAR_TOKENS(){return new Set([...he.ID_VAR_TOKENS,"sessionUser","currentCatalog","straightJoin"])}static get FUNCTIONS(){return{...he.FUNCTIONS,ARBITRARY:t=>Ic.fromArgList(t),APPROX_DISTINCT:t=>hl.fromArgList(t),APPROX_PERCENTILE:ij,BITWISE_AND:MM(Cn),BITWISE_NOT:t=>new bn({this:b(t,0)}),BITWISE_OR:MM(ui),BITWISE_XOR:MM(Ei),CARDINALITY:t=>lr.fromArgList(t),CONTAINS:t=>PR.fromArgList(t),DATE_ADD:t=>new ut({this:b(t,2),expression:b(t,1),unit:b(t,0)}),DATE_DIFF:t=>new ks({this:b(t,2),expression:b(t,1),unit:b(t,0)}),DATE_FORMAT:Ri(Ns,{dialect:"presto"}),DATE_PARSE:Ri(Jt,{dialect:"presto"}),DATE_TRUNC:hB,DAY_OF_WEEK:t=>Bp.fromArgList(t),DOW:t=>Bp.fromArgList(t),DOY:t=>Qr.fromArgList(t),ELEMENT_AT:t=>new fs({this:b(t,0),expressions:[t[1]],offset:1,safe:!0}),FROM_HEX:t=>mi.fromArgList(t),FROM_UNIXTIME:aj,FROM_UTF8:t=>new OE({this:b(t,0),replace:b(t,1),charset:new w({this:"utf-8",isString:!0})}),JSON_FORMAT:t=>new Sc({this:b(t,0),options:b(t,1),isJson:!0}),LEVENSHTEIN_DISTANCE:t=>Si.fromArgList(t),NOW:t=>ir.fromArgList(t),REGEXP_EXTRACT:jR(br),REGEXP_EXTRACT_ALL:jR(kn),REGEXP_REPLACE:t=>new Xa({this:b(t,0),expression:b(t,1),replacement:_nullishCoalesce(b(t,2), () => (""))}),REPLACE:yB,ROW:t=>Hs.fromArgList(t),SEQUENCE:t=>Os.fromArgList(t),SET_AGG:t=>vn.fromArgList(t),SPLIT_TO_MAP:t=>Wh.fromArgList(t),STRPOS:t=>new ps({this:b(t,0),substr:b(t,1),occurrence:b(t,2)}),SLICE:t=>Uh.fromArgList(t),TO_CHAR:pj,TO_UNIXTIME:t=>Za.fromArgList(t),TO_UTF8:t=>new Wp({this:b(t,0),charset:new w({this:"utf-8",isString:!0})}),MD5:t=>en.fromArgList(t),SHA256:t=>new Qa({this:b(t,0),length:new w({this:"256",isString:!1})}),SHA512:t=>new Qa({this:b(t,0),length:new w({this:"512",isString:!1})}),WEEK:t=>xi.fromArgList(t)}}static get FUNCTION_PARSERS(){let t={...he.FUNCTION_PARSERS};return delete t.TRIM,t}static get TABLE_ALIAS_TOKENS(){return new Set([...he.TABLE_ALIAS_TOKENS,"straightJoin"])}};zR=re(k$),T(zR,10,"ID_VAR_TOKENS",_$,ao),T(zR,10,"FUNCTIONS",D$,ao),T(zR,10,"FUNCTION_PARSERS",L$,ao),T(zR,10,"TABLE_ALIAS_TOKENS",M$,ao),te(zR,ao),se(zR,3,ao),ao.VALUES_FOLLOWED_BY_PAREN=!1,ao.ZONE_AWARE_TIMESTAMP_CONSTRUCTOR=!0;var U$,q$,v$,F$,B$,G$,$$,ng,tt=class extends($$=L,G$=[O],B$=[O],F$=[O],v$=[O],q$=[O],U$=[O],$$){static get AFTER_HAVING_MODIFIER_TRANSFORMS(){let t=new Map(super.AFTER_HAVING_MODIFIER_TRANSFORMS);return["cluster","distribute","sort"].forEach(s=>t.delete(s)),t}static get STRUCT_DELIMITER(){return["(",")"]}static get PROPERTIES_LOCATION(){return new Map([...L.PROPERTIES_LOCATION,[Es,"unsupported"],[Vs,"unsupported"]])}static get TYPE_MAPPING(){return new Map([...L.TYPE_MAPPING,["binary","VARBINARY"],["bit","BOOLEAN"],["datetime","TIMESTAMP"],["datetime64","TIMESTAMP"],["float","REAL"],["hllsketch","HYPERLOGLOG"],["int","INTEGER"],["struct","ROW"],["text","VARCHAR"],["timestamptz","TIMESTAMP"],["timestampntz","TIMESTAMP"],["timetz","TIME"]])}static get ORIGINAL_TRANSFORMS(){return new Map([...L.TRANSFORMS,[Ic,X("ARBITRARY")],[_s,function(t){return this.func("APPROX_PERCENTILE",[t.args.this,t.args.weight,t.args.quantile,t.args.accuracy])}],[Wr,X("MAX_BY")],[jr,X("MIN_BY")],[Ne,Ks([SM],function(t){return`ARRAY[${this.expressions(t,{flat:!0})}]`})],[ky,X("ANY_MATCH")],[Pn,X("CONCAT")],[PR,X("CONTAINS")],[qp,X("ARRAY_JOIN")],[vn,X("SET_AGG")],[Uh,X("SLICE")],[Or,X("AT_TIMEZONE")],[Cn,function(t){return this.func("BITWISE_AND",[t.args.this,t.args.expression])}],[tp,function(t){return this.func("BITWISE_ARITHMETIC_SHIFT_LEFT",[t.args.this,t.args.expression])}],[bn,function(t){return this.func("BITWISE_NOT",[t.args.this])}],[ui,function(t){return this.func("BITWISE_OR",[t.args.this,t.args.expression])}],[nc,function(t){return this.func("BITWISE_ARITHMETIC_SHIFT_RIGHT",[t.args.this,t.args.expression])}],[Ei,function(t){return this.func("BITWISE_XOR",[t.args.this,t.args.expression])}],[Z,Ks([zD])],[Ba,()=>"CURRENT_TIME"],[ir,()=>"CURRENT_TIMESTAMP"],[ap,()=>"CURRENT_USER"],[ut,L_("DATE_ADD")],[ks,function(t){return this.func("DATE_DIFF",[ro(t),t.args.expression,t.args.this])}],[Wa,YR],[Yp,function(t){return`CAST(DATE_FORMAT(${this.sql(t,"this")}, ${this.dialect._constructor.DATEINT_FORMAT}) AS INT)`}],[Wt,L_("DATE_ADD",{negateInterval:!0})],[ur,function(t){return`((${this.func("DAY_OF_WEEK",[t.args.this])} % 7) + 1)`}],[Bp,X("DAY_OF_WEEK")],[OE,function(t){return p_.call(this,t,"FROM_UTF8")}],[Vp,function(t){return`CAST(DATE_PARSE(CAST(${this.sql(t,"this")} AS VARCHAR), ${this.dialect._constructor.DATEINT_FORMAT}) AS DATE)`}],[Wp,function(t){return p_.call(this,t,"TO_UTF8")}],[$s,function(t){return`format=${this.sql(new w({this:t.name,isString:!0}))}`}],[gT,C$],[bh,function(t){return`WITH_TIMEZONE(${this.sql(t,"this")}, ${this.sql(t,"zone")}) AT TIME ZONE 'UTC'`}],[Os,WR],[Mn,WR],[He,RM()],[ms,GR],[cp,QW],[dT,C$],[vh,function(t){return this.func("LAST_DAY_OF_MONTH",[t.args.this])}],[kt,lj],[Ja,CM],[Si,function(t){return so.call(this,t,"insCost","delCost","subCost","maxDist"),X("LEVENSHTEIN_DISTANCE").call(this,t)}],[Al,X("BOOL_AND")],[dl,X("BOOL_OR")],[ls,OM],[eo,tj],[br,VR],[kn,VR],[_n,bM],[Lt,ej],[Nr,function(t){return this.nakedProperty(t)}],[$,Ks([iF,Kh,zh,TM(1),kR,__])],[oT,ZW],[ps,function(t){return $R.call(this,t,{supportsOccurrence:!0})}],[ar,function(t){return`CAST(${D_.call(this,t)} AS DATE)`}],[Wh,X("SPLIT_TO_MAP")],[Jt,D_],[cT,IM],[V,Ks([xM])],[$p,function(t){return`CAST(${this.sql(t.args.this)} AS TIMESTAMP)`}],[Tc,L_("DATE_ADD")],[er,gB()],[al,Tl],[Xs,Tl],[ol,function(t){return this.func("TO_UNIXTIME",[this.func("DATE_PARSE",[t.args.this,this.dialect._constructor.TIME_FORMAT])])}],[Ns,function(t){return this.func("DATE_FORMAT",[t.args.this,this.formatTime(t)])}],[Za,X("TO_UNIXTIME")],[bR,function(t){return this.func("DATE_FORMAT",[t.args.this,this.formatTime(t)])}],[Ft,Ks([zD])],[ll,function(t){return`CAST(SUBSTR(REPLACE(CAST(${this.sql(t,"this")} AS VARCHAR), '-', ''), 1, 8) AS INT)`}],[sn,rj],[cl,nj],[Ue,sj],[mi,X("FROM_HEX")],[mc,function(t){return`DATE_FORMAT(FROM_UNIXTIME(${this.sql(t,"this")}), ${this.formatTime(t)})`}],[Us,oj],[El,function(t){return`CAST(FROM_UNIXTIME(${this.sql(t,"this")}) AS VARCHAR)`}],[xl,X("VAR_POP")],[ve,Ks([Qv])],[Cs,Ks([Kv])],[Yh,X("TRUNCATE")],[Ur,AB],[en,X("MD5")],[el,X("SHA1")],[tl,X("SHA1")],[Qa,mB],[sl,RB]])}static get RESERVED_KEYWORDS(){return new Set(["alter","and","as","between","by","case","cast","constraint","create","cross","current_time","current_timestamp","deallocate","delete","describe","distinct","drop","else","end","escape","except","execute","exists","extract","false","for","from","full","group","having","in","inner","insert","intersect","into","is","join","left","like","natural","not","undefined","on","or","order","outer","prepare","right","select","table","then","true","union","using","values","when","where","with"])}extractSql(t){let s=t.name.toUpperCase();if(!s.startsWith("EPOCH"))return super.extractSql(t);let r;s==="EPOCH_MILLISECOND"?r=10**3:s==="EPOCH_MICROSECOND"?r=10**6:s==="EPOCH_NANOSECOND"&&(r=10**9);let i=t.args.expression,a=new Z({this:i,to:C.build("TIMESTAMP")}),o=new Za({this:a});return r&&(o=new Ts({this:o,expression:new w({this:r.toString(),isString:!1})})),this.sql(o)}jsonFormatSql(t){let s=t.args.this,r=t.args.isJson;if(s&&!(r||s.type)&&(s=os(s,{dialect:this.dialect})),!(r||_optionalChain([s, 'optionalAccess', _1441 => _1441.isType, 'call', _1442 => _1442("json")]))){let i=new Z({to:"json".toUpperCase()});_optionalChain([s, 'optionalAccess', _1443 => _1443.replace, 'call', _1444 => _1444(i)]),i.setArgKey("this",s)}return this.functionFallbackSql(t)}md5Sql(t){let s=t.args.this;return!_optionalChain([s, 'optionalAccess', _1445 => _1445.type])&&s&&(s=os(s,{dialect:this.dialect})),_optionalChain([s, 'optionalAccess', _1446 => _1446.isType, 'call', _1447 => _1447(C.TEXT_TYPES)])&&(s=new Wp({this:s,charset:new w({this:"utf-8",isString:!0})})),this.func("LOWER",[this.func("TO_HEX",[this.func("MD5",[this.sql(s)])])])}strToUnixSql(t){let s=t.args.this,r=new Z({this:s,to:"VARCHAR"}),i=_optionalChain([s, 'optionalAccess', _1448 => _1448.args, 'access', _1449 => _1449.isString])?new Z({this:s,to:"timestamp".toUpperCase()}):s,a=this.func("DATE_PARSE",[r,this.formatTime(t)]),o=this.func("DATE_FORMAT",[i,this.formatTime(t)]),c=this.func("PARSE_DATETIME",[o,this.formatTime(t,de.INVERSE_TIME_MAPPING,de.INVERSE_TIME_TRIE)]),p=this.func("COALESCE",[this.func("TRY",[a]),c]);return this.func("TO_UNIXTIME",[p])}bracketSql(t){return t.args.safe?this.func("ELEMENT_AT",[t.args.this,t.args.this instanceof h?b(WT(t.args.this,_nullishCoalesce(t.args.expressions, () => ([])),1-(t.args.offset||0),{dialect:this.dialect}),0):void 0]):super.bracketSql(t)}structSql(t){t.type||os(t,{dialect:this.dialect});let s=[],r=[],i=!1;for(let o of t.args.expressions||[])if(o instanceof At){if(wi(o.type,"unknown"))i=!0;else{let c=typeof o.type=="string"?new C({this:o.type}):o.type;r.push(`${this.sql(o,"this")} ${this.sql(c)}`)}s.push(this.sql(o,"expression"))}else s.push(this.sql(o));let a=_optionalChain([t, 'access', _1450 => _1450.args, 'access', _1451 => _1451.expressions, 'optionalAccess', _1452 => _1452.length]);return!a||r.length!==a?(i&&this.unsupported("Cannot convert untyped key-value definitions (try annotate_types)."),this.func("ROW",s)):`CAST(ROW(${s.join(", ")}) AS ROW(${r.join(", ")}))`}intervalSql(t){let s=t.text("unit").toUpperCase();return t.args.this&&s.startsWith("WEEK")?`(${t.args.this.name} * INTERVAL '7' DAY)`:super.intervalSql(t)}transactionSql(t){let s=t.args.modes;return`START TRANSACTION${s?` ${s.join(", ")}`:""}`}createSql(t){let s=t.args.this instanceof h?t.args.this:void 0;return t.args.kind==="view"&&_optionalChain([s, 'optionalAccess', _1453 => _1453.args, 'access', _1454 => _1454.expressions])&&s.setArgKey("expressions",void 0),super.createSql(t)}deleteSql(t){let s=t.args.tables||[t.args.this];if(1<s.length)return super.deleteSql(t);let r=s[0];if(t.setArgKey("this",r),t.setArgKey("tables",void 0),r instanceof V){let i=r.args.alias;i&&(i.pop(),t=t.transform(tF))}return super.deleteSql(t)}jsonExtractSql(t){let s=_nullishCoalesce(this.dialect.settings.variantExtractIsJsonExtract, () => (!0));if(!t.args.variantExtract||s)return this.func("JSON_EXTRACT",[t.args.this,t.args.expression,...t.args.expressions||[]]);let r=this.sql(t,"this"),i=[];for(let a of _optionalChain([Pt, 'call', _1455 => _1455(t.args.expression,h), 'optionalAccess', _1456 => _1456.args, 'access', _1457 => _1457.expressions, 'optionalAccess', _1458 => _1458.slice, 'call', _1459 => _1459(1)])||[]){if(!(a instanceof Gt)){this.unsupported(`Cannot transpile JSONPath segment '${a}' to ROW access`);continue}let o=_optionalChain([a, 'access', _1460 => _1460.args, 'access', _1461 => _1461.this, 'optionalAccess', _1462 => _1462.toString, 'call', _1463 => _1463()]);/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(_nullishCoalesce(o, () => ("")))||(o=`"${o}"`),i.push(`.${o}`)}return`${r}${i.join("")}`}groupConcatSql(t){return this.func("ARRAY_JOIN",[this.func("ARRAY_AGG",[t.args.this]),t.args.separator])}};ng=re($$),T(ng,10,"AFTER_HAVING_MODIFIER_TRANSFORMS",G$,tt),T(ng,10,"STRUCT_DELIMITER",B$,tt),T(ng,10,"PROPERTIES_LOCATION",F$,tt),T(ng,10,"TYPE_MAPPING",v$,tt),T(ng,10,"ORIGINAL_TRANSFORMS",q$,tt),T(ng,10,"RESERVED_KEYWORDS",U$,tt),te(ng,tt),se(ng,3,tt),tt.SUPPORTS_DECODE_CASE=!1,tt.SELECT_KINDS=[],tt.INTERVAL_ALLOWS_PLURAL_FORM=!1,tt.JOIN_HINTS=!1,tt.TABLE_HINTS=!1,tt.QUERY_HINTS=!1,tt.IS_BOOL_ALLOWED=!1,tt.TZ_TO_WITH_TIME_ZONE=!0,tt.NVL2_SUPPORTED=!1,tt.LIMIT_ONLY_LITERALS=!0,tt.SUPPORTS_SINGLE_ARG_CONCAT=!1,tt.LIKE_PROPERTY_INSIDE_SCHEMA=!0,tt.MULTI_ARG_DISTINCT=!1,tt.SUPPORTS_TO_NUMBER=!1,tt.HEX_FUNC="TO_HEX",tt.PARSE_JSON_NAME="JSON_PARSE",tt.PAD_FILL_PATTERN_IS_REQUIRED=!0,tt.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE=!1,tt.SUPPORTS_MEDIAN=!1,tt.ARRAY_SIZE_NAME="CARDINALITY";var Y$,H$,V$,W$,j$,J$,bT,De=class extends(J$=W,j$=[O],W$=[O],V$=[O],H$=[O],Y$=[O],J$){static get NULL_ORDERING(){return"nulls_are_last"}static get EXPRESSION_METADATA(){return new Map(eg.EXPRESSION_METADATA)}static get TIME_FORMAT(){return Nt.TIME_FORMAT}static get TIME_MAPPING(){return Nt.TIME_MAPPING}static get NORMALIZATION_STRATEGY(){return"caseInsensitive"}static get SUPPORTED_SETTINGS(){return new Set([...W.SUPPORTED_SETTINGS,"variantExtractIsJsonExtract"])}};bT=re(J$),T(bT,10,"NULL_ORDERING",j$,De),T(bT,10,"TIME_FORMAT",W$,De),T(bT,10,"TIME_MAPPING",V$,De),T(bT,10,"NORMALIZATION_STRATEGY",H$,De),T(bT,10,"SUPPORTED_SETTINGS",Y$,De),te(bT,De),se(bT,3,De),De.DIALECT_NAME="presto",De.INDEX_OFFSET=1,De.STRICT_STRING_CONCAT=!0,De.SUPPORTS_SEMI_ANTI_JOIN=!1,De.TYPED_DIVISION=!0,De.TABLESAMPLE_SIZE_IS_PERCENT=!0,De.LOG_BASE_FIRST=void 0,De.SUPPORTS_VALUES_DEFAULT=!1,De.LEAST_GREATEST_IGNORES_NULLS=!1,De.Tokenizer=ig,De.Parser=ao,De.Generator=tt;W.register("presto",De);var X$,z$,k_,QR=class extends(z$=De.Tokenizer,X$=[O],z$){static get ORIGINAL_KEYWORDS(){return{...De.Tokenizer.KEYWORDS,REFRESH:"refresh"}}};k_=re(z$),T(k_,10,"ORIGINAL_KEYWORDS",X$,QR),te(k_,QR),se(k_,3,QR);var K$,Q$,Z$,eY,tY,sY,rY,ag,oo=class extends(rY=De.Parser,sY=[O],tY=[O],eY=[O],Z$=[O],Q$=[O],K$=[O],rY){static get ID_VAR_TOKENS(){return new Set([...De.Parser.ID_VAR_TOKENS,"sessionUser","straightJoin"])}static get NO_PAREN_FUNCTIONS(){let t={...De.Parser.NO_PAREN_FUNCTIONS};return t.currentCatalog=vp,t}static get FUNCTIONS(){return{...De.Parser.FUNCTIONS,VERSION:t=>Dn.fromArgList(t)}}static get FUNCTION_PARSERS(){return{...De.Parser.FUNCTION_PARSERS,TRIM:function(){return this.parseTrim()},JSON_QUERY:function(){return this.parseJsonQuery()},JSON_VALUE:function(){return this.parseJsonValue()},LISTAGG:function(){return this.parseStringAgg()}}}static get JSON_QUERY_OPTIONS(){return{WITH:[["WRAPPER"],["ARRAY","WRAPPER"],["CONDITIONAL","WRAPPER"],["CONDITIONAL","ARRAY","WRAPPED"],["UNCONDITIONAL","WRAPPER"],["UNCONDITIONAL","ARRAY","WRAPPER"]],WITHOUT:[["WRAPPER"],["ARRAY","WRAPPER"],["CONDITIONAL","WRAPPER"],["CONDITIONAL","ARRAY","WRAPPED"],["UNCONDITIONAL","WRAPPER"],["UNCONDITIONAL","ARRAY","WRAPPER"]]}}parseJsonQueryQuote(){if(this.matchTextSeq(["KEEP","QUOTES"])||this.matchTextSeq(["OMIT","QUOTES"]))return this.expression(wh,{option:this.tokens[this.index-2].text.toUpperCase(),scalar:this.matchTextSeq(["ON","SCALAR","STRING"])})}parseJsonQuery(){return this.expression(Zt,{this:this.parseBitwise(),expression:this.match("comma")?this.parseBitwise():void 0,option:this.parseVarFromOptions(this._constructor.JSON_QUERY_OPTIONS,{raiseUnmatched:!1}),jsonQuery:!0,quote:this.parseJsonQueryQuote(),onCondition:this.parseOnCondition()})}static get TABLE_ALIAS_TOKENS(){return new Set([...De.Parser.TABLE_ALIAS_TOKENS,"straightJoin"])}};ag=re(rY),T(ag,10,"ID_VAR_TOKENS",sY,oo),T(ag,10,"NO_PAREN_FUNCTIONS",tY,oo),T(ag,10,"FUNCTIONS",eY,oo),T(ag,10,"FUNCTION_PARSERS",Z$,oo),T(ag,10,"JSON_QUERY_OPTIONS",Q$,oo),T(ag,10,"TABLE_ALIAS_TOKENS",K$,oo),te(ag,oo),se(ag,3,oo);var nY,iY,aY,oY,cY,KR,co=class extends(cY=De.Generator,oY=[O],aY=[O],iY=[O],nY=[O],cY){static get AFTER_HAVING_MODIFIER_TRANSFORMS(){let t=new Map(super.AFTER_HAVING_MODIFIER_TRANSFORMS);return["cluster","distribute","sort"].forEach(s=>t.delete(s)),t}static get PROPERTIES_LOCATION(){return new Map([...De.Generator.PROPERTIES_LOCATION,[Es,"postWith"]])}static get ORIGINAL_TRANSFORMS(){return new Map([...De.Generator.TRANSFORMS,[Vy,function(t){return`REDUCE(${this.sql(t,"this")}, 0, (acc, x) -> acc + x, acc -> acc)`}],[vn,function(t){return`ARRAY_AGG(DISTINCT ${this.sql(t,"this")})`}],[Dn,X("VERSION")],[tr,function(t){return IB.call(this,t,{onOverflow:!0})}],[Es,function(t){return this.propertySql(t)}],[va,SB],[$,Ks([Kh,zh,TM(1),kR,__])],[Xs,function(t){return Tl.call(this,t,{includePrecision:!0})}],[or,HR]])}static get SUPPORTED_JSON_PATH_PARTS(){return new Set([Gt,Ls,Ds])}jsonExtractSql(t){if(!t.args.jsonQuery)return super.jsonExtractSql(t);let s=this.sql(t,"expression"),r=this.sql(t,"option"),i=r?` ${r}`:"",a=this.sql(t,"quote"),o=a?` ${a}`:"",c=this.sql(t,"onCondition"),p=c?` ${c}`:"";return this.func("JSON_QUERY",[t.args.this,s+i+o+p])}};KR=re(cY),T(KR,10,"AFTER_HAVING_MODIFIER_TRANSFORMS",oY,co),T(KR,10,"PROPERTIES_LOCATION",aY,co),T(KR,10,"ORIGINAL_TRANSFORMS",iY,co),T(KR,10,"SUPPORTED_JSON_PATH_PARTS",nY,co),te(KR,co),se(KR,3,co),co.SUPPORTS_DECODE_CASE=!1,co.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE=!0;var Ot=class extends De{};Ot.DIALECT_NAME="trino",Ot.SUPPORTS_USER_DEFINED_TYPES=!1,Ot.LOG_BASE_FIRST=!0,Ot.Tokenizer=QR,Ot.Parser=oo,Ot.Generator=co;W.register("trino",Ot);function uj(n){if(n.length<2)return!1;let[e,t,...s]=n,r=e.tokenType,i=e.text.toUpperCase(),a=t.tokenType,o=t.text.toUpperCase();return["describe","show"].includes(r)||i==="MSCK REPAIR"?!0:["alter","create","drop"].includes(r)?["DATABASE","EXTERNAL","SCHEMA"].includes(o)?!0:a==="view"?!1:s.every(c=>c.tokenType!=="select"):!1}function Ej(n){if(n instanceof us)if(n.args.kind==="table"){let e=n.args.properties;if(e&&e.find(Nn)||!(n.args.expression instanceof ce))return!0}else return n.args.kind!=="view";else if(n instanceof mn||n instanceof Tn||n instanceof ei||n instanceof gc)return!(n instanceof Tn&&n.args.kind==="view");return!1}function bY(n){for(let e of n.args.expressions||[])if(e instanceof U&&e.text("this").toLowerCase()==="table_type")return e.text("value").toLowerCase()==="iceberg";return!1}function hj(n){let e="external_location";return n.parent instanceof mt&&bY(n.parent)&&(e="location"),`${e}=${this.sql(n,"this")}`}function gj(n){let e="partitioned_by";return n.parent instanceof mt&&bY(n.parent)&&(e="partitioning"),`${e}=${this.sql(n,"this")}`}var $M=class extends de.Generator{alterSql(e){if(e instanceof mn&&e.args.kind==="table"&&e.args.actions&&e.args.actions[0]instanceof we){let t=new Lt({expressions:e.args.actions});e.setArgKey("actions",[t])}return super.alterSql(e)}};$M.SUPPORTS_DECODE_CASE=!1;var pY,lY,U_,eO=class extends(lY=Ot.Tokenizer,pY=[O],lY){static get ORIGINAL_KEYWORDS(){return{...Ot.Tokenizer.ORIGINAL_KEYWORDS,UNLOAD:"command"}}};U_=re(lY),T(U_,10,"ORIGINAL_KEYWORDS",pY,eO),te(U_,eO),se(U_,3,eO);var uY,EY,hY,gY,dY,ZR,Sl=class extends(dY=Ot.Parser,gY=[O],hY=[O],EY=[O],uY=[O],dY){static get ID_VAR_TOKENS(){return new Set([...he.ID_VAR_TOKENS,"sessionUser","currentCatalog","straightJoin"])}static get NO_PAREN_FUNCTIONS(){let t={...he.NO_PAREN_FUNCTIONS};return delete t.localtime,delete t.localtimestamp,t}static get STATEMENT_PARSERS(){return{...Ot.Parser.STATEMENT_PARSERS,using:function(){return this.parseAsCommand(this.prev)}}}static get TABLE_ALIAS_TOKENS(){return new Set([...he.TABLE_ALIAS_TOKENS,"straightJoin"])}};ZR=re(dY),T(ZR,10,"ID_VAR_TOKENS",gY,Sl),T(ZR,10,"NO_PAREN_FUNCTIONS",hY,Sl),T(ZR,10,"STATEMENT_PARSERS",EY,Sl),T(ZR,10,"TABLE_ALIAS_TOKENS",uY,Sl),te(ZR,Sl),se(ZR,3,Sl);var AY,fY,xY,GM,PT=class extends(xY=Ot.Generator,fY=[O],AY=[O],xY){static get PROPERTIES_LOCATION(){let t=new Map(Ot.Generator.PROPERTIES_LOCATION);return t.set(Es,"postWith"),t}static get ORIGINAL_TRANSFORMS(){let t=new Map(Ot.Generator.ORIGINAL_TRANSFORMS);return t.set(Bt,gj),t.set(Es,hj),t}};GM=re(xY),T(GM,10,"PROPERTIES_LOCATION",fY,PT),T(GM,10,"ORIGINAL_TRANSFORMS",AY,PT),te(GM,PT),se(GM,3,PT);var TY,SY,mY,RY,OY,NY,IY,og,po=class extends(IY=Dt,NY=[O],OY=[O],RY=[O],mY=[O],SY=[O],TY=[O],IY){constructor(t={}){let{hive:s=new de,trino:r=new Ot}=t;super(t);this.hiveTokenizer=void 0;this.trinoTokenizer=void 0;this.hiveTokenizer=s.tokenizer({...t,dialect:s}),this.trinoTokenizer=new eO({...t,dialect:r})}static get IDENTIFIERS(){return[...Ot.Tokenizer.IDENTIFIERS,...de.Tokenizer.IDENTIFIERS]}static get STRING_ESCAPES(){return[...Ot.Tokenizer.STRING_ESCAPES,...de.Tokenizer.STRING_ESCAPES]}static get HEX_STRINGS(){return[...Ot.Tokenizer.HEX_STRINGS,...de.Tokenizer.HEX_STRINGS]}static get UNICODE_STRINGS(){return[...Ot.Tokenizer.UNICODE_STRINGS,...de.Tokenizer.UNICODE_STRINGS]}static get NUMERIC_LITERALS(){return{...Ot.Tokenizer.NUMERIC_LITERALS,...de.Tokenizer.NUMERIC_LITERALS}}static get ORIGINAL_KEYWORDS(){return{...de.Tokenizer.ORIGINAL_KEYWORDS,...Ot.Tokenizer.ORIGINAL_KEYWORDS,UNLOAD:"command"}}tokenize(t){let s=super.tokenize(t);return uj(s)?[new Lg("hiveTokenStream","")].concat(this.hiveTokenizer.tokenize(t)):this.trinoTokenizer.tokenize(t)}};og=re(IY),T(og,10,"IDENTIFIERS",NY,po),T(og,10,"STRING_ESCAPES",OY,po),T(og,10,"HEX_STRINGS",RY,po),T(og,10,"UNICODE_STRINGS",mY,po),T(og,10,"NUMERIC_LITERALS",SY,po),T(og,10,"ORIGINAL_KEYWORDS",TY,po),te(og,po),se(og,3,po);var v_=class extends he{constructor(e={}){let{hive:t=new de,trino:s=new Ot}=e;super(e),this.hiveParser=t.parser({...e,dialect:t}),this.trinoParser=new Sl({...e,dialect:s})}parse(e,t){return e&&e[0].tokenType==="hiveTokenStream"?this.hiveParser.parse(e.slice(1),t):this.trinoParser.parse(e,t)}parseIntoTypes(e,t,s){return t&&t[0].tokenType==="hiveTokenStream"?this.hiveParser.parseIntoTypes(e,t.slice(1),s):this.trinoParser.parseIntoTypes(e,t,s)}},yY,CY,q_,wT=class extends(CY=L,yY=[O],CY){constructor(t={}){let{hive:s=new de,trino:r=new Ot}=t;super(t);this.hiveGenerator=void 0;this.trinoGenerator=void 0;this.hiveGenerator=new $M({...t,dialect:s}),this.trinoGenerator=new PT({...t,dialect:r})}static get AFTER_HAVING_MODIFIER_TRANSFORMS(){let t=new Map(super.AFTER_HAVING_MODIFIER_TRANSFORMS);return["cluster","distribute","sort"].forEach(s=>t.delete(s)),t}generate(t,s={}){let{copy:r=!0}=s;return(Ej(t)?this.hiveGenerator:this.trinoGenerator).generate(t,{copy:r})}};q_=re(CY),T(q_,10,"AFTER_HAVING_MODIFIER_TRANSFORMS",yY,wT),te(q_,wT),se(q_,3,wT),wT.SELECT_KINDS=[];var ml=class extends W{constructor(e={}){super(e),this.hive=new de(e),this.trino=new Ot(e)}tokenize(e,t={}){return t.hive=this.hive,t.trino=this.trino,super.tokenize(e,t)}parse(e,t={}){return t.hive=this.hive,t.trino=this.trino,super.parse(e,t)}parseIntoTypes(e,t,s={}){return s.hive=this.hive,s.trino=this.trino,super.parseIntoTypes(e,t,s)}generate(e,t={}){return t.hive=this.hive,t.trino=this.trino,super.generate(e,t)}};ml.DIALECT_NAME="athena",ml.Tokenizer=po,ml.Parser=v_,ml.Generator=wT;W.register("athena",ml);function y_(n,e={}){let{dialect:t}=e,s=Ci(n),r=W.getOrRaise(t),i=r instanceof ml||r instanceof De;if(s){let a=s.refCount();for(let o of Array.from(s.traverse()).reverse()){let c=o.expression,p=c.getArgKey("where");if(p){let E=o.selectedSources,g=c.getArgKey("joins"),A=new Map;g&&g.forEach((m,N)=>{let R=m.aliasOrName;R&&A.set(R,N)});let x=!0;for(let[m,N]of Object.entries(E)){let[R]=N;if(!R)continue;let S=R.findAncestor(z,Ge);if(S instanceof z){if(S.args.side==="right"){E={[m]:N};break}if(R instanceof Pe&&i){x=!1;break}}}if(x){let m=p.args.this;m instanceof h&&PY(m,E,a,r,A)}}let u=c.getArgKey("joins");if(u)for(let E of u){let g=E.aliasOrName;if(g&&g in o.selectedSources){let A=E.args.on;PY(A,{[g]:o.selectedSources[g]},a,r)}}}}return n}function PY(n,e,t,s,r){if(!n)return;let i=vc(n,{dialect:s});n=n.replace(i);let a=Mi(n)||!Mi(n,{dnf:!0}),o=(a?n instanceof Oe:n instanceof pt)?Array.from(n.flatten()):[n];a?dj(o,e,t,r):Aj(o,e,t)}function dj(n,e,t,s){let r=s||new Map;for(let i of n){let a=wY(i,e,t);for(let[o,c]of Object.entries(a))if(c instanceof z){let p=to(i,{exclude:o}),u=_nullishCoalesce(r.get(o), () => (-1));if(Array.from(p).every(g=>(_nullishCoalesce(r.get(g), () => (-1)))<u)){i.replace($e()),c.on(i,{copy:!1});break}}else if(c instanceof $){i.replace($e());let p=MY(c,i);Pl(p,q)?c.having(p,{copy:!1}):c.where(p,{copy:!1})}}}function Aj(n,e,t){let s=new Set;for(let a of n){let o=to(a);for(let c of n){let p=to(c);o=new Set(Array.from(o).filter(u=>p.has(u)))}for(let c of o)s.add(c)}let r=new Map,i={};for(let a of Array.from(s).sort()){for(let o of n){if(i=wY(o,e,t),!(a in i))continue;let c=r.get(a);r.set(a,c?bs([c,o]):o)}for(let[o,c]of Object.entries(i)){let p=r.get(o);if(p){if(c instanceof z)c.on(p,{copy:!1});else if(c instanceof $){let u=MY(c,p);Pl(u,q)?c.having(u,{copy:!1}):c.where(u,{copy:!1})}}}}}function wY(n,e,t){let s={},r=to(n),i=n.findAncestor(z,at)instanceof at;for(let a of Array.from(r).sort()){let o=e[a];if(!o)continue;let c=o[0],[,p]=o;if(c&&i&&(c=c.findAncestor(z,Ge)),c instanceof Ge&&!(p instanceof V)){let u=_optionalChain([Pt, 'call', _1464 => _1464(_optionalChain([(p instanceof Ce?p.parent:_optionalChain([p, 'access', _1465 => _1465.parent, 'optionalAccess', _1466 => _1466.args])), 'optionalAccess', _1467 => _1467.expression]),h), 'optionalAccess', _1468 => _1468.getArgKey, 'call', _1469 => _1469("with")]);if(u instanceof ve&&_optionalChain([u, 'optionalAccess', _1470 => _1470.recursive]))return{};c=p instanceof Ce?p.expression:p.args.expression}if(c instanceof z){let u=c.side;if(u&&u!=="right")return{};s[a]=c}else if(c instanceof $&&r.size===1){let u=c.selects.some(A=>A instanceof h?A.find(Fe)!==void 0:!1),E=!!c.args.group,g=t.get(p)||0;!E&&g<2&&!u&&(s[a]=c)}}return s}function MY(n,e){let t=new Map;for(let r of n.selects)if(r instanceof h)if(r instanceof Se){let i=r.args.this;i instanceof h&&t.set(r.alias,i)}else t.set(r.name,r);function s(r){if(r instanceof k){let i=t.get(r.name);if(i)return i.copy()}return r}return e.transform(s)}var lG=[gw,O_,RL,N_,y_,jD,qM,R_,m_,S_,hw,os,VD,vc];function F_(n,e={}){let{schema:t,db:s,catalog:r,dialect:i,rules:a=lG,sql:o,isolateTables:c=!0,quoteIdentifiers:p=!1,...u}=e,E=Qs(t,{dialect:i}),g={db:s,catalog:r,schema:E,dialect:i,sql:o,isolateTables:c,quoteIdentifiers:p,...u},A=ne(n,{dialect:i,copy:!0});for(let x of a)A=x(A,g);return A}var YM=class{constructor(e){this._dag=void 0;this.expression=e.copy(),this.root=lo.fromExpression(this.expression)}get dag(){if(this._dag)return this._dag;let e=new Map,t=new Set,s=[this.root];for(;0<s.length;){let r=s.pop();if(t.has(r))continue;t.add(r);let i=new Set;for(let a of r.dependencies)i.add(a),s.push(a);e.set(r,i)}return this._dag=e,this._dag}get leaves(){let e=[];for(let[t,s]of this.dag.entries())s.size===0&&e.push(t);return e[Symbol.iterator]()}toString(){return`Plan
|
|
42
|
+
----
|
|
43
|
+
${_nullishCoalesce(_optionalChain([this, 'access', _1471 => _1471.root, 'optionalAccess', _1472 => _1472.toString, 'call', _1473 => _1473()]), () => ("unnamed"))}`}},lo=class n{constructor(){this.name="";this.dependencies=new Set;this.dependents=new Set;this.projections=[];this.limit=1/0;this.condition=void 0;this.operands=[];this.aggregations=[]}static fromExpression(e,t=new Map){if(!e)return;let s=e.unnest(),r=s.getArgKey("with");if(D(r,ve)){t=new Map(t);for(let S of r.args.expressions||[]){ue(S.args.this,h);let I=n.fromExpression(S.args.this,t);I&&(I.name=S.alias,t.set(I.name,I))}}let i=s.args.from,a;s instanceof $&&i instanceof h?(ue(i.args.this,h),a=LT.fromExpression(i.args.this,t)):s instanceof be?a=Tw.fromExpression(s,t):a=new LT;let o=Xe(s.args.joins||[],z);if(o&&0<o.length){let S=fw.fromJoins(o,t);a&&(S.name=a.name,S.sourceName=a.name,S.addDependency(a)),a=S}let c=[],p=new Map,u=new Map,E=go("_a_"),g=S=>{let I=Array.from(S.findAll(q));0<I.length&&u.set(S,void 0);for(let y of I)for(let P of y.unnestOperands())P instanceof k||(p.has(P)||p.set(P,E()),P.replace(new k({this:new G({this:p.get(P),quoted:!0})})));return 0<I.length},A=S=>{S.operands=Array.from(p.entries()).map(([I,y])=>oe(I,y)),S.aggregations=Array.from(u.keys())};for(let S of s.args.expressions||[])ue(S,h),S.find(q)?(c.push(Ie({col:S.aliasOrName,table:_optionalChain([a, 'optionalAccess', _1474 => _1474.name])},{quoted:!0})),g(S)):c.push(S);let x=s.getArgKey("where");a&&x instanceof h&&x.args.this instanceof h&&(a.condition=x.args.this);let m=s.getArgKey("group");if(m||0<u.size){let S=new MT;a&&(S.source=a.name,S.name=a.name);let I=s.getArgKey("having");I instanceof h&&D(I.args.this,"string",h)&&(g(oe(I.args.this,"_h",{quoted:!0}))?S.condition=Ie({col:"_h",table:_optionalChain([a, 'optionalAccess', _1475 => _1475.name])},{quoted:!0}):D(I.args.this,h)&&(S.condition=I.args.this)),A(S);let y=D(m,h)?Xe(_nullishCoalesce(m.args.expressions, () => ([])),h):[];S.group=Object.fromEntries(y.map((H,B)=>[`_g${B}`,H]));let P=new Map;Object.entries(S.group).forEach(([H,B])=>{P.set(B.sql(),H),B instanceof k&&P.set(B.name,H)});let v=H=>_nullishCoalesce(P.get(H.sql()), () => ((H instanceof k?P.get(H.name):void 0)));for(let H of c)for(let B of H.walk()){let fe=v(B);fe&&B.replace(Ie({col:fe,table:_optionalChain([a, 'optionalAccess', _1476 => _1476.name])},{quoted:!0}))}if(S.condition)for(let H of S.condition.walk()){let B=v(H);B&&H.replace(Ie({col:B,table:_optionalChain([a, 'optionalAccess', _1477 => _1477.name])},{quoted:!0}))}S.addDependency(a),a=S}let N=s.getArgKey("order");if(D(N,h)){if(a instanceof MT){let I=Xe(N.args.expressions||[],h);for(let y=0;y<I.length;y++){let v=I[y].args.this;v&&g(oe(v,`_o_${y}`,{quoted:!0}))&&v.replace(Ie({col:`_o_${y}`,table:a.name},{quoted:!0}))}A(a)}let S=new xw;S.name=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _1478 => _1478.name]), () => ("")),S.key=Xe(N.args.expressions||[],h),S.addDependency(a),a=S}if(a&&(a.projections=c),s instanceof $&&s.args.distinct){let S=new MT;S.source=_optionalChain([a, 'optionalAccess', _1479 => _1479.name]),S.name=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _1480 => _1480.name]), () => ("")),S.group=Object.fromEntries((c.length?c:Xe(s.args.expressions||[],h)).map(I=>[I.aliasOrName,Ie({col:I.aliasOrName,table:_optionalChain([a, 'optionalAccess', _1481 => _1481.name])},{quoted:!0})])),S.addDependency(a),a=S}let R=s.getArgKey("limit");return a&&D(R,h)&&(a.limit=parseInt(R.text("expression"))),a}addDependency(e){e&&(this.dependencies.add(e),e.dependents.add(this))}toString(){return this.toS()}toS(e=0){let t=" ".repeat(e),s=`${t} `,r=this._toS(`${s} `);0<r.length&&(r=[`${s}Context:`,...r]);let i=[`${t}- ${this.id}`,...r,`${s}Projections:`];for(let a of this.projections)i.push(`${s} - ${a.sql()}`);if(this.condition&&i.push(`${s}Condition: ${this.condition.sql()}`),this.limit!==1/0&&i.push(`${s}Limit: ${this.limit}`),0<this.dependencies.size){i.push(`${s}Dependencies:`);for(let a of this.dependencies)i.push(` ${a.toS(e+1)}`)}return i.join(`
|
|
44
|
+
`)}get typeName(){return this.constructor.name}get id(){let e=this.name?` ${this.name}`:"";return`${this.typeName}:${e} (${_T(this)})`}_toS(e){return[]}},LT=class n extends lo{constructor(){super(...arguments);this.source=void 0}static fromExpression(t,s=new Map){let r=t,i=t.aliasOrName;if(t instanceof ae){let c=t.args.this,p=c!==void 0?lo.fromExpression(c,s):void 0;return p&&(p.name=i),p}let a=new n;a.name=i,a.source=t;let o=r.name;return s.has(o)&&a.addDependency(s.get(o)),a}_toS(t){let s=this.source instanceof h?this.source.sql():_nullishCoalesce(this.source, () => ("-static-"));return[`${t}Source: ${s}`]}},fw=class n extends lo{constructor(){super(...arguments);this.sourceName=void 0;this.joins={}}static fromJoins(t,s=new Map){let r=new n;for(let i of t){let{sourceKeys:a,joinKeys:o,on:c}=UM(i);r.joins[i.aliasOrName]={side:i.side,joinKey:o||[],sourceKey:a||[],condition:c||void 0},i.args.this!==void 0&&r.addDependency(LT.fromExpression(i.args.this,s))}return r}_toS(t){let s=[`${t}Source: ${this.sourceName||this.name}`];for(let[r,i]of Object.entries(this.joins)){s.push(`${t}${r}: ${i.side||"INNER"}`);let a=i.joinKey.map(o=>String(o)).join(", ");a&&s.push(`${t}Key: ${a}`),i.condition&&s.push(`${t}On: ${i.condition.sql()}`)}return s}},MT=class extends lo{constructor(){super();this.aggregations=[];this.operands=[];this.group={};this.source=void 0}_toS(t){let s=[`${t}Aggregations:`];for(let r of this.aggregations)s.push(`${t} - ${r.sql()}`);if(0<Object.keys(this.group).length){s.push(`${t}Group:`);for(let r of Object.values(this.group))s.push(`${t} - ${r.sql()}`)}if(this.condition&&(s.push(`${t}Having:`),s.push(`${t} - ${this.condition.sql()}`)),0<this.operands.length){s.push(`${t}Operands:`);for(let r of this.operands)s.push(`${t} - ${r.sql()}`)}return s}},xw=class extends lo{constructor(){super();this.key=[]}_toS(t){let s=[`${t}Key:`];for(let r of this.key)s.push(`${t} - ${r.sql()}`);return s}},Tw=class n extends lo{constructor(e,t,s,r={}){let{distinct:i=!1}=r;super(),this.op=e,this.left=t,this.right=s,this.distinct=i}static fromExpression(e,t=new Map){if(!(e instanceof be))throw new Error("Expected SetOperation expression");let s=e.args.this!==void 0?lo.fromExpression(e.args.this,t):void 0;s&&(s.name=s.name||"left");let r=e.args.expression!==void 0?lo.fromExpression(e.args.expression,t):void 0;r&&(r.name=r.name||"right");let i=new n(e._constructor,_optionalChain([s, 'optionalAccess', _1482 => _1482.name]),_optionalChain([r, 'optionalAccess', _1483 => _1483.name]),{distinct:!!e.args.distinct});s&&i.addDependency(s),r&&i.addDependency(r);let a=e.args.limit;return D(a,h)&&(i.limit=parseInt(a.text("expression"))),i}_toS(e){let t=[];return this.distinct&&t.push(`${e}Distinct: ${this.distinct}`),t}get typeName(){return this.op.name}};function xe(...n){let e=n.length===2&&typeof n[0]=="function"&&n[1]!==void 0&&typeof n[1]=="object"&&n[1].kind==="method",t=(r,i)=>{let a=0<i.length?(...o)=>i.some(c=>o[c]===void 0):(...o)=>o.some(c=>c===void 0);return(...o)=>a(...o)?void 0:r(...o)};if(e)return t(n[0],[]);let s=n;return r=>t(r,s)}var B_=class{constructor(e){this.obj=e}eq(e){return e.obj===this.obj}lt(e){return Pc(e.obj,this.obj)}};function tO(n,e=!0){return t=>{let r=(Array.isArray(t)?t:t!=null&&typeof t[Symbol.iterator]=="function"?[...t]:[t]).filter(i=>i!==void 0);if(!(r.length===0&&e))return n(r)}}function xj(n){return Ow(n.reduce((e,t)=>pO(e,t),0),n.length)}var LY,DY,_Y,kY,UY,qY,vY,FY,BY,GY,$Y,YY,HY,VY,WY,jY,JY,XY,zY,KY,QY,ZY,eH,tH,sH,rH,nH,iH,aH,oH,cH,pH,lH,uH,EH,hH,gH,dH,AH,fH,xH,TH,SH,mH,Ae;mH=[xe],SH=[xe],TH=[xe],xH=[xe(0,1),xe(0,1)],fH=[xe],AH=[xe],dH=[xe],gH=[xe],hH=[xe],EH=[xe],uH=[xe],lH=[xe],pH=[xe],cH=[xe],oH=[xe],aH=[xe],iH=[xe],nH=[xe],rH=[xe],sH=[xe],tH=[xe],eH=[xe],ZY=[xe(0,1)],QY=[xe],KY=[xe],zY=[xe],XY=[xe],JY=[xe],jY=[xe],WY=[xe],VY=[xe],HY=[xe],YY=[xe],$Y=[xe],GY=[xe],BY=[xe],FY=[xe],vY=[xe],qY=[xe],UY=[xe],kY=[xe],_Y=[xe],DY=[xe],LY=[xe];var ee=class ee{static ABS(e){return Math.abs(e)}static ADD(e,t){return pO(e,t)}static ARRAYANY(e,t){return e.some(s=>t(s))}static ARRAYTOSTRING(e,t,s){return e.map(r=>r!==void 0?r:s).filter(r=>r!==void 0).join(t)}static BETWEEN(e,t,s){return lO(t,e)&&lO(e,s)}static BITWISEAND(e,t){return uL(e,t)}static BITWISELEFTSHIFT(e,t){return hL(e,t)}static BITWISEOR(e,t){return lL(e,t)}static BITWISERIGHTSHIFT(e,t){return gL(e,t)}static BITWISEXOR(e,t){return EL(e,t)}static CAST(e,t){if(e!==void 0){if(t==="date"){if(e instanceof _luxon.DateTime)return e.startOf("day");if(typeof e=="string")return _luxon.DateTime.fromISO(e).startOf("day")}if(t==="time"){if(e instanceof _luxon.DateTime)return e;if(typeof e=="string")return _luxon.DateTime.fromISO(`1970-01-01T${e}`)}if(t==="datetime"||t==="timestamp"){if(e instanceof _luxon.DateTime)return e;if(typeof e=="string")return _luxon.DateTime.fromISO(e)}if(t==="boolean")return!!e;if(C.TEXT_TYPES.has(t))return String(e);if(t==="float"||t==="double")return Number(e);if(C.NUMERIC_TYPES.has(t))return Math.trunc(Number(e));throw new Error(`Casting ${e} to '${t}' not implemented.`)}}static CONCAT(...e){return e.join("")}static SAFECONCAT(...e){return e.map(String).join("")}static CONCATWS(e,...t){return t.join(e)}static DATEDIFF(e,t){return Math.floor(e.diff(t,"days").days)}static DATESTRTODATE(e){return _luxon.DateTime.fromISO(e).startOf("day")}static DIV(e,t){if(t===0)throw new Error("division by zero");return Ow(e,t)}static DOT(e,t){if(!(e===void 0||t===void 0))return e[t]}static EQ(e,t){return Nw(e,t)}static EXTRACT(e,t){return t[e]}static GT(e,t){return aL(e,t)}static GTE(e,t){return cL(e,t)}static INTDIV(e,t){return eL(e,t)}static INTERVAL(e,t){let s=t+"S";return s in L.TIME_PART_SINGULARS&&(t=s),_luxon.Duration.fromObject({[t.toLowerCase()]:parseFloat(e)}).toMillis()}static JSONEXTRACT(e,t){let s=e;for(let r of t){if(s===void 0)break;if(typeof s=="object"&&!Array.isArray(s))s=s[r];else if(Array.isArray(s)&&kL(String(r)))s=b(s,parseInt(r));else throw new Error(`Unable to extract value for ${s} at ${r}.`)}return s}static LEFT(e,t){return e.slice(0,t)}static LIKE(e,t){return new RegExp("^"+t.replace(/_/g,".").replace(/%/g,".*")+"$").test(e)}static LOWER(e){return e.toLowerCase()}static LT(e,t){return Pc(e,t)}static LTE(e,t){return lO(e,t)}static MAP(e,t){if(!(e===void 0||t===void 0))return Object.fromEntries(e.map((s,r)=>[s,t[r]]))}static MOD(e,t){return tL(e,t)}static MUL(e,t){return ZM(e,t)}static NEQ(e,t){return pL(e,t)}static ORD(e){return e.codePointAt(0)}static ORDERED(e,t){let{desc:s}=t;return s?new B_(e):e}static RIGHT(e,t){return e.slice(-t)}static ROUND(e,t,s){return t===void 0?Math.round(e):parseFloat(e.toFixed(t))}static STRPOSITION(e,t,s){if(e===void 0||t===void 0)return;let r=s!==void 0?s-1:0;return e.indexOf(t,r)+1}static SUB(e,t){return QM(e,t)}static SUBSTRING(e,t,s){if(e===void 0)return;if(t===void 0)return e;if(t===0)return"";let r=t<0?e.length+t:t-1,i=s===void 0?void 0:r+s;return e.slice(r,i)}static TIMESTRTOTIME(e){return _luxon.DateTime.fromISO(e)}static UPPER(e){return e.toUpperCase()}static YEAR(e){return e.year}static MONTH(e){return e.month}static DAY(e){return e.day}static STRFTIME(e,t){let s=_luxon.DateTime.fromISO(t);return e.replace("%Y",String(s.year)).replace("%m",String(s.month).padStart(2,"0")).replace("%d",String(s.day).padStart(2,"0")).replace("%H",String(s.hour).padStart(2,"0")).replace("%M",String(s.minute).padStart(2,"0")).replace("%S",String(s.second).padStart(2,"0"))}static STRTOTIME(e,t){return _luxon.DateTime.fromISO(e)}static TRIM(e,t){return t===void 0?e.trim():e.replace(new RegExp(`^[${t}]+|[${t}]+$`,"g"),"")}static UNIXTOTIME(e){return _luxon.DateTime.fromSeconds(e)}};Ae=re(null),T(Ae,9,"ABS",mH,ee),T(Ae,9,"ADD",SH,ee),T(Ae,9,"ARRAYANY",TH,ee),T(Ae,9,"ARRAYTOSTRING",xH,ee),T(Ae,9,"BETWEEN",fH,ee),T(Ae,9,"BITWISEAND",AH,ee),T(Ae,9,"BITWISELEFTSHIFT",dH,ee),T(Ae,9,"BITWISEOR",gH,ee),T(Ae,9,"BITWISERIGHTSHIFT",hH,ee),T(Ae,9,"BITWISEXOR",EH,ee),T(Ae,9,"CONCAT",uH,ee),T(Ae,9,"SAFECONCAT",lH,ee),T(Ae,9,"CONCATWS",pH,ee),T(Ae,9,"DATEDIFF",cH,ee),T(Ae,9,"DATESTRTODATE",oH,ee),T(Ae,9,"DIV",aH,ee),T(Ae,9,"EQ",iH,ee),T(Ae,9,"EXTRACT",nH,ee),T(Ae,9,"GT",rH,ee),T(Ae,9,"GTE",sH,ee),T(Ae,9,"INTDIV",tH,ee),T(Ae,9,"INTERVAL",eH,ee),T(Ae,9,"JSONEXTRACT",ZY,ee),T(Ae,9,"LEFT",QY,ee),T(Ae,9,"LIKE",KY,ee),T(Ae,9,"LOWER",zY,ee),T(Ae,9,"LT",XY,ee),T(Ae,9,"LTE",JY,ee),T(Ae,9,"MOD",jY,ee),T(Ae,9,"MUL",WY,ee),T(Ae,9,"NEQ",VY,ee),T(Ae,9,"ORD",HY,ee),T(Ae,9,"RIGHT",YY,ee),T(Ae,9,"ROUND",$Y,ee),T(Ae,9,"SUB",GY,ee),T(Ae,9,"TIMESTRTOTIME",BY,ee),T(Ae,9,"UPPER",FY,ee),T(Ae,9,"YEAR",vY,ee),T(Ae,9,"MONTH",qY,ee),T(Ae,9,"DAY",UY,ee),T(Ae,9,"STRFTIME",kY,ee),T(Ae,9,"STRTOTIME",_Y,ee),T(Ae,9,"TRIM",DY,ee),T(Ae,9,"UNIXTOTIME",LY,ee),te(Ae,ee),se(Ae,3,ee),ee.ARRAYAGG=e=>[...e],ee.ARRAYUNIQUEAGG=tO(e=>[...new Set(e)]),ee.AVG=tO(e=>xj(e)),ee.COUNT=tO(e=>e.length,!1),ee.MAX=tO(e=>e.reduce((t,s)=>Pc(t,s)?s:t)),ee.MIN=tO(e=>e.reduce((t,s)=>Pc(s,t)?s:t)),ee.SUM=tO(e=>e.reduce((t,s)=>pO(t,s),0)),ee.COALESCE=(...e)=>e.find(t=>t!==void 0),ee.IF=(e,t,s)=>e?t:s,ee.POW=(e,t)=>sL(e,t),ee.CURRENTDATETIME=()=>_luxon.DateTime.now(),ee.CURRENTTIMESTAMP=()=>_luxon.DateTime.now(),ee.CURRENTTIME=()=>_luxon.DateTime.now(),ee.CURRENTDATE=()=>_luxon.DateTime.now().startOf("day"),ee.STRUCT=(...e)=>{let t={};for(let s=0;s<e.length;s+=2)e[s]!==void 0&&e[s+1]!==void 0&&(t[e[s]]=e[s+1]);return t},(()=>{for(let e of Object.getOwnPropertyNames(ee)){let t=Object.getOwnPropertyDescriptor(ee,e);_optionalChain([t, 'optionalAccess', _1484 => _1484.configurable])&&(t.enumerable||Object.defineProperty(ee,e,{...t,enumerable:!0}))}})();var sO=ee;var HM=class{constructor(e,t){this._table=void 0;this.tables=e,this.rangeReaders={},this.rowReaders={};for(let[s,r]of this.tables)this.rangeReaders[s]=r.rangeReader,this.rowReaders[s]=r.reader;this.env={...sO,...t||{},scope:this.rowReaders}}eval(e){let t=Object.keys(this.env),s=Object.values(this.env);return new Function(...t,`return ${e};`)(...s)}evalTuple(e){return e.map(t=>this.eval(t))}get table(){if(this._table===void 0){let e=Array.from(this.tables.values());this._table=e[0];for(let t of e){if(this._table.columns.join(",")!==t.columns.join(","))throw new Error("Columns are different.");if(this._table.rows.length!==t.rows.length)throw new Error("Rows are different.")}}return this._table}addColumns(...e){for(let t of this.tables.values())t.addColumns(...e)}get columns(){return this.table.columns}*[Symbol.iterator](){this.env.scope=this.rowReaders;for(let e=0;e<this.table.rows.length;e++){let t;for(let s of this.tables.values())t=s.get(e);t&&(yield[t,this])}}tableIter(e){this.env.scope=this.rowReaders;let t=this.tables.get(e);if(!t)throw new Error(`Table ${e} not found in context.`);return t[Symbol.iterator]()}filter(e){let t=[];for(let[s]of this)this.eval(e)&&t.push(s.row);for(let s of this.tables.values())s.rows=t}sort(e){let t=this.table.rows.map(r=>{this.setRow(r);let i=this.evalTuple(e).map(a=>[a===void 0,a]);return{row:r,evaluatedKeys:i}});t.sort((r,i)=>{for(let a=0;a<e.length;a++){let o=r.evaluatedKeys[a],c=i.evaluatedKeys[a];if(o[0]!==c[0])return o[0]?1:-1;if(Pc(o[1],c[1]))return-1;if(Pc(c[1],o[1]))return 1}return 0});let s=t.map(r=>r.row);for(let r of this.tables.values())r.rows=s}setRow(e){for(let t of this.tables.values())t.reader.row=e;this.env.scope=this.rowReaders}setIndex(e){for(let t of this.tables.values())t.get(e);this.env.scope=this.rowReaders}setRange(e,t){for(let[s]of this.tables)this.rangeReaders[s].range={start:e,stop:t};this.env.scope=this.rangeReaders}has(e){return this.tables.has(e)}};var gt=class{constructor(e,t=[],s){if(this.columns=Array.from(e),this.columnRange=s,this.reader=new rO(this.columns,this.columnRange),this.rows=t,0<this.rows.length&&this.rows[0].length!==this.columns.length)throw new Error("Row length does not match column length.");this.rangeReader=new $_(this)}addColumns(...e){this.columns.push(...e),this.columnRange&&(this.columnRange={start:this.columnRange.start,stop:this.columnRange.stop+e.length}),this.reader=new rO(this.columns,this.columnRange)}append(e){if(e.length!==this.columns.length)throw new Error("Row length does not match column length.");this.rows.push(e)}pop(){this.rows.pop()}toJslist(){return this.rows.map(e=>{let t={};return this.columns.forEach((s,r)=>{t[s]=e[r]}),t})}get width(){return this.columns.length}get length(){return this.rows.length}*[Symbol.iterator](){for(let e=0;e<this.rows.length;e++)yield this.get(e)}get(e){return this.reader.row=this.rows[e],this.reader}toString(){let e=this.columns.filter((r,i)=>!this.columnRange||this.columnRange.start<=i&&i<this.columnRange.stop),t={};e.forEach(r=>{t[r]=r.length});let s=[e.join(" ")];for(let r=0;r<this.length&&!(10<r);r++){let i=this.get(r),a=e.map(o=>String(_nullishCoalesce(i.row[i.columns[o]], () => (""))).padStart(t[o]," ").substring(0,t[o])).join(" ");s.push(a)}return s.join(`
|
|
45
|
+
`)}};var G_=class extends yl{depth(){return Ii(this.mapping)}};function RH(n,e){return new G_(OH(n,e),{normalize:!1,dialect:e})}function OH(n,e){if(typeof n!="object"||!n||Object.keys(n).length===0)return{};if(1<Ii(n)){let r={};for(let[i,a]of Object.entries(n)){let o=wc(i,{dialect:e,isTable:!0}).name;r[o]=OH(a,e)}return r}let s={};for(let[r,i]of Object.entries(n)){let a=wc(r,{dialect:e}).name;if(i instanceof gt)s[a]=i;else{let o=i.map(u=>{let E={};for(let[g,A]of Object.entries(u))E[wc(g,{dialect:e}).name]=A;return E}),c=0<o.length?Object.keys(o[0]):[],p=o.map(u=>c.map(E=>u[E]));s[a]=new gt(c,p)}}return s}var rO=class{constructor(e,t){this.columns={};this.row=[];return e.forEach((s,r)=>{(!t||t.start<=r&&r<t.stop)&&(this.columns[s]=r)}),new Proxy(this,{get(s,r){if(r in s)return s[r];if(typeof r=="string"&&r in s.columns&&s.row)return s.row[s.columns[r]]}})}},$_=class{constructor(e){this.range={start:0,stop:0};return this.table=e,new Proxy(this,{get(t,s){if(s in t)return t[s];if(typeof s=="string")return(function*(){for(let r=t.range.start;r<t.range.stop;r++)yield t.table.rows[r][t.table.columns.indexOf(s)]})()}})}get length(){return Math.max(0,this.range.stop-this.range.start)}};function Tj(n){let e=this.sql(n,"this"),t=n.args.desc?"true":"false",s=n.args.nullsFirst?"true":"false";return`ORDERED(${e}, { desc: ${t}, undefinedFirst: ${s} })`}function NH(n){try{let e=Object.values(n.args);if(e.length===1){let t=e[0];return Array.isArray(t)?this.func(n._constructor.key,t):this.func(n._constructor.key,[t])}if(n instanceof d&&n._constructor.isVarLenArgs){let t=[];for(let s of e)Array.isArray(s)?t.push(...s):s!==void 0&&t.push(s);return this.func(n._constructor.key,t)}return this.func(n._constructor.key,e.filter(t=>t!==void 0))}catch(e){throw new Error(`Could not rename ${n}: ${e}`)}}function Sj(n){let e=this.sql(n,"this"),t=this.sql(n,"default")||"null",s=_nullishCoalesce(n.args.ifs, () => ([]));for(let r of[...s].reverse()){let i=this.sql(r,"true"),a=this.sql(r,"this");e&&(a=`${e} === (${a})`),t=`(${a} ? ${i} : (${t}))`}return t}function mj(n){return`(${this.expressions(n,{flat:!0})}) => ${this.sql(n,"this")}`}function Rj(n){let e=this.sql(n,"expression");n.args.safe&&(e+=" || undefined");let t=`DIV(${this.sql(n,"this")}, ${e})`;return n.args.typed&&(t=`Math.trunc(${t})`),t}var Y_=class extends L{static get TRANSFORMS(){let e=super.TRANSFORMS,t=new Map([...e.entries(),[lt,function(s){return`ADD(${this.sql(s,"this")}, ${this.sql(s,"expression")})`}],[st,function(s){return this.func(s.name,_nullishCoalesce(s.args.expressions, () => ([])))}],[Se,function(s){return this.sql(s.args.this)}],[Oe,function(s){return this.binary(s,"&&")}],[Ne,function(s){return`[${this.expressions(s,{flat:!0})}]`}],[Fs,NH],[Et,function(s){return s.args.this?"true":"false"}],[Ht,Sj],[Z,function(s){let r=s.args.to,i=typeof r=="string"?r.toLowerCase():this.sql(r).toLowerCase();return`CAST(${this.sql(s.args.this)}, '${i}')`}],[k,function(s){let r=this.sql(s,"table")||void 0,i=this.sql(s.args.this);return`scope[${r}][${i}]`}],[Vt,function(s){return this.func(s.args.safe?"SAFECONCAT":"CONCAT",_nullishCoalesce(s.args.expressions, () => ([])))}],[ct,function(s){return`new Set([${this.sql(s,"this")}])`}],[me,function(s){let r=this.sql(s.args.this),i=this.sql(s.args.expression);return`${r}[${i}]`}],[jt,Rj],[Ee,function(s){return`EQ(${this.sql(s,"this")}, ${this.sql(s,"expression")})`}],[vt,function(s){return`NEQ(${this.sql(s,"this")}, ${this.sql(s,"expression")})`}],[Hr,function(s){return`MOD(${this.sql(s,"this")}, ${this.sql(s,"expression")})`}],[Ts,function(s){return`MUL(${this.sql(s,"this")}, ${this.sql(s,"expression")})`}],[dt,function(s){return`SUB(${this.sql(s,"this")}, ${this.sql(s,"expression")})`}],[Zn,function(s){return`EXTRACT('${s.name.toLowerCase()}', ${this.sql(s,"expression")})`}],[it,function(s){return`[${this.expressions(s,{flat:!0})}].includes(${this.sql(s,"this")})`}],[ze,function(s){return`INTERVAL(${this.sql(s.args.this)}, '${this.sql(s.args.unit)}')`}],[Ut,function(s){return s.args.this instanceof w?this.binary(s,"==="):this.binary(s,"===")}],[Zt,function(s){return this.func(Zt.key,[s.args.this,s.args.expression,..._nullishCoalesce(s.args.expressions, () => ([]))])}],[Ya,function(s){return`[${(_nullishCoalesce(s.args.expressions, () => ([]))).slice(1).map(i=>this.sql(i)).join(",")}]`}],[Gt,function(s){return`'${this.sql(s.args.this)}'`}],[Ds,function(s){return`'${s.args.this}'`}],[vs,mj],[rt,function(s){return`!(${this.sql(s.args.this)})`}],[Qt,()=>"undefined"],[pt,function(s){return this.binary(s,"||")}],[es,Tj],[ye,()=>"1"]]);for(let s of fg)t.has(s)||t.set(s,NH);return t}},VM=class extends W{};VM.Generator=Y_;var WM=class{constructor(e,t){this.generator=new VM().generator({identify:!0,comments:!1}),this.env={...sO,...e||{}},this.tables=t||{}}execute(e){let t=new Set,s=new Set(e.leaves),r=new Map;for(;0<s.size;){let a=Array.from(s).pop();if(!a)break;s.delete(a);try{let o=new Map;for(let p of a.dependencies){let u=r.get(p);if(u)for(let[E,g]of u.tables)o.set(E,g)}let c=this.context(o);if(a instanceof LT)r.set(a,this.scan(a,c));else if(a instanceof MT)r.set(a,this.aggregate(a,c));else if(a instanceof fw)r.set(a,this.join(a,c));else if(a instanceof xw)r.set(a,this.sort(a,c));else if(a instanceof Tw)r.set(a,this.setOperation(a,c));else throw new Error(`NotImplementedError: ${a.constructor.name}`);t.add(a);for(let p of a.dependents)Array.from(p.dependencies).every(u=>r.has(u))&&s.add(p);for(let p of a.dependencies)Array.from(p.dependents).every(u=>t.has(u))&&r.delete(p)}catch(o){throw new DT(`Step '${a.name}' failed: ${o.message}`)}}let i=e.root;return i?_nullishCoalesce(_optionalChain([r, 'access', _1485 => _1485.get, 'call', _1486 => _1486(i), 'optionalAccess', _1487 => _1487.tables, 'access', _1488 => _1488.get, 'call', _1489 => _1489(i.name)]), () => (new gt([]))):new gt([])}generate(e){if(e)return this.generator.generate(e)}generateTuple(e){return!e||e.length===0?[]:e.map(t=>_nullishCoalesce(this.generate(t), () => ("")))}context(e){let t=e instanceof Map?e:new Map(Object.entries(e));return new HM(t,this.env)}table(e){let t=e.map(s=>s instanceof h?s.aliasOrName:s);return new gt(t)}scan(e,t){let s;e.source&&e.source instanceof h?s=e.source.name||e.source.alias:typeof e.source=="string"&&(s=e.source);let r;if(s===void 0){let i=this.static();t=i[0],r=i[1]}else if(t.has(s)){if(!_optionalChain([e, 'access', _1490 => _1490.projections, 'optionalAccess', _1491 => _1491.length])&&!e.condition){let i=t.tables.get(s);return i?this.context({[e.name]:i}):t}r=t.tableIter(s)}else{let i=this.scanTable(e);t=i[0],r=i[1]}return this.context({[e.name]:this.projectAndFilter(t,e,r)})}projectAndFilter(e,t,s){let r=this.table(_optionalChain([t, 'access', _1492 => _1492.projections, 'optionalAccess', _1493 => _1493.length])?t.projections:e.columns),i=this.generate(t.condition),a=this.generateTuple(t.projections||[]);if(0<a.length&&a[0].includes(`scope["${t.name}"]`)&&!e.has(t.name)){let o={};for(let[c,p]of e.tables)p&&(o[c]=p);o[t.name]=new gt(r.columns),e=this.context(new Map(Object.entries(o)))}for(let o of s){let c=Array.isArray(o)?o[0]:o;if(t.limit<=r.length)break;i&&!e.eval(i)||(0<a.length?r.append(e.evalTuple(a)):r.append(c.row))}return r}static(){return[this.context(new Map),[new rO([])]]}scanTable(e){let t=this.tables,s=e.source,r;if(s.args.catalog||s.args.db){if(r=t,s.args.catalog){let c=typeof s.args.catalog=="string"?s.args.catalog:s.args.catalog.name;r=r[c]}if(s.args.db&&r!==void 0){let c=typeof s.args.db=="string"?s.args.db:s.args.db.name;r=r[c]}if(r!==void 0){let c=s.name;r=r[c]}}else{let c=s.name;if(r=t[c],!r||typeof r=="object"&&!(r instanceof gt))for(let p of Object.values(t)){if(p&&typeof p=="object"&&!(p instanceof gt)){let u=p[c];if(u instanceof gt){r=u;break}for(let E of Object.values(p))if(E&&typeof E=="object"&&!(E instanceof gt)){let g=E[c];if(g instanceof gt){r=g;break}}}if(r instanceof gt)break}}let i=r instanceof gt?r:new gt([]),a=new Map;return a.set(s.aliasOrName,i),[this.context(a),i[Symbol.iterator]()]}join(e,t){let s=e.sourceName;if(!s)return t;let r=_nullishCoalesce(t.tables.get(s), () => (new gt([]))),i=this.context(new Map([[s,r]])),a=new Map;a.set(s,{start:0,stop:r.columns.length});for(let[c,p]of Object.entries(e.joins||{})){let u=_nullishCoalesce(t.tables.get(c), () => (new gt([]))),E=Math.max(...Array.from(a.values()).map(I=>I.stop));a.set(c,{start:E,stop:u.columns.length+E});let g=this.context(new Map([[c,u]])),A,x=p;x.sourceKey.length?A=this.hashJoin(x,i,g):A=this.nestedLoopJoin(x,i,g);let m=new Map;for(let[I,y]of a.entries())m.set(I,new gt(A.columns,A.rows,y));i=this.context(m);let N=this.generate(x.condition),R=String(x.side).toLowerCase(),S=R==="left"||R==="right";N&&!S&&i.filter(N)}if(!e.condition&&!_optionalChain([e, 'access', _1494 => _1494.projections, 'optionalAccess', _1495 => _1495.length]))return i;let o=this.projectAndFilter(i,e,(function*(c){for(let[p]of c)yield p})(i));if(_optionalChain([e, 'access', _1496 => _1496.projections, 'optionalAccess', _1497 => _1497.length]))return this.context(new Map([[_nullishCoalesce(e.name, () => ("")),o]]));{let c=new Map;for(let[p,u]of i.tables.entries())c.set(p,new gt(u.columns,o.rows,u.columnRange));return this.context(c)}}nestedLoopJoin(e,t,s){let r=new gt([...t.columns,...s.columns]);for(let[i]of t)for(let[a]of s)r.append([...i.row,...a.row]);return r}hashJoin(e,t,s){let r=this.generateTuple(e.sourceKey),i=this.generateTuple(e.joinKey),a=String(e.side).toLowerCase(),o=a==="left",c=a==="right",p=new Map,u=[];for(let[x,m]of t){let N=JSON.stringify(m.evalTuple(r));p.has(N)||p.set(N,[[],[]]),_optionalChain([p, 'access', _1498 => _1498.get, 'call', _1499 => _1499(N), 'optionalAccess', _1500 => _1500[0], 'access', _1501 => _1501.push, 'call', _1502 => _1502([...x.row])]),u.push([N,x.row])}for(let[x,m]of s){let N=JSON.stringify(m.evalTuple(i));p.has(N)||p.set(N,[[],[]]),_optionalChain([p, 'access', _1503 => _1503.get, 'call', _1504 => _1504(N), 'optionalAccess', _1505 => _1505[1], 'access', _1506 => _1506.push, 'call', _1507 => _1507([...x.row])])}let E=new gt([...t.columns,...s.columns]),g=[new Array(s.columns.length).fill(void 0)],A=[new Array(t.columns.length).fill(void 0)];if(o)for(let[,[x,m]]of p.entries()){if(x.length===0)continue;let N=0<m.length?m:g;for(let R of x)for(let S of N)E.append([...R,...S])}else if(c)for(let[,[x,m]]of p.entries()){let N=0<x.length?x:A;for(let R of N)for(let S of m)E.append([...R,...S])}else for(let[,[x,m]]of p.entries())for(let N of x)for(let R of m)E.append([...N,...R]);return E}aggregate(e,t){let s=this.generateTuple(Object.values(e.group||{})),r=this.generateTuple(e.aggregations||[]),i=this.generateTuple(e.operands||[]);if(0<i.length){let x=new gt(this.table(e.operands).columns);for(let[,S]of t)x.append(S.evalTuple(i));for(let S=0;S<t.table.rows.length;S++)t.table.rows[S]=[...t.table.rows[S],...x.rows[S]];let m=t.columns.length;t.addColumns(...x.columns);let N=new gt(t.columns,t.table.rows,{start:m,stop:m+x.columns.length}),R=new Map([...t.tables.entries()].filter(([S,I])=>typeof S=="string"&&I instanceof gt));R.set(void 0,N),t=this.context(R)}t.sort(s);let a,o=0,c=1,p=t.table.length,u=Object.keys(e.group||{}),E=this.table([...u,...e.aggregations||[]]),g=()=>{let x=a?JSON.parse(a):[];E.append([...x,...t.evalTuple(r)])};if(0<p)for(let x=0;x<p;x++){t.setIndex(x);let m=JSON.stringify(t.evalTuple(s));if(a=a===void 0?m:a,c+=1,m!==a&&(t.setRange(o,c-2),g(),a=m,o=c-2),e.limit<=E.rows.length)break;x===p-1&&(t.setRange(o,c-1),g())}else 0<e.limit&&s.length===0&&(t.setRange(0,0),E.append(t.evalTuple(r)));let A=new Map;A.set(e.name,E);for(let[x]of t.tables.entries())A.set(x,E);return t=this.context(A),_optionalChain([e, 'access', _1508 => _1508.projections, 'optionalAccess', _1509 => _1509.length])||e.condition?this.scan(e,t):t}sort(e,t){let s=this.generateTuple(e.projections||[]),r=(e.projections||[]).map(A=>A.aliasOrName),i=[...t.columns,...r],a=this.table(i),o=this.generateTuple(e.key||[]);for(let[A,x]of t){let m=x.evalTuple(s);a.append([...A.row,...m])}let c=new Map;c.set(void 0,a);for(let A of t.tables.keys())c.set(A,a);let p=this.context(c);p.sort(o),Number.isFinite(e.limit)&&(p.table.rows=p.table.rows.slice(0,e.limit));let u=t.columns.length,E=i.length,g=new gt(r,p.table.rows.map(A=>A.slice(u,E)));return this.context(new Map([[_nullishCoalesce(e.name, () => ("")),g]]))}setOperation(e,t){let s=_nullishCoalesce(t.tables.get(_nullishCoalesce(e.left, () => (""))), () => (new gt([]))),r=_nullishCoalesce(t.tables.get(_nullishCoalesce(e.right, () => (""))), () => (new gt([]))),i=this.table(s.columns);if(e.op&&(e.op===yn||e.op.prototype instanceof yn)){let a=new Set(s.rows.map(c=>JSON.stringify(c))),o=new Set(r.rows.map(c=>JSON.stringify(c)));i.rows=[...a].filter(c=>o.has(c)).map(c=>JSON.parse(c))}else if(e.op&&(e.op===Yr||e.op.prototype instanceof Yr)){let a=new Set(r.rows.map(o=>JSON.stringify(o)));i.rows=s.rows.filter(o=>!a.has(JSON.stringify(o)))}else if(e.op&&(e.op===$r||e.op.prototype instanceof $r)&&e.distinct){let a=new Set([...s.rows,...r.rows].map(o=>JSON.stringify(o)));i.rows=[...a].map(o=>JSON.parse(o))}else i.rows=[...s.rows,...r.rows];return Number.isFinite(e.limit)&&(i.rows=i.rows.slice(0,e.limit)),this.context(new Map([[e.name,i]]))}};function Oj(n,e,t,s){let r=RH(s,t),i;if(e)i=e;else{i={};let p=r.mapping,u=Ii(p),E=Mc(p,u);for(let g of E){let A=g.map(m=>[m,m]),x=pg(p,A,{raiseOnMissing:!1});if(x)for(let m of x.columns){let N=x.get(0)[m],R=_nullishCoalesce(_optionalChain([os, 'call', _1510 => _1510(ts(N),{dialect:t}), 'optionalAccess', _1511 => _1511.type, 'optionalAccess', _1512 => _1512.toString, 'call', _1513 => _1513()]), () => (typeof N));hO(i,[...g,m],R)}}}let a=Qs(i,{dialect:t});if(0<r.supportedTableArgs.length&&r.supportedTableArgs.join(",")!==a.supportedTableArgs.join(","))throw new DT("Tables must support the same table args as schema");let o=F_(n,{schema:a,dialect:t,isolateTables:!0}),c=new YM(o);return new WM(void 0,r.mapping).execute(c)}var F2=X_.version;var Nj=!1;function B2(n){Nj= exports.pretty =n}function G2(n,e,t){return W.getOrRaise(_nullishCoalesce(e, () => (t))).tokenize(n)}function $2(n,e={}){let{read:t,dialect:s,write:r,identity:i=!0,errorLevel:a,...o}=e,c=i?_nullishCoalesce(_nullishCoalesce(r, () => (t)), () => (s)):r,p=W.getOrRaise(c);return Iv(n,{read:_nullishCoalesce(t, () => (s)),errorLevel:a,...o}).map(u=>u?p.generate(u,{copy:!1,...o}):"")}exports.Dialect = W; exports.ErrorLevel = aO; exports.Expression = h; exports.Generator = L; exports.MappingSchema = yl; exports.ParseError = ns; exports.Parser = he; exports.Schema = qT; exports.SqlglotError = Bn; exports.TokenError = cg; exports.TokenType = gi; exports.Tokenizer = Dt; exports.UnsupportedError = uo; exports.alias = oe; exports.and = nt; exports.case_ = dM; exports.cast = Le; exports.column = Ie; exports.condition = pw; exports.delete_ = vv; exports.diff = oW; exports.dump = Uw; exports.except = qD; exports.execute = Oj; exports.findTables = Bv; exports.from = Uv; exports.func = DR; exports.generate = YV; exports.insert = qv; exports.intersect = UD; exports.lineage = TW; exports.load = qw; exports.maybeParse = ne; exports.merge = Fv; exports.not = Hn; exports.optimize = F_; exports.or = bs; exports.parse = Iv; exports.parseOne = _w; exports.pretty = Nj; exports.select = ft; exports.setPretty = B2; exports.subquery = gM; exports.table = LR; exports.toColumn = Bw; exports.toIdentifier = K; exports.toTable = RT; exports.tokenize = G2; exports.transpile = $2; exports.union = NT; exports.version = F2;
|
|
46
|
+
//# sourceMappingURL=index.cjs.map
|