@malloydata/render 0.0.248-dev250325232143 → 0.0.248-dev250325235002
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/dist/module/index.mjs +26 -11
- package/dist/module/index.umd.js +98 -98
- package/dist/register/register.mjs +604 -589
- package/dist/register/register.umd.js +7 -7
- package/dist/webcomponent/malloy-render.mjs +604 -589
- package/dist/webcomponent/malloy-render.umd.js +7 -7
- package/package.json +5 -5
|
@@ -1209,7 +1209,7 @@ ${e.map(i=>` ${i}`).join(`,
|
|
|
1209
1209
|
transition: all 0s;
|
|
1210
1210
|
animation: modal-slide-in 2s forwards;
|
|
1211
1211
|
}
|
|
1212
|
-
`;var H$={},p2={},lt={},et={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.sourceBase=t.isSegmentSQL=t.isIndexSegment=t.isRawSegment=t.isSamplingEnable=t.isSamplingPercent=t.isSamplingRows=t.isQuerySegment=t.isProjectSegment=t.isPartialSegment=t.isReduceSegment=t.structHasErrors=t.segmentHasErrors=t.refIsStructDef=t.ValueType=t.isExtractUnit=t.isTimestampUnit=t.isDateUnit=t.isJoinedSource=t.isJoined=t.isJoinable=t.isMatrixOperation=t.isScalarArray=t.isRepeatedRecord=t.isRepeatedRecordFunctionParam=t.mkArrayDef=t.mkFieldDef=t.fieldIsIntrinsic=t.isCastType=t.canOrderBy=t.isAtomicFieldType=t.isTemporalType=t.hasExpression=t.maxOfExpressionTypes=t.maxExpressionType=t.isExpressionTypeLEQ=t.expressionIsAnalytic=t.expressionIsCalculation=t.expressionInvolvesAggregate=t.expressionIsUngroupedAggregate=t.expressionIsAggregate=t.expressionIsScalar=t.paramHasValue=t.isFilterExprType=t.isRawCast=t.mkTemporal=t.isAsymmetricExpr=t.exprIsLeaf=t.exprHasE=t.exprHasKids=void 0,t.TD=t.isValueDate=t.isValueTimestamp=t.isValueBoolean=t.isValueNumber=t.isValueString=t.isAtomic=t.isTurtle=t.getIdentifier=t.isLeafAtomic=t.mergeEvalSpaces=t.isLiteral=t.isBaseTable=t.isSourceDef=void 0;function e(P){return"kids"in P}t.exprHasKids=e;function r(P){return"e"in P}t.exprHasE=r;function i(P){return!(e(P)||r(P))}t.exprIsLeaf=i;function s(P){return P.node==="aggregate"&&["sum","avg","count","distinct"].includes(P.function)}t.isAsymmetricExpr=s;function o(P){return P.node!=="arrayLiteral"&&P.node!=="recordLiteral"}function u(P,K){if(!("typeDef"in P)){const ae=typeof K=="string"?{type:K}:K;if(o(P))return{...P,typeDef:{...ae}}}return P}t.mkTemporal=u;function a(P){return"dstSQLType"in P}t.isRawCast=a;function l(P){return["string","number","boolean","date","timestamp"].includes(P)}t.isFilterExprType=l;function c(P){return P.value!==null}t.paramHasValue=c;function f(P){return P===void 0||P==="scalar"}t.expressionIsScalar=f;function x(P){return P==="aggregate"||P==="ungrouped_aggregate"}t.expressionIsAggregate=x;function h(P){return P==="ungrouped_aggregate"}t.expressionIsUngroupedAggregate=h;function p(P){return P==="aggregate"||P==="ungrouped_aggregate"||P==="aggregate_analytic"}t.expressionInvolvesAggregate=p;function m(P){return P==="aggregate"||P==="scalar_analytic"||P==="aggregate_analytic"||P==="ungrouped_aggregate"}t.expressionIsCalculation=m;function y(P){return P==="aggregate_analytic"||P==="scalar_analytic"}t.expressionIsAnalytic=y;function g(P){return{scalar:0,aggregate:1,ungrouped_aggregate:2,scalar_analytic:2,aggregate_analytic:3}[P]}function E(P,K){return P===K||g(P)<g(K)}t.isExpressionTypeLEQ=E;function A(P,K){let ae="scalar";return(P==="aggregate"||K==="aggregate")&&(ae="aggregate"),(P==="ungrouped_aggregate"||K==="ungrouped_aggregate")&&(ae="ungrouped_aggregate"),(P==="scalar_analytic"||K==="scalar_analytic")&&(ae="scalar_analytic"),(P==="aggregate_analytic"||K==="aggregate_analytic")&&(ae="aggregate_analytic"),(P==="scalar_analytic"&&K==="aggregate"||P==="aggregate"&&K==="scalar_analytic")&&(ae="aggregate_analytic"),ae}t.maxExpressionType=A;function _(P){return P.reduce(A,"scalar")}t.maxOfExpressionTypes=_;function v(P){return"e"in P}t.hasExpression=v;function C(P){return P==="date"||P==="timestamp"}t.isTemporalType=C;function S(P){return["string","number","date","timestamp","boolean","json","sql native","record","array","error"].includes(P)}t.isAtomicFieldType=S;function b(P){return["string","number","date","boolean","date","timestamp"].includes(P)}t.canOrderBy=b;function R(P){return["string","number","date","timestamp","boolean","json"].includes(P)}t.isCastType=R;function O(P){return S(P.type)&&!v(P)}t.fieldIsIntrinsic=O;function B(P,K){if(V(P))return D(P.elementTypeDef,K);if(U(P)){const{type:ae,fields:je,elementTypeDef:te}=P;return{type:ae,fields:je,elementTypeDef:te,join:"many",name:K}}if(P.type==="record"){const{type:ae,fields:je}=P;return{type:ae,fields:je,join:"one",name:K}}return{...P,name:K}}t.mkFieldDef=B;function D(P,K){if(P.type==="record")return{type:"array",join:"many",name:K,elementTypeDef:{type:"record_element"},fields:P.fields};const ae=B(P,"value");return{type:"array",join:"many",name:K,elementTypeDef:P,fields:[ae,{...ae,name:"each",e:{node:"field",path:["value"]}}]}}t.mkArrayDef=D;function $(P){return P.type==="array"&&P.elementTypeDef.type==="record_element"}t.isRepeatedRecordFunctionParam=$;function U(P){return P.type==="array"&&P.elementTypeDef.type==="record_element"}t.isRepeatedRecord=U;function V(P){return P.type==="array"&&P.elementTypeDef.type!=="record_element"}t.isScalarArray=V;function Q(P){return["left","right","full","inner"].includes(P)}t.isMatrixOperation=Q;function Z(P){return["composite","table","sql_select","query_source","array","record"].includes(P.type)}t.isJoinable=Z;function de(P){return"join"in P}t.isJoined=de;function he(P){return pe(P)&&de(P)}t.isJoinedSource=he;function ie(P){return["day","week","month","quarter","year"].includes(P)}t.isDateUnit=ie;function ee(P){return ie(P)||["hour","minute","second"].includes(P)}t.isTimestampUnit=ee;function X(P){return ee(P)||P==="day_of_week"||P==="day_of_year"}t.isExtractUnit=X;var ce;(function(P){P.Date="date",P.Timestamp="timestamp",P.Number="number",P.String="string"})(ce||(t.ValueType=ce={}));function N(P){return typeof P!="string"}t.refIsStructDef=N;function w(P){return!!((P.type==="reduce"||P.type==="project"||P.type==="partial")&&(P.extendSource&&P.extendSource.some(K=>K.type==="error")||P.queryFields.some(K=>K.type==="error")))}t.segmentHasErrors=w;function F(P){return P.fields.some(K=>K.type==="error")}t.structHasErrors=F;function j(P){return P.type==="reduce"}t.isReduceSegment=j;function Y(P){return P.type==="partial"}t.isPartialSegment=Y;function z(P){return P.type==="project"}t.isProjectSegment=z;function L(P){return z(P)||j(P)}t.isQuerySegment=L;function M(P){return P.rows!==void 0}t.isSamplingRows=M;function q(P){return P.percent!==void 0}t.isSamplingPercent=q;function G(P){return P.enable!==void 0}t.isSamplingEnable=G;function k(P){return P.type==="raw"}t.isRawSegment=k;function W(P){return P.type==="index"}t.isIndexSegment=W;function H(P){return"sql"in P}t.isSegmentSQL=H;function re(P){return{...P}}t.sourceBase=re;function pe(P){return P.type==="table"||P.type==="sql_select"||P.type==="query_source"||P.type==="query_result"||P.type==="finalize"||P.type==="nest_source"||P.type==="composite"}t.isSourceDef=pe;function oe(P){return he(P)?!1:!!pe(P)}t.isBaseTable=oe;function J(P){return P==="literal"}t.isLiteral=J;function fe(...P){return P.length<=1&&P.every(K=>K==="literal")?"literal":P.every(K=>K==="constant"||K==="literal")?"constant":P.every(K=>K==="output"||K==="constant"||K==="literal")?"output":"input"}t.mergeEvalSpaces=fe;function Se(P){return P.type==="string"||C(P.type)||P.type==="number"||P.type==="boolean"||P.type==="json"||P.type==="sql native"||P.type==="error"}t.isLeafAtomic=Se;function Be(P){return P.as!==void 0?P.as:P.name}t.getIdentifier=Be;function xt(P){return P.type==="turtle"}t.isTurtle=xt;function se(P){return S(P.type)}t.isAtomic=se;function xe(P,K){return K.type==="string"}t.isValueString=xe;function we(P,K){return K.type==="number"}t.isValueNumber=we;function qe(P,K){return K.type==="boolean"}t.isValueBoolean=qe;function De(P,K){return K.type==="timestamp"}t.isValueTimestamp=De;function Oe(P,K){return K.type==="date"}t.isValueDate=Oe,t.TD={isAtomic(P){return P!==void 0&&S(P.type)},isLeafAtomic(P){return P!==void 0&&Se({type:P.type})},isString:P=>(P==null?void 0:P.type)==="string",isNumber:P=>(P==null?void 0:P.type)==="number",isBoolean:P=>(P==null?void 0:P.type)==="boolean",isJSON:P=>(P==null?void 0:P.type)==="json",isSQL:P=>(P==null?void 0:P.type)==="sql native",isDate:P=>(P==null?void 0:P.type)==="date",isTimestamp:P=>(P==null?void 0:P.type)==="timestamp",isTemporal(P){var K;const ae=(K=P==null?void 0:P.type)!==null&&K!==void 0?K:"";return C(ae)},isError:P=>(P==null?void 0:P.type)==="error",eq(P,K){if(P===void 0||K===void 0)return!1;function ae(je,te){const me={};for(const Ie of je.fields||[])if(Ie.name)me[Ie.name]=Ie;else return!1;for(const Ie of te.fields||[])if(!t.TD.eq(me[Ie.name],Ie))return!1;return!0}return P.type==="array"&&K.type==="array"?P.elementTypeDef.type!==K.elementTypeDef.type?!1:P.elementTypeDef.type!=="record_element"&&K.elementTypeDef.type!=="record_element"?t.TD.eq(P.elementTypeDef,K.elementTypeDef):t.TD.isAtomic(P)&&t.TD.isAtomic(K)&&ae(P,K):P.type==="record"&&K.type==="record"?t.TD.isAtomic(P)&&t.TD.isAtomic(K)&&ae(P,K):P.type==="sql native"&&K.type==="sql native"?P.rawType!==void 0&&P.rawType===K.rawType:P.type===K.type}}})(et),Object.defineProperty(lt,"__esModule",{value:!0}),lt.def=lt.expandOverrideMapFromBase=lt.expandBlueprintMap=lt.overload=lt.minAnalytic=lt.minAggregate=lt.minScalar=lt.maxAnalytic=lt.maxUngroupedAggregate=lt.anyExprType=lt.maxAggregate=lt.maxScalar=lt.makeParam=lt.param=lt.variadicParam=lt.literal=lt.output=lt.constant=lt.sql=lt.spread=lt.arg=void 0;const Sae=et;function bae(t){return{node:"function_parameter",name:t}}lt.arg=bae;function dXe(t,e=void 0,r=void 0){return{node:"spread",e:t,prefix:e,suffix:r}}lt.spread=dXe;function hXe(t,...e){const r={node:"genericSQLExpr",kids:{args:[]},src:[]},i=[...e];let s="";for(const o of t){s+=o;const u=i.shift();u!==void 0&&(typeof u=="string"?s+=u:(r.src.push(s),r.kids.args.push(u),s=""))}return s.length>0&&r.src.push(s),r}lt.sql=hXe;function Q$(t){return{...t,evalSpace:"constant"}}lt.constant=Q$;function pXe(t){return{...t,evalSpace:"output"}}lt.output=pXe;function z$(t){return{...t,evalSpace:"literal"}}lt.literal=z$;function mXe(t,...e){return{name:t,isVariadic:!0,allowedTypes:e}}lt.variadicParam=mXe;function Tae(t,...e){return{name:t,isVariadic:!1,allowedTypes:e}}lt.param=Tae;function gXe(t,...e){return{param:Tae(t,...e),arg:bae(t)}}lt.makeParam=gXe;function f4(t){return{...t,expressionType:"scalar",evalSpace:"input"}}lt.maxScalar=f4;function Rae(t){return{...t,expressionType:"aggregate",evalSpace:"input"}}lt.maxAggregate=Rae;function h0(t){return{...t,expressionType:void 0,evalSpace:"input"}}lt.anyExprType=h0;function yXe(t){return{...t,expressionType:"ungrouped_aggregate",evalSpace:"input"}}lt.maxUngroupedAggregate=yXe;function Dae(t){return{...t,expressionType:"aggregate_analytic",evalSpace:"input"}}lt.maxAnalytic=Dae;function m2(t){return{...t,expressionType:"scalar",evalSpace:"input"}}lt.minScalar=m2;function Oae(t){return{...t,expressionType:"aggregate",evalSpace:"input"}}lt.minAggregate=Oae;function wae(t){return{...t,expressionType:"scalar_analytic",evalSpace:"input"}}lt.minAnalytic=wae;function EXe(t,e,r,i){return{returnType:t,params:e,e:r,needsWindowOrderBy:i==null?void 0:i.needsWindowOrderBy,between:i==null?void 0:i.between,isSymmetric:i==null?void 0:i.isSymmetric,supportsOrderBy:i==null?void 0:i.supportsOrderBy,defaultOrderByArgIndex:i==null?void 0:i.defaultOrderByArgIndex,supportsLimit:i==null?void 0:i.supportsLimit}}lt.overload=EXe;function zn(t,e=!0,r=!0){if(!e&&t==="any")throw new Error("Return type cannot include any");if(typeof t=="string")return{type:t};if("array"in t){const i=e?zn(t.array,!0):zn(t.array,!1);return i.type==="record"?{type:"array",elementTypeDef:{type:"record_element"},fields:i.fields}:{type:"array",elementTypeDef:i}}else if("record"in t){const i=[];for(const[s,o]of Object.entries(t.record)){const u=e?zn(o,!0):zn(o,!1);Sae.TD.isAtomic(u)&&i.push((0,Sae.mkFieldDef)(u,s))}return{type:"record",fields:i}}else if("generic"in t){if(!r)throw new Error("Cannot use generic");return{type:"generic",generic:t.generic}}else if("sql_native"in t)return{type:"sql native",rawType:t.sql_native};throw new Error("Cannot figure out type")}function AXe(t){if(t==="any")throw new Error("Cannot return any type");return typeof t=="string"?m2({type:t}):"array"in t||"record"in t?h0(zn(t,!1)):"generic"in t?m2(zn(t,!1)):"literal"in t?z$(m2(zn(t.literal,!1))):"constant"in t?Q$(m2(zn(t.constant,!1))):"dimension"in t?m2(zn(t.dimension,!1)):"measure"in t?Oae(zn(t.measure,!1)):"sql_native"in t?h0({type:"sql native",rawType:t.sql_native}):wae(zn(t.calculation,!1))}function Fae(t){return typeof t=="string"||"array"in t||"record"in t||"generic"in t||"literal"in t||"constant"in t||"dimension"in t||"measure"in t||"calculation"in t||"sql_native"in t}function _Xe(t){return Fae(t)?[t]:Array.isArray(t)?t:Fae(t.variadic)?[t.variadic]:t.variadic}function vXe(t){return typeof t=="string"?h0({type:t}):"generic"in t?h0(zn(t)):"literal"in t?z$(f4(zn(t.literal))):"constant"in t?Q$(f4(zn(t.constant))):"dimension"in t?f4(zn(t.dimension)):"measure"in t?Rae(zn(t.measure)):"array"in t||"record"in t?h0(zn(t,!1)):"sql_native"in t?h0({type:"sql native",rawType:t.sql_native}):Dae(zn(t.calculation))}function CXe(t){return t.map(e=>vXe(e))}function Nae(t){return typeof t!="string"&&"variadic"in t}function SXe(t,e){return{name:t,allowedTypes:CXe(_Xe(e)),isVariadic:Nae(e)}}function bXe(t){return Object.entries(t).map(r=>SXe(r[0],r[1]))}function TXe(t){const e=[],r=[];let i=t;for(;i.length>0;){const o=i.indexOf("${");if(o===-1){e.push(i);break}const u=i.slice(0,o);i=i.slice(o);const a=i.indexOf("}");if(a===-1){e.push(u+i);break}const l=i.slice(2,a);i=i.slice(a+1);const c=l.startsWith("..."),f=l.endsWith(":"),x=c?l.slice(3):f?l.slice(0,-1):l,h={node:"function_parameter",name:x};e.push(u),c?r.push({node:"spread",e:h,prefix:"",suffix:""}):f&&x==="order_by"?r.push({node:"aggregate_order_by"}):f&&x==="limit"?r.push({node:"aggregate_limit"}):r.push(h)}return{node:"genericSQLExpr",kids:{args:r},src:e}}function RXe(t,e){return Nae(e)?{node:"spread",e:{node:"function_parameter",name:t},prefix:"",suffix:""}:{node:"function_parameter",name:t}}function DXe(t,e){const r=Object.entries(e.takes),i=r.length>0?r.length-1:0;return{node:"genericSQLExpr",kids:{args:r.map(s=>RXe(s[0],s[1]))},src:[`${t}(`,...Array(i).fill(","),")"]}}function OXe(t){return"sql"in t.impl?TXe(t.impl.sql):"expr"in t.impl?t.impl.expr:DXe(t.impl.function,t)}function wXe(t){return{e:OXe(t),between:t.impl.between,needsWindowOrderBy:t.impl.needsWindowOrderBy,defaultOrderByArgIndex:t.impl.defaultOrderByArgIndex}}function FXe(t){if(t!==void 0)return Object.entries(t).map(([e,r])=>({name:e,acceptibleTypes:r.map(i=>zn(i,!0,!1))}))}function W$(t){return{returnType:AXe(t.returns),params:bXe(t.takes),isSymmetric:t.isSymmetric,supportsOrderBy:t.supportsOrderBy,supportsLimit:t.supportsLimit,genericTypes:FXe(t.generic),...wXe(t)}}function G$(t){return"takes"in t&&"returns"in t&&"impl"in t}function NXe(t){return"function"in t||"sql"in t||"expr"in t}function LXe(t){return G$(t)?[W$(t)]:Object.values(t).flatMap(e=>W$(e))}function IXe(t){const e={};for(const r in t)e[r]=LXe(t[r]);return e}lt.expandBlueprintMap=IXe;function Lae(t,e){return[W$({...t,impl:e})]}function $Xe(t,e,r){if(NXe(r)){if(!G$(e))throw new Error(`Malformed function override: ${t}. Attempt to override multiple overloads with a single overload (missing: ${Object.keys(e)})`);return Lae(e,r)}else{if(G$(e))throw new Error(`Malformed function override: ${t}. Attempt to override a single overload with multiple overloads (extraneous: ${Object.keys(r)})`);return Object.entries(r).flatMap(([i,s])=>{const o=e[i];if(o===void 0)throw new Error(`Malformed function override: ${t}. No overload named ${i}`);return Lae(o,s)})}}function BXe(t,e){const r={};for(const i in e){if(!(i in t))throw new Error(`Malformed function override: ${i}. No such function in Malloy standard`);r[i]=$Xe(i,t[i],e[i])}return r}lt.expandOverrideMapFromBase=BXe;function*V$(t){if(typeof t!="string"){if("generic"in t)yield t;else if("record"in t)for(const e of Object.values(t.record))yield*V$(e);else for(const e of["array","literal","measure","dimension","measure","constant","cacluation"])if(e in t){yield*V$(t[e]);return}}}function kXe(t,e,r,i={}){let s=!1;const o={};for(const a of Object.values(e))for(const l of V$(a))o[l.generic]=["any"],s=!0;s&&i.generic===void 0&&(i.generic=o);const u={takes:e,returns:r,impl:{function:t.toUpperCase()},...i};return{[t]:u}}lt.def=kXe;var qc={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.Dialect=t.qtz=t.inDays=t.dayIndex=t.isDialectFieldStruct=void 0;const e=et;function r(a){return a.type==="struct"}t.isDialectFieldStruct=r;const i=["microsecond","millisecond","second","minute","hour","day","week","month","quarter","year"];t.dayIndex=i.indexOf("day");function s(a){return i.indexOf(a)>=t.dayIndex}t.inDays=s;function o(a){const l=a.queryTimezone;if(!(l===void 0||l===a.systemTimezone))return l}t.qtz=o;class u{constructor(){this.cantPartitionWindowFunctionsOnExpressions=!1,this.supportsPipelinesInViews=!0,this.supportsArraysInData=!0,this.readsNestedData=!0,this.orderByClause="ordinal",this.nullMatchesFunctionSignature=!0,this.supportsSelectReplace=!0,this.supportsComplexFilteredSources=!0,this.supportsTempTables=!0,this.hasModOperator=!0,this.supportsLeftJoinUnnest=!0,this.supportsCountApprox=!1,this.supportsHyperLogLog=!1,this.supportsFullJoin=!0,this.nestedArrays=!0,this.compoundObjectInSchema=!0,this.booleanAsNumbers=!1,this.likeEscape=!0}sqlFinalStage(l,c){throw new Error("Dialect has no final Stage but called Anyway")}sqlDateToString(l){return this.castToString(`DATE(${l})`)}sqlLiteralNumber(l){return l}ignoreInProject(l){return!1}exprToSQL(l,c){switch(c.node){case"now":return this.sqlNowExpr();case"timeDiff":return this.sqlMeasureTimeExpr(c);case"delta":return this.sqlAlterTimeExpr(c);case"trunc":return this.sqlTruncExpr(l,c);case"extract":return this.sqlTimeExtractExpr(l,c);case"cast":return this.sqlCast(l,c);case"regexpMatch":return this.sqlRegexpMatch(c);case"/":return this.divisionIsInteger?`${c.kids.left.sql}*1.0/${c.kids.right.sql}`:void 0;case"%":return this.hasModOperator?void 0:`MOD(${c.kids.left.sql},${c.kids.right.sql})`;case"timeLiteral":return this.sqlLiteralTime(l,c);case"stringLiteral":return this.sqlLiteralString(c.literal);case"numberLiteral":return this.sqlLiteralNumber(c.literal);case"regexpLiteral":return this.sqlLiteralRegexp(c.literal);case"recordLiteral":return this.sqlLiteralRecord(c);case"arrayLiteral":return this.sqlLiteralArray(c)}}sqlSumDistinct(l,c,f){return"sqlSumDistinct called but not implemented"}sqlAggDistinct(l,c,f){return"sqlAggDistinct called but not implemented"}sqlSampleTable(l,c){if(c!==void 0)throw new Error(`Sampling is not supported on dialect ${this.name}.`);return l}sqlOrderBy(l){return`ORDER BY ${l.join(",")}`}sqlTzStr(l){return`"${l.queryTimezone}"`}sqlMakeUnnestKey(l,c){return this.concat(l,"'x'",c)}sqlStringAggDistinct(l,c,f){const x="__STRING_AGG_KS__",h="__STRING_AGG_KE__";return`REGEXP_REPLACE(
|
|
1212
|
+
`;var H$={},p2={},lt={},et={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.sourceBase=t.isSegmentSQL=t.isIndexSegment=t.isRawSegment=t.isSamplingEnable=t.isSamplingPercent=t.isSamplingRows=t.isQuerySegment=t.isProjectSegment=t.isPartialSegment=t.isReduceSegment=t.structHasErrors=t.segmentHasErrors=t.refIsStructDef=t.ValueType=t.isExtractUnit=t.isTimestampUnit=t.isDateUnit=t.isJoinedSource=t.isJoined=t.isJoinable=t.isMatrixOperation=t.isScalarArray=t.isRepeatedRecord=t.isRepeatedRecordFunctionParam=t.mkArrayDef=t.mkFieldDef=t.fieldIsIntrinsic=t.isCastType=t.canOrderBy=t.isAtomicFieldType=t.isTemporalType=t.hasExpression=t.maxOfExpressionTypes=t.maxExpressionType=t.isExpressionTypeLEQ=t.expressionIsAnalytic=t.expressionIsCalculation=t.expressionInvolvesAggregate=t.expressionIsUngroupedAggregate=t.expressionIsAggregate=t.expressionIsScalar=t.paramHasValue=t.isFilterExprType=t.isRawCast=t.mkTemporal=t.isAsymmetricExpr=t.exprIsLeaf=t.exprHasE=t.exprHasKids=void 0,t.TD=t.isValueDate=t.isValueTimestamp=t.isValueBoolean=t.isValueNumber=t.isValueString=t.isAtomic=t.isTurtle=t.getIdentifier=t.isLeafAtomic=t.mergeEvalSpaces=t.isLiteral=t.isBaseTable=t.isSourceDef=void 0;function e(P){return"kids"in P}t.exprHasKids=e;function r(P){return"e"in P}t.exprHasE=r;function i(P){return!(e(P)||r(P))}t.exprIsLeaf=i;function s(P){return P.node==="aggregate"&&["sum","avg","count","distinct"].includes(P.function)}t.isAsymmetricExpr=s;function o(P){return P.node!=="arrayLiteral"&&P.node!=="recordLiteral"}function u(P,K){if(!("typeDef"in P)){const ae=typeof K=="string"?{type:K}:K;if(o(P))return{...P,typeDef:{...ae}}}return P}t.mkTemporal=u;function a(P){return"dstSQLType"in P}t.isRawCast=a;function l(P){return["string","number","boolean","date","timestamp"].includes(P)}t.isFilterExprType=l;function c(P){return P.value!==null}t.paramHasValue=c;function f(P){return P===void 0||P==="scalar"}t.expressionIsScalar=f;function x(P){return P==="aggregate"||P==="ungrouped_aggregate"}t.expressionIsAggregate=x;function h(P){return P==="ungrouped_aggregate"}t.expressionIsUngroupedAggregate=h;function p(P){return P==="aggregate"||P==="ungrouped_aggregate"||P==="aggregate_analytic"}t.expressionInvolvesAggregate=p;function m(P){return P==="aggregate"||P==="scalar_analytic"||P==="aggregate_analytic"||P==="ungrouped_aggregate"}t.expressionIsCalculation=m;function y(P){return P==="aggregate_analytic"||P==="scalar_analytic"}t.expressionIsAnalytic=y;function g(P){return{scalar:0,aggregate:1,ungrouped_aggregate:2,scalar_analytic:2,aggregate_analytic:3}[P]}function E(P,K){return P===K||g(P)<g(K)}t.isExpressionTypeLEQ=E;function A(P,K){let ae="scalar";return(P==="aggregate"||K==="aggregate")&&(ae="aggregate"),(P==="ungrouped_aggregate"||K==="ungrouped_aggregate")&&(ae="ungrouped_aggregate"),(P==="scalar_analytic"||K==="scalar_analytic")&&(ae="scalar_analytic"),(P==="aggregate_analytic"||K==="aggregate_analytic")&&(ae="aggregate_analytic"),(P==="scalar_analytic"&&K==="aggregate"||P==="aggregate"&&K==="scalar_analytic")&&(ae="aggregate_analytic"),ae}t.maxExpressionType=A;function _(P){return P.reduce(A,"scalar")}t.maxOfExpressionTypes=_;function v(P){return"e"in P}t.hasExpression=v;function C(P){return P==="date"||P==="timestamp"}t.isTemporalType=C;function S(P){return["string","number","date","timestamp","boolean","json","sql native","record","array","error"].includes(P)}t.isAtomicFieldType=S;function b(P){return["string","number","date","boolean","date","timestamp"].includes(P)}t.canOrderBy=b;function R(P){return["string","number","date","timestamp","boolean","json"].includes(P)}t.isCastType=R;function O(P){return S(P.type)&&!v(P)}t.fieldIsIntrinsic=O;function B(P,K){if(V(P))return D(P.elementTypeDef,K);if(U(P)){const{type:ae,fields:je,elementTypeDef:te}=P;return{type:ae,fields:je,elementTypeDef:te,join:"many",name:K}}if(P.type==="record"){const{type:ae,fields:je}=P;return{type:ae,fields:je,join:"one",name:K}}return{...P,name:K}}t.mkFieldDef=B;function D(P,K){if(P.type==="record")return{type:"array",join:"many",name:K,elementTypeDef:{type:"record_element"},fields:P.fields};const ae=B(P,"value");return{type:"array",join:"many",name:K,elementTypeDef:P,fields:[ae,{...ae,name:"each",e:{node:"field",path:["value"]}}]}}t.mkArrayDef=D;function $(P){return P.type==="array"&&P.elementTypeDef.type==="record_element"}t.isRepeatedRecordFunctionParam=$;function U(P){return P.type==="array"&&P.elementTypeDef.type==="record_element"}t.isRepeatedRecord=U;function V(P){return P.type==="array"&&P.elementTypeDef.type!=="record_element"}t.isScalarArray=V;function Q(P){return["left","right","full","inner"].includes(P)}t.isMatrixOperation=Q;function Z(P){return["composite","table","sql_select","query_source","array","record"].includes(P.type)}t.isJoinable=Z;function de(P){return"join"in P}t.isJoined=de;function he(P){return pe(P)&&de(P)}t.isJoinedSource=he;function ie(P){return["day","week","month","quarter","year"].includes(P)}t.isDateUnit=ie;function ee(P){return ie(P)||["hour","minute","second"].includes(P)}t.isTimestampUnit=ee;function X(P){return ee(P)||P==="day_of_week"||P==="day_of_year"}t.isExtractUnit=X;var ce;(function(P){P.Date="date",P.Timestamp="timestamp",P.Number="number",P.String="string"})(ce||(t.ValueType=ce={}));function N(P){return typeof P!="string"}t.refIsStructDef=N;function w(P){return!!((P.type==="reduce"||P.type==="project"||P.type==="partial")&&(P.extendSource&&P.extendSource.some(K=>K.type==="error")||P.queryFields.some(K=>K.type==="error")))}t.segmentHasErrors=w;function F(P){return P.fields.some(K=>K.type==="error")}t.structHasErrors=F;function j(P){return P.type==="reduce"}t.isReduceSegment=j;function Y(P){return P.type==="partial"}t.isPartialSegment=Y;function z(P){return P.type==="project"}t.isProjectSegment=z;function L(P){return z(P)||j(P)}t.isQuerySegment=L;function M(P){return P.rows!==void 0}t.isSamplingRows=M;function q(P){return P.percent!==void 0}t.isSamplingPercent=q;function G(P){return P.enable!==void 0}t.isSamplingEnable=G;function k(P){return P.type==="raw"}t.isRawSegment=k;function W(P){return P.type==="index"}t.isIndexSegment=W;function H(P){return"sql"in P}t.isSegmentSQL=H;function re(P){return{...P}}t.sourceBase=re;function pe(P){return P.type==="table"||P.type==="sql_select"||P.type==="query_source"||P.type==="query_result"||P.type==="finalize"||P.type==="nest_source"||P.type==="composite"}t.isSourceDef=pe;function oe(P){return he(P)?!1:!!pe(P)}t.isBaseTable=oe;function J(P){return P==="literal"}t.isLiteral=J;function fe(...P){return P.length<=1&&P.every(K=>K==="literal")?"literal":P.every(K=>K==="constant"||K==="literal")?"constant":P.every(K=>K==="output"||K==="constant"||K==="literal")?"output":"input"}t.mergeEvalSpaces=fe;function Se(P){return P.type==="string"||C(P.type)||P.type==="number"||P.type==="boolean"||P.type==="json"||P.type==="sql native"||P.type==="error"}t.isLeafAtomic=Se;function Be(P){return P.as!==void 0?P.as:P.name}t.getIdentifier=Be;function xt(P){return P.type==="turtle"}t.isTurtle=xt;function se(P){return S(P.type)}t.isAtomic=se;function xe(P,K){return K.type==="string"}t.isValueString=xe;function we(P,K){return K.type==="number"}t.isValueNumber=we;function qe(P,K){return K.type==="boolean"}t.isValueBoolean=qe;function De(P,K){return K.type==="timestamp"}t.isValueTimestamp=De;function Oe(P,K){return K.type==="date"}t.isValueDate=Oe,t.TD={isAtomic(P){return P!==void 0&&S(P.type)},isLeafAtomic(P){return P!==void 0&&Se({type:P.type})},isString:P=>(P==null?void 0:P.type)==="string",isNumber:P=>(P==null?void 0:P.type)==="number",isBoolean:P=>(P==null?void 0:P.type)==="boolean",isJSON:P=>(P==null?void 0:P.type)==="json",isSQL:P=>(P==null?void 0:P.type)==="sql native",isDate:P=>(P==null?void 0:P.type)==="date",isTimestamp:P=>(P==null?void 0:P.type)==="timestamp",isTemporal(P){var K;const ae=(K=P==null?void 0:P.type)!==null&&K!==void 0?K:"";return C(ae)},isError:P=>(P==null?void 0:P.type)==="error",eq(P,K){if(P===void 0||K===void 0)return!1;function ae(je,te){const me={};for(const Ie of je.fields||[])if(Ie.name)me[Ie.name]=Ie;else return!1;for(const Ie of te.fields||[])if(!t.TD.eq(me[Ie.name],Ie))return!1;return!0}return P.type==="array"&&K.type==="array"?P.elementTypeDef.type!==K.elementTypeDef.type?!1:P.elementTypeDef.type!=="record_element"&&K.elementTypeDef.type!=="record_element"?t.TD.eq(P.elementTypeDef,K.elementTypeDef):t.TD.isAtomic(P)&&t.TD.isAtomic(K)&&ae(P,K):P.type==="record"&&K.type==="record"?t.TD.isAtomic(P)&&t.TD.isAtomic(K)&&ae(P,K):P.type==="sql native"&&K.type==="sql native"?P.rawType!==void 0&&P.rawType===K.rawType:P.type===K.type}}})(et),Object.defineProperty(lt,"__esModule",{value:!0}),lt.def=lt.expandOverrideMapFromBase=lt.expandBlueprintMap=lt.overload=lt.minAnalytic=lt.minAggregate=lt.minScalar=lt.maxAnalytic=lt.maxUngroupedAggregate=lt.anyExprType=lt.maxAggregate=lt.maxScalar=lt.makeParam=lt.param=lt.variadicParam=lt.literal=lt.output=lt.constant=lt.sql=lt.spread=lt.arg=void 0;const Sae=et;function bae(t){return{node:"function_parameter",name:t}}lt.arg=bae;function dXe(t,e=void 0,r=void 0){return{node:"spread",e:t,prefix:e,suffix:r}}lt.spread=dXe;function hXe(t,...e){const r={node:"genericSQLExpr",kids:{args:[]},src:[]},i=[...e];let s="";for(const o of t){s+=o;const u=i.shift();u!==void 0&&(typeof u=="string"?s+=u:(r.src.push(s),r.kids.args.push(u),s=""))}return s.length>0&&r.src.push(s),r}lt.sql=hXe;function Q$(t){return{...t,evalSpace:"constant"}}lt.constant=Q$;function pXe(t){return{...t,evalSpace:"output"}}lt.output=pXe;function z$(t){return{...t,evalSpace:"literal"}}lt.literal=z$;function mXe(t,...e){return{name:t,isVariadic:!0,allowedTypes:e}}lt.variadicParam=mXe;function Tae(t,...e){return{name:t,isVariadic:!1,allowedTypes:e}}lt.param=Tae;function gXe(t,...e){return{param:Tae(t,...e),arg:bae(t)}}lt.makeParam=gXe;function f4(t){return{...t,expressionType:"scalar",evalSpace:"input"}}lt.maxScalar=f4;function Rae(t){return{...t,expressionType:"aggregate",evalSpace:"input"}}lt.maxAggregate=Rae;function h0(t){return{...t,expressionType:void 0,evalSpace:"input"}}lt.anyExprType=h0;function yXe(t){return{...t,expressionType:"ungrouped_aggregate",evalSpace:"input"}}lt.maxUngroupedAggregate=yXe;function Dae(t){return{...t,expressionType:"aggregate_analytic",evalSpace:"input"}}lt.maxAnalytic=Dae;function m2(t){return{...t,expressionType:"scalar",evalSpace:"input"}}lt.minScalar=m2;function Oae(t){return{...t,expressionType:"aggregate",evalSpace:"input"}}lt.minAggregate=Oae;function wae(t){return{...t,expressionType:"scalar_analytic",evalSpace:"input"}}lt.minAnalytic=wae;function EXe(t,e,r,i){return{returnType:t,params:e,e:r,needsWindowOrderBy:i==null?void 0:i.needsWindowOrderBy,between:i==null?void 0:i.between,isSymmetric:i==null?void 0:i.isSymmetric,supportsOrderBy:i==null?void 0:i.supportsOrderBy,defaultOrderByArgIndex:i==null?void 0:i.defaultOrderByArgIndex,supportsLimit:i==null?void 0:i.supportsLimit}}lt.overload=EXe;function zn(t,e=!0,r=!0){if(!e&&t==="any")throw new Error("Return type cannot include any");if(typeof t=="string")return{type:t};if("array"in t){const i=e?zn(t.array,!0):zn(t.array,!1);return i.type==="record"?{type:"array",elementTypeDef:{type:"record_element"},fields:i.fields}:{type:"array",elementTypeDef:i}}else if("record"in t){const i=[];for(const[s,o]of Object.entries(t.record)){const u=e?zn(o,!0):zn(o,!1);Sae.TD.isAtomic(u)&&i.push((0,Sae.mkFieldDef)(u,s))}return{type:"record",fields:i}}else if("generic"in t){if(!r)throw new Error("Cannot use generic");return{type:"generic",generic:t.generic}}else if("sql_native"in t)return{type:"sql native",rawType:t.sql_native};throw new Error("Cannot figure out type")}function AXe(t){if(t==="any")throw new Error("Cannot return any type");return typeof t=="string"?m2({type:t}):"array"in t||"record"in t?h0(zn(t,!1)):"generic"in t?m2(zn(t,!1)):"literal"in t?z$(m2(zn(t.literal,!1))):"constant"in t?Q$(m2(zn(t.constant,!1))):"dimension"in t?m2(zn(t.dimension,!1)):"measure"in t?Oae(zn(t.measure,!1)):"sql_native"in t?h0({type:"sql native",rawType:t.sql_native}):wae(zn(t.calculation,!1))}function Fae(t){return typeof t=="string"||"array"in t||"record"in t||"generic"in t||"literal"in t||"constant"in t||"dimension"in t||"measure"in t||"calculation"in t||"sql_native"in t}function _Xe(t){return Fae(t)?[t]:Array.isArray(t)?t:Fae(t.variadic)?[t.variadic]:t.variadic}function vXe(t){return typeof t=="string"?h0({type:t}):"generic"in t?h0(zn(t)):"literal"in t?z$(f4(zn(t.literal))):"constant"in t?Q$(f4(zn(t.constant))):"dimension"in t?f4(zn(t.dimension)):"measure"in t?Rae(zn(t.measure)):"array"in t||"record"in t?h0(zn(t,!1)):"sql_native"in t?h0({type:"sql native",rawType:t.sql_native}):Dae(zn(t.calculation))}function CXe(t){return t.map(e=>vXe(e))}function Nae(t){return typeof t!="string"&&"variadic"in t}function SXe(t,e){return{name:t,allowedTypes:CXe(_Xe(e)),isVariadic:Nae(e)}}function bXe(t){return Object.entries(t).map(r=>SXe(r[0],r[1]))}function TXe(t){const e=[],r=[];let i=t;for(;i.length>0;){const o=i.indexOf("${");if(o===-1){e.push(i);break}const u=i.slice(0,o);i=i.slice(o);const a=i.indexOf("}");if(a===-1){e.push(u+i);break}const l=i.slice(2,a);i=i.slice(a+1);const c=l.startsWith("..."),f=l.endsWith(":"),x=c?l.slice(3):f?l.slice(0,-1):l,h={node:"function_parameter",name:x};e.push(u),c?r.push({node:"spread",e:h,prefix:"",suffix:""}):f&&x==="order_by"?r.push({node:"aggregate_order_by"}):f&&x==="limit"?r.push({node:"aggregate_limit"}):r.push(h)}return{node:"genericSQLExpr",kids:{args:r},src:e}}function RXe(t,e){return Nae(e)?{node:"spread",e:{node:"function_parameter",name:t},prefix:"",suffix:""}:{node:"function_parameter",name:t}}function DXe(t,e){const r=Object.entries(e.takes),i=r.length>0?r.length-1:0;return{node:"genericSQLExpr",kids:{args:r.map(s=>RXe(s[0],s[1]))},src:[`${t}(`,...Array(i).fill(","),")"]}}function OXe(t){return"sql"in t.impl?TXe(t.impl.sql):"expr"in t.impl?t.impl.expr:DXe(t.impl.function,t)}function wXe(t){return{e:OXe(t),between:t.impl.between,needsWindowOrderBy:t.impl.needsWindowOrderBy,defaultOrderByArgIndex:t.impl.defaultOrderByArgIndex}}function FXe(t){if(t!==void 0)return Object.entries(t).map(([e,r])=>({name:e,acceptibleTypes:r.map(i=>zn(i,!0,!1))}))}function W$(t){return{returnType:AXe(t.returns),params:bXe(t.takes),isSymmetric:t.isSymmetric,supportsOrderBy:t.supportsOrderBy,supportsLimit:t.supportsLimit,genericTypes:FXe(t.generic),...wXe(t)}}function G$(t){return"takes"in t&&"returns"in t&&"impl"in t}function NXe(t){return"function"in t||"sql"in t||"expr"in t}function LXe(t){return G$(t)?[W$(t)]:Object.values(t).flatMap(e=>W$(e))}function IXe(t){const e={};for(const r in t)e[r]=LXe(t[r]);return e}lt.expandBlueprintMap=IXe;function Lae(t,e){return[W$({...t,impl:e})]}function $Xe(t,e,r){if(NXe(r)){if(!G$(e))throw new Error(`Malformed function override: ${t}. Attempt to override multiple overloads with a single overload (missing: ${Object.keys(e)})`);return Lae(e,r)}else{if(G$(e))throw new Error(`Malformed function override: ${t}. Attempt to override a single overload with multiple overloads (extraneous: ${Object.keys(r)})`);return Object.entries(r).flatMap(([i,s])=>{const o=e[i];if(o===void 0)throw new Error(`Malformed function override: ${t}. No overload named ${i}`);return Lae(o,s)})}}function BXe(t,e){const r={};for(const i in e){if(!(i in t))throw new Error(`Malformed function override: ${i}. No such function in Malloy standard`);r[i]=$Xe(i,t[i],e[i])}return r}lt.expandOverrideMapFromBase=BXe;function*V$(t){if(typeof t!="string"){if("generic"in t)yield t;else if("record"in t)for(const e of Object.values(t.record))yield*V$(e);else for(const e of["array","literal","measure","dimension","measure","constant","cacluation"])if(e in t){yield*V$(t[e]);return}}}function kXe(t,e,r,i={}){let s=!1;const o={};for(const a of Object.values(e))for(const l of V$(a))o[l.generic]=["any"],s=!0;s&&i.generic===void 0&&(i.generic=o);const u={takes:e,returns:r,impl:{function:t.toUpperCase()},...i};return{[t]:u}}lt.def=kXe;var qc={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.Dialect=t.qtz=t.inDays=t.dayIndex=t.isDialectFieldStruct=void 0;const e=et;function r(a){return a.type==="struct"}t.isDialectFieldStruct=r;const i=["microsecond","millisecond","second","minute","hour","day","week","month","quarter","year"];t.dayIndex=i.indexOf("day");function s(a){return i.indexOf(a)>=t.dayIndex}t.inDays=s;function o(a){const l=a.queryTimezone;if(!(l===void 0||l===a.systemTimezone))return l}t.qtz=o;class u{constructor(){this.cantPartitionWindowFunctionsOnExpressions=!1,this.supportsPipelinesInViews=!0,this.supportsArraysInData=!0,this.readsNestedData=!0,this.orderByClause="ordinal",this.nullMatchesFunctionSignature=!0,this.supportsSelectReplace=!0,this.supportsComplexFilteredSources=!0,this.supportsTempTables=!0,this.hasModOperator=!0,this.supportsLeftJoinUnnest=!0,this.supportsCountApprox=!1,this.supportsHyperLogLog=!1,this.supportsFullJoin=!0,this.nestedArrays=!0,this.compoundObjectInSchema=!0,this.booleanAsNumbers=!1,this.likeEscape=!0}sqlFinalStage(l,c){throw new Error("Dialect has no final Stage but called Anyway")}sqlDateToString(l){return this.castToString(`DATE(${l})`)}sqlLiteralNumber(l){return l}ignoreInProject(l){return!1}exprToSQL(l,c){switch(c.node){case"now":return this.sqlNowExpr();case"timeDiff":return this.sqlMeasureTimeExpr(c);case"delta":return this.sqlAlterTimeExpr(c);case"trunc":return this.sqlTruncExpr(l,c);case"extract":return this.sqlTimeExtractExpr(l,c);case"cast":return this.sqlCast(l,c);case"regexpMatch":return this.sqlRegexpMatch(c);case"/":return this.divisionIsInteger?`${c.kids.left.sql}*1.0/${c.kids.right.sql}`:void 0;case"%":return this.hasModOperator?void 0:`MOD(${c.kids.left.sql},${c.kids.right.sql})`;case"timeLiteral":return this.sqlLiteralTime(l,c);case"stringLiteral":return this.sqlLiteralString(c.literal);case"numberLiteral":return this.sqlLiteralNumber(c.literal);case"regexpLiteral":return this.sqlLiteralRegexp(c.literal);case"recordLiteral":return this.sqlLiteralRecord(c);case"arrayLiteral":return this.sqlLiteralArray(c)}}sqlSumDistinct(l,c,f){return"sqlSumDistinct called but not implemented"}sqlAggDistinct(l,c,f){return"sqlAggDistinct called but not implemented"}sqlSampleTable(l,c){if(c!==void 0)throw new Error(`Sampling is not supported on dialect ${this.name}.`);return l}sqlOrderBy(l,c){return`ORDER BY ${l.join(",")}`}sqlTzStr(l){return`"${l.queryTimezone}"`}sqlMakeUnnestKey(l,c){return this.concat(l,"'x'",c)}sqlStringAggDistinct(l,c,f){const x="__STRING_AGG_KS__",h="__STRING_AGG_KE__";return`REGEXP_REPLACE(
|
|
1213
1213
|
STRING_AGG(DISTINCT ${`concat('${x}', ${l}, '${h}', ${c})`}${f.length>0?","+f:""}),
|
|
1214
1214
|
'${x}.*?${h}',
|
|
1215
1215
|
''
|
|
@@ -1217,7 +1217,7 @@ ${e.map(i=>` ${i}`).join(`,
|
|
|
1217
1217
|
`)}kt.indent=rZe;function iZe(t){return`'${t.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}kt.generateSQLStringLiteral=iZe;class tB{constructor(e){this.clauses=[],e&&this.clauses.push(e)}clone(){const e=new tB;return e.addChain(this),e}add(e){return this.clauses.push(e),this}addChain(e){return this.clauses.push(...e.clauses),this}empty(){return this.clauses.length===0}present(){return this.clauses.length>0}sqlOr(){return this.empty()?"":this.clauses.map(e=>`(${e})`).join("OR ")+`
|
|
1218
1218
|
`}sql(e){if(this.empty())return"";let r="",i="";return e&&(r=e.toUpperCase()+" ",i=`
|
|
1219
1219
|
`),this.clauses.length===1?r+this.clauses[0]+i:r+this.clauses.map(s=>`(${s})`).join(`
|
|
1220
|
-
AND `)+i}}kt.AndChain=tB;function sZe(t){return(0,nZe.v5)(t,"76c17e9d-f3ce-5f2d-bfde-98ad3d2a37f6")}kt.generateHash=sZe;function oZe(t,e){const r=[];for(let i=0;i<t.length;i++)r.push(...t[i]),i<t.length-1&&r.push(e);return r}kt.joinWith=oZe;function uZe(t,e){return Array.from({length:e-t},(r,i)=>i+t)}kt.range=uZe;function*Pae(t){if((0,m4.exprHasKids)(t))for(const e of Object.values(t.kids))Array.isArray(e)?yield*e:e!==null&&(yield e);else(0,m4.exprHasE)(t)&&(yield t.e)}kt.exprKids=Pae;function*Uae(t,e="post"){e==="pre"&&(yield t);for(const r of Pae(t))yield*Uae(r,e);e==="post"&&(yield t)}kt.exprWalk=Uae;function aZe(t,e){let r={...t};if((0,m4.exprHasKids)(t)){const i={...t};i.kids={};for(const[s,o]of Object.entries(t.kids))Array.isArray(o)?i.kids[s]=o.map(u=>e(u)):o!==null&&(i.kids[s]=e(o));r=i}return(0,m4.exprHasE)(r)&&(r.e=e(r.e)),e(r)}kt.exprMap=aZe;function lZe(t){const e={node:"genericSQLExpr",kids:{args:[]},src:[]};let r=!1;for(const i of t)typeof i=="string"?(r?e.src[e.src.length-1]+=i:e.src.push(i),r=!0):(r||e.src.push(""),e.kids.args.push(i),r=!1);return e}kt.composeSQLExpr=lZe;var Qc={},jae={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.expandOverrideMap=t.getMalloyStandardFunctions=t.MALLOY_STANDARD_FUNCTIONS=void 0;const e=lt,r={takes:{value:"number"},returns:"number",impl:{function:"ABS"}},i={takes:{value:"number"},returns:"number",impl:{function:"ACOS"}},s={takes:{value:"string"},returns:"number",impl:{function:"ASCII"}},o={takes:{value:"number"},returns:"number",impl:{function:"ASIN"}},u={takes:{y:"number",x:"number"},returns:"number",impl:{function:"ATAN2"}},a={takes:{value:"number"},returns:"number",impl:{function:"ATAN"}},l={takes:{value:"string"},returns:"number",impl:{function:"BYTE_LENGTH"}},c={takes:{value:"number"},returns:"number",impl:{function:"CEIL"}},f={takes:{value:"number"},returns:"string",impl:{sql:"CASE WHEN ${value} = 0 THEN '' ELSE CHR(${value}) END"}},x={generic:{T:["string","number","timestamp","date","json"]},takes:{value:{variadic:{generic:"T"}}},returns:{generic:"T"},impl:{function:"COALESCE"}},h={empty:{takes:{},returns:"string",impl:{expr:{node:"stringLiteral",literal:""}}},variadic:{takes:{values:{variadic:["string","number","date","timestamp","boolean"]}},returns:"string",impl:{function:"CONCAT"}}},p={takes:{value:"number"},returns:"number",impl:{function:"COS"}},m={takes:{dividend:"number",divisor:"number"},returns:"number",impl:{function:"DIV"}},y={takes:{value:"string",suffix:"string"},returns:"boolean",impl:{sql:"COALESCE(ENDS_WITH(${value}, ${suffix}), false)"}},g={takes:{value:"number"},returns:"number",impl:{function:"EXP"}},E={takes:{value:"number"},returns:"number",impl:{function:"FLOOR"}},A={generic:{T:["string","number","timestamp","date","json"]},takes:{values:{variadic:{generic:"T"}}},returns:{generic:"T"},impl:{function:"GREATEST"}},_={generic:{T:["string","number","timestamp","date","json"]},takes:{value:{generic:"T"},default:{generic:"T"}},returns:{generic:"T"},impl:{function:"IFNULL"}},v={takes:{value:"number"},returns:"boolean",impl:{sql:"COALESCE(IS_INF(${value}), false)"}},C={takes:{value:"number"},returns:"boolean",impl:{sql:"COALESCE(IS_NAN(${value}), false)"}},S={...A,impl:{function:"LEAST"}},b={takes:{value:"string"},returns:"number",impl:{function:"LENGTH"}},R={takes:{value:"number"},returns:"number",impl:{function:"LN"}},O={takes:{value:"number",base:"number"},returns:"number",impl:{function:"LOG"}},B={takes:{value:"string"},returns:"string",impl:{function:"LOWER"}},D={whitespace:{takes:{value:"string"},returns:"string",impl:{function:"LTRIM"}},characters:{takes:{value:"string",trim_characters:"string"},returns:"string",impl:{function:"LTRIM"}}},$={generic:{T:["string","number","timestamp","date","json"]},takes:{value1:{generic:"T"},value2:{generic:"T"}},returns:{generic:"T"},impl:{function:"NULLIF"}},U={takes:{},returns:"number",impl:{function:"PI"}},V={takes:{base:"number",exponent:"number"},returns:"number",impl:{function:"POW"}},Q={takes:{},returns:"number",impl:{function:"RAND"}},Z={takes:{value:"string",pattern:"regular expression"},returns:"string",impl:{function:"REGEXP_EXTRACT"}},de={takes:{value:"string",count:"number"},returns:"string",impl:{function:"REPEAT"}},he={string:{takes:{value:"string",pattern:"string",replacement:"string"},returns:"string",impl:{function:"REPLACE"}},regular_expression:{takes:{value:"string",pattern:"regular expression",replacement:"string"},returns:"string",impl:{function:"REGEXP_REPLACE"}}},ie={to_integer:{takes:{value:"number"},returns:"number",impl:{function:"ROUND"}},to_precision:{takes:{value:"number",precision:"number"},returns:"number",impl:{function:"ROUND"}}},ee={whitespace:{...D.whitespace,impl:{function:"RTRIM"}},characters:{...D.characters,impl:{function:"RTRIM"}}},X={takes:{value:"number"},returns:"number",impl:{function:"SIGN"}},ce={takes:{value:"number"},returns:"number",impl:{function:"SIN"}},N={takes:{value:"number"},returns:"number",impl:{function:"SQRT"}},w={takes:{value:"string",prefix:"string"},returns:"boolean",impl:{sql:"COALESCE(STARTS_WITH(${value}, ${prefix}), false)"}},F={takes:{test_string:"string",search_string:"string"},returns:"number",impl:{function:"STRPOS"}},j={position_only:{takes:{value:"string",position:"number"},returns:"string",impl:{function:"SUBSTR"}},with_length:{takes:{value:"string",position:"number",length:"number"},returns:"string",impl:{function:"SUBSTR"}}},Y={takes:{value:"number"},returns:"number",impl:{function:"TAN"}},z={whitespace:{...D.whitespace,impl:{function:"TRIM"}},characters:{...D.characters,impl:{function:"TRIM"}}},L={to_integer:{takes:{value:"number"},returns:"number",impl:{function:"TRUNC"}},to_precision:{takes:{value:"number",precision:"number"},returns:"number",impl:{function:"TRUNC"}}},M={takes:{value:"string"},returns:"number",impl:{function:"UNICODE"}},q={takes:{value:"string"},returns:"string",impl:{function:"UPPER"}},G={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"STDDEV"}},k={preceding:{generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}},preceding:{literal:"number"}},returns:{calculation:{generic:"T"}},impl:{sql:"AVG(${value})",needsWindowOrderBy:!0,between:{preceding:"preceding",following:0}}},following:{generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}},preceding:{literal:"number"},following:{literal:"number"}},returns:{calculation:{generic:"T"}},impl:{sql:"AVG(${value})",needsWindowOrderBy:!0,between:{preceding:"preceding",following:"following"}}}},W={generic:{T:["string","number","timestamp","date","json"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"FIRST_VALUE",needsWindowOrderBy:!0}},H=["string","number","timestamp","date","json","boolean"],re={bare:{generic:{T:H},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"LAG",needsWindowOrderBy:!0}},with_offset:{generic:{T:H},takes:{value:{measure:{generic:"T"}},offset:{literal:"number"}},returns:{calculation:{generic:"T"}},impl:{function:"LAG",needsWindowOrderBy:!0}},with_default:{generic:{T:H},takes:{value:{measure:{generic:"T"}},offset:{literal:"number"},default:{constant:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"LAG",needsWindowOrderBy:!0}}},pe={generic:{T:["string","number","timestamp","date","json"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"LAST_VALUE",needsWindowOrderBy:!0,between:{preceding:-1,following:-1}}},oe={bare:{...re.bare,impl:{function:"LEAD",needsWindowOrderBy:!0}},with_offset:{...re.with_offset,impl:{function:"LEAD",needsWindowOrderBy:!0}},with_default:{...re.with_default,impl:{function:"LEAD",needsWindowOrderBy:!0}}},J={generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"MAX",needsWindowOrderBy:!0}},fe={generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"MAX",needsWindowOrderBy:!1}},Se={generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"MIN",needsWindowOrderBy:!0}},Be={generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"MIN",needsWindowOrderBy:!1}},xt={takes:{},returns:{calculation:"number"},impl:{function:"RANK",needsWindowOrderBy:!0}},se={takes:{},returns:{calculation:"number"},impl:{function:"ROW_NUMBER",needsWindowOrderBy:!0}},xe={generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"SUM",needsWindowOrderBy:!0}},we={preceding:{generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}},preceding:{literal:"number"}},returns:{calculation:{generic:"T"}},impl:{sql:"SUM(${value})",needsWindowOrderBy:!0,between:{preceding:"preceding",following:0}}},following:{generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}},preceding:{literal:"number"},following:{literal:"number"}},returns:{calculation:{generic:"T"}},impl:{sql:"SUM(${value})",needsWindowOrderBy:!0,between:{preceding:"preceding",following:"following"}}}},qe={generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"SUM",needsWindowOrderBy:!1}},De={takes:{value:{literal:"string"}},returns:"boolean",impl:{expr:{node:"function_parameter",name:"value"}}},Oe={takes:{value:{literal:"string"}},returns:"date",impl:{expr:{node:"function_parameter",name:"value"}}},P={takes:{value:{literal:"string"}},returns:"number",impl:{expr:{node:"function_parameter",name:"value"}}},K={takes:{value:{literal:"string"}},returns:"string",impl:{expr:{node:"function_parameter",name:"value"}}},ae={takes:{value:{literal:"string"}},returns:"timestamp",impl:{expr:{node:"function_parameter",name:"value"}}};t.MALLOY_STANDARD_FUNCTIONS={abs:r,acos:i,ascii:s,asin:o,atan2:u,atan:a,byte_length:l,ceil:c,chr:f,coalesce:x,concat:h,cos:p,div:m,ends_with:y,exp:g,floor:E,greatest:A,ifnull:_,is_inf:v,is_nan:C,least:S,length:b,ln:R,log:O,lower:B,ltrim:D,nullif:$,pi:U,pow:V,rand:Q,regexp_extract:Z,replace:he,round:ie,rtrim:ee,sign:X,sin:ce,sqrt:N,starts_with:w,string_repeat:de,strpos:F,substr:j,tan:Y,trim:z,trunc:L,unicode:M,upper:q,stddev:G,avg_moving:k,first_value:W,lag:re,last_value:pe,lead:oe,max_cumulative:J,max_window:fe,min_cumulative:Se,min_window:Be,rank:xt,row_number:se,sum_cumulative:xe,sum_moving:we,sum_window:qe,sql_boolean:De,sql_date:Oe,sql_number:P,sql_string:K,sql_timestamp:ae};function je(){return(0,e.expandBlueprintMap)(t.MALLOY_STANDARD_FUNCTIONS)}t.getMalloyStandardFunctions=je;function te(me){return(0,e.expandOverrideMapFromBase)(t.MALLOY_STANDARD_FUNCTIONS,me)}t.expandOverrideMap=te})(jae),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.expandOverrideMap=t.getMalloyStandardFunctions=t.expandBlueprintMap=void 0;var e=lt;Object.defineProperty(t,"expandBlueprintMap",{enumerable:!0,get:function(){return e.expandBlueprintMap}});var r=jae;Object.defineProperty(t,"getMalloyStandardFunctions",{enumerable:!0,get:function(){return r.getMalloyStandardFunctions}}),Object.defineProperty(t,"expandOverrideMap",{enumerable:!0,get:function(){return r.expandOverrideMap}})}(Qc);var g4={};Object.defineProperty(g4,"__esModule",{value:!0}),g4.STANDARDSQL_DIALECT_FUNCTIONS=void 0;const qae=lt,cZe={generic:"T"},fZe={takes:{unix_date:"number"},returns:"date",impl:{function:"DATE_FROM_UNIX_DATE"}},nB={default_separator:{takes:{value:{dimension:"string"}},returns:{measure:"string"},supportsOrderBy:!0,supportsLimit:!0,impl:{sql:"STRING_AGG(${value}${order_by:}${limit:})",defaultOrderByArgIndex:0}},with_separator:{takes:{value:{dimension:"string"},separator:{literal:"string"}},returns:{measure:"string"},supportsOrderBy:!0,supportsLimit:!0,impl:{sql:"STRING_AGG(${value}, ${separator}${order_by:}${limit:})",defaultOrderByArgIndex:0}}},xZe={default_separator:{...nB.default_separator,isSymmetric:!0,supportsOrderBy:"only_default",impl:{sql:"STRING_AGG(DISTINCT ${value}${order_by:}${limit:})",defaultOrderByArgIndex:0}},with_separator:{...nB.with_separator,isSymmetric:!0,supportsOrderBy:"only_default",impl:{sql:"STRING_AGG(DISTINCT ${value}, ${separator}${order_by:}${limit:})",defaultOrderByArgIndex:0}}};g4.STANDARDSQL_DIALECT_FUNCTIONS={date_from_unix_date:fZe,string_agg:nB,string_agg_distinct:xZe,hll_accumulate:{default:{takes:{value:{dimension:cZe}},returns:{measure:{sql_native:"bytes"}},generic:{T:["string","number"]},isSymmetric:!0,impl:{function:"HLL_COUNT.INIT"}}},hll_combine:{takes:{value:{sql_native:"bytes"}},returns:{measure:{sql_native:"bytes"}},impl:{function:"HLL_COUNT.MERGE_PARTIAL"},isSymmetric:!0},hll_estimate:{takes:{value:{sql_native:"bytes"}},returns:{dimension:"number"},impl:{function:"HLL_COUNT.EXTRACT"}},hll_export:{takes:{value:{sql_native:"bytes"}},returns:{dimension:{sql_native:"bytes"}},impl:{sql:"CAST(${value} AS BYTES)"}},hll_import:{takes:{value:{sql_native:"bytes"}},returns:{dimension:{sql_native:"bytes"}},impl:{sql:"CAST(${value} AS BYTES)"}},...(0,qae.def)("repeat",{str:"string",n:"number"},"string"),...(0,qae.def)("reverse",{str:"string"},"string")};var y4={};Object.defineProperty(y4,"__esModule",{value:!0}),y4.STANDARDSQL_MALLOY_STANDARD_OVERLOADS=void 0,y4.STANDARDSQL_MALLOY_STANDARD_OVERLOADS={chr:{sql:"CASE WHEN IFNULL(${value}, 1) = 0 THEN '' ELSE CHR(${value}) END"},pi:{sql:"ACOS(-1)"}},Object.defineProperty(eE,"__esModule",{value:!0}),eE.StandardSQLDialect=void 0;const Hae=kt,Ba=et,Qae=Qc,dZe=qc,hZe=g4,pZe=y4;function zae(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function mZe(t){return["day","week","month","quarter","year"].includes(t)}const gZe={day_of_week:"dayofweek",day_of_year:"dayofyear"};function E4(t){const e=t.queryTimezone;if(e&&e!=="UTC")return e}const yZe={DATE:{type:"date"},STRING:{type:"string"},INTEGER:{type:"number",numberType:"integer"},INT64:{type:"number",numberType:"integer"},FLOAT:{type:"number",numberType:"float"},FLOAT64:{type:"number",numberType:"float"},NUMERIC:{type:"number",numberType:"float"},BIGNUMERIC:{type:"number",numberType:"float"},TIMESTAMP:{type:"timestamp"},BOOLEAN:{type:"boolean"},BOOL:{type:"boolean"},JSON:{type:"json"}};class EZe extends dZe.Dialect{constructor(){super(...arguments),this.name="standardsql",this.experimental=!1,this.defaultNumberType="FLOAT64",this.defaultDecimalType="NUMERIC",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!1,this.supportsSumDistinctFunction=!1,this.unnestWithNumbers=!1,this.defaultSampling={enable:!1},this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!0,this.supportsQualify=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.cantPartitionWindowFunctionsOnExpressions=!0,this.hasModOperator=!1,this.nestedArrays=!1,this.supportsHyperLogLog=!0,this.likeEscape=!1}quoteTablePath(e){return`\`${e}\``}sqlGroupSetTable(e){return`CROSS JOIN (SELECT row_number() OVER() -1 group_set FROM UNNEST(GENERATE_ARRAY(0,${e},1)))`}sqlAnyValue(e,r){return`ANY_VALUE(CASE WHEN group_set=${e} THEN ${r} END)`}sqlAggregateTurtle(e,r,i,s){let o="";s!==void 0&&(o+=` LIMIT ${s}`);const u=r.map(a=>`
|
|
1220
|
+
AND `)+i}}kt.AndChain=tB;function sZe(t){return(0,nZe.v5)(t,"76c17e9d-f3ce-5f2d-bfde-98ad3d2a37f6")}kt.generateHash=sZe;function oZe(t,e){const r=[];for(let i=0;i<t.length;i++)r.push(...t[i]),i<t.length-1&&r.push(e);return r}kt.joinWith=oZe;function uZe(t,e){return Array.from({length:e-t},(r,i)=>i+t)}kt.range=uZe;function*Pae(t){if((0,m4.exprHasKids)(t))for(const e of Object.values(t.kids))Array.isArray(e)?yield*e:e!==null&&(yield e);else(0,m4.exprHasE)(t)&&(yield t.e)}kt.exprKids=Pae;function*Uae(t,e="post"){e==="pre"&&(yield t);for(const r of Pae(t))yield*Uae(r,e);e==="post"&&(yield t)}kt.exprWalk=Uae;function aZe(t,e){let r={...t};if((0,m4.exprHasKids)(t)){const i={...t};i.kids={};for(const[s,o]of Object.entries(t.kids))Array.isArray(o)?i.kids[s]=o.map(u=>e(u)):o!==null&&(i.kids[s]=e(o));r=i}return(0,m4.exprHasE)(r)&&(r.e=e(r.e)),e(r)}kt.exprMap=aZe;function lZe(t){const e={node:"genericSQLExpr",kids:{args:[]},src:[]};let r=!1;for(const i of t)typeof i=="string"?(r?e.src[e.src.length-1]+=i:e.src.push(i),r=!0):(r||e.src.push(""),e.kids.args.push(i),r=!1);return e}kt.composeSQLExpr=lZe;var Qc={},jae={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.expandOverrideMap=t.getMalloyStandardFunctions=t.MALLOY_STANDARD_FUNCTIONS=void 0;const e=lt,r={takes:{value:"number"},returns:"number",impl:{function:"ABS"}},i={takes:{value:"number"},returns:"number",impl:{function:"ACOS"}},s={takes:{value:"string"},returns:"number",impl:{function:"ASCII"}},o={takes:{value:"number"},returns:"number",impl:{function:"ASIN"}},u={takes:{y:"number",x:"number"},returns:"number",impl:{function:"ATAN2"}},a={takes:{value:"number"},returns:"number",impl:{function:"ATAN"}},l={takes:{value:"string"},returns:"number",impl:{function:"BYTE_LENGTH"}},c={takes:{value:"number"},returns:"number",impl:{function:"CEIL"}},f={takes:{value:"number"},returns:"string",impl:{sql:"CASE WHEN ${value} = 0 THEN '' ELSE CHR(${value}) END"}},x={generic:{T:["string","number","timestamp","date","json"]},takes:{value:{variadic:{generic:"T"}}},returns:{generic:"T"},impl:{function:"COALESCE"}},h={empty:{takes:{},returns:"string",impl:{expr:{node:"stringLiteral",literal:""}}},variadic:{takes:{values:{variadic:["string","number","date","timestamp","boolean"]}},returns:"string",impl:{function:"CONCAT"}}},p={takes:{value:"number"},returns:"number",impl:{function:"COS"}},m={takes:{dividend:"number",divisor:"number"},returns:"number",impl:{function:"DIV"}},y={takes:{value:"string",suffix:"string"},returns:"boolean",impl:{sql:"COALESCE(ENDS_WITH(${value}, ${suffix}), false)"}},g={takes:{value:"number"},returns:"number",impl:{function:"EXP"}},E={takes:{value:"number"},returns:"number",impl:{function:"FLOOR"}},A={generic:{T:["string","number","timestamp","date","json"]},takes:{values:{variadic:{generic:"T"}}},returns:{generic:"T"},impl:{function:"GREATEST"}},_={generic:{T:["string","number","timestamp","date","json"]},takes:{value:{generic:"T"},default:{generic:"T"}},returns:{generic:"T"},impl:{function:"IFNULL"}},v={takes:{value:"number"},returns:"boolean",impl:{sql:"COALESCE(IS_INF(${value}), false)"}},C={takes:{value:"number"},returns:"boolean",impl:{sql:"COALESCE(IS_NAN(${value}), false)"}},S={...A,impl:{function:"LEAST"}},b={takes:{value:"string"},returns:"number",impl:{function:"LENGTH"}},R={takes:{value:"number"},returns:"number",impl:{function:"LN"}},O={takes:{value:"number",base:"number"},returns:"number",impl:{function:"LOG"}},B={takes:{value:"string"},returns:"string",impl:{function:"LOWER"}},D={whitespace:{takes:{value:"string"},returns:"string",impl:{function:"LTRIM"}},characters:{takes:{value:"string",trim_characters:"string"},returns:"string",impl:{function:"LTRIM"}}},$={generic:{T:["string","number","timestamp","date","json"]},takes:{value1:{generic:"T"},value2:{generic:"T"}},returns:{generic:"T"},impl:{function:"NULLIF"}},U={takes:{},returns:"number",impl:{function:"PI"}},V={takes:{base:"number",exponent:"number"},returns:"number",impl:{function:"POW"}},Q={takes:{},returns:"number",impl:{function:"RAND"}},Z={takes:{value:"string",pattern:"regular expression"},returns:"string",impl:{function:"REGEXP_EXTRACT"}},de={takes:{value:"string",count:"number"},returns:"string",impl:{function:"REPEAT"}},he={string:{takes:{value:"string",pattern:"string",replacement:"string"},returns:"string",impl:{function:"REPLACE"}},regular_expression:{takes:{value:"string",pattern:"regular expression",replacement:"string"},returns:"string",impl:{function:"REGEXP_REPLACE"}}},ie={to_integer:{takes:{value:"number"},returns:"number",impl:{function:"ROUND"}},to_precision:{takes:{value:"number",precision:"number"},returns:"number",impl:{function:"ROUND"}}},ee={whitespace:{...D.whitespace,impl:{function:"RTRIM"}},characters:{...D.characters,impl:{function:"RTRIM"}}},X={takes:{value:"number"},returns:"number",impl:{function:"SIGN"}},ce={takes:{value:"number"},returns:"number",impl:{function:"SIN"}},N={takes:{value:"number"},returns:"number",impl:{function:"SQRT"}},w={takes:{value:"string",prefix:"string"},returns:"boolean",impl:{sql:"COALESCE(STARTS_WITH(${value}, ${prefix}), false)"}},F={takes:{test_string:"string",search_string:"string"},returns:"number",impl:{function:"STRPOS"}},j={position_only:{takes:{value:"string",position:"number"},returns:"string",impl:{function:"SUBSTR"}},with_length:{takes:{value:"string",position:"number",length:"number"},returns:"string",impl:{function:"SUBSTR"}}},Y={takes:{value:"number"},returns:"number",impl:{function:"TAN"}},z={whitespace:{...D.whitespace,impl:{function:"TRIM"}},characters:{...D.characters,impl:{function:"TRIM"}}},L={to_integer:{takes:{value:"number"},returns:"number",impl:{function:"TRUNC"}},to_precision:{takes:{value:"number",precision:"number"},returns:"number",impl:{function:"TRUNC"}}},M={takes:{value:"string"},returns:"number",impl:{function:"UNICODE"}},q={takes:{value:"string"},returns:"string",impl:{function:"UPPER"}},G={takes:{value:{dimension:"number"}},returns:{measure:"number"},impl:{function:"STDDEV"}},k={preceding:{generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}},preceding:{literal:"number"}},returns:{calculation:{generic:"T"}},impl:{sql:"AVG(${value})",needsWindowOrderBy:!0,between:{preceding:"preceding",following:0}}},following:{generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}},preceding:{literal:"number"},following:{literal:"number"}},returns:{calculation:{generic:"T"}},impl:{sql:"AVG(${value})",needsWindowOrderBy:!0,between:{preceding:"preceding",following:"following"}}}},W={generic:{T:["string","number","timestamp","date","json"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"FIRST_VALUE",needsWindowOrderBy:!0}},H=["string","number","timestamp","date","json","boolean"],re={bare:{generic:{T:H},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"LAG",needsWindowOrderBy:!0}},with_offset:{generic:{T:H},takes:{value:{measure:{generic:"T"}},offset:{literal:"number"}},returns:{calculation:{generic:"T"}},impl:{function:"LAG",needsWindowOrderBy:!0}},with_default:{generic:{T:H},takes:{value:{measure:{generic:"T"}},offset:{literal:"number"},default:{constant:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"LAG",needsWindowOrderBy:!0}}},pe={generic:{T:["string","number","timestamp","date","json"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"LAST_VALUE",needsWindowOrderBy:!0,between:{preceding:-1,following:-1}}},oe={bare:{...re.bare,impl:{function:"LEAD",needsWindowOrderBy:!0}},with_offset:{...re.with_offset,impl:{function:"LEAD",needsWindowOrderBy:!0}},with_default:{...re.with_default,impl:{function:"LEAD",needsWindowOrderBy:!0}}},J={generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"MAX",needsWindowOrderBy:!0}},fe={generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"MAX",needsWindowOrderBy:!1}},Se={generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"MIN",needsWindowOrderBy:!0}},Be={generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"MIN",needsWindowOrderBy:!1}},xt={takes:{},returns:{calculation:"number"},impl:{function:"RANK",needsWindowOrderBy:!0}},se={takes:{},returns:{calculation:"number"},impl:{function:"ROW_NUMBER",needsWindowOrderBy:!0}},xe={generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"SUM",needsWindowOrderBy:!0}},we={preceding:{generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}},preceding:{literal:"number"}},returns:{calculation:{generic:"T"}},impl:{sql:"SUM(${value})",needsWindowOrderBy:!0,between:{preceding:"preceding",following:0}}},following:{generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}},preceding:{literal:"number"},following:{literal:"number"}},returns:{calculation:{generic:"T"}},impl:{sql:"SUM(${value})",needsWindowOrderBy:!0,between:{preceding:"preceding",following:"following"}}}},qe={generic:{T:["string","number","timestamp","date"]},takes:{value:{measure:{generic:"T"}}},returns:{calculation:{generic:"T"}},impl:{function:"SUM",needsWindowOrderBy:!1}},De={takes:{value:{literal:"string"}},returns:"boolean",impl:{expr:{node:"function_parameter",name:"value"}}},Oe={takes:{value:{literal:"string"}},returns:"date",impl:{expr:{node:"function_parameter",name:"value"}}},P={takes:{value:{literal:"string"}},returns:"number",impl:{expr:{node:"function_parameter",name:"value"}}},K={takes:{value:{literal:"string"}},returns:"string",impl:{expr:{node:"function_parameter",name:"value"}}},ae={takes:{value:{literal:"string"}},returns:"timestamp",impl:{expr:{node:"function_parameter",name:"value"}}};t.MALLOY_STANDARD_FUNCTIONS={abs:r,acos:i,ascii:s,asin:o,atan2:u,atan:a,byte_length:l,ceil:c,chr:f,coalesce:x,concat:h,cos:p,div:m,ends_with:y,exp:g,floor:E,greatest:A,ifnull:_,is_inf:v,is_nan:C,least:S,length:b,ln:R,log:O,lower:B,ltrim:D,nullif:$,pi:U,pow:V,rand:Q,regexp_extract:Z,replace:he,round:ie,rtrim:ee,sign:X,sin:ce,sqrt:N,starts_with:w,string_repeat:de,strpos:F,substr:j,tan:Y,trim:z,trunc:L,unicode:M,upper:q,stddev:G,avg_moving:k,first_value:W,lag:re,last_value:pe,lead:oe,max_cumulative:J,max_window:fe,min_cumulative:Se,min_window:Be,rank:xt,row_number:se,sum_cumulative:xe,sum_moving:we,sum_window:qe,sql_boolean:De,sql_date:Oe,sql_number:P,sql_string:K,sql_timestamp:ae};function je(){return(0,e.expandBlueprintMap)(t.MALLOY_STANDARD_FUNCTIONS)}t.getMalloyStandardFunctions=je;function te(me){return(0,e.expandOverrideMapFromBase)(t.MALLOY_STANDARD_FUNCTIONS,me)}t.expandOverrideMap=te})(jae),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.expandOverrideMap=t.getMalloyStandardFunctions=t.expandBlueprintMap=void 0;var e=lt;Object.defineProperty(t,"expandBlueprintMap",{enumerable:!0,get:function(){return e.expandBlueprintMap}});var r=jae;Object.defineProperty(t,"getMalloyStandardFunctions",{enumerable:!0,get:function(){return r.getMalloyStandardFunctions}}),Object.defineProperty(t,"expandOverrideMap",{enumerable:!0,get:function(){return r.expandOverrideMap}})}(Qc);var g4={};Object.defineProperty(g4,"__esModule",{value:!0}),g4.STANDARDSQL_DIALECT_FUNCTIONS=void 0;const qae=lt,cZe={generic:"T"},fZe={takes:{unix_date:"number"},returns:"date",impl:{function:"DATE_FROM_UNIX_DATE"}},nB={default_separator:{takes:{value:{dimension:"string"}},returns:{measure:"string"},supportsOrderBy:!0,supportsLimit:!0,impl:{sql:"STRING_AGG(${value}${order_by:}${limit:})",defaultOrderByArgIndex:0}},with_separator:{takes:{value:{dimension:"string"},separator:{literal:"string"}},returns:{measure:"string"},supportsOrderBy:!0,supportsLimit:!0,impl:{sql:"STRING_AGG(${value}, ${separator}${order_by:}${limit:})",defaultOrderByArgIndex:0}}},xZe={default_separator:{...nB.default_separator,isSymmetric:!0,supportsOrderBy:"only_default",impl:{sql:"STRING_AGG(DISTINCT ${value}${order_by:}${limit:})",defaultOrderByArgIndex:0}},with_separator:{...nB.with_separator,isSymmetric:!0,supportsOrderBy:"only_default",impl:{sql:"STRING_AGG(DISTINCT ${value}, ${separator}${order_by:}${limit:})",defaultOrderByArgIndex:0}}};g4.STANDARDSQL_DIALECT_FUNCTIONS={date_from_unix_date:fZe,string_agg:nB,string_agg_distinct:xZe,hll_accumulate:{default:{takes:{value:{dimension:cZe}},returns:{measure:{sql_native:"bytes"}},generic:{T:["string","number"]},isSymmetric:!0,impl:{function:"HLL_COUNT.INIT"}}},hll_combine:{takes:{value:{sql_native:"bytes"}},returns:{measure:{sql_native:"bytes"}},impl:{function:"HLL_COUNT.MERGE_PARTIAL"},isSymmetric:!0},hll_estimate:{takes:{value:{sql_native:"bytes"}},returns:{dimension:"number"},impl:{function:"HLL_COUNT.EXTRACT"}},hll_export:{takes:{value:{sql_native:"bytes"}},returns:{dimension:{sql_native:"bytes"}},impl:{sql:"CAST(${value} AS BYTES)"}},hll_import:{takes:{value:{sql_native:"bytes"}},returns:{dimension:{sql_native:"bytes"}},impl:{sql:"CAST(${value} AS BYTES)"}},...(0,qae.def)("repeat",{str:"string",n:"number"},"string"),...(0,qae.def)("reverse",{str:"string"},"string")};var y4={};Object.defineProperty(y4,"__esModule",{value:!0}),y4.STANDARDSQL_MALLOY_STANDARD_OVERLOADS=void 0,y4.STANDARDSQL_MALLOY_STANDARD_OVERLOADS={chr:{sql:"CASE WHEN IFNULL(${value}, 1) = 0 THEN '' ELSE CHR(${value}) END"},pi:{sql:"ACOS(-1)"}},Object.defineProperty(eE,"__esModule",{value:!0}),eE.StandardSQLDialect=void 0;const Hae=kt,Ba=et,Qae=Qc,dZe=qc,hZe=g4,pZe=y4;function zae(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function mZe(t){return["day","week","month","quarter","year"].includes(t)}const gZe={day_of_week:"dayofweek",day_of_year:"dayofyear"};function E4(t){const e=t.queryTimezone;if(e&&e!=="UTC")return e}const yZe={DATE:{type:"date"},STRING:{type:"string"},INTEGER:{type:"number",numberType:"integer"},INT64:{type:"number",numberType:"integer"},FLOAT:{type:"number",numberType:"float"},FLOAT64:{type:"number",numberType:"float"},NUMERIC:{type:"number",numberType:"float"},BIGNUMERIC:{type:"number",numberType:"float"},TIMESTAMP:{type:"timestamp"},BOOLEAN:{type:"boolean"},BOOL:{type:"boolean"},JSON:{type:"json"}};class EZe extends dZe.Dialect{constructor(){super(...arguments),this.name="standardsql",this.experimental=!1,this.defaultNumberType="FLOAT64",this.defaultDecimalType="NUMERIC",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!1,this.supportsSumDistinctFunction=!1,this.unnestWithNumbers=!1,this.defaultSampling={enable:!1},this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!0,this.supportsQualify=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.cantPartitionWindowFunctionsOnExpressions=!0,this.hasModOperator=!1,this.nestedArrays=!1,this.supportsHyperLogLog=!0,this.likeEscape=!1}quoteTablePath(e){return`\`${e}\``}sqlGroupSetTable(e){return`CROSS JOIN (SELECT row_number() OVER() -1 group_set FROM UNNEST(GENERATE_ARRAY(0,${e},1)))`}sqlAnyValue(e,r){return`ANY_VALUE(CASE WHEN group_set=${e} THEN ${r} END)`}sqlOrderBy(e,r){return r==="analytical"||r==="turtle"?`ORDER BY ${e.join(",")}`:`ORDER BY ${e.map(i=>`${i} NULLS LAST`).join(",")}`}sqlAggregateTurtle(e,r,i,s){let o="";s!==void 0&&(o+=` LIMIT ${s}`);const u=r.map(a=>`
|
|
1221
1221
|
${a.sqlExpression} as ${a.sqlOutputName}`).join(", ");return`ARRAY_AGG(CASE WHEN group_set=${e} THEN STRUCT(${u}
|
|
1222
1222
|
) END IGNORE NULLS ${i} ${o})`}sqlAnyValueTurtle(e,r){const i=r.map(s=>`${s.sqlExpression} as ${s.sqlOutputName}`).join(", ");return`ANY_VALUE(CASE WHEN group_set=${e} THEN STRUCT(${i}))`}sqlAnyValueLastTurtle(e,r,i){return`ANY_VALUE(CASE WHEN group_set=${r} THEN ${e} END) as ${i}`}sqlCoaleseMeasuresInline(e,r){const i=r.map(o=>`${o.sqlExpression} as ${o.sqlOutputName}`).join(", "),s=r.map(o=>`NULL as ${o.sqlOutputName}`).join(", ");return`COALESCE(ANY_VALUE(CASE WHEN group_set=${e} THEN STRUCT(${i}) END), STRUCT(${s}))`}sqlUnnestAlias(e,r,i,s,o,u){return o?s?`LEFT JOIN UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, value FROM UNNEST(${e}) value))) as ${r}`:`LEFT JOIN UNNEST(ARRAY((SELECT AS STRUCT value FROM unnest(${e}) value))) as ${r}`:s?`LEFT JOIN UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, * FROM UNNEST(${e})))) as ${r}`:`LEFT JOIN UNNEST(${e}) as ${r}`}sqlSumDistinctHashedKey(e){e=`CAST(${e} AS STRING)`;const r=`cast(cast(concat('0x', substr(to_hex(md5(${e})), 1, 15)) as int64) as numeric) * 4294967296`,i=`cast(cast(concat('0x', substr(to_hex(md5(${e})), 16, 8)) as int64) as numeric)`;return`(${r} + ${i}) * 0.000000001`}sqlGenerateUUID(){return"GENERATE_UUID()"}sqlFieldReference(e,r,i,s){const o=this.sqlMaybeQuoteIdentifier(i);return`${e}.${o}`}sqlUnnestPipelineHead(e,r){let i=r;return e&&(i=`[${i}]`),`UNNEST(${i})`}sqlCreateFunction(e,r){return`CREATE TEMPORARY FUNCTION ${e}(__param ANY TYPE) AS ((
|
|
1223
1223
|
${(0,Hae.indent)(r)}));
|
|
@@ -1400,7 +1400,7 @@ ${(0,ile.indent)(r)}
|
|
|
1400
1400
|
CROSS JOIN UNNEST(COALESCE(${e},ARRAY[NULL])) WITH ORDINALITY as ${r}(value, __row_id_almost_${r})
|
|
1401
1401
|
CROSS JOIN UNNEST(ARRAY[CASE WHEN ${e} IS NOT NULL THEN __row_id_almost_${r} END]) as ${r}_ignore(__row_id_from_${r})`:`CROSS JOIN UNNEST(COALESCE(${e}, ARRAY[NULL])) as ${r}(value) `:s?`-- Simulate a left join
|
|
1402
1402
|
CROSS JOIN UNNEST(COALESCE(${e}, ARRAY[NULL])) WITH ORDINALITY as ${r}_outer(${r}, __row_id_almost_${r})
|
|
1403
|
-
CROSS JOIN UNNEST(ARRAY[CASE WHEN ${e} IS NOT NULL THEN __row_id_almost_${r} END]) as ${r}_ignore(__row_id_from_${r})`:`CROSS JOIN UNNEST(COALESCE(${e}, ARRAY[NULL])) as ${r}_outer(${r})`}getDialectFunctions(){return(0,dB.expandBlueprintMap)(ole.PRESTO_DIALECT_FUNCTIONS)}}E2.PrestoDialect=net,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(E2,t)}(fB);var pB={},N4={},L4={};Object.defineProperty(L4,"__esModule",{value:!0}),L4.MYSQL_DIALECT_FUNCTIONS=void 0;const ule=lt,mB={default_separator:{takes:{value:{dimension:"string"}},returns:{measure:"string"},supportsOrderBy:!0,impl:{sql:"GROUP_CONCAT(${value} ${order_by:})"}},with_separator:{takes:{value:{dimension:"string"},separator:{literal:"string"}},returns:{measure:"string"},supportsOrderBy:!0,impl:{sql:"GROUP_CONCAT(${value} ${order_by:} SEPARATOR ${separator})"}}},ret={default_separator:{...mB.default_separator,isSymmetric:!0,supportsOrderBy:"only_default",impl:{sql:"GROUP_CONCAT(DISTINCT ${value} ${order_by:})",defaultOrderByArgIndex:0}},with_separator:{...mB.with_separator,isSymmetric:!0,supportsOrderBy:"only_default",impl:{sql:"GROUP_CONCAT(DISTINCT ${value} ${order_by:} SEPARATOR ${separator})",defaultOrderByArgIndex:0}}};L4.MYSQL_DIALECT_FUNCTIONS={string_agg:mB,string_agg_distinct:ret,...(0,ule.def)("repeat",{str:"string",n:"number"},"string"),...(0,ule.def)("reverse",{str:"string"},"string")};var I4={};Object.defineProperty(I4,"__esModule",{value:!0}),I4.MYSQL_MALLOY_STANDARD_OVERLOADS=void 0,I4.MYSQL_MALLOY_STANDARD_OVERLOADS={regexp_extract:{function:"REGEXP_SUBSTR"},replace:{regular_expression:{sql:"REGEXP_REPLACE(${value}, ${pattern}, ${replacement}, 1,0)"}},trunc:{to_integer:{sql:"(FLOOR(${value}) + IF(${value} < 0,1,0))"},to_precision:{sql:"(ABS(FLOOR(${value} * POW(10,${precision}))/POW(10,${precision}))*IF(${value} < 0, -1, 1))"}},log:{sql:"log(${base},${value})"},div:{sql:"FLOOR(${dividend} / ${divisor})"},strpos:{sql:"LOCATE(${search_string},${test_string})"},starts_with:{sql:"COALESCE(${value} LIKE CONCAT(${prefix}, '%'),0)"},ends_with:{sql:"COALESCE(${value} LIKE CONCAT('%',${suffix}),0)"},trim:{characters:{sql:"TRIM(BOTH ${trim_characters} FROM ${value})"}},ltrim:{characters:{sql:"TRIM(LEADING ${trim_characters} FROM ${value})"}},rtrim:{characters:{sql:"TRIM(TRAILING ${trim_characters} FROM ${value})"}},byte_length:{sql:"(LENGTH(CAST(${value} AS VARBINARY)))"},chr:{sql:"CASE WHEN ${value} = 0 THEN '' ELSE CHAR(${value} USING latin1) END"}},Object.defineProperty(N4,"__esModule",{value:!0}),N4.MySQLDialect=void 0;const Wc=et,iet=kt,nE=qc,ale=Qc,set=L4,oet=I4,uet={day_of_week:"DAYOFWEEK",day_of_year:"DAYOFYEAR"},lle={second:1,minute:60,hour:3600,day:24*3600,week:7*24*3600},aet={tinyint:{type:"boolean"},smallint:{type:"number",numberType:"integer"},mediumint:{type:"number",numberType:"integer"},int:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},"tinyint unsigned":{type:"number",numberType:"integer"},"smallint unsigned":{type:"number",numberType:"integer"},"mediumint unsigned":{type:"number",numberType:"integer"},"int unsigned":{type:"number",numberType:"integer"},"bigint unsigned":{type:"number",numberType:"integer"},double:{type:"number",numberType:"float"},varchar:{type:"string"},varbinary:{type:"string"},char:{type:"string"},text:{type:"string"},date:{type:"date"},datetime:{type:"timestamp"},timestamp:{type:"timestamp"},time:{type:"string"},decimal:{type:"number",numberType:"float"},"tinyint(1)":{type:"boolean"}};class cet extends nE.Dialect{constructor(){super(...arguments),this.name="mysql",this.defaultNumberType="DOUBLE PRECISION",this.defaultDecimalType="DECIMAL",this.udfPrefix="ms_temp.__udf",this.hasFinalStage=!1,this.stringTypeName="VARCHAR(255)",this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!0,this.unnestWithNumbers=!1,this.defaultSampling={rows:5e4},this.supportUnnestArrayAgg=!0,this.supportsAggDistinct=!0,this.supportsCTEinCoorelatedSubQueries=!0,this.supportsSafeCast=!1,this.dontUnionIndex=!1,this.supportsQualify=!1,this.supportsNesting=!0,this.experimental=!1,this.supportsFullJoin=!1,this.supportsPipelinesInViews=!1,this.readsNestedData=!1,this.supportsComplexFilteredSources=!1,this.supportsArraysInData=!1,this.compoundObjectInSchema=!1,this.booleanAsNumbers=!0}malloyTypeToSQLType(e){switch(e.type){case"number":return e.numberType==="integer"?"BIGINT":"DOUBLE";case"string":return"CHAR";case"date":case"timestamp":default:return e.type}}sqlTypeToMalloyType(e){var r,i;const s=(i=(r=e.match(/^(\w+)/))===null||r===void 0?void 0:r.at(0))!==null&&i!==void 0?i:e;return aet[s.toLowerCase()]||{type:"sql native",rawType:s}}quoteTablePath(e){return e.split(".").map(r=>`\`${r}\``).join(".")}sqlGroupSetTable(e){return`CROSS JOIN (select number - 1 as group_set from JSON_TABLE(cast(concat("[1", repeat(",1", ${e}), "]") as JSON),"$[*]" COLUMNS(number FOR ORDINALITY)) group_set) as group_set`}sqlAnyValue(e,r){return`MAX(${r})`}mapFields(e){return e.map(r=>`"${r.rawName}", ${r.sqlExpression}`).join(", ")}sqlAggregateTurtle(e,r,i,s){const o=s?",xrmmex":",";let u=`GROUP_CONCAT(
|
|
1403
|
+
CROSS JOIN UNNEST(ARRAY[CASE WHEN ${e} IS NOT NULL THEN __row_id_almost_${r} END]) as ${r}_ignore(__row_id_from_${r})`:`CROSS JOIN UNNEST(COALESCE(${e}, ARRAY[NULL])) as ${r}_outer(${r})`}getDialectFunctions(){return(0,dB.expandBlueprintMap)(ole.PRESTO_DIALECT_FUNCTIONS)}}E2.PrestoDialect=net,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(E2,t)}(fB);var pB={},N4={},L4={};Object.defineProperty(L4,"__esModule",{value:!0}),L4.MYSQL_DIALECT_FUNCTIONS=void 0;const ule=lt,mB={default_separator:{takes:{value:{dimension:"string"}},returns:{measure:"string"},supportsOrderBy:!0,impl:{sql:"GROUP_CONCAT(${value} ${order_by:})"}},with_separator:{takes:{value:{dimension:"string"},separator:{literal:"string"}},returns:{measure:"string"},supportsOrderBy:!0,impl:{sql:"GROUP_CONCAT(${value} ${order_by:} SEPARATOR ${separator})"}}},ret={default_separator:{...mB.default_separator,isSymmetric:!0,supportsOrderBy:"only_default",impl:{sql:"GROUP_CONCAT(DISTINCT ${value} ${order_by:})",defaultOrderByArgIndex:0}},with_separator:{...mB.with_separator,isSymmetric:!0,supportsOrderBy:"only_default",impl:{sql:"GROUP_CONCAT(DISTINCT ${value} ${order_by:} SEPARATOR ${separator})",defaultOrderByArgIndex:0}}};L4.MYSQL_DIALECT_FUNCTIONS={string_agg:mB,string_agg_distinct:ret,...(0,ule.def)("repeat",{str:"string",n:"number"},"string"),...(0,ule.def)("reverse",{str:"string"},"string")};var I4={};Object.defineProperty(I4,"__esModule",{value:!0}),I4.MYSQL_MALLOY_STANDARD_OVERLOADS=void 0,I4.MYSQL_MALLOY_STANDARD_OVERLOADS={regexp_extract:{function:"REGEXP_SUBSTR"},replace:{regular_expression:{sql:"REGEXP_REPLACE(${value}, ${pattern}, ${replacement}, 1,0)"}},trunc:{to_integer:{sql:"(FLOOR(${value}) + IF(${value} < 0,1,0))"},to_precision:{sql:"(ABS(FLOOR(${value} * POW(10,${precision}))/POW(10,${precision}))*IF(${value} < 0, -1, 1))"}},log:{sql:"log(${base},${value})"},div:{sql:"FLOOR(${dividend} / ${divisor})"},strpos:{sql:"LOCATE(${search_string},${test_string})"},starts_with:{sql:"COALESCE(${value} LIKE CONCAT(${prefix}, '%'),0)"},ends_with:{sql:"COALESCE(${value} LIKE CONCAT('%',${suffix}),0)"},trim:{characters:{sql:"TRIM(BOTH ${trim_characters} FROM ${value})"}},ltrim:{characters:{sql:"TRIM(LEADING ${trim_characters} FROM ${value})"}},rtrim:{characters:{sql:"TRIM(TRAILING ${trim_characters} FROM ${value})"}},byte_length:{sql:"(LENGTH(CAST(${value} AS VARBINARY)))"},chr:{sql:"CASE WHEN ${value} = 0 THEN '' ELSE CHAR(${value} USING latin1) END"}},Object.defineProperty(N4,"__esModule",{value:!0}),N4.MySQLDialect=void 0;const Wc=et,iet=kt,nE=qc,ale=Qc,set=L4,oet=I4,uet={day_of_week:"DAYOFWEEK",day_of_year:"DAYOFYEAR"},lle={second:1,minute:60,hour:3600,day:24*3600,week:7*24*3600},aet={tinyint:{type:"boolean"},smallint:{type:"number",numberType:"integer"},mediumint:{type:"number",numberType:"integer"},int:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},"tinyint unsigned":{type:"number",numberType:"integer"},"smallint unsigned":{type:"number",numberType:"integer"},"mediumint unsigned":{type:"number",numberType:"integer"},"int unsigned":{type:"number",numberType:"integer"},"bigint unsigned":{type:"number",numberType:"integer"},double:{type:"number",numberType:"float"},varchar:{type:"string"},varbinary:{type:"string"},char:{type:"string"},text:{type:"string"},date:{type:"date"},datetime:{type:"timestamp"},timestamp:{type:"timestamp"},time:{type:"string"},decimal:{type:"number",numberType:"float"},"tinyint(1)":{type:"boolean"}};class cet extends nE.Dialect{constructor(){super(...arguments),this.name="mysql",this.defaultNumberType="DOUBLE PRECISION",this.defaultDecimalType="DECIMAL",this.udfPrefix="ms_temp.__udf",this.hasFinalStage=!1,this.stringTypeName="VARCHAR(255)",this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!0,this.unnestWithNumbers=!1,this.defaultSampling={rows:5e4},this.supportUnnestArrayAgg=!0,this.supportsAggDistinct=!0,this.supportsCTEinCoorelatedSubQueries=!0,this.supportsSafeCast=!1,this.dontUnionIndex=!1,this.supportsQualify=!1,this.supportsNesting=!0,this.experimental=!1,this.supportsFullJoin=!1,this.supportsPipelinesInViews=!1,this.readsNestedData=!1,this.supportsComplexFilteredSources=!1,this.supportsArraysInData=!1,this.compoundObjectInSchema=!1,this.booleanAsNumbers=!0,this.orderByClause="ordinal"}malloyTypeToSQLType(e){switch(e.type){case"number":return e.numberType==="integer"?"BIGINT":"DOUBLE";case"string":return"CHAR";case"date":case"timestamp":default:return e.type}}sqlTypeToMalloyType(e){var r,i;const s=(i=(r=e.match(/^(\w+)/))===null||r===void 0?void 0:r.at(0))!==null&&i!==void 0?i:e;return aet[s.toLowerCase()]||{type:"sql native",rawType:s}}quoteTablePath(e){return e.split(".").map(r=>`\`${r}\``).join(".")}sqlGroupSetTable(e){return`CROSS JOIN (select number - 1 as group_set from JSON_TABLE(cast(concat("[1", repeat(",1", ${e}), "]") as JSON),"$[*]" COLUMNS(number FOR ORDINALITY)) group_set) as group_set`}sqlAnyValue(e,r){return`MAX(${r})`}mapFields(e){return e.map(r=>`"${r.rawName}", ${r.sqlExpression}`).join(", ")}sqlAggregateTurtle(e,r,i,s){const o=s?",xrmmex":",";let u=`GROUP_CONCAT(
|
|
1404
1404
|
IF(group_set=${e},
|
|
1405
1405
|
JSON_OBJECT(${this.mapFields(r)})
|
|
1406
1406
|
, null
|
|
@@ -1418,7 +1418,7 @@ CROSS JOIN UNNEST(ARRAY[CASE WHEN ${e} IS NOT NULL THEN __row_id_almost_${r} END
|
|
|
1418
1418
|
${(0,iet.indent)(r)}
|
|
1419
1419
|
$$ LANGUAGE SQL;
|
|
1420
1420
|
`}sqlCreateFunctionCombineLastStage(e){return`SELECT ARRAY((SELECT AS STRUCT * FROM ${e}))
|
|
1421
|
-
`}sqlSelectAliasAsStruct(e,r){return"MYSQL: Implement this"}sqlMaybeQuoteIdentifier(e){return"`"+e.replace(/`/g,"``")+"`"}sqlCreateTableAsSelect(e,r){throw new Error("Not implemented Yet")}sqlNowExpr(){return"LOCALTIMESTAMP"}sqlTruncExpr(e,r){let i=r.e.sql||"why could this be undefined";if(r.units==="week"&&(i=`DATE_SUB(${i}, INTERVAL DAYOFWEEK(${i}) - 1 DAY)`),Wc.TD.isTimestamp(r.e.typeDef)){const o=(0,nE.qtz)(e);if(o){const u=`(CONVERT_TZ(${i}, 'UTC','${o}'))`;return`(${`CONVERT_TZ(${`${this.truncToUnit(u,r.units)}`}, '${o}', 'UTC')`})`}}return`${this.truncToUnit(i,r.units)}`}truncToUnit(e,r){let i="'%Y-%m-%d %H:%i:%s'";switch(r){case"minute":i="'%Y-%m-%d %H:%i:00'";break;case"hour":i="'%Y-%m-%d %H:00:00'";break;case"day":case"week":i="'%Y-%m-%d 00:00:00'";break;case"month":i="'%Y-%m-01 00:00:00'";break;case"quarter":i=`CASE WHEN MONTH(${e}) > 9 THEN '%Y-10-01 00:00:00' WHEN MONTH(${e}) > 6 THEN '%Y-07-01 00:00:00' WHEN MONTH(${e}) > 3 THEN '%Y-04-01 00:00:00' ELSE '%Y-01-01 00:00:00' end`;break;case"year":i="'%Y-01-01 00:00:00'";break}return`TIMESTAMP(DATE_FORMAT(${e}, ${i}))`}sqlTimeExtractExpr(e,r){const i=uet[r.units]||r.units;let s=r.e.sql;if(Wc.TD.isTimestamp(r.e.typeDef)){const o=(0,nE.qtz)(e);o&&(s=`CONVERT_TZ(${s}, 'UTC', '${o}')`)}return`${i}(${s})`}sqlAlterTimeExpr(e){let r=e.units,i=e.kids.delta.sql;r==="quarter"?(r="month",i=`${i}*3`):r==="week"&&(r="day",i=`${i}*7`);const s=`INTERVAL ${i} ${r} `;return`(${e.kids.base.sql})${e.op}${s}`}sqlCast(e,r){const i=r.e.sql||"internal-error-in-sql-generation",{op:s,srcTypeDef:o,dstTypeDef:u,dstSQLType:a}=this.sqlCastPrep(r),l=(0,nE.qtz)(e);if(s==="timestamp::date"&&l)return`CAST(CONVERT_TZ(${i}, 'UTC', '${l}') AS DATE) `;if(s==="date::timestamp"&&l)return` CONVERT_TZ(${i}, '${l}', 'UTC')`;if(!Wc.TD.eq(o,u)){if(r.safe)throw new Error("Mysql dialect doesn't support Safe Cast");return Wc.TD.isString(u)?`CONCAT(${i}, '')`:`CAST(${i} AS ${a})`}return i}sqlRegexpMatch(e){return`REGEXP_LIKE(${e.kids.expr.sql}, ${e.kids.regex.sql})`}sqlLiteralTime(e,r){if(Wc.TD.isDate(r.typeDef))return`DATE '${r.literal}'`;const i=r.timezone||(0,nE.qtz)(e);return i?` CONVERT_TZ('${r.literal}', '${i}', 'UTC')`:`TIMESTAMP '${r.literal}'`}sqlMeasureTimeExpr(e){let r=e.kids.left.sql,i=e.kids.right.sql;if(lle[e.units]){r=`UNIX_TIMESTAMP(${r})`,i=`UNIX_TIMESTAMP(${i})`;const s=`${i}-${r}`;return e.units==="second"?`FLOOR(${s})`:`FLOOR((${s})/${lle[e.units].toString()}.0)`}throw new Error(`Unknown or unhandled MySQL time unit: ${e.units}`)}sqlAggDistinct(e,r,i){throw new Error("MySQL dialect does not support nesting.")}sqlSampleTable(e,r){if(r!==void 0){if((0,Wc.isSamplingEnable)(r)&&r.enable&&(r=this.defaultSampling),(0,Wc.isSamplingRows)(r))return`(SELECT * FROM ${e} ORDER BY rand() LIMIT ${r.rows} )`;if((0,Wc.isSamplingPercent)(r))return`(SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY rand()) as __row_number, __source_tbl.* from ${e} as __source_tbl) as __rand_tbl where __row_number % FLOOR(100.0 / ${r.percent}) = 1)`}return e}
|
|
1421
|
+
`}sqlSelectAliasAsStruct(e,r){return"MYSQL: Implement this"}sqlMaybeQuoteIdentifier(e){return"`"+e.replace(/`/g,"``")+"`"}sqlCreateTableAsSelect(e,r){throw new Error("Not implemented Yet")}sqlNowExpr(){return"LOCALTIMESTAMP"}sqlTruncExpr(e,r){let i=r.e.sql||"why could this be undefined";if(r.units==="week"&&(i=`DATE_SUB(${i}, INTERVAL DAYOFWEEK(${i}) - 1 DAY)`),Wc.TD.isTimestamp(r.e.typeDef)){const o=(0,nE.qtz)(e);if(o){const u=`(CONVERT_TZ(${i}, 'UTC','${o}'))`;return`(${`CONVERT_TZ(${`${this.truncToUnit(u,r.units)}`}, '${o}', 'UTC')`})`}}return`${this.truncToUnit(i,r.units)}`}truncToUnit(e,r){let i="'%Y-%m-%d %H:%i:%s'";switch(r){case"minute":i="'%Y-%m-%d %H:%i:00'";break;case"hour":i="'%Y-%m-%d %H:00:00'";break;case"day":case"week":i="'%Y-%m-%d 00:00:00'";break;case"month":i="'%Y-%m-01 00:00:00'";break;case"quarter":i=`CASE WHEN MONTH(${e}) > 9 THEN '%Y-10-01 00:00:00' WHEN MONTH(${e}) > 6 THEN '%Y-07-01 00:00:00' WHEN MONTH(${e}) > 3 THEN '%Y-04-01 00:00:00' ELSE '%Y-01-01 00:00:00' end`;break;case"year":i="'%Y-01-01 00:00:00'";break}return`TIMESTAMP(DATE_FORMAT(${e}, ${i}))`}sqlTimeExtractExpr(e,r){const i=uet[r.units]||r.units;let s=r.e.sql;if(Wc.TD.isTimestamp(r.e.typeDef)){const o=(0,nE.qtz)(e);o&&(s=`CONVERT_TZ(${s}, 'UTC', '${o}')`)}return`${i}(${s})`}sqlAlterTimeExpr(e){let r=e.units,i=e.kids.delta.sql;r==="quarter"?(r="month",i=`${i}*3`):r==="week"&&(r="day",i=`${i}*7`);const s=`INTERVAL ${i} ${r} `;return`(${e.kids.base.sql})${e.op}${s}`}sqlCast(e,r){const i=r.e.sql||"internal-error-in-sql-generation",{op:s,srcTypeDef:o,dstTypeDef:u,dstSQLType:a}=this.sqlCastPrep(r),l=(0,nE.qtz)(e);if(s==="timestamp::date"&&l)return`CAST(CONVERT_TZ(${i}, 'UTC', '${l}') AS DATE) `;if(s==="date::timestamp"&&l)return` CONVERT_TZ(${i}, '${l}', 'UTC')`;if(!Wc.TD.eq(o,u)){if(r.safe)throw new Error("Mysql dialect doesn't support Safe Cast");return Wc.TD.isString(u)?`CONCAT(${i}, '')`:`CAST(${i} AS ${a})`}return i}sqlRegexpMatch(e){return`REGEXP_LIKE(${e.kids.expr.sql}, ${e.kids.regex.sql})`}sqlLiteralTime(e,r){if(Wc.TD.isDate(r.typeDef))return`DATE '${r.literal}'`;const i=r.timezone||(0,nE.qtz)(e);return i?` CONVERT_TZ('${r.literal}', '${i}', 'UTC')`:`TIMESTAMP '${r.literal}'`}sqlMeasureTimeExpr(e){let r=e.kids.left.sql,i=e.kids.right.sql;if(lle[e.units]){r=`UNIX_TIMESTAMP(${r})`,i=`UNIX_TIMESTAMP(${i})`;const s=`${i}-${r}`;return e.units==="second"?`FLOOR(${s})`:`FLOOR((${s})/${lle[e.units].toString()}.0)`}throw new Error(`Unknown or unhandled MySQL time unit: ${e.units}`)}sqlAggDistinct(e,r,i){throw new Error("MySQL dialect does not support nesting.")}sqlSampleTable(e,r){if(r!==void 0){if((0,Wc.isSamplingEnable)(r)&&r.enable&&(r=this.defaultSampling),(0,Wc.isSamplingRows)(r))return`(SELECT * FROM ${e} ORDER BY rand() LIMIT ${r.rows} )`;if((0,Wc.isSamplingPercent)(r))return`(SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY rand()) as __row_number, __source_tbl.* from ${e} as __source_tbl) as __rand_tbl where __row_number % FLOOR(100.0 / ${r.percent}) = 1)`}return e}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/'/g,"''")+"'"}getDialectFunctionOverrides(){return(0,ale.expandOverrideMap)(oet.MYSQL_MALLOY_STANDARD_OVERLOADS)}getDialectFunctions(){return(0,ale.expandBlueprintMap)(set.MYSQL_DIALECT_FUNCTIONS)}mapFieldsForJsonObject(e,r){return e.map(i=>`${i.sqlOutputName.replace(/`/g,"'")}, ${r?"NULL":i.sqlExpression}
|
|
1422
1422
|
`).join(", ")}castToString(e){return`CONCAT(${e}, '')`}concat(...e){return`CONCAT(${e.join(",")})`}validateTypeName(e){return e.match(/^[A-Za-z\s(),0-9]*$/)!==null}sqlLiteralArray(e){return`JSON_ARRAY(${e.kids.values.map(i=>i.sql).join(",")})`}sqlLiteralRecord(e){return`JSON_OBJECT(${Object.entries(e.kids).map(([i,s])=>`${this.sqlLiteralString(i)},${s.sql}`).join(", ")})`}}N4.MySQLDialect=cet,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(N4,t)}(pB);var Ma={};Object.defineProperty(Ma,"__esModule",{value:!0}),Ma.getDialects=Ma.registerDialect=Ma.getDialect=void 0;const fet=oB,xet=rB,det=lB,het=Y$,cle=fB,pet=pB,gB=new Map;function met(t){const e=gB.get(t);if(e===void 0)throw new Error(`Unknown Dialect ${t}`);return e}Ma.getDialect=met;function Gc(t){gB.set(t.name,t)}Ma.registerDialect=Gc;function get(){return[...gB.values()]}Ma.getDialects=get,Gc(new xet.PostgresDialect),Gc(new het.StandardSQLDialect),Gc(new fet.DuckDBDialect),Gc(new det.SnowflakeDialect),Gc(new cle.TrinoDialect),Gc(new cle.PrestoDialect),Gc(new pet.MySQLDialect),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TinyParser=t.getMalloyStandardFunctions=t.registerDialect=t.getDialect=t.MySQLDialect=t.TrinoDialect=t.SnowflakeDialect=t.DuckDBDialect=t.PostgresDialect=t.StandardSQLDialect=t.qtz=t.Dialect=t.sql=t.literal=t.variadicParam=t.param=t.spread=t.maxScalar=t.minAggregate=t.minScalar=t.overload=t.makeParam=t.anyExprType=t.arg=void 0;var e=lt;Object.defineProperty(t,"arg",{enumerable:!0,get:function(){return e.arg}}),Object.defineProperty(t,"anyExprType",{enumerable:!0,get:function(){return e.anyExprType}}),Object.defineProperty(t,"makeParam",{enumerable:!0,get:function(){return e.makeParam}}),Object.defineProperty(t,"overload",{enumerable:!0,get:function(){return e.overload}}),Object.defineProperty(t,"minScalar",{enumerable:!0,get:function(){return e.minScalar}}),Object.defineProperty(t,"minAggregate",{enumerable:!0,get:function(){return e.minAggregate}}),Object.defineProperty(t,"maxScalar",{enumerable:!0,get:function(){return e.maxScalar}}),Object.defineProperty(t,"spread",{enumerable:!0,get:function(){return e.spread}}),Object.defineProperty(t,"param",{enumerable:!0,get:function(){return e.param}}),Object.defineProperty(t,"variadicParam",{enumerable:!0,get:function(){return e.variadicParam}}),Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return e.literal}}),Object.defineProperty(t,"sql",{enumerable:!0,get:function(){return e.sql}});var r=qc;Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return r.Dialect}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return r.qtz}});var i=Y$;Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return i.StandardSQLDialect}});var s=rB;Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return s.PostgresDialect}});var o=oB;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return o.DuckDBDialect}});var u=lB;Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return u.SnowflakeDialect}});var a=fB;Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return a.TrinoDialect}});var l=pB;Object.defineProperty(t,"MySQLDialect",{enumerable:!0,get:function(){return l.MySQLDialect}});var c=Ma;Object.defineProperty(t,"getDialect",{enumerable:!0,get:function(){return c.getDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return c.registerDialect}});var f=Qc;Object.defineProperty(t,"getMalloyStandardFunctions",{enumerable:!0,get:function(){return f.getMalloyStandardFunctions}});var x=Cd;Object.defineProperty(t,"TinyParser",{enumerable:!0,get:function(){return x.TinyParser}})}(p2);var Yi={},Hs={},A2={},gi={};Object.defineProperty(gi,"__esModule",{value:!0}),gi.annotationToTag=gi.annotationToTaglines=gi.addModelScope=void 0;const fle=$o;function yet(t,e){const r=t?{...t}:{};return r.scopes?r.scopes=r.scopes.concat(e):r.scopes=[e],r}gi.addModelScope=yet;function xle(t,e){t||(t={});const r=t.inherits?xle(t.inherits,e):[];function i(s){const o=[];for(const u of s||[])(e===void 0||u.text.match(e))&&o.push(u.text);return o}return r.concat(i(t.blockNotes),i(t.notes))}gi.annotationToTaglines=xle;function dle(t,e={}){var r;let i=e.extending||new fle.Tag;const s=e.prefix||/^##? /;t||(t={});const o=[];if(t.inherits){const l=dle(t.inherits,e);o.push(...l.log),i=l.tag}const u=[];t.blockNotes&&u.push(...t.blockNotes),t.notes&&u.push(...t.notes);const a=[];for(const l of u)l.text.match(s)&&a.push(l);for(let l=0;l<a.length;l++){const c=a[l];if(c.text.match(s)){const f=fle.Tag.fromTagLine(c.text,l,i,...(r=e.scopes)!==null&&r!==void 0?r:[]);i=f.tag,o.push(...f.log.map(x=>Eet(x,c)))}}return{tag:i,log:o}}gi.annotationToTag=dle;function Eet(t,e){const r={line:e.at.range.start.line,character:e.at.range.start.character+t.offset};return{code:"tag-parse-error",severity:"error",message:t.message,at:{url:e.at.url,range:{start:r,end:r}}}}Object.defineProperty(A2,"__esModule",{value:!0}),A2.buildQueryMaterializationSpec=A2.shouldMaterialize=void 0;const Aet=kt,_et=gi;function vet(t){const e=structuredClone(t);return e&&(e.inherits=void 0),(0,_et.annotationToTag)(e).tag.has("materialize")}A2.shouldMaterialize=vet;function Cet(t,e,r){if(!e)throw new Error(`Query tagged to materialize, but its name is not specified. ${t}`);if(!t)throw new Error(`Query tagged to materialize, but its path is not specified: ${e}`);const i={path:t,source:void 0,queryName:e},s=(0,Aet.generateHash)(JSON.stringify(i)).replace(/-/g,"_"),o=`${r?`${r}_`:""}${e}_${s}`;return{...i,id:o}}A2.buildQueryMaterializationSpec=Cet;var hle={},$4={},wn={};Object.defineProperty(wn,"__esModule",{value:!0}),wn.isFilterable=wn.isFilterExpression=wn.isTemporalFilter=wn.isNumberFilter=wn.isBooleanFilter=wn.isStringFilter=wn.isStringCondition=wn.isChainOp=void 0;function bet(t){return["and","or",","].includes(t)}wn.isChainOp=bet;function Tet(t){return["starts","ends","contains","="].includes(t.operator)}wn.isStringCondition=Tet;function Ret(t){return"operator"in t&&typeof t.operator=="string"&&["starts","ends","contains","=","~","null","empty","and","or",",","()"].includes(t.operator)}wn.isStringFilter=Ret;function Det(t){return"operator"in t&&typeof t.operator=="string"&&["null","true","false","false_or_null"].includes(t.operator)}wn.isBooleanFilter=Det;function Oet(t){return"operator"in t&&typeof t.operator=="string"&&["range","<=",">=","!=","=",">","<","and","or","()","null"].includes(t.operator)}wn.isNumberFilter=Oet;function wet(t){return"operator"in t&&typeof t.operator=="string"&&["literal","before","after","to","for","in","and","or","in_last","this","last","next","()","null"].includes(t.operator)}wn.isTemporalFilter=wet;function Fet(t){return"operator"in t}wn.isFilterExpression=Fet;function Net(t){return["string","number","boolean","timestamp","date"].includes(t)}wn.isFilterable=Net;var B4={};Object.defineProperty(B4,"__esModule",{value:!0}),B4.BooleanFilterExpression=void 0,B4.BooleanFilterExpression={parse(t){var e;const r={parsed:null,log:[]};let i=t.toLowerCase().trim().replace(/\s\s+/," "),s=!1;if(i.startsWith("not ")&&(s=!0,i=i.slice(4)),i==="true")r.parsed={operator:"true"};else if(i==="false")r.parsed={operator:"false_or_null"};else if(i==="=false")r.parsed={operator:"false"};else if(i==="null")r.parsed={operator:"null"};else if(i==="not null")r.parsed={operator:"null",not:!0};else{const o=t.match(/[^\s]/),u=o&&(e=o.index)!==null&&e!==void 0?e:0;r.log=[{message:"Illegal boolean filter. Must be one of true,false,=false,null,not null",severity:"error",startIndex:u,endIndex:u+t.length-1}]}return s&&r.parsed&&(r.parsed.not=!0),r},unparse(t){if(t===null)return"";const e=t.not?"not ":"";switch(t.operator){case"true":case"null":return e+t.operator;case"false_or_null":return e+"false";case"false":return e+"=false"}}};var ple={},mle={exports:{}};(function(t){(function(e,r){t.exports?t.exports=r():e.nearley=r()})(T,function(){function e(c,f,x){return this.id=++e.highestId,this.name=c,this.symbols=f,this.postprocess=x,this}e.highestId=0,e.prototype.toString=function(c){var f=typeof c>"u"?this.symbols.map(l).join(" "):this.symbols.slice(0,c).map(l).join(" ")+" ● "+this.symbols.slice(c).map(l).join(" ");return this.name+" → "+f};function r(c,f,x,h){this.rule=c,this.dot=f,this.reference=x,this.data=[],this.wantedBy=h,this.isComplete=this.dot===c.symbols.length}r.prototype.toString=function(){return"{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0)},r.prototype.nextState=function(c){var f=new r(this.rule,this.dot+1,this.reference,this.wantedBy);return f.left=this,f.right=c,f.isComplete&&(f.data=f.build(),f.right=void 0),f},r.prototype.build=function(){var c=[],f=this;do c.push(f.right.data),f=f.left;while(f.left);return c.reverse(),c},r.prototype.finish=function(){this.rule.postprocess&&(this.data=this.rule.postprocess(this.data,this.reference,u.fail))};function i(c,f){this.grammar=c,this.index=f,this.states=[],this.wants={},this.scannable=[],this.completed={}}i.prototype.process=function(c){for(var f=this.states,x=this.wants,h=this.completed,p=0;p<f.length;p++){var m=f[p];if(m.isComplete){if(m.finish(),m.data!==u.fail){for(var y=m.wantedBy,g=y.length;g--;){var E=y[g];this.complete(E,m)}if(m.reference===this.index){var A=m.rule.name;(this.completed[A]=this.completed[A]||[]).push(m)}}}else{var A=m.rule.symbols[m.dot];if(typeof A!="string"){this.scannable.push(m);continue}if(x[A]){if(x[A].push(m),h.hasOwnProperty(A))for(var _=h[A],g=0;g<_.length;g++){var v=_[g];this.complete(m,v)}}else x[A]=[m],this.predict(A)}}},i.prototype.predict=function(c){for(var f=this.grammar.byName[c]||[],x=0;x<f.length;x++){var h=f[x],p=this.wants[c],m=new r(h,0,this.index,p);this.states.push(m)}},i.prototype.complete=function(c,f){var x=c.nextState(f);this.states.push(x)};function s(c,f){this.rules=c,this.start=f||this.rules[0].name;var x=this.byName={};this.rules.forEach(function(h){x.hasOwnProperty(h.name)||(x[h.name]=[]),x[h.name].push(h)})}s.fromCompiled=function(h,f){var x=h.Lexer;h.ParserStart&&(f=h.ParserStart,h=h.ParserRules);var h=h.map(function(m){return new e(m.name,m.symbols,m.postprocess)}),p=new s(h,f);return p.lexer=x,p};function o(){this.reset("")}o.prototype.reset=function(c,f){this.buffer=c,this.index=0,this.line=f?f.line:1,this.lastLineBreak=f?-f.col:0},o.prototype.next=function(){if(this.index<this.buffer.length){var c=this.buffer[this.index++];return c===`
|
|
1423
1423
|
`&&(this.line+=1,this.lastLineBreak=this.index),{value:c}}},o.prototype.save=function(){return{line:this.line,col:this.index-this.lastLineBreak}},o.prototype.formatError=function(c,f){var x=this.buffer;if(typeof x=="string"){var h=x.split(`
|
|
1424
1424
|
`).slice(Math.max(0,this.line-5),this.line),p=x.indexOf(`
|
|
@@ -1445,7 +1445,7 @@ ${(0,Fn.indent)(u)})
|
|
|
1445
1445
|
`),i=this.pdts.join(`
|
|
1446
1446
|
`),s=this.combineStages(!1).sql;return r+i+s+this.withs[e]}generateCoorelatedSubQuery(e,r){var i,s;return this.useCTE?this.combineStages(!0).sql+e.sqlCreateFunctionCombineLastStage(this.getName(this.withs.length-1),C2(r),(s=r.resultMetadata)===null||s===void 0?void 0:s.orderBy):e.sqlCreateFunctionCombineLastStage(`(${this.withs[0]})`,C2(r),(i=r.resultMetadata)===null||i===void 0?void 0:i.orderBy)}}class sE{constructor(){this.totalGroupSet=-1}withWhere(e){const r=new sE;return r.whereSQL=e,r.applyValue=this.applyValue,r.totalGroupSet=this.totalGroupSet,r}withApply(e){const r=new sE;return r.whereSQL=this.whereSQL,r.applyValue=e,r.totalGroupSet=this.totalGroupSet,r}withTotal(e){const r=new sE;return r.whereSQL=this.whereSQL,r.applyValue=this.applyValue,r.totalGroupSet=e,r}}class ptt{constructor(e){this.referenceId=e??(0,utt.v4)()}getChildByName(e){}}let DB=class extends ptt{constructor(e,r,i){super(i),this.fieldDef=e,this.parent=r,this.fieldDef=e}getIdentifier(){return(0,Ue.getIdentifier)(this.fieldDef)}uniqueKeyPossibleUse(){}getJoinableParent(){const e=this.parent;return e.structDef.type==="record"?e.getJoinableParent():e}isAtomic(){return(0,Ue.isAtomic)(this.fieldDef)}caseGroup(e,r){return e.length===0?r:`CASE WHEN group_set${e.length===1?`=${e[0]}`:` IN (${e.join(",")})`} THEN
|
|
1447
1447
|
${r}
|
|
1448
|
-
END`}getFullOutputName(){return this.parent.getFullOutputName()+this.getIdentifier()}generateFieldFragment(e,r,i,s){const o=r.getFieldByName(i.path);return(0,Ue.hasExpression)(o.fieldDef)?`(${this.exprToSQL(e,o.parent,o.fieldDef.e,s)})`:o.generateExpression(e)}generateOutputFieldFragment(e,r,i,s){return`(${e.getField(i.name).getAnalyticalSQL(!1)})`}*stringsFromSQLExpression(e,r,i,s){const o=[...i.kids.args];for(const u of i.src){yield u;const a=o.shift();a&&(yield this.exprToSQL(e,r,a,s))}}getParameterMap(e,r){return new Map(e.params.map((i,s)=>{const o=i.isVariadic?(0,Fn.range)(s,r):[s];return[i.name,{param:i,argIndexes:o}]}))}expandFunctionCall(e,r,i,s,o){function u(c){const f=[];for(let x=0;x<c.length;)f.push(c[x]),x+=1,x<c.length&&f.push(",");return f}const a=this.getParameterMap(r,i.length);if(r.dialect[e]===void 0)throw new Error(`Function is not defined for '${e}' dialect`);return(0,Fn.exprMap)(r.dialect[e].e,c=>{var f,x;if(c.node==="spread"){const h=c.e;if(h.node!=="function_parameter")throw new Error("Invalid function definition. Argument to spread must be a function parameter.");const p=a.get(h.name);if(p===void 0)return c;const m=p.argIndexes.map(y=>i[y]);return(0,Fn.composeSQLExpr)(u(m))}else if(c.node==="function_parameter"){const h=a.get(c.name);if(h===void 0)return c;if(h.param.isVariadic){const p=h.argIndexes.map(m=>i[m]);return(0,Fn.composeSQLExpr)(u(p))}else return i[h.argIndexes[0]]}else{if(c.node==="aggregate_order_by")return s?(0,Fn.composeSQLExpr)([` ${(f=c.prefix)!==null&&f!==void 0?f:""}${s}${(x=c.suffix)!==null&&x!==void 0?x:""}`]):{node:""};if(c.node==="aggregate_limit")return o?(0,Fn.composeSQLExpr)([` ${o}`]):{node:""}}return c})}getFunctionOrderBy(e,r,i,s,o,u){if(s.length!==0)return"ORDER BY "+s.map(a=>{var l;const c=(l=u.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&l!==void 0?l:0,f=a.node==="functionOrderBy"?a.e:o[c],x=this.generateDimFragment(e,r,f,i),h=a.dir==="asc"?" ASC":a.dir==="desc"?" DESC":"";return`${x}${h}`}).join(", ")}generateAsymmetricStringAggExpression(e,r,i,s,o,u,a,l){if(u)throw new Error(`Function \`string_agg\` does not support fanning out with an order by in ${a}`);const c=this.generateDimFragment(e,r,i,l),f=s?this.generateDimFragment(e,r,s,l):"";return this.parent.dialect.sqlStringAggDistinct(o,c,f)}getParamForArgIndex(e,r){const i=e.slice(0,r).find(s=>s.isVariadic);return i??e[r]}generateFunctionCallExpression(e,r,i,s){var o,u,a;const l=i.overload,c=i.kids.args,f=(o=i.overload.isSymmetric)!==null&&o!==void 0?o:!1,x=(0,Ue.expressionIsAggregate)(l.returnType.expressionType)&&!f&&this.generateDistinctKeyIfNecessary(e,r,i.structPath),h=i.limit?`LIMIT ${i.limit}`:void 0;if(i.name==="string_agg"&&x&&!r.dialect.supportsAggDistinct&&r.dialect.name!=="snowflake")return this.generateAsymmetricStringAggExpression(e,r,c[0],c[1],x,i.kids.orderBy,r.dialect.name,s);if(x){if(!r.dialect.supportsAggDistinct)throw new Error(`Function \`${i.name}\` does not support fanning out in ${r.dialect.name}`);const p=c.map(g=>this.generateDimFragment(e,r,g,s)),m=(u=i.kids.orderBy)!==null&&u!==void 0?u:[],y=m.map(g=>{var E;const A=(E=l.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&E!==void 0?E:0,_=g.node==="functionOrderBy"?g.e:c[A];return this.generateDimFragment(e,r,_,s)});return r.dialect.sqlAggDistinct(x,[...p,...y],g=>{const E=g.map((S,b)=>b<c.length&&this.getParamForArgIndex(l.params,b).allowedTypes.every(O=>(0,Ue.isLiteral)(O.evalSpace))?c[b]:(0,Fn.composeSQLExpr)([S])),A=E.slice(0,p.length),_=E.slice(p.length).map((S,b)=>({node:"functionOrderBy",e:S,dir:m[b].dir})),v=this.getFunctionOrderBy(e,r,s,_,A,l),C=this.expandFunctionCall(r.dialect.name,l,A,v,h);return this.exprToSQL(e,r,C,s)})}else{const p=(0,Ue.expressionIsAggregate)(l.returnType.expressionType)?c.map((g,E)=>this.getParamForArgIndex(l.params,E).allowedTypes.every(_=>(0,Ue.isLiteral)(_.evalSpace))?g:(0,Fn.composeSQLExpr)([this.generateDimFragment(e,r,g,s)])):c,m=i.kids.orderBy?this.getFunctionOrderBy(e,r,s,i.kids.orderBy,c,l):"",y=this.expandFunctionCall(r.dialect.name,l,p,m,h);if((0,Ue.expressionIsAnalytic)(l.returnType.expressionType)){const g=((a=i.partitionBy)!==null&&a!==void 0?a:[]).map(E=>`(${e.getField(E).getAnalyticalSQL(!1)})`);return this.generateAnalyticFragment(r.dialect.name,e,r,y,l,s,c,g,m)}return this.exprToSQL(e,r,y,s)}}generateSpread(e,r,i,s){throw new Error("Unexpanded spread encountered during SQL generation")}generateParameterFragment(e,r,i,s){var o;const u=i.path[0];(o=r.eventStream)===null||o===void 0||o.emit("source-argument-compiled",{name:u});const a=r.arguments()[u];if(a.value)return this.exprToSQL(e,r,a.value,s);throw new Error(`Can't generate SQL, no value for ${i.path}`)}generateFilterFragment(e,r,i,s){const o=new Fn.AndChain(s.whereSQL);for(const u of i.kids.filterList)o.add(this.exprToSQL(e,r,u.e,s.withWhere()));return this.exprToSQL(e,r,i.kids.e,s.withWhere(o.sql()))}generateDimFragment(e,r,i,s){let o=this.exprToSQL(e,r,i,s);return s.whereSQL&&(o=`CASE WHEN ${s.whereSQL} THEN ${o} END`),o}generateUngroupedFragment(e,r,i,s){if(s.totalGroupSet!==-1)throw new Error("Already in ALL. Cannot nest within an all calcuation.");let o,u;if(i.fields&&i.fields.length>0){const x=i.fields.sort().join("|")+i.node;if(u=e.ungroupedSets.get(x),u===void 0)throw new Error(`Internal Error, cannot find groupset with key ${x}`);o=u.groupSet}else o=e.parent?e.parent.groupSet:0;const a=this.exprToSQL(e,r,i.e,s.withTotal(o)),l=e.getUngroupPartitions(u);let c="";const f=l.map(x=>x.getAnalyticalSQL(!0)).join(", ");return f.length>0&&(c=`PARTITION BY ${f}`),`MAX(${a}) OVER (${c})`}generateDistinctKeyIfNecessary(e,r,i){let s=r;if(i&&(s=this.parent.root().getStructByName(i)),s.needsSymetricCalculation(e))return s.getDistinctKey().generateExpression(e)}generateSumFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);let a;return u?this.parent.dialect.supportsSumDistinctFunction?a=this.parent.dialect.sqlSumDistinct(u,o,"SUM"):a=Ole(this.parent.dialect,o,u):a=`SUM(${o})`,`COALESCE(${a},0)`}generateSymmetricFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s);return`${i.function==="distinct"?"count(distinct ":i.function+"("}${o})`}generateAvgFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);if(u){let a=u;s.whereSQL&&(a=`CASE WHEN ${s.whereSQL} THEN ${u} END`);let l,c;return this.parent.dialect.supportsSumDistinctFunction?c=this.parent.dialect.sqlSumDistinct(u,o,"AVG"):(l=Ole(this.parent.dialect,o,u),c=`(${l})/NULLIF(COUNT(DISTINCT CASE WHEN ${o} IS NOT NULL THEN ${a} END),0)`),c}else return`AVG(${o})`}generateCountFragment(e,r,i,s){let o="COUNT(",u="1",a=r;i.structPath&&(a=this.parent.root().getStructByName(i.structPath));const l=a.getJoinableParent().getIdentifier(),c=e.root().joins.get(l);if(!c)throw new Error(`Join ${l} not found in result set`);return(!c.leafiest||c.makeUniqueKey)&&(o="COUNT(DISTINCT ",u=a.getDistinctKey().generateExpression(e)),s.whereSQL?`${o}CASE WHEN ${s.whereSQL} THEN ${u} END)`:`${o}${u})`}generateSourceReference(e,r,i){return i.path===void 0?r.getSQLIdentifier():r.getFieldByName(i.path).getIdentifier()}getAnalyticPartitions(e,r){const i=[];let s=e.parent;for(;s!==void 0;){const u=s.fields(a=>Qr(a.f)&&a.fieldUsage.type==="result").map(a=>a.getAnalyticalSQL(!0));i.push(...u),s=s.parent}return r&&i.push(...r),i}generateAnalyticFragment(e,r,i,s,o,u,a,l,c){const f=r.root().isComplexQuery,x=this.getAnalyticPartitions(r,l),h=[...f?["group_set"]:[],...x],p=h.length>0?`PARTITION BY ${h.join(", ")}`:"";let m=c??"";const y=o.dialect[e];if(!c&&y.needsWindowOrderBy){const _=[];let v;const C=r.firstSegment.orderBy||r.calculateDefaultOrderBy();for(const S of C){typeof S.field=="string"?v={name:S.field,fif:r.getField(S.field)}:v=r.getFieldByNumber(S.field);const b=v.fif.f.fieldDef.expressionType;if(!(0,Ue.expressionIsAnalytic)(b))if(r.firstSegment.type==="reduce"){const R=v.fif.getAnalyticalSQL(!1);_.push(` ${R} ${S.dir||"ASC"}`)}else r.firstSegment.type==="project"&&_.push(` ${v.fif.f.generateExpression(r)} ${S.dir||"ASC"}`)}_.length>0&&(m=" "+this.parent.dialect.sqlOrderBy(_))}let g="";if(y.between){const[_,v]=[y.between.preceding,y.between.following].map(C=>{if(C===-1)return"UNBOUNDED";if(typeof C=="number")return C;const S=o.params.findIndex(R=>R.name===C),b=a[S];if(b.node!=="numberLiteral")throw new Error("Invalid number of rows for window spec");return b.literal});g=`ROWS BETWEEN ${_} PRECEDING AND ${v} FOLLOWING`}let A=`${this.exprToSQL(r,i,s,u)} OVER(${p} ${m} ${g})`;return f&&(A=`CASE WHEN group_set=${r.groupSet} THEN ${A} END`),A}generateCaseSQL(e){const r=["CASE"];e.kids.caseValue!==void 0&&r.push(`${e.kids.caseValue.sql}`);for(let i=0;i<e.kids.caseWhen.length;i+=1)r.push(`WHEN ${e.kids.caseWhen[i].sql} THEN ${e.kids.caseThen[i].sql}`);return e.kids.caseElse!==void 0&&r.push(`ELSE ${e.kids.caseElse.sql}`),r.push("END"),r.join(" ")}exprToSQL(e,r,i,s=new sE){var o;const u=function(f,x){const h=f.exprToSQL(e,r,x,s);return(0,Ue.exprHasKids)(x)?`(${h})`:h};let a=i;if((0,Ue.exprHasE)(i)){a={...i};const f=u(this,a.e);a.e={...a.e,sql:f}}else if((0,Ue.exprHasKids)(i)){a={...i};const f=i.kids;for(const[x,h]of Object.entries(f))h!==null&&(Array.isArray(h)?a.kids[x]=h.map(p=>({...p,sql:u(this,p)})):a.kids[x]={...f[x],sql:u(this,h)})}const l=e.getQueryInfo(),c=this.parent.dialect.exprToSQL(l,a);if(c)return c;switch(a.node){case"field":return this.generateFieldFragment(e,r,a,s);case"parameter":return this.generateParameterFragment(e,r,a,s);case"filteredExpr":return this.generateFilterFragment(e,r,a,s);case"all":case"exclude":return this.generateUngroupedFragment(e,r,a,s);case"genericSQLExpr":return Array.from(this.stringsFromSQLExpression(e,r,a,s)).join("");case"aggregate":{let f="";if(a.function==="sum")f=this.generateSumFragment(e,r,a,s);else if(a.function==="avg")f=this.generateAvgFragment(e,r,a,s);else if(a.function==="count")f=this.generateCountFragment(e,r,a,s);else if(a.function==="min"||a.function==="max"||a.function==="distinct")f=this.generateSymmetricFragment(e,r,a,s);else throw new Error(`Internal Error: Unknown aggregate function ${a.function}`);if(e.root().isComplexQuery){let x=e.groupSet;return s.totalGroupSet!==-1&&(x=s.totalGroupSet),this.caseGroup([x],f)}return f}case"function_parameter":throw new Error("Internal Error: Function parameter fragment remaining during SQL generation");case"outputField":return this.generateOutputFieldFragment(e,r,a,s);case"function_call":return this.generateFunctionCallExpression(e,r,a,s);case"spread":return this.generateSpread(e,r,a,s);case"source-reference":return this.generateSourceReference(e,r,a);case"+":case"-":case"*":case"%":case"/":case">":case"<":case">=":case"<=":case"=":return`${a.kids.left.sql}${a.node}${a.kids.right.sql}`;case"!=":return`COALESCE(${`${a.kids.left.sql}!=${a.kids.right.sql}`},true)`;case"and":case"or":return`${a.kids.left.sql} ${a.node} ${a.kids.right.sql}`;case"coalesce":return`COALESCE(${a.kids.left.sql},${a.kids.right.sql})`;case"in":{const f=a.kids.oneOf.map(x=>x.sql).join(",");return`${a.kids.e.sql} ${a.not?"NOT IN":"IN"} (${f})`}case"like":case"!like":{const f=a.node==="like"?"LIKE":"NOT LIKE",x=a.kids.right.node==="stringLiteral"?this.parent.dialect.sqlLike(f,(o=a.kids.left.sql)!==null&&o!==void 0?o:"",a.kids.right.literal):`${a.kids.left.sql} ${f} ${a.kids.right.sql}`;return a.node==="like"?x:`COALESCE(${x},true)`}case"()":return`(${a.e.sql})`;case"not":return`COALESCE(NOT ${a.e.sql},TRUE)`;case"unary-":return`-${a.e.sql}`;case"is-null":return`${a.e.sql} IS NULL`;case"is-not-null":return`${a.e.sql} IS NOT NULL`;case"true":case"false":return a.node;case"null":return"NULL";case"case":return this.generateCaseSQL(a);case"":return"";case"filterCondition":return a.e.sql?(a.sql=a.e.sql,a.sql):"";case"functionDefaultOrderBy":case"functionOrderBy":return"";case"compositeField":return"{COMPOSITE_FIELD}";case"filterMatch":if((a.dataType==="string"||a.dataType==="number"||a.dataType==="date"||a.dataType==="timestamp"||a.dataType==="boolean")&&(0,xtt.isFilterExpression)(a.filter))return ftt.FilterCompilers.compile(a.dataType,a.filter,a.e.sql||"",this.parent.dialect);throw new Error(`Internal Error: Filter Compiler Undefined Type '${a.dataType}'`);default:throw new Error(`Internal Error: Unknown expression node '${a.node}' ${JSON.stringify(a,void 0,2)}`)}}isNestedInParent(e){switch(e.type){case"record":case"array":return!0;default:return!1}}isArrayElement(e){return e.type==="array"&&e.elementTypeDef.type!=="record_element"}generateExpression(e){if((0,Ue.hasExpression)(this.fieldDef))return this.exprToSQL(e,this.parent,this.fieldDef.e);for(let r=this.parent;r!==void 0;r=r.parent)if(r.structDef.type==="record"&&(0,Ue.hasExpression)(r.structDef)&&r.recordAlias===void 0){if(!r.parent)throw new Error("Inconcievable record ancestor with expression but no parent");const i=this.exprToSQL(e,r.parent,r.structDef.e);r.informOfAliasValue(i)}return this.parent.sqlChildReference(this.fieldDef.name,this.parent.structDef.type==="record"?{result:e,field:this}:void 0)}};function U4(t){return t instanceof Qs&&t.isCalculated()}function Rle(t){return t instanceof Qs&&t.isAggregate()}function Qr(t){return t instanceof Qs&&!t.isCalculated()&&!t.isAggregate()}class Qs extends DB{constructor(e,r,i){super(e,r,i),this.fieldDef=e}includeInWildcard(){return!0}isCalculated(){return(0,Ue.hasExpression)(this.fieldDef)&&(0,Ue.expressionIsCalculation)(this.fieldDef.expressionType)}isAggregate(){return(0,Ue.hasExpression)(this.fieldDef)&&(0,Ue.expressionIsAggregate)(this.fieldDef.expressionType)}getFilterList(){return[]}hasExpression(){return(0,Ue.hasExpression)(this.fieldDef)}isAtomic(){return!0}}class mtt extends Qs{}class gtt extends Qs{}class OB extends Qs{}class ytt extends Qs{}class Ett extends Qs{}class wB extends Qs{generateExpression(e){const r=this.fieldDef,i=super.generateExpression(e);if(r.timeframe){const s={node:"trunc",e:(0,Ue.mkTemporal)({node:"genericSQLExpr",src:[i],kids:{args:[]}},"date"),units:r.timeframe};return this.exprToSQL(e,this.parent,s)}else return i}getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new wB(r,this.parent)}}class FB extends Qs{getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new FB(r,this.parent)}}class Att extends Qs{generateExpression(e){var r;if(this.parent.primaryKey())return this.parent.getPrimaryKeyField(this.fieldDef).generateExpression(e);if(this.parent.structDef.type==="array"){const i=(r=this.parent.parent)===null||r===void 0?void 0:r.getDistinctKey().generateExpression(e);return this.parent.dialect.sqlMakeUnnestKey(i||"",this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__row_id","string"))}else return this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__distinct_key","string")}includeInWildcard(){return!1}}const Dle=9;function Ole(t,e,r){const s=t.sqlSumDistinctHashedKey(r),o=10**(9-Dle);let a=`(${`
|
|
1448
|
+
END`}getFullOutputName(){return this.parent.getFullOutputName()+this.getIdentifier()}generateFieldFragment(e,r,i,s){const o=r.getFieldByName(i.path);return(0,Ue.hasExpression)(o.fieldDef)?`(${this.exprToSQL(e,o.parent,o.fieldDef.e,s)})`:o.generateExpression(e)}generateOutputFieldFragment(e,r,i,s){return`(${e.getField(i.name).getAnalyticalSQL(!1)})`}*stringsFromSQLExpression(e,r,i,s){const o=[...i.kids.args];for(const u of i.src){yield u;const a=o.shift();a&&(yield this.exprToSQL(e,r,a,s))}}getParameterMap(e,r){return new Map(e.params.map((i,s)=>{const o=i.isVariadic?(0,Fn.range)(s,r):[s];return[i.name,{param:i,argIndexes:o}]}))}expandFunctionCall(e,r,i,s,o){function u(c){const f=[];for(let x=0;x<c.length;)f.push(c[x]),x+=1,x<c.length&&f.push(",");return f}const a=this.getParameterMap(r,i.length);if(r.dialect[e]===void 0)throw new Error(`Function is not defined for '${e}' dialect`);return(0,Fn.exprMap)(r.dialect[e].e,c=>{var f,x;if(c.node==="spread"){const h=c.e;if(h.node!=="function_parameter")throw new Error("Invalid function definition. Argument to spread must be a function parameter.");const p=a.get(h.name);if(p===void 0)return c;const m=p.argIndexes.map(y=>i[y]);return(0,Fn.composeSQLExpr)(u(m))}else if(c.node==="function_parameter"){const h=a.get(c.name);if(h===void 0)return c;if(h.param.isVariadic){const p=h.argIndexes.map(m=>i[m]);return(0,Fn.composeSQLExpr)(u(p))}else return i[h.argIndexes[0]]}else{if(c.node==="aggregate_order_by")return s?(0,Fn.composeSQLExpr)([` ${(f=c.prefix)!==null&&f!==void 0?f:""}${s}${(x=c.suffix)!==null&&x!==void 0?x:""}`]):{node:""};if(c.node==="aggregate_limit")return o?(0,Fn.composeSQLExpr)([` ${o}`]):{node:""}}return c})}getFunctionOrderBy(e,r,i,s,o,u){if(s.length!==0)return"ORDER BY "+s.map(a=>{var l;const c=(l=u.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&l!==void 0?l:0,f=a.node==="functionOrderBy"?a.e:o[c],x=this.generateDimFragment(e,r,f,i),h=a.dir==="asc"?" ASC":a.dir==="desc"?" DESC":"";return`${x}${h}`}).join(", ")}generateAsymmetricStringAggExpression(e,r,i,s,o,u,a,l){if(u)throw new Error(`Function \`string_agg\` does not support fanning out with an order by in ${a}`);const c=this.generateDimFragment(e,r,i,l),f=s?this.generateDimFragment(e,r,s,l):"";return this.parent.dialect.sqlStringAggDistinct(o,c,f)}getParamForArgIndex(e,r){const i=e.slice(0,r).find(s=>s.isVariadic);return i??e[r]}generateFunctionCallExpression(e,r,i,s){var o,u,a;const l=i.overload,c=i.kids.args,f=(o=i.overload.isSymmetric)!==null&&o!==void 0?o:!1,x=(0,Ue.expressionIsAggregate)(l.returnType.expressionType)&&!f&&this.generateDistinctKeyIfNecessary(e,r,i.structPath),h=i.limit?`LIMIT ${i.limit}`:void 0;if(i.name==="string_agg"&&x&&!r.dialect.supportsAggDistinct&&r.dialect.name!=="snowflake")return this.generateAsymmetricStringAggExpression(e,r,c[0],c[1],x,i.kids.orderBy,r.dialect.name,s);if(x){if(!r.dialect.supportsAggDistinct)throw new Error(`Function \`${i.name}\` does not support fanning out in ${r.dialect.name}`);const p=c.map(g=>this.generateDimFragment(e,r,g,s)),m=(u=i.kids.orderBy)!==null&&u!==void 0?u:[],y=m.map(g=>{var E;const A=(E=l.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&E!==void 0?E:0,_=g.node==="functionOrderBy"?g.e:c[A];return this.generateDimFragment(e,r,_,s)});return r.dialect.sqlAggDistinct(x,[...p,...y],g=>{const E=g.map((S,b)=>b<c.length&&this.getParamForArgIndex(l.params,b).allowedTypes.every(O=>(0,Ue.isLiteral)(O.evalSpace))?c[b]:(0,Fn.composeSQLExpr)([S])),A=E.slice(0,p.length),_=E.slice(p.length).map((S,b)=>({node:"functionOrderBy",e:S,dir:m[b].dir})),v=this.getFunctionOrderBy(e,r,s,_,A,l),C=this.expandFunctionCall(r.dialect.name,l,A,v,h);return this.exprToSQL(e,r,C,s)})}else{const p=(0,Ue.expressionIsAggregate)(l.returnType.expressionType)?c.map((g,E)=>this.getParamForArgIndex(l.params,E).allowedTypes.every(_=>(0,Ue.isLiteral)(_.evalSpace))?g:(0,Fn.composeSQLExpr)([this.generateDimFragment(e,r,g,s)])):c,m=i.kids.orderBy?this.getFunctionOrderBy(e,r,s,i.kids.orderBy,c,l):"",y=this.expandFunctionCall(r.dialect.name,l,p,m,h);if((0,Ue.expressionIsAnalytic)(l.returnType.expressionType)){const g=((a=i.partitionBy)!==null&&a!==void 0?a:[]).map(E=>`(${e.getField(E).getAnalyticalSQL(!1)})`);return this.generateAnalyticFragment(r.dialect.name,e,r,y,l,s,c,g,m)}return this.exprToSQL(e,r,y,s)}}generateSpread(e,r,i,s){throw new Error("Unexpanded spread encountered during SQL generation")}generateParameterFragment(e,r,i,s){var o;const u=i.path[0];(o=r.eventStream)===null||o===void 0||o.emit("source-argument-compiled",{name:u});const a=r.arguments()[u];if(a.value)return this.exprToSQL(e,r,a.value,s);throw new Error(`Can't generate SQL, no value for ${i.path}`)}generateFilterFragment(e,r,i,s){const o=new Fn.AndChain(s.whereSQL);for(const u of i.kids.filterList)o.add(this.exprToSQL(e,r,u.e,s.withWhere()));return this.exprToSQL(e,r,i.kids.e,s.withWhere(o.sql()))}generateDimFragment(e,r,i,s){let o=this.exprToSQL(e,r,i,s);return s.whereSQL&&(o=`CASE WHEN ${s.whereSQL} THEN ${o} END`),o}generateUngroupedFragment(e,r,i,s){if(s.totalGroupSet!==-1)throw new Error("Already in ALL. Cannot nest within an all calcuation.");let o,u;if(i.fields&&i.fields.length>0){const x=i.fields.sort().join("|")+i.node;if(u=e.ungroupedSets.get(x),u===void 0)throw new Error(`Internal Error, cannot find groupset with key ${x}`);o=u.groupSet}else o=e.parent?e.parent.groupSet:0;const a=this.exprToSQL(e,r,i.e,s.withTotal(o)),l=e.getUngroupPartitions(u);let c="";const f=l.map(x=>x.getAnalyticalSQL(!0)).join(", ");return f.length>0&&(c=`PARTITION BY ${f}`),`MAX(${a}) OVER (${c})`}generateDistinctKeyIfNecessary(e,r,i){let s=r;if(i&&(s=this.parent.root().getStructByName(i)),s.needsSymetricCalculation(e))return s.getDistinctKey().generateExpression(e)}generateSumFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);let a;return u?this.parent.dialect.supportsSumDistinctFunction?a=this.parent.dialect.sqlSumDistinct(u,o,"SUM"):a=Ole(this.parent.dialect,o,u):a=`SUM(${o})`,`COALESCE(${a},0)`}generateSymmetricFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s);return`${i.function==="distinct"?"count(distinct ":i.function+"("}${o})`}generateAvgFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);if(u){let a=u;s.whereSQL&&(a=`CASE WHEN ${s.whereSQL} THEN ${u} END`);let l,c;return this.parent.dialect.supportsSumDistinctFunction?c=this.parent.dialect.sqlSumDistinct(u,o,"AVG"):(l=Ole(this.parent.dialect,o,u),c=`(${l})/NULLIF(COUNT(DISTINCT CASE WHEN ${o} IS NOT NULL THEN ${a} END),0)`),c}else return`AVG(${o})`}generateCountFragment(e,r,i,s){let o="COUNT(",u="1",a=r;i.structPath&&(a=this.parent.root().getStructByName(i.structPath));const l=a.getJoinableParent().getIdentifier(),c=e.root().joins.get(l);if(!c)throw new Error(`Join ${l} not found in result set`);return(!c.leafiest||c.makeUniqueKey)&&(o="COUNT(DISTINCT ",u=a.getDistinctKey().generateExpression(e)),s.whereSQL?`${o}CASE WHEN ${s.whereSQL} THEN ${u} END)`:`${o}${u})`}generateSourceReference(e,r,i){return i.path===void 0?r.getSQLIdentifier():r.getFieldByName(i.path).getIdentifier()}getAnalyticPartitions(e,r){const i=[];let s=e.parent;for(;s!==void 0;){const u=s.fields(a=>Qr(a.f)&&a.fieldUsage.type==="result").map(a=>a.getAnalyticalSQL(!0));i.push(...u),s=s.parent}return r&&i.push(...r),i}generateAnalyticFragment(e,r,i,s,o,u,a,l,c){const f=r.root().isComplexQuery,x=this.getAnalyticPartitions(r,l),h=[...f?["group_set"]:[],...x],p=h.length>0?`PARTITION BY ${h.join(", ")}`:"";let m=c??"";const y=o.dialect[e];if(!c&&y.needsWindowOrderBy){const _=[];let v;const C=r.firstSegment.orderBy||r.calculateDefaultOrderBy();for(const S of C){typeof S.field=="string"?v={name:S.field,fif:r.getField(S.field)}:v=r.getFieldByNumber(S.field);const b=v.fif.f.fieldDef.expressionType;if(!(0,Ue.expressionIsAnalytic)(b))if(r.firstSegment.type==="reduce"){const R=v.fif.getAnalyticalSQL(!1);_.push(` ${R} ${S.dir||"ASC"}`)}else r.firstSegment.type==="project"&&_.push(` ${v.fif.f.generateExpression(r)} ${S.dir||"ASC"}`)}_.length>0&&(m=" "+this.parent.dialect.sqlOrderBy(_,"analytical"))}let g="";if(y.between){const[_,v]=[y.between.preceding,y.between.following].map(C=>{if(C===-1)return"UNBOUNDED";if(typeof C=="number")return C;const S=o.params.findIndex(R=>R.name===C),b=a[S];if(b.node!=="numberLiteral")throw new Error("Invalid number of rows for window spec");return b.literal});g=`ROWS BETWEEN ${_} PRECEDING AND ${v} FOLLOWING`}let A=`${this.exprToSQL(r,i,s,u)} OVER(${p} ${m} ${g})`;return f&&(A=`CASE WHEN group_set=${r.groupSet} THEN ${A} END`),A}generateCaseSQL(e){const r=["CASE"];e.kids.caseValue!==void 0&&r.push(`${e.kids.caseValue.sql}`);for(let i=0;i<e.kids.caseWhen.length;i+=1)r.push(`WHEN ${e.kids.caseWhen[i].sql} THEN ${e.kids.caseThen[i].sql}`);return e.kids.caseElse!==void 0&&r.push(`ELSE ${e.kids.caseElse.sql}`),r.push("END"),r.join(" ")}exprToSQL(e,r,i,s=new sE){var o;const u=function(f,x){const h=f.exprToSQL(e,r,x,s);return(0,Ue.exprHasKids)(x)?`(${h})`:h};let a=i;if((0,Ue.exprHasE)(i)){a={...i};const f=u(this,a.e);a.e={...a.e,sql:f}}else if((0,Ue.exprHasKids)(i)){a={...i};const f=i.kids;for(const[x,h]of Object.entries(f))h!==null&&(Array.isArray(h)?a.kids[x]=h.map(p=>({...p,sql:u(this,p)})):a.kids[x]={...f[x],sql:u(this,h)})}const l=e.getQueryInfo(),c=this.parent.dialect.exprToSQL(l,a);if(c)return c;switch(a.node){case"field":return this.generateFieldFragment(e,r,a,s);case"parameter":return this.generateParameterFragment(e,r,a,s);case"filteredExpr":return this.generateFilterFragment(e,r,a,s);case"all":case"exclude":return this.generateUngroupedFragment(e,r,a,s);case"genericSQLExpr":return Array.from(this.stringsFromSQLExpression(e,r,a,s)).join("");case"aggregate":{let f="";if(a.function==="sum")f=this.generateSumFragment(e,r,a,s);else if(a.function==="avg")f=this.generateAvgFragment(e,r,a,s);else if(a.function==="count")f=this.generateCountFragment(e,r,a,s);else if(a.function==="min"||a.function==="max"||a.function==="distinct")f=this.generateSymmetricFragment(e,r,a,s);else throw new Error(`Internal Error: Unknown aggregate function ${a.function}`);if(e.root().isComplexQuery){let x=e.groupSet;return s.totalGroupSet!==-1&&(x=s.totalGroupSet),this.caseGroup([x],f)}return f}case"function_parameter":throw new Error("Internal Error: Function parameter fragment remaining during SQL generation");case"outputField":return this.generateOutputFieldFragment(e,r,a,s);case"function_call":return this.generateFunctionCallExpression(e,r,a,s);case"spread":return this.generateSpread(e,r,a,s);case"source-reference":return this.generateSourceReference(e,r,a);case"+":case"-":case"*":case"%":case"/":case">":case"<":case">=":case"<=":case"=":return`${a.kids.left.sql}${a.node}${a.kids.right.sql}`;case"!=":return`COALESCE(${`${a.kids.left.sql}!=${a.kids.right.sql}`},true)`;case"and":case"or":return`${a.kids.left.sql} ${a.node} ${a.kids.right.sql}`;case"coalesce":return`COALESCE(${a.kids.left.sql},${a.kids.right.sql})`;case"in":{const f=a.kids.oneOf.map(x=>x.sql).join(",");return`${a.kids.e.sql} ${a.not?"NOT IN":"IN"} (${f})`}case"like":case"!like":{const f=a.node==="like"?"LIKE":"NOT LIKE",x=a.kids.right.node==="stringLiteral"?this.parent.dialect.sqlLike(f,(o=a.kids.left.sql)!==null&&o!==void 0?o:"",a.kids.right.literal):`${a.kids.left.sql} ${f} ${a.kids.right.sql}`;return a.node==="like"?x:`COALESCE(${x},true)`}case"()":return`(${a.e.sql})`;case"not":return`COALESCE(NOT ${a.e.sql},TRUE)`;case"unary-":return`-${a.e.sql}`;case"is-null":return`${a.e.sql} IS NULL`;case"is-not-null":return`${a.e.sql} IS NOT NULL`;case"true":case"false":return a.node;case"null":return"NULL";case"case":return this.generateCaseSQL(a);case"":return"";case"filterCondition":return a.e.sql?(a.sql=a.e.sql,a.sql):"";case"functionDefaultOrderBy":case"functionOrderBy":return"";case"compositeField":return"{COMPOSITE_FIELD}";case"filterMatch":if((a.dataType==="string"||a.dataType==="number"||a.dataType==="date"||a.dataType==="timestamp"||a.dataType==="boolean")&&(0,xtt.isFilterExpression)(a.filter))return ftt.FilterCompilers.compile(a.dataType,a.filter,a.e.sql||"",this.parent.dialect);throw new Error(`Internal Error: Filter Compiler Undefined Type '${a.dataType}'`);default:throw new Error(`Internal Error: Unknown expression node '${a.node}' ${JSON.stringify(a,void 0,2)}`)}}isNestedInParent(e){switch(e.type){case"record":case"array":return!0;default:return!1}}isArrayElement(e){return e.type==="array"&&e.elementTypeDef.type!=="record_element"}generateExpression(e){if((0,Ue.hasExpression)(this.fieldDef))return this.exprToSQL(e,this.parent,this.fieldDef.e);for(let r=this.parent;r!==void 0;r=r.parent)if(r.structDef.type==="record"&&(0,Ue.hasExpression)(r.structDef)&&r.recordAlias===void 0){if(!r.parent)throw new Error("Inconcievable record ancestor with expression but no parent");const i=this.exprToSQL(e,r.parent,r.structDef.e);r.informOfAliasValue(i)}return this.parent.sqlChildReference(this.fieldDef.name,this.parent.structDef.type==="record"?{result:e,field:this}:void 0)}};function U4(t){return t instanceof Qs&&t.isCalculated()}function Rle(t){return t instanceof Qs&&t.isAggregate()}function Qr(t){return t instanceof Qs&&!t.isCalculated()&&!t.isAggregate()}class Qs extends DB{constructor(e,r,i){super(e,r,i),this.fieldDef=e}includeInWildcard(){return!0}isCalculated(){return(0,Ue.hasExpression)(this.fieldDef)&&(0,Ue.expressionIsCalculation)(this.fieldDef.expressionType)}isAggregate(){return(0,Ue.hasExpression)(this.fieldDef)&&(0,Ue.expressionIsAggregate)(this.fieldDef.expressionType)}getFilterList(){return[]}hasExpression(){return(0,Ue.hasExpression)(this.fieldDef)}isAtomic(){return!0}}class mtt extends Qs{}class gtt extends Qs{}class OB extends Qs{}class ytt extends Qs{}class Ett extends Qs{}class wB extends Qs{generateExpression(e){const r=this.fieldDef,i=super.generateExpression(e);if(r.timeframe){const s={node:"trunc",e:(0,Ue.mkTemporal)({node:"genericSQLExpr",src:[i],kids:{args:[]}},"date"),units:r.timeframe};return this.exprToSQL(e,this.parent,s)}else return i}getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new wB(r,this.parent)}}class FB extends Qs{getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new FB(r,this.parent)}}class Att extends Qs{generateExpression(e){var r;if(this.parent.primaryKey())return this.parent.getPrimaryKeyField(this.fieldDef).generateExpression(e);if(this.parent.structDef.type==="array"){const i=(r=this.parent.parent)===null||r===void 0?void 0:r.getDistinctKey().generateExpression(e);return this.parent.dialect.sqlMakeUnnestKey(i||"",this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__row_id","string"))}else return this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__distinct_key","string")}includeInWildcard(){return!1}}const Dle=9;function Ole(t,e,r){const s=t.sqlSumDistinctHashedKey(r),o=10**(9-Dle);let a=`(${`
|
|
1449
1449
|
(
|
|
1450
1450
|
SUM(DISTINCT
|
|
1451
1451
|
(CAST(ROUND(COALESCE(${e},0)*(${o}*1.0), ${Dle}) AS ${t.defaultDecimalType}) +
|
|
@@ -1464,7 +1464,7 @@ ${(0,Fn.indent)(p)}) AS ${r.alias}
|
|
|
1464
1464
|
ON ${f}
|
|
1465
1465
|
`,o}}else if(a.type==="array"){if(u.parent===void 0||r.parent===void 0)throw new Error("Internal Error, nested structure with no parent.");let l;(0,Ue.hasExpression)(a)?l=this.exprToSQL(this.rootResult,u.parent,a.e):l=u.parent.sqlChildReference(a.name,i===0?{result:this.rootResult,field:this}:void 0),o+=`${this.parent.dialect.sqlUnnestAlias(l,r.alias,r.getDialectFieldList(),r.makeUniqueKey,(0,Ue.isScalarArray)(a),this.inNestedPipeline())}
|
|
1466
1466
|
`}else throw a.type==="record"?new Error("Internal Error: records should never appear in join trees"):new Error(`Join type not implemented ${u.structDef.type}`);for(const l of r.children)o+=this.generateSQLJoinBlock(e,l,i+1);return o}generateSQLPassthroughKeys(e){let r="";if(e.dialect.name==="standardsql"){const i=["_TABLE_SUFFIX","_PARTITIONDATE","_PARTITIONTIME"].filter(s=>e.getChildByName(s)!==void 0);i.length>0&&(r=", "+i.join(", "))}return r}generateSQLJoins(e){let r="";const[[,i]]=this.rootResult.joins,s=i.queryStruct;let o=s.structSourceSQL(e);if((0,Ue.isIndexSegment)(this.firstSegment)&&(o=this.parent.dialect.sqlSampleTable(o,this.firstSegment.sample),this.firstSegment.sample&&(o=e.addStage(`SELECT * from ${o} as x limit 100000 `))),(0,Ue.isBaseTable)(s.structDef)){if(i.makeUniqueKey){const u=this.generateSQLPassthroughKeys(s);o=`(SELECT ${s.dialect.sqlGenerateUUID()} as ${s.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${u} FROM ${o} as x)`}r+=`FROM ${o} as ${i.alias}
|
|
1467
|
-
`}else throw new Error("Internal Error, queries must start from a basetable");for(const u of i.children)r+=this.generateSQLJoinBlock(e,u,0);return r}genereateSQLOrderBy(e,r){let i="";if(this.firstSegment.type==="project"&&!e.orderBy||this.fieldDef.pipeline.length>1&&e.limit===void 0||r.getRepeatedResultType()==="inline_all_numbers"||this.isJoinedSubquery&&this.fieldDef.pipeline.length===1&&e.limit===void 0)return"";const s=e.orderBy||r.calculateDefaultOrderBy(),o=[];for(const u of s)if(typeof u.field=="string"){const a=r.getField(u.field);if(a&&a.fieldUsage.type==="result")this.parent.dialect.orderByClause==="ordinal"
|
|
1467
|
+
`}else throw new Error("Internal Error, queries must start from a basetable");for(const u of i.children)r+=this.generateSQLJoinBlock(e,u,0);return r}genereateSQLOrderBy(e,r){let i="";if(this.firstSegment.type==="project"&&!e.orderBy||this.fieldDef.pipeline.length>1&&e.limit===void 0||r.getRepeatedResultType()==="inline_all_numbers"||this.isJoinedSubquery&&this.fieldDef.pipeline.length===1&&e.limit===void 0)return"";const s=e.orderBy||r.calculateDefaultOrderBy(),o=[];for(const u of s)if(typeof u.field=="string"){const a=r.getField(u.field);if(a&&a.fieldUsage.type==="result"){if(this.parent.dialect.orderByClause==="ordinal")o.push(`${a.fieldUsage.resultIndex} ${u.dir||"ASC"}`);else if(this.parent.dialect.orderByClause==="output_name")o.push(`${this.parent.dialect.sqlMaybeQuoteIdentifier(u.field)} ${u.dir||"ASC"}`);else if(this.parent.dialect.orderByClause==="expression"){const l=a.getSQL();o.push(`${l} ${u.dir||"ASC"}`)}}else throw new Error(`Unknown field in ORDER BY ${u.field}`)}else if(this.parent.dialect.orderByClause==="ordinal")o.push(`${u.field} ${u.dir||"ASC"}`);else if(this.parent.dialect.orderByClause==="output_name"){const a=r.getFieldByNumber(u.field);o.push(`${this.parent.dialect.sqlMaybeQuoteIdentifier(a.name)} ${u.dir||"ASC"}`)}else if(this.parent.dialect.orderByClause==="expression"){const l=r.getFieldByNumber(u.field).fif.getSQL();o.push(`${l} ${u.dir||"ASC"}`)}return o.length>0&&(i=this.parent.dialect.sqlOrderBy(o,"query")+`
|
|
1468
1468
|
`),i}generateSimpleSQL(e){let r="";r+=`SELECT
|
|
1469
1469
|
`;const i=[];for(const[s,o]of this.rootResult.allFields){const u=o,a=this.parent.dialect.sqlMaybeQuoteIdentifier(s);u.fieldUsage.type==="result"&&i.push(` ${u.f.generateExpression(this.rootResult)} as ${a}`)}if(r+=(0,Fn.indent)(i.join(`,
|
|
1470
1470
|
`))+`
|
|
@@ -1499,7 +1499,7 @@ FROM ${r}
|
|
|
1499
1499
|
`;const l=this.rootResult.eliminateComputeGroupsSQL();return l.length>0&&(i+=`WHERE ${l}
|
|
1500
1500
|
`),a.length>0&&(i+=`GROUP BY ${a.join(",")}
|
|
1501
1501
|
`),i+=this.genereateSQLOrderBy(this.firstSegment,this.rootResult),!(0,Ue.isRawSegment)(this.firstSegment)&&this.firstSegment.limit&&(i+=`LIMIT ${this.firstSegment.limit}
|
|
1502
|
-
`),this.resultStage=e.addStage(i),this.resultStage=this.generatePipelinedStages(u,this.resultStage,e),this.resultStage}buildDialectFieldList(e){const r=[];for(const[i,s]of e.allFields){const o=this.parent.dialect.sqlMaybeQuoteIdentifier(i);if(e.firstSegment.type==="reduce"&&s instanceof Ua){const u={type:"struct",sqlExpression:this.parent.dialect.sqlMaybeQuoteIdentifier(`${i}__${e.groupSet}`),rawName:i,sqlOutputName:o,isArray:s.getRepeatedResultType()==="nested",nestedStruct:this.buildDialectFieldList(s)};r.push(u)}else e.firstSegment.type==="reduce"&&s instanceof Ki&&s.fieldUsage.type==="result"?r.push({type:s.f.fieldDef.type,sqlExpression:this.parent.dialect.sqlMaybeQuoteIdentifier(`${i}__${e.groupSet}`),rawName:i,sqlOutputName:o}):e.firstSegment.type==="project"&&s instanceof Ki&&s.fieldUsage.type==="result"&&r.push({type:s.f.fieldDef.type,sqlExpression:s.f.generateExpression(e),rawName:i,sqlOutputName:o})}return r}generateTurtleSQL(e,r,i,s){let o="";const u=(0,Ue.isRawSegment)(e.firstSegment)?void 0:e.firstSegment.limit,a=[];let l;const c=e.firstSegment.orderBy||e.calculateDefaultOrderBy();for(const g of c)typeof g.field=="string"?l={name:g.field,fif:e.getField(g.field)}:l=e.getFieldByNumber(g.field),e.firstSegment.type==="reduce"?a.push(" "+this.parent.dialect.sqlMaybeQuoteIdentifier(`${l.name}__${e.groupSet}`)+` ${g.dir||"ASC"}`):e.firstSegment.type==="project"&&a.push(` ${l.fif.f.generateExpression(e)} ${g.dir||"ASC"}`);a.length>0&&(o=" "+this.parent.dialect.sqlOrderBy(a));const f=this.buildDialectFieldList(e);let x,h;(x=e.getRepeatedResultType())!=="nested"?x==="inline_all_numbers"?h=this.parent.dialect.sqlCoaleseMeasuresInline(e.groupSet,f):h=this.parent.dialect.sqlAnyValueTurtle(e.groupSet,f):h=this.parent.dialect.sqlAggregateTurtle(e.groupSet,f,o,u);const p=new iE(this.parent.dialect.supportsCTEinCoorelatedSubQueries,r),{structDef:m,pipeOut:y}=this.generateTurtlePipelineSQL(e,p,this.parent.dialect.supportUnnestArrayAgg?h:i);if(y!==void 0){const g=p.generateCoorelatedSubQuery(this.parent.dialect,m);this.parent.dialect.supportUnnestArrayAgg?h=`(${g})`:s.push({sqlFieldName:i,pipelineSQL:`(${g})`})}return h}generateTurtlePipelineSQL(e,r,i){let s=this.getResultStructDef(e,!1);const o=e.getRepeatedResultType(),u=e.turtleDef.pipeline.length>1;let a,l=o;if(u){const c=[...e.turtleDef.pipeline];c.shift();const f={type:"turtle",name:"starthere",pipeline:c},x={type:"nest_source",name:"~pipe~",pipeSQL:this.parent.dialect.sqlUnnestPipelineHead(o==="inline_all_numbers",i,C2(s)),fields:s.fields,connection:s.connection,dialect:s.dialect},h=new p0(x,void 0,{model:this.parent.getModel()},this.parent.prepareResultOptions),p=Es.makeQuery(f,h,r,this.isJoinedSubquery);a=p.generateSQLFromPipeline(r),l=p.rootResult.getRepeatedResultType(),s=a.outputStruct}return s.annotation=e.turtleDef.annotation,{structDef:s,pipeOut:a,repeatedResultType:l}}generateComplexSQL(e){let r=this.generateSQLStage0(e);if(this.maxDepth>1){let i=this.maxDepth;for(;i>1;)r=this.generateSQLDepthN(i,e,r),i--}return this.genereateSQLCombineTurtles(e,r)}generateSQL(e){var r;const i=this.rootResult.computeGroups(0,0);return this.maxDepth=i.maxDepth,this.maxGroupSet=i.nextGroupSetNumber-1,this.rootResult.assignFieldsToGroups(),(r=this.rootResult).isComplexQuery||(r.isComplexQuery=this.maxDepth>0||i.isComplex),this.rootResult.isComplexQuery?this.generateComplexSQL(e):this.generateSimpleSQL(e)}generateSQLFromPipeline(e){this.parent.maybeEmitParameterizedSourceUsage(),this.prepare(e);let r=this.generateSQL(e),i=this.getResultStructDef();if(this.fieldDef.pipeline.length>1){const s=[...this.fieldDef.pipeline];let o={...i,type:"finalize"};s.shift();for(const u of s){const a=this.parent.parent?{struct:this.parent.parent}:{model:this.parent.getModel()},l=new p0(o,void 0,a,this.parent.prepareResultOptions),c=Es.makeQuery({type:"turtle",name:"~computeLastStage~",pipeline:[u]},l,e,this.isJoinedSubquery);c.prepare(e),r=c.generateSQL(e),i=c.getResultStructDef(),o={...i,type:"finalize"}}}return{lastStageName:r,outputStruct:i}}}class Ttt extends Es{}class Rtt extends Es{}class Dtt extends Es{constructor(e,r,i,s){super(e,r,i,s),this.indexPaths={},this.fieldDef=e}expandField(e){const r=e.path.join("."),i=this.parent.getQueryFieldByName(e.path);return{as:r,field:i}}expandFields(e){let r=1;const i=e.groupSet;this.maxGroupSet=i;for(const o of this.firstSegment.indexFields){const{as:u,field:a}=this.expandField(o);this.indexPaths[u]=o.path,e.addField(u,a,{resultIndex:r,type:"result"}),a instanceof Qs&&this.addDependancies(e,a),r++}const s=this.firstSegment.weightMeasure;if(s!==void 0){const o=this.parent.getFieldByName([s]);e.addField(s,o,{resultIndex:r,type:"result"}),this.addDependancies(e,o)}this.expandFilters(e)}generateSQL(e){let r="COUNT(*)";const i=this.parent.dialect,s=i.sqlMaybeQuoteIdentifier("fieldName"),o=i.sqlMaybeQuoteIdentifier("fieldPath"),u=i.sqlMaybeQuoteIdentifier("fieldValue"),a=i.sqlMaybeQuoteIdentifier("fieldType"),l=i.sqlMaybeQuoteIdentifier("fieldRange"),c=i.sqlMaybeQuoteIdentifier("weight"),f=this.firstSegment.weightMeasure;f&&(r=this.rootResult.getField(f).f.generateExpression(this.rootResult));const x=[];for(const[m,y]of this.rootResult.allFields){const g=y;if(g.fieldUsage.type==="result"&&Qr(g.f)){const E=g.f.generateExpression(this.rootResult),A=this.indexPaths[m]||[];x.push({name:m,path:A,type:g.f.fieldDef.type,expression:E})}}let h=`SELECT
|
|
1502
|
+
`),this.resultStage=e.addStage(i),this.resultStage=this.generatePipelinedStages(u,this.resultStage,e),this.resultStage}buildDialectFieldList(e){const r=[];for(const[i,s]of e.allFields){const o=this.parent.dialect.sqlMaybeQuoteIdentifier(i);if(e.firstSegment.type==="reduce"&&s instanceof Ua){const u={type:"struct",sqlExpression:this.parent.dialect.sqlMaybeQuoteIdentifier(`${i}__${e.groupSet}`),rawName:i,sqlOutputName:o,isArray:s.getRepeatedResultType()==="nested",nestedStruct:this.buildDialectFieldList(s)};r.push(u)}else e.firstSegment.type==="reduce"&&s instanceof Ki&&s.fieldUsage.type==="result"?r.push({type:s.f.fieldDef.type,sqlExpression:this.parent.dialect.sqlMaybeQuoteIdentifier(`${i}__${e.groupSet}`),rawName:i,sqlOutputName:o}):e.firstSegment.type==="project"&&s instanceof Ki&&s.fieldUsage.type==="result"&&r.push({type:s.f.fieldDef.type,sqlExpression:s.f.generateExpression(e),rawName:i,sqlOutputName:o})}return r}generateTurtleSQL(e,r,i,s){let o="";const u=(0,Ue.isRawSegment)(e.firstSegment)?void 0:e.firstSegment.limit,a=[];let l;const c=e.firstSegment.orderBy||e.calculateDefaultOrderBy();for(const g of c)typeof g.field=="string"?l={name:g.field,fif:e.getField(g.field)}:l=e.getFieldByNumber(g.field),e.firstSegment.type==="reduce"?a.push(" "+this.parent.dialect.sqlMaybeQuoteIdentifier(`${l.name}__${e.groupSet}`)+` ${g.dir||"ASC"}`):e.firstSegment.type==="project"&&a.push(` ${l.fif.f.generateExpression(e)} ${g.dir||"ASC"}`);a.length>0&&(o=" "+this.parent.dialect.sqlOrderBy(a,"turtle"));const f=this.buildDialectFieldList(e);let x,h;(x=e.getRepeatedResultType())!=="nested"?x==="inline_all_numbers"?h=this.parent.dialect.sqlCoaleseMeasuresInline(e.groupSet,f):h=this.parent.dialect.sqlAnyValueTurtle(e.groupSet,f):h=this.parent.dialect.sqlAggregateTurtle(e.groupSet,f,o,u);const p=new iE(this.parent.dialect.supportsCTEinCoorelatedSubQueries,r),{structDef:m,pipeOut:y}=this.generateTurtlePipelineSQL(e,p,this.parent.dialect.supportUnnestArrayAgg?h:i);if(y!==void 0){const g=p.generateCoorelatedSubQuery(this.parent.dialect,m);this.parent.dialect.supportUnnestArrayAgg?h=`(${g})`:s.push({sqlFieldName:i,pipelineSQL:`(${g})`})}return h}generateTurtlePipelineSQL(e,r,i){let s=this.getResultStructDef(e,!1);const o=e.getRepeatedResultType(),u=e.turtleDef.pipeline.length>1;let a,l=o;if(u){const c=[...e.turtleDef.pipeline];c.shift();const f={type:"turtle",name:"starthere",pipeline:c},x={type:"nest_source",name:"~pipe~",pipeSQL:this.parent.dialect.sqlUnnestPipelineHead(o==="inline_all_numbers",i,C2(s)),fields:s.fields,connection:s.connection,dialect:s.dialect},h=new p0(x,void 0,{model:this.parent.getModel()},this.parent.prepareResultOptions),p=Es.makeQuery(f,h,r,this.isJoinedSubquery);a=p.generateSQLFromPipeline(r),l=p.rootResult.getRepeatedResultType(),s=a.outputStruct}return s.annotation=e.turtleDef.annotation,{structDef:s,pipeOut:a,repeatedResultType:l}}generateComplexSQL(e){let r=this.generateSQLStage0(e);if(this.maxDepth>1){let i=this.maxDepth;for(;i>1;)r=this.generateSQLDepthN(i,e,r),i--}return this.genereateSQLCombineTurtles(e,r)}generateSQL(e){var r;const i=this.rootResult.computeGroups(0,0);return this.maxDepth=i.maxDepth,this.maxGroupSet=i.nextGroupSetNumber-1,this.rootResult.assignFieldsToGroups(),(r=this.rootResult).isComplexQuery||(r.isComplexQuery=this.maxDepth>0||i.isComplex),this.rootResult.isComplexQuery?this.generateComplexSQL(e):this.generateSimpleSQL(e)}generateSQLFromPipeline(e){this.parent.maybeEmitParameterizedSourceUsage(),this.prepare(e);let r=this.generateSQL(e),i=this.getResultStructDef();if(this.fieldDef.pipeline.length>1){const s=[...this.fieldDef.pipeline];let o={...i,type:"finalize"};s.shift();for(const u of s){const a=this.parent.parent?{struct:this.parent.parent}:{model:this.parent.getModel()},l=new p0(o,void 0,a,this.parent.prepareResultOptions),c=Es.makeQuery({type:"turtle",name:"~computeLastStage~",pipeline:[u]},l,e,this.isJoinedSubquery);c.prepare(e),r=c.generateSQL(e),i=c.getResultStructDef(),o={...i,type:"finalize"}}}return{lastStageName:r,outputStruct:i}}}class Ttt extends Es{}class Rtt extends Es{}class Dtt extends Es{constructor(e,r,i,s){super(e,r,i,s),this.indexPaths={},this.fieldDef=e}expandField(e){const r=e.path.join("."),i=this.parent.getQueryFieldByName(e.path);return{as:r,field:i}}expandFields(e){let r=1;const i=e.groupSet;this.maxGroupSet=i;for(const o of this.firstSegment.indexFields){const{as:u,field:a}=this.expandField(o);this.indexPaths[u]=o.path,e.addField(u,a,{resultIndex:r,type:"result"}),a instanceof Qs&&this.addDependancies(e,a),r++}const s=this.firstSegment.weightMeasure;if(s!==void 0){const o=this.parent.getFieldByName([s]);e.addField(s,o,{resultIndex:r,type:"result"}),this.addDependancies(e,o)}this.expandFilters(e)}generateSQL(e){let r="COUNT(*)";const i=this.parent.dialect,s=i.sqlMaybeQuoteIdentifier("fieldName"),o=i.sqlMaybeQuoteIdentifier("fieldPath"),u=i.sqlMaybeQuoteIdentifier("fieldValue"),a=i.sqlMaybeQuoteIdentifier("fieldType"),l=i.sqlMaybeQuoteIdentifier("fieldRange"),c=i.sqlMaybeQuoteIdentifier("weight"),f=this.firstSegment.weightMeasure;f&&(r=this.rootResult.getField(f).f.generateExpression(this.rootResult));const x=[];for(const[m,y]of this.rootResult.allFields){const g=y;if(g.fieldUsage.type==="result"&&Qr(g.f)){const E=g.f.generateExpression(this.rootResult),A=this.indexPaths[m]||[];x.push({name:m,path:A,type:g.f.fieldDef.type,expression:E})}}let h=`SELECT
|
|
1503
1503
|
group_set,
|
|
1504
1504
|
`;h+=` CASE group_set
|
|
1505
1505
|
`;for(let m=0;m<x.length;m++)h+=` WHEN ${m} THEN '${x[m].name}'
|